-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutils.dart
1257 lines (1163 loc) · 39.6 KB
/
utils.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:io';
import 'dart:math';
import 'dart:ui';
import 'package:ensemble/ensemble.dart';
import 'package:ensemble/ensemble_app.dart';
import 'package:ensemble/framework/action.dart';
import 'package:ensemble/framework/assets_service.dart';
import 'package:ensemble/framework/ensemble_config_service.dart';
import 'package:ensemble/framework/stub/location_manager.dart';
import 'package:ensemble/framework/theme/theme_manager.dart';
import 'package:ensemble/screen_controller.dart';
import 'package:ensemble/widget/helpers/tooltip_composite.dart';
import 'package:ensemble_ts_interpreter/invokables/UserLocale.dart';
import 'package:path/path.dart' as p;
import 'package:ensemble/framework/error_handling.dart';
import 'package:ensemble/framework/extensions.dart';
import 'package:ensemble/framework/model.dart';
import 'package:ensemble/framework/scope.dart';
import 'package:ensemble/widget/helpers/controllers.dart';
import 'package:ensemble_ts_interpreter/invokables/invokableprimitives.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:yaml/yaml.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class Utils {
/// global appKey to get the context
static final GlobalKey<NavigatorState> globalAppKey =
GlobalKey<NavigatorState>();
/// some Flutter widgets (TextInput) has no width constraint, so using them inside
/// Rows will cause layout exception. We'll just artificially cap them at a max width,
/// such that they'll overflow the UI instead of layout exception
static const double widgetMaxWidth = 2000;
/// return an Integer if it is, or null if not
static int? optionalInt(dynamic value, {int? min, int? max}) {
int? rtn = value is int
? value
: (value is double
? value.round()
: (value is String ? int.tryParse(value) : null));
if (rtn != null && min != null && rtn < min) {
rtn = null;
}
if (rtn != null && max != null && rtn > max) {
rtn = null;
}
return rtn;
}
static bool? optionalBool(dynamic value) {
return value is bool ? value : null;
}
/// return anything as a string if exists, or null if not
static String? optionalString(dynamic value) {
String? val = value?.toString();
if (val != null) {
return translate(val, null);
}
return val;
}
static double? optionalDouble(dynamic value, {double? min, double? max}) {
double? rtn = value is double
? value
: value is int
? value.toDouble()
: value is String
? double.tryParse(value)
: null;
if (rtn != null && min != null && rtn < min) {
rtn = null;
}
if (rtn != null && max != null && rtn > max) {
rtn = null;
}
return rtn;
}
/// expect a value in seconds
static Duration? getDuration(dynamic value) {
double? number = optionalDouble(value, min: 0);
if (number != null) {
return Duration(milliseconds: (number * 1000).toInt());
}
return null;
}
/// value in milliseconds
static Duration? getDurationMs(dynamic value) {
int? number = optionalInt(value, min: 0);
return number != null ? Duration(milliseconds: number) : null;
}
static BackgroundImage? getBackgroundImage(dynamic value) {
if (value is Map) {
if (value['source'] != null) {
return BackgroundImage(
value['source'].toString(),
fit: BoxFit.values.from(value['fit']),
alignment: getAlignment(value['alignment']),
fallback: value['fallback'],
);
}
}
// legacy, just a simply URL string
else if (value is String) {
return BackgroundImage(value);
}
return null;
}
static LinearGradient? getBackgroundGradient(dynamic value) {
if (value is Map) {
if (value['colors'] is List) {
List<Color> colors = [];
for (dynamic colorEntry in value['colors']) {
Color? color = Utils.getColor(colorEntry);
if (color == null) {
throw LanguageError("Invalid color $colorEntry");
}
colors.add(color);
}
// only valid if have at least 2 colors
if (colors.length >= 2) {
List<double>? stops;
if (value['stops'] is List) {
for (dynamic stop in value['stops']) {
double? stopValue = Utils.optionalDouble(stop, min: 0, max: 1.0);
if (stopValue == null) {
throw LanguageError(
"Gradient's stop has to be a number from 0.0 to 1.0");
}
(stops ??= []).add(stopValue);
}
}
if (stops != null && stops.length != colors.length) {
throw LanguageError(
"Gradient's number of colors and stops should be the same.");
}
return LinearGradient(
colors: colors,
stops: stops,
begin: getAlignment(value['start']) ?? Alignment.centerLeft,
end: getAlignment(value['end']) ?? Alignment.centerRight);
}
}
}
return null;
}
static Alignment? getAlignment(dynamic value) {
switch (value) {
case 'topLeft':
return Alignment.topLeft;
case 'topCenter':
return Alignment.topCenter;
case 'topRight':
return Alignment.topRight;
case 'centerLeft':
return Alignment.centerLeft;
case 'center':
return Alignment.center;
case 'centerRight':
return Alignment.centerRight;
case 'bottomLeft':
return Alignment.bottomLeft;
case 'bottomCenter':
return Alignment.bottomCenter;
case 'bottomRight':
return Alignment.bottomRight;
}
return null;
}
static TextDirection? getTextDirection(dynamic value) {
if (value is String) {
if (value == "leftToRight") {
return TextDirection.ltr;
} else if (value == "rightToLeft") {
return TextDirection.rtl;
}
}
return null;
}
static WrapAlignment? getWrapAlignment(dynamic value) {
switch (value) {
case 'center':
return WrapAlignment.center;
case 'start':
return WrapAlignment.start;
case 'end':
return WrapAlignment.end;
case 'spaceAround':
return WrapAlignment.spaceAround;
case 'spaceBetween':
return WrapAlignment.spaceBetween;
case 'spaceEvenly':
return WrapAlignment.spaceEvenly;
}
}
static InputValidator? getValidator(dynamic value) {
if (value is Map) {
int? minLength = Utils.optionalInt(value['minLength']);
int? maxLength = Utils.optionalInt(value['maxLength']);
String? regex = Utils.optionalString(value['regex']);
String? regexError = Utils.optionalString(value['regexError']);
if (minLength != null || maxLength != null || regex != null) {
return InputValidator(
minLength: minLength,
maxLength: maxLength,
regex: regex,
regexError: regexError);
}
}
return null;
}
static DateTime? getDate(dynamic value) {
return InvokablePrimitive.parseDateTime(value);
}
static TimeOfDay? getTimeOfDay(dynamic value) {
List<dynamic>? tokens = value?.toString().split(':');
if (tokens != null && (tokens.length == 2 || tokens.length == 3)) {
int? hour = optionalInt(int.tryParse(tokens[0]), min: 0, max: 23);
int? minute = optionalInt(int.tryParse(tokens[1]), min: 0, max: 59);
if (hour != null && minute != null) {
return TimeOfDay(hour: hour, minute: minute);
}
}
return null;
}
static String? getUrl(dynamic value) {
if (value != null) {
return Uri.tryParse(value.toString())?.toString();
}
return null;
}
static bool isUrl(String source) {
return source.startsWith('https://') || source.startsWith('http://');
}
static String getAssetName(String source) {
try {
Uri uri = Uri.parse(source);
String path =
uri.pathSegments!.last; // Get the last segment with encoding
return Uri.decodeFull(path)
.split('/')
.last
.split('?')
.first; // Decode and extract the file name
} catch (e) {
return '';
}
}
static LocationData? getLatLng(dynamic value) {
if (value is String) {
List<String> tokens = value.split(RegExp('\\s+'));
if (tokens.length == 2) {
double? lat = double.tryParse(tokens[0]);
double? lng = double.tryParse(tokens[1]);
if (lat != null && lng != null) {
return LocationData(latitude: lat, longitude: lng);
}
}
}
return null;
}
static String getString(dynamic value, {required String fallback}) {
String val = value?.toString() ?? fallback;
return translate(val, null);
}
static bool getBool(dynamic value, {required bool fallback}) {
return value is bool ? value : fallback;
}
static int getInt(dynamic value,
{required int fallback, int? min, int? max}) {
return optionalInt(value, min: min, max: max) ?? fallback;
}
static double getDouble(dynamic value,
{required double fallback, double? min, double? max}) {
return optionalDouble(value, min: min, max: max) ?? fallback;
}
static List<T>? getList<T>(dynamic value) {
if (value is List) {
List<T> results = [];
for (var item in value) {
if (item is T) {
results.add(genericTranslate(item));
}
}
return results;
}
return null;
}
static List<String>? getListOfStrings(dynamic value) {
if (value is YamlList || value is List) {
List<String> results = [];
for (var item in value) {
if (item is String) {
results.add(translate(item, null));
} else {
results.add(translate(item.toString(), null));
}
}
return results;
}
return null;
}
static List<Map>? getListOfMap(dynamic value) {
if (value is List) {
List<Map> results = [];
for (var item in value) {
if (item is Map) {
results.add(item);
} else {
results.add(getMap(item) ?? Map());
}
}
return results;
}
return null;
}
static Map<String, dynamic>? getMap(dynamic value) {
if (value is Map) {
Map<String, dynamic> results = {};
value.forEach((key, value) {
results[key.toString()] = value;
});
return results;
}
return null;
}
static YamlMap? getYamlMap(dynamic value) {
Map? map = getMap(value);
return map != null ? YamlMap.wrap(map) : null;
}
static dynamic convertYamlToDart(dynamic yaml) {
if (yaml is YamlMap) {
// Convert the YamlMap to a Map<String, dynamic>
return yaml.map(
(key, value) => MapEntry(key.toString(), convertYamlToDart(value)));
} else if (yaml is YamlList) {
// Convert the YamlList to a List
return yaml.map((item) => convertYamlToDart(item)).toList();
} else {
// Return the value directly if it's not a YamlMap or YamlList
return yaml;
}
}
//this is semantically different from the methods above as it is doesn't return null when value is not a map
static dynamic maybeYamlMap(dynamic value) {
if (value is Map) {
return YamlMap.wrap(value);
}
return value;
}
static Color? getColor(dynamic value) {
if (value is String) {
value = value.trim();
// Check for hexadecimal color pattern (with or without alpha). It begins with #
RegExp hexColor = RegExp(r'^#?([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$');
if (hexColor.hasMatch(value)) {
// Remove the '#' if it exists
String hexValue = value.replaceFirst('#', '');
// Ensure full opacity if no alpha value is provided
if (hexValue.length == 6) {
hexValue = 'FF$hexValue'; // Add full opacity for RGB values
}
// else move alpha to the front (Flutter specific)
else if (hexValue.length == 8) {
hexValue = "${hexValue.substring(6, 8)}${hexValue.substring(0, 6)}";
}
// Convert to an integer and create a Color object
try {
return Color(int.parse('0x$hexValue'));
} catch (e) {
// Handle or log the error
print('Failed to convert hex to Color: $e');
return null;
}
} else if (value.startsWith("0x")) {
try {
return Color(int.parse(value));
} catch (e) {
debugPrint("fail to convert 0x to Color");
return null;
}
}
// check for name values
switch (value) {
case '.transparent':
case 'transparent':
return Colors.transparent;
case 'black':
return Colors.black;
case 'blue':
return Colors.blue;
case 'white':
return Colors.white;
case 'red':
return Colors.red;
case 'grey':
return Colors.grey;
case 'teal':
return Colors.teal;
case 'amber':
return Colors.amber;
case 'pink':
return Colors.pink;
case 'purple':
return Colors.purple;
case 'yellow':
return Colors.yellow;
case 'green':
return Colors.green;
case 'brown':
return Colors.brown;
case 'cyan':
return Colors.cyan;
case 'indigo':
return Colors.indigo;
case 'lime':
return Colors.lime;
case 'orange':
return Colors.orange;
}
} else if (value is int) {
return Color(value);
}
return null;
}
static IconModel? getIcon(dynamic value) {
dynamic icon;
String? fontFamily;
// short-hand e.g. 'inbox fontAwesome'
if (value is String) {
List<dynamic> tokens = value.split(RegExp(r'\s+'));
if (tokens.isNotEmpty) {
return IconModel(tokens[0],
library: tokens.length >= 2 ? tokens[1].toString() : null);
}
}
// key/value
else if (value is Map && value['name'] != null) {
return IconModel(value['name'],
library: Utils.optionalString(value['library']),
color: Utils.getColor(value['color']),
size: Utils.optionalInt(value['size']));
}
return null;
}
static FontWeight? getFontWeight(dynamic value) {
if (value is String) {
switch (value) {
case 'w100':
return FontWeight.w100;
case 'w200':
return FontWeight.w200;
case 'w300':
case 'light':
return FontWeight.w300;
case 'w400':
case 'normal':
return FontWeight.w400;
case 'w500':
return FontWeight.w500;
case 'w600':
return FontWeight.w600;
case 'w700':
case 'bold':
return FontWeight.w700;
case 'w800':
return FontWeight.w800;
case 'w900':
return FontWeight.w900;
}
}
return null;
}
// Creates tooltip composite from inputs
static TooltipStyleComposite? getTooltipStyleComposite(
ChangeNotifier controller, dynamic inputs) {
if (inputs is Map) {
return TooltipStyleComposite(controller, inputs: inputs);
}
return null;
}
/// Creates tooltip widget with configured styles and behavior
static Widget getTooltipWidget(
BuildContext context,
Widget child,
Map<String, dynamic>? tooltipData,
ChangeNotifier controller
) {
if (tooltipData == null) return child;
final tooltip = TooltipData.from(tooltipData, controller);
if (tooltip == null) return child;
final tooltipKey = GlobalKey();
// Start with the original child
Widget tooltipChild = child;
if (kIsWeb && tooltip.styles?.triggerMode == null) {
tooltipChild = MouseRegion(
onEnter: (_) {
final dynamic tooltip = tooltipKey.currentState;
tooltip?.ensureTooltipVisible();
},
onExit: (_) {
final dynamic tooltip = tooltipKey.currentState;
tooltip?.deactivate();
},
child: tooltipChild,
);
}
return Tooltip(
key: tooltipKey,
message: tooltip.message,
textStyle: tooltip.styles?.textStyle,
padding: tooltip.styles?.padding,
margin: tooltip.styles?.margin,
verticalOffset: tooltip.styles?.verticalOffset,
preferBelow: tooltip.styles?.preferBelow,
waitDuration:
tooltip.styles?.waitDuration ?? const Duration(milliseconds: 0),
showDuration:
tooltip.styles?.showDuration ?? const Duration(milliseconds: 1500),
triggerMode: tooltip.styles?.triggerMode ?? TooltipTriggerMode.tap,
enableFeedback: true,
decoration: BoxDecoration(
color: tooltip.styles?.backgroundColor ?? Colors.grey[700],
borderRadius: tooltip.styles?.borderRadius,
border: (tooltip.styles?.borderColor != null ||
tooltip.styles?.borderWidth != null)
? Border.all(
color: tooltip.styles?.borderColor ??
ThemeManager().getBorderColor(context),
width: (tooltip.styles?.borderWidth ??
ThemeManager().getBorderThickness(context))
.toDouble(),
)
: null,
),
onTriggered: tooltip.onTriggered != null
? () =>
ScreenController().executeAction(context, tooltip.onTriggered!)
: null,
child: tooltipChild,
);
}
static BoxShadowComposite? getBoxShadowComposite(
ChangeNotifier widgetController, dynamic inputs) {
if (inputs is Map) {
return BoxShadowComposite(widgetController, inputs: inputs);
}
return null;
}
static BoxShadow? getBoxShadow(dynamic inputs) {
if (inputs is Map) {
return BoxShadow(
color: Utils.getColor(inputs['color']) ?? Colors.black,
offset: Utils.getOffset(inputs['offset']) ?? Offset.zero,
blurRadius: Utils.getInt(inputs['blur'], fallback: 0).toDouble(),
spreadRadius: Utils.getInt(inputs['spread'], fallback: 0).toDouble(),
blurStyle:
BlurStyle.values.from(inputs['blurStyle']) ?? BlurStyle.normal,
);
}
return null;
}
static TextStyleComposite getTextStyleAsComposite(
WidgetController widgetController,
{dynamic style}) {
return TextStyleComposite(
widgetController,
textGradient: Utils.getBackgroundGradient(style['gradient']),
textAlign: style['textAlign'],
styleWithFontFamily: getTextStyle(style),
);
}
static TextStyle? getTextStyle(dynamic style) {
if (style is Map) {
TextStyle textStyle =
getFontFamily(style['fontFamily']) ?? const TextStyle();
return textStyle.copyWith(
shadows: [
Shadow(
blurRadius: Utils.optionalDouble(style['shadowRadius']) ?? 0.0,
color: Utils.getColor(style['shadowColor']) ??
const Color(0xFF000000),
offset: Utils.getOffset(style['shadowOffset']) ?? Offset.zero,
)
],
fontSize: Utils.optionalInt(style['fontSize'], min: 1, max: 1000)
?.toDouble(),
height: Utils.optionalDouble(style['lineHeightMultiple'],
min: 0.1, max: 10),
fontWeight: getFontWeight(style['fontWeight']),
fontStyle: Utils.optionalBool(style['isItalic']) == true
? FontStyle.italic
: FontStyle.normal,
color: Utils.getColor(style['color']) ??
ThemeManager().defaultTextColor(),
backgroundColor: Utils.getColor(style['backgroundColor']),
decoration: getDecoration(style['decoration']),
decorationStyle:
TextDecorationStyle.values.from(style['decorationStyle']),
decorationColor: Utils.getColor(style['decorationColor']),
decorationThickness:
Utils.optionalDouble(style['decorationThickness']),
overflow: TextOverflow.values.from(style['overflow']),
letterSpacing: Utils.optionalDouble(style['letterSpacing']),
wordSpacing: Utils.optionalDouble(style['wordSpacing']));
} else if (style is String) {}
return null;
}
//fontFamily could either be a string or a map where the key is the language code and the value is the font family name
static TextStyle? getFontFamily(dynamic name) {
String? fontFamily;
// Check if the name is a map with language codes
if (name is Map) {
// Retrieve the current language code
String? languageCode =
UserLocale.from(Ensemble().getLocale())?.languageCode;
if (languageCode != null && name.containsKey(languageCode)) {
fontFamily = name[languageCode]?.toString();
}
// If language code is null or not found in the map, use the default font family if specified
if (fontFamily == null || fontFamily.isEmpty) {
fontFamily = name['default']?.toString();
}
} else if (name is String) {
// Handle the case where name is a string
fontFamily = name;
}
// If a valid font family is found, apply it
if (fontFamily != null && fontFamily.trim().isNotEmpty) {
try {
return GoogleFonts.getFont(fontFamily.trim());
} catch (_) {
return TextStyle(fontFamily: fontFamily);
}
}
// Return null if no valid font family is found
return null;
}
static TextAlign? getTextAlignment(dynamic align) {
TextAlign? textAlign;
switch (align) {
case 'start':
textAlign = TextAlign.start;
break;
case 'end':
textAlign = TextAlign.end;
break;
case 'left':
textAlign = TextAlign.left;
break;
case 'center':
textAlign = TextAlign.center;
break;
case 'right':
textAlign = TextAlign.right;
break;
case 'justify':
textAlign = TextAlign.justify;
break;
}
return textAlign;
}
static Curve? getCurve(String? curveType) {
Curve? curve;
switch (curveType) {
case 'bounceIn':
curve = Curves.bounceIn;
case 'bounceInOut':
curve = Curves.bounceInOut;
case 'bounceOut':
curve = Curves.bounceOut;
case 'decelerate':
curve = Curves.decelerate;
case 'ease':
curve = Curves.ease;
case 'easeIn':
curve = Curves.easeIn;
case 'easeInBack':
curve = Curves.easeInBack;
case 'easeInCirc':
curve = Curves.easeInCirc;
case 'easeInCubic':
curve = Curves.easeInCubic;
case 'easeInExpo':
curve = Curves.easeInExpo;
case 'easeInOut':
curve = Curves.easeInOut;
case 'easeInOutBack':
curve = Curves.easeInOutBack;
case 'easeInOutCirc':
curve = Curves.easeInOutCirc;
case 'easeInOutCubic':
curve = Curves.easeInOutCubic;
case 'easeInOutCubicEmphasized':
curve = Curves.easeInOutCubicEmphasized;
case 'easeInOutExpo':
curve = Curves.easeInOutExpo;
case 'easeInOutQuad':
curve = Curves.easeInOutQuad;
case 'easeInOutQuart':
curve = Curves.easeInOutQuart;
case 'easeInOutQuint':
curve = Curves.easeInOutQuint;
case 'easeInOutSine':
curve = Curves.easeInOutSine;
case 'easeInQuad':
curve = Curves.easeInQuad;
case 'easeInQuart':
curve = Curves.easeInQuart;
case 'easeInQuint':
curve = Curves.easeInQuint;
case 'easeInSine':
curve = Curves.easeInSine;
case 'easeInToLinear':
curve = Curves.easeInToLinear;
case 'easeOut':
curve = Curves.easeOut;
case 'easeOutBack':
curve = Curves.easeOutBack;
case 'easeOutCirc':
curve = Curves.easeOutCirc;
case 'easeOutCubic':
curve = Curves.easeOutCubic;
case 'easeOutExpo':
curve = Curves.easeOutExpo;
case 'easeOutQuad':
curve = Curves.easeOutQuad;
case 'easeOutQuart':
curve = Curves.easeOutQuart;
case 'easeOutQuint':
curve = Curves.easeOutQuint;
case 'easeOutSine':
curve = Curves.easeOutSine;
case 'elasticIn':
curve = Curves.elasticIn;
case 'elasticInOut':
curve = Curves.elasticInOut;
case 'elasticOut':
curve = Curves.elasticOut;
case 'fastEaseInToSlowEaseOut':
curve = Curves.fastEaseInToSlowEaseOut;
case 'fastLinearToSlowEaseIn':
curve = Curves.fastLinearToSlowEaseIn;
case 'linear':
curve = Curves.linear;
case 'linearToEaseOut':
curve = Curves.linearToEaseOut;
case 'slowMiddle':
curve = Curves.slowMiddle;
default:
curve = null;
}
return curve;
}
static TextDecoration? getDecoration(dynamic decoration) {
if (decoration is String) {
switch (decoration) {
case 'underline':
return TextDecoration.underline;
case 'overline':
return TextDecoration.overline;
case 'lineThrough':
return TextDecoration.lineThrough;
}
}
return null;
}
static BorderRadiusGeometry? getBorderRadiusGeometry(dynamic value) {
if (value is int) {
// Optimize: Ignore zero border radius as it causes unnecessary clipping
if (value != 0) {
return BorderRadius.all(Radius.circular(value.toDouble()));
}
} else if (value is String) {
// Convert the string to a list of integers
List<int> numbers = stringToIntegers(value, min: 0);
// Handle 1 to 4 values for BorderRadius
switch (numbers.length) {
case 1:
return BorderRadius.all(Radius.circular(numbers[0].toDouble()));
case 2:
return BorderRadius.vertical(
top: Radius.circular(numbers[0].toDouble()),
bottom: Radius.circular(numbers[1].toDouble()),
);
case 3:
return BorderRadius.only(
topLeft: Radius.circular(numbers[0].toDouble()),
topRight: Radius.circular(numbers[1].toDouble()),
bottomLeft: Radius.circular(numbers[2].toDouble()),
);
case 4:
return BorderRadius.only(
topLeft: Radius.circular(numbers[0].toDouble()),
topRight: Radius.circular(numbers[1].toDouble()),
bottomRight: Radius.circular(numbers[2].toDouble()),
bottomLeft: Radius.circular(numbers[3].toDouble()),
);
default:
throw LanguageError('borderRadius requires 1 to 4 integers');
}
}
// If the input is invalid, return null
return null;
}
static BoxDecoration? getBoxDecoration(dynamic style) {
if (style is Map) {
return BoxDecoration(
color: Utils.getColor(style['backgroundColor']),
border: Border.all(
color: Utils.getColor(style['borderColor']) ?? Colors.transparent,
width: Utils.optionalDouble(style['borderWidth']) ?? 1.0,
),
borderRadius: getBorderRadiusGeometry(style['borderRadius']),
boxShadow: [
if (style['shadow'] != null) BoxShadow(
blurRadius: Utils.optionalDouble(style['shadow']['blurRadius']) ?? 0.0,
color: Utils.getColor(style['shadow']['color']) ?? Colors.black,
offset: Utils.getOffset(style['shadow']['offset']) ?? Offset.zero,
spreadRadius: Utils.optionalDouble(style['shadow']['spreadRadius']) ?? 0.0,
),
],
gradient: style['gradient'] != null ? LinearGradient(
begin: getAlignment(style['gradient']['begin']) ?? Alignment.centerLeft,
end: getAlignment(style['gradient']['end']) ?? Alignment.centerRight,
colors: (style['gradient']['colors'] as List?)
?.map((c) => Utils.getColor(c) ?? Colors.transparent)
.toList() ?? [Colors.transparent],
stops: (style['gradient']['stops'] as List?)
?.map((s) => Utils.optionalDouble(s) ?? 0.0)
.toList(),
) : null,
backgroundBlendMode: BlendMode.values.from(style['blendMode']),
shape: BoxShape.values.from(style['shape']) ?? BoxShape.rectangle,
);
}
return null;
}
/// return the padding/margin value
static EdgeInsets getInsets(dynamic value, {EdgeInsets? fallback}) {
return optionalInsets(value) ?? fallback ?? const EdgeInsets.all(0);
}
static EdgeInsets? optionalInsets(dynamic value) {
if (value is int && value >= 0) {
return EdgeInsets.all(value.toDouble());
} else if (value is String) {
List<String> values = value.split(' ');
if (values.isEmpty || values.length > 4) {
throw LanguageError(
"shorthand notion top/right/bottom/left requires 1 to 4 integers");
}
double top = (parseIntFromString(values[0]) ?? 0).toDouble(),
right = 0,
bottom = 0,
left = 0;
if (values.length == 4) {
right = (parseIntFromString(values[1]) ?? 0).toDouble();
bottom = (parseIntFromString(values[2]) ?? 0).toDouble();
left = (parseIntFromString(values[3]) ?? 0).toDouble();
} else if (values.length == 3) {
left = right = (parseIntFromString(values[1]) ?? 0).toDouble();
bottom = (parseIntFromString(values[2]) ?? 0).toDouble();
} else if (values.length == 2) {
left = right = (parseIntFromString(values[1]) ?? 0).toDouble();
bottom = top;
} else {
left = right = bottom = top;
}
return EdgeInsets.only(
top: top, right: right, bottom: bottom, left: left);
}
return null;
}
static EBorderRadius? getBorderRadius(dynamic value) {
if (value is int) {
// optimize, ignore zero border radius as that causes extra processing for clipping
if (value != 0) {
return EBorderRadius.all(value);
}
} else if (value is String) {
List<int> numbers = stringToIntegers(value, min: 0);
if (numbers.length == 1) {
return EBorderRadius.all(numbers[0]);
} else if (numbers.length == 2) {
return EBorderRadius.two(numbers[0], numbers[1]);
} else if (numbers.length == 3) {
return EBorderRadius.three(numbers[0], numbers[1], numbers[2]);
} else if (numbers.length == 4) {
return EBorderRadius.only(
numbers[0], numbers[1], numbers[2], numbers[3]);
} else {
throw LanguageError('borderRadius requires 1 to 4 integers');
}
}
return null;
}
static Offset? getOffset(dynamic offset) {
if (offset is YamlList) {
List<dynamic> list = offset.toList();
if (list.length >= 2 && list[0] is int && list[1] is int) {
return Offset(list[0].toDouble(), list[1].toDouble());
}
}
return null;
}
static BlurStyle? getShadowBlurStyle(dynamic style) {
return BlurStyle.values.from(style);
}
static Map<String, dynamic>? parseYamlMap(dynamic value) {
Map<String, dynamic>? rtn;
if (value is YamlMap) {
rtn = {};
value.forEach((key, value) {
rtn![key] = value;
});
}
return rtn;
}
/// parse a string and return a list of integers
static List<int> stringToIntegers(String value, {int? min, int? max}) {
List<int> rtn = [];
List<String> values = value.split(' ');
for (var val in values) {
int? number = int.tryParse(val);
if (number != null &&
(min == null || number >= min) &&
(max == null || number <= max)) {
rtn.add(number);
}
}
return rtn;
}
static int? parseIntFromString(String value) {
return int.tryParse(value);