forked from TrackMan/Unity.Package.FigmaToUnity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFigmaParser.cs
2365 lines (2078 loc) · 112 KB
/
FigmaParser.cs
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
using UnityEngine;
using Trackman;
using UnityEngine.UIElements;
// ReSharper disable UnusedMember.Local
// ReSharper disable UnusedParameter.Local
#pragma warning disable S1144 // Unused private types or members should be removed
namespace Figma
{
using global;
using number = Double;
class FigmaParser
{
internal const string images = "Images";
internal const string elements = "Elements";
internal static readonly CultureInfo culture = CultureInfo.GetCultureInfo("en-US");
class StyleSlot : Style
{
#region Fields
public bool Text { get; }
public string Slot { get; }
#endregion
#region Constructors
public StyleSlot(bool text, string slot, Style style)
{
Text = text;
Slot = slot;
styleType = style.styleType;
key = style.key;
name = style.name;
description = style.description;
}
#endregion
#region Methods
public override string ToString() => $"text={Text} slot={Slot} styleType={styleType} key={key} name={name} description={description}";
#endregion
}
class UssStyle
{
internal const string viewportClass = "unity-viewport";
internal const string overrideClass = "unity-base-override";
readonly string[] fontWeights = { "Thin", "ExtraLight", "Light", "Regular", "Medium", "SemiBold", "Bold", "ExtraBold", "Black" };
#region Containers
enum Unit
{
Default,
None,
Initial,
Auto,
Pixel,
Degrees,
Percent
}
enum Align
{
Auto,
FlexStart,
FlexEnd,
Center,
Stretch
}
enum FlexDirection
{
Row,
RowReverse,
Column,
ColumnReverse
}
enum FlexWrap
{
Nowrap,
Wrap,
WrapReverse
}
enum JustifyContent
{
FlexStart,
FlexEnd,
Center,
SpaceBetween,
SpaceAround
}
enum Position
{
Absolute,
Relative
}
enum Visibility
{
Visible,
Hidden
}
enum OverflowClip
{
PaddingBox,
ContentBox
}
enum Display
{
Flex,
None
}
enum FontStyle
{
Normal,
Italic,
Bold,
BoldAndItalic
}
enum TextAlign
{
UpperLeft,
MiddleLeft,
LowerLeft,
UpperCenter,
MiddleCenter,
LowerCenter,
UpperRight,
MiddleRight,
LowerRight
}
enum Wrap
{
Normal,
Nowrap,
}
/// <summary>
/// Represents a distance value.
/// </summary>
readonly struct LengthProperty
{
#region Fields
readonly number value;
readonly Unit unit;
#endregion
#region Constructors
internal LengthProperty(Unit unit)
{
value = default;
this.unit = unit;
}
internal LengthProperty(number value, Unit unit)
{
this.value = value;
this.unit = unit;
}
#endregion
#region Operators
public static implicit operator LengthProperty(Unit value) => new(default, value);
public static implicit operator LengthProperty(number? value) => new(value!.Value, Unit.Pixel);
public static implicit operator LengthProperty(number value) => new(value, Unit.Pixel);
public static implicit operator LengthProperty(string value)
{
if (Enum.TryParse(value, true, out Unit unit)) return new LengthProperty(unit);
if (value.Contains("px")) return new LengthProperty(number.Parse(value.ToLower().Replace("px", ""), culture), Unit.Pixel);
if (value.Contains("deg")) return new LengthProperty(number.Parse(value.ToLower().Replace("deg", ""), culture), Unit.Degrees);
if (value.Contains('%')) return new LengthProperty(number.Parse(value.Replace("%", ""), culture), Unit.Percent);
return default;
}
public static implicit operator string(LengthProperty value)
{
return value.unit switch
{
Unit.Pixel => $"{(int)Math.Round(value.value)}px",
Unit.Degrees => $"{value.value.ToString("F2", culture).Replace(".00", "")}deg",
Unit.Percent => $"{value.value.ToString("F2", culture).Replace(".00", "")}%",
Unit.Auto => "auto",
Unit.None => "none",
Unit.Initial => "initial",
Unit.Default => "0px",
_ => throw new ArgumentException(value)
};
}
public static LengthProperty operator +(LengthProperty a) => a;
public static LengthProperty operator -(LengthProperty a) => new(-a.value, a.unit);
public static LengthProperty operator +(LengthProperty a, number b) => new(a.value + b, a.unit);
public static LengthProperty operator -(LengthProperty a, number b) => new(a.value - b, a.unit);
public static bool operator ==(LengthProperty a, Unit b) => a.unit == b;
public static bool operator !=(LengthProperty a, Unit b) => a.unit != b;
public override bool Equals(object obj) => obj is LengthProperty property && value == property.value && unit == property.unit;
public override int GetHashCode() => HashCode.Combine(value, unit);
public override string ToString() => this;
#endregion
}
/// <summary>
/// Represents either an integer or a number with a fractional component.
/// </summary>
struct NumberProperty
{
#region Fields
readonly number value;
#endregion
#region Constructors
NumberProperty(number value) => this.value = value;
#endregion
#region Operators
public static implicit operator NumberProperty(number? value) => new(value!.Value);
public static implicit operator NumberProperty(number value) => new(value);
public static implicit operator NumberProperty(string value) => new(number.Parse(value, culture));
public static implicit operator string(NumberProperty value) => value.value.ToString("F2", culture).Replace(".00", "");
public static NumberProperty operator +(NumberProperty a) => a;
public static NumberProperty operator -(NumberProperty a) => new(-a.value);
public static NumberProperty operator +(NumberProperty a, number b) => new(a.value + b);
public static NumberProperty operator -(NumberProperty a, number b) => new(a.value - b);
#endregion
}
/// <summary>
/// Represents a whole number.
/// </summary>
struct IntegerProperty
{
#region Fields
readonly int value;
#endregion
#region Constructors
IntegerProperty(int value) => this.value = value;
#endregion
#region Operators
public static implicit operator IntegerProperty(int? value) => new(value!.Value);
public static implicit operator IntegerProperty(int value) => new(value);
public static implicit operator IntegerProperty(string value) => new(int.Parse(value));
public static implicit operator string(IntegerProperty value) => value.value.ToString(culture);
public static IntegerProperty operator +(IntegerProperty a) => a;
public static IntegerProperty operator -(IntegerProperty a) => new(-a.value);
public static IntegerProperty operator +(IntegerProperty a, int b) => new(a.value + b);
public static IntegerProperty operator -(IntegerProperty a, int b) => new(a.value - b);
#endregion
}
/// <summary>
/// Represents a color. You can define a color with a #hexadecimal code, the rgb() or rgba() function, or a color keyword (for example, blue or transparent).
/// </summary>
readonly struct ColorProperty
{
#region Fields
readonly string rgba;
readonly string rgb;
readonly string hex;
readonly string name;
#endregion
#region Constructors
internal ColorProperty(RGBA color, number? opacity = 1, float alphaMult = 1.0f)
{
rgba = $"rgba({(byte)(color.r * 255.0f)},{(byte)(color.g * 255.0f)},{(byte)(color.b * 255.0f)},{(color.a * (opacity ?? alphaMult)).ToString("F2", culture).Replace(".00", "")})";
rgb = default;
hex = default;
name = default;
}
ColorProperty(string value)
{
rgba = default;
rgb = default;
hex = default;
name = default;
if (value.StartsWith("rgba")) rgba = value;
else if (value.StartsWith("rgb")) rgb = value;
else if (value.StartsWith('#')) hex = value;
else name = value;
}
#endregion
#region Operators
public static implicit operator ColorProperty(Unit _) => new();
public static implicit operator ColorProperty(RGBA value) => new(value);
public static implicit operator ColorProperty(string value) => new(value);
public static implicit operator string(ColorProperty value)
{
if (value.rgba.NotNullOrEmpty()) return value.rgba;
if (value.rgb.NotNullOrEmpty()) return value.rgb;
if (value.hex.NotNullOrEmpty()) return value.hex;
if (value.name.NotNullOrEmpty()) return value.name;
return "initial";
}
public override string ToString() => this;
#endregion
}
/// <summary>
/// Represents an asset in a Resources folder or represents an asset specified by a path, it can be expressed as either a relative path or an absolute path.
/// </summary>
struct AssetProperty
{
#region Fields
readonly string url;
readonly string resource;
readonly Unit unit;
#endregion
#region Constructors
AssetProperty(Unit unit)
{
url = default;
resource = default;
this.unit = unit;
}
AssetProperty(string value)
{
url = default;
resource = default;
unit = default;
if (value.StartsWith("url")) url = value;
else if (value.StartsWith("resource")) resource = value;
else throw new NotSupportedException();
}
#endregion
#region Operators
public static implicit operator AssetProperty(Unit value) => new(value);
public static implicit operator AssetProperty(string value) => Enum.TryParse(value, true, out Unit unit) ? new AssetProperty(unit) : new AssetProperty(value);
public static implicit operator string(AssetProperty value)
{
if (value.url.NotNullOrEmpty()) return value.url;
if (value.resource.NotNullOrEmpty()) return value.resource;
return value.unit switch
{
Unit.None => "none",
Unit.Initial => "initial",
_ => throw new ArgumentException(value)
};
}
#endregion
}
#pragma warning disable CS0660, CS0661
struct EnumProperty<T> where T : struct, Enum
#pragma warning restore CS0660, CS0661
{
// ReSharper disable StaticMemberInGenericType
static readonly Regex enumParserRegexString = new("(?<name>([a-z]+\\-?))", RegexOptions.Compiled);
static readonly Regex enumParserRegexValue = new("(?<name>([A-Z][a-z]+)?)", RegexOptions.Compiled);
// ReSharper restore StaticMemberInGenericType
#region Fields
T value;
readonly Unit unit;
#endregion
#region Constructors
EnumProperty(T value)
{
this.value = value;
unit = Unit.None;
}
EnumProperty(Unit unit)
{
value = default;
this.unit = unit;
}
#endregion
#region Operators
public static implicit operator EnumProperty<T>(Unit unit) => new(unit);
public static implicit operator EnumProperty<T>(T value) => new(value);
public static implicit operator EnumProperty<T>(string value) => Enum.TryParse(enumParserRegexString.Replace(value, "${name}").Replace("-", ""), true, out T result) ? new EnumProperty<T>(result) : default;
public static implicit operator string(EnumProperty<T> value) => value.unit == Unit.None ? enumParserRegexValue.Replace(value.value.ToString(), "${name}-").ToLower().TrimEnd('-') : "initial";
public static bool operator ==(EnumProperty<T> a, T b) => a.value.Equals(b);
public static bool operator !=(EnumProperty<T> a, T b) => !a.value.Equals(b);
public override string ToString() => this;
#endregion
}
struct ShadowProperty
{
static readonly Regex regex = new(@"(?<offsetHorizontal>\d+[px]*)\s+(?<offsetVertical>\d+[px]*)\s+(?<blurRadius>\d+[px]*)\s+(?<color>(rgba\([\d,\.\s]+\))|#\w{2,8}|[^#][\w-]+)");
#region Fields
readonly LengthProperty offsetHorizontal;
readonly LengthProperty offsetVertical;
readonly LengthProperty blurRadius;
readonly ColorProperty color;
#endregion
#region Constructors
internal ShadowProperty(LengthProperty offsetHorizontal, LengthProperty offsetVertical, LengthProperty blurRadius, ColorProperty color)
{
this.offsetHorizontal = offsetHorizontal;
this.offsetVertical = offsetVertical;
this.blurRadius = blurRadius;
this.color = color;
}
ShadowProperty(string value)
{
Match match = regex.Match(value);
offsetHorizontal = match.Groups["offsetHorizontal"].Value;
offsetVertical = match.Groups["offsetVertical"].Value;
blurRadius = match.Groups["blurRadius"].Value;
color = match.Groups["color"].Value;
}
#endregion
#region Operators
public static implicit operator ShadowProperty(string value) => new(value);
public static implicit operator string(ShadowProperty value) => $"{value.offsetHorizontal} {value.offsetVertical} {value.blurRadius} {value.color}";
#endregion
}
readonly struct Length4Property
{
#region Fields
readonly Unit unit;
readonly LengthProperty[] properties;
#endregion
#region Properties
internal LengthProperty this[int index] { get => properties[index]; set => properties[index] = value; }
#endregion
#region Constructors
internal Length4Property(Unit unit)
{
this.unit = unit;
properties = new LengthProperty[] { new(unit), new(unit), new(unit), new(unit) };
}
internal Length4Property(LengthProperty[] properties)
{
unit = Unit.None;
this.properties = properties;
}
#endregion
#region Operators
public static implicit operator Length4Property(Unit unit) => new(unit);
public static implicit operator Length4Property(number? value) => new(new LengthProperty[] { value!.Value });
public static implicit operator Length4Property(number value) => new(new LengthProperty[] { value });
public static implicit operator Length4Property(number[] values)
{
LengthProperty[] properties = new LengthProperty[values.Length];
for (int i = 0; i < values.Length; i++) properties[i] = values[i];
return new Length4Property(properties);
}
public static implicit operator Length4Property(string value)
{
string[] values = value.Split(" ", StringSplitOptions.RemoveEmptyEntries);
LengthProperty[] properties = new LengthProperty[values.Length];
for (int i = 0; i < values.Length; i++) properties[i] = values[i];
return new Length4Property(properties);
}
public static implicit operator string(Length4Property value)
{
if (value is { unit: Unit.None, properties: not null })
{
string[] values = new string[value.properties.Length];
for (int i = 0; i < values.Length; i++) values[i] = value.properties[i];
return string.Join(" ", values);
}
return new LengthProperty(value.unit);
}
public static Length4Property operator +(Length4Property a) => a;
public static Length4Property operator -(Length4Property a) => new(a.properties.Select(x => -x).ToArray());
public static Length4Property operator +(Length4Property a, number b) => new(a.properties.Select(x => x + b).ToArray());
public static Length4Property operator -(Length4Property a, number b) => new(a.properties.Select(x => x - b).ToArray());
#endregion
}
struct FlexProperty
{
#region Operators
public static implicit operator FlexProperty(string value) => default;
public static implicit operator string(FlexProperty value) => default;
#endregion
}
struct CursorProperty
{
#region Operators
public static implicit operator CursorProperty(string value) => default;
public static implicit operator string(CursorProperty value) => default;
#endregion
}
#endregion
#region Fields
readonly Func<string, string, (bool valid, string path)> getAssetPath;
readonly Func<string, string, (bool valid, int width, int height)> getAssetSize;
readonly List<UssStyle> inherited = new();
readonly Dictionary<string, string> defaults = new();
readonly Dictionary<string, string> attributes = new();
#endregion
#region Properties
public string Name { get; set; }
public bool HasAttributes => attributes.Count > 0;
// Box model
// Dimensions
LengthProperty width { get => Get("width"); set => Set("width", value); }
LengthProperty height { get => Get("height"); set => Set("height", value); }
LengthProperty minWidth { get => Get("min-width"); set => Set("min-width", value); }
LengthProperty minHeight { get => Get("min-height"); set => Set("min-height", value); }
LengthProperty maxWidth { get => Get("max-width"); set => Set("max-width", value); }
LengthProperty maxHeight { get => Get("max-height"); set => Set("max-height", value); }
// Margins
LengthProperty marginLeft { get => Get1("margin-left", "margin", 0); set => Set4("margin-left", value, "margin", 0); }
LengthProperty marginTop { get => Get1("margin-top", "margin", 1); set => Set4("margin-top", value, "margin", 1); }
LengthProperty marginRight { get => Get1("margin-right", "margin", 2); set => Set4("margin-right", value, "margin", 2); }
LengthProperty marginBottom { get => Get1("margin-bottom", "margin", 3); set => Set4("margin-bottom", value, "margin", 3); }
Length4Property margin { get => Get4("margin", "margin-left", "margin-top", "margin-right", "margin-bottom"); set => Set1("margin", value, "margin-left", "margin-top", "margin-right", "margin-bottom"); }
// Borders
LengthProperty borderLeftWidth { get => Get1("border-left-width", "border-width", 0); set => Set4("border-left-width", value, "border-width", 0); }
LengthProperty borderTopWidth { get => Get1("border-top-width", "border-width", 1); set => Set4("border-top-width", value, "border-width", 1); }
LengthProperty borderRightWidth { get => Get1("border-right-width", "border-width", 2); set => Set4("border-right-width", value, "border-width", 2); }
LengthProperty borderBottomWidth { get => Get1("border-bottom-width", "border-width", 3); set => Set4("border-bottom-width", value, "border-width", 3); }
Length4Property borderWidth { get => Get4("border-width", "border-left-width", "border-top-width", "border-right-width", "border-bottom-width"); set => Set1("border-width", value, "border-left-width", "border-top-width", "border-right-width", "border-bottom-width"); }
// Padding
LengthProperty paddingLeft { get => Get1("padding-left", "padding", 0); set => Set4("padding-left", value, "padding", 0); }
LengthProperty paddingTop { get => Get1("padding-top", "padding", 1); set => Set4("padding-top", value, "padding", 1); }
LengthProperty paddingRight { get => Get1("padding-right", "padding", 2); set => Set4("padding-right", value, "padding", 2); }
LengthProperty paddingBottom { get => Get1("padding-bottom", "padding", 3); set => Set4("padding-bottom", value, "padding", 3); }
Length4Property padding { get => Get4("padding", "padding-left", "padding-top", "padding-right", "padding-bottom"); set => Set1("padding", value, "padding-left", "padding-top", "padding-right", "padding-bottom"); }
// Flex
// Items
NumberProperty flexGrow { get => Get("flex-grow"); set => Set("flex-grow", value); }
NumberProperty flexShrink { get => Get("flex-shrink"); set => Set("flex-shrink", value); }
LengthProperty flexBasis { get => Get("flex-basis"); set => Set("flex-basis", value); }
FlexProperty flex { get => Get("flex"); set => Set("flex", value); }
EnumProperty<Align> alignSelf { get => Get("align-self"); set => Set("align-self", value); }
NumberProperty itemSpacing { get => Get("--item-spacing"); set => Set("--item-spacing", value); }
// Containers
EnumProperty<FlexDirection> flexDirection { get => Get("flex-direction"); set => Set("flex-direction", value); }
EnumProperty<FlexWrap> flexWrap { get => Get("flex-wrap"); set => Set("flex-wrap", value); }
EnumProperty<Align> alignContent { get => Get("align-content"); set => Set("align-content", value); }
EnumProperty<Align> alignItems { get => Get("align-items"); set => Set("align-items", value); }
EnumProperty<JustifyContent> justifyContent { get => Get("justify-content"); set => Set("justify-content", value); }
// Positioning
EnumProperty<Position> position { get => Get("position"); set => Set("position", value); }
LengthProperty left { get => Get("left"); set => Set("left", value); }
LengthProperty top { get => Get("top"); set => Set("top", value); }
LengthProperty right { get => Get("right"); set => Set("right", value); }
LengthProperty bottom { get => Get("bottom"); set => Set("bottom", value); }
LengthProperty rotate { get => Get("rotate"); set => Set("rotate", value); }
// Drawing
// Background
ColorProperty backgroundColor { get => Get("background-color"); set => Set("background-color", value); }
AssetProperty backgroundImage { get => Get("background-image"); set => Set("background-image", value); }
EnumProperty<BackgroundPositionKeyword> unityBackgroundPositionX { get => Get("background-position-x"); set => Set("background-position-x", value); }
EnumProperty<BackgroundPositionKeyword> unityBackgroundPositionY { get => Get("background-position-y"); set => Set("background-position-y", value); }
EnumProperty<Repeat> unityBackgroundRepeat { get => Get("background-repeat"); set => Set("background-repeat", value); }
EnumProperty<BackgroundSizeType> unityBackgroundSize { get => Get("background-size"); set => Set("background-size", value); }
ColorProperty unityBackgroundImageTintColor { get => Get("-unity-background-image-tint-color"); set => Set("-unity-background-image-tint-color", value); }
// Slicing
IntegerProperty unitySliceLeft { get => Get("-unity-slice-left"); set => Set("-unity-slice-left", value); }
IntegerProperty unitySliceTop { get => Get("-unity-slice-top"); set => Set("-unity-slice-top", value); }
IntegerProperty unitySliceRight { get => Get("-unity-slice-right"); set => Set("-unity-slice-right", value); }
IntegerProperty unitySliceBottom { get => Get("-unity-slice-bottom"); set => Set("-unity-slice-bottom", value); }
// Borders
ColorProperty borderColor { get => Get("border-color"); set => Set("border-color", value); }
LengthProperty borderTopLeftRadius { get => Get1("border-top-left-radius", "border-radius", 0); set => Set4("border-top-left-radius", value, "border-radius", 0); }
LengthProperty borderTopRightRadius { get => Get1("border-top-right-radius", "border-radius", 1); set => Set4("border-top-right-radius", value, "border-radius", 1); }
LengthProperty borderBottomLeftRadius { get => Get1("border-bottom-left-radius", "border-radius", 2); set => Set4("border-bottom-left-radius", value, "border-radius", 2); }
LengthProperty borderBottomRightRadius { get => Get1("border-bottom-right-radius", "border-radius", 3); set => Set4("border-bottom-right-radius", value, "border-radius", 3); }
Length4Property borderRadius { get => Get4("border-radius", "border-top-left-radius", "border-top-right-radius", "border-bottom-left-radius", "border-bottom-right-radius"); set => Set1("border-radius", value, "border-top-left-radius", "border-top-right-radius", "border-bottom-left-radius", "border-bottom-right-radius"); }
// Appearance
EnumProperty<Visibility> overflow { get => Get("overflow"); set => Set("overflow", value); }
EnumProperty<OverflowClip> unityOverflowClipBox { get => Get("-unity-overflow-clip-box"); set => Set("-unity-overflow-clip-box", value); }
NumberProperty opacity { get => Get("opacity"); set => Set("opacity", value); }
EnumProperty<Visibility> visibility { get => Get("visibility"); set => Set("visibility", value); }
EnumProperty<Display> display { get => Get("display"); set => Set("display", value); }
// Text
ColorProperty color { get => Get("color"); set => Set("color", value); }
AssetProperty unityFont { get => Get("-unity-font"); set => Set("-unity-font", value); }
AssetProperty unityFontMissing { get => Get("--unity-font-missing"); set => Set("--unity-font-missing", value); }
AssetProperty unityFontDefinition { get => Get("-unity-font-definition"); set => Set("-unity-font-definition", value); }
LengthProperty fontSize { get => Get("font-size"); set => Set("font-size", value); }
EnumProperty<FontStyle> unityFontStyle { get => Get("-unity-font-style"); set => Set("-unity-font-style", value); }
EnumProperty<TextAlign> unityTextAlign { get => Get("-unity-text-align"); set => Set("-unity-text-align", value); }
EnumProperty<Wrap> whiteSpace { get => Get("white-space"); set => Set("white-space", value); }
ShadowProperty textShadow { get => Get("text-shadow"); set => Set("text-shadow", value); }
// Cursor
CursorProperty cursor { get => Get("cursor"); set => Set("cursor", value); }
// Effects
ShadowProperty boxShadow { get => Get("--box-shadow"); set => Set("--box-shadow", value); }
#endregion
#region Constructors
public UssStyle(string name)
{
Name = name;
switch (name)
{
case overrideClass:
backgroundColor = Unit.Initial;
borderWidth = Unit.Initial;
overflow = Unit.Initial;
padding = Unit.Initial;
margin = Unit.Initial;
unityFontDefinition = Unit.Initial;
justifyContent = JustifyContent.Center;
alignItems = Align.Center;
unityBackgroundPositionX = BackgroundPositionKeyword.Center;
unityBackgroundPositionY = BackgroundPositionKeyword.Center;
unityBackgroundRepeat = Repeat.NoRepeat;
break;
case viewportClass:
position = Position.Absolute;
width = "100%";
height = "100%";
break;
}
}
public UssStyle(string name, Func<string, string, (bool valid, string path)> getAssetPath, Func<string, string, (bool valid, int width, int height)> getAssetSize, string slot, Style.StyleType type, BaseNode node)
{
Name = name;
this.getAssetPath = getAssetPath;
this.getAssetSize = getAssetSize;
if (type == Style.StyleType.FILL && node is GeometryMixin geometry)
{
if (slot == "fill")
{
if (node is TextNode)
{
Name += "-Text";
AddTextFillStyle(geometry.fills);
}
else
{
AddFillStyle(geometry.fills);
}
}
else if (slot == "stroke")
{
if (node is TextNode)
{
Name += "-TextStroke";
}
else
{
Name += "-Border";
AddStrokeFillStyle(geometry.strokes);
}
}
}
else if (type == Style.StyleType.TEXT && node is TextNode text)
{
AddTextStyle(text.style);
}
else if (type == Style.StyleType.EFFECT && node is BlendMixin blend)
{
AddNodeEffects(blend.effects);
}
}
public UssStyle(string name, Func<string, string, (bool valid, string path)> getAssetPath, Func<string, string, (bool valid, int width, int height)> getAssetSize, BaseNode node)
{
Name = name;
this.getAssetPath = getAssetPath;
this.getAssetSize = getAssetSize;
if (node is FrameNode frame) AddFrameNode(frame);
if (node is GroupNode group) AddGroupNode(group);
if (node is SliceNode slice) AddSliceNode(slice);
if (node is RectangleNode rectangle) AddRectangleNode(rectangle);
if (node is LineNode line) AddLineNode(line);
if (node is EllipseNode ellipse) AddEllipseNode(ellipse);
if (node is RegularPolygonNode regularPolygon) AddRegularPolygonNode(regularPolygon);
if (node is StarNode star) AddStarNode(star);
if (node is VectorNode vector) AddVectorNode(vector);
if (node is TextNode text) AddTextNode(text);
if (node is ComponentSetNode set) AddComponentSetNode(set);
if (node is ComponentNode component) AddComponentNode(component);
if (node is InstanceNode instance) AddInstanceNode(instance);
if (node is BooleanOperationNode booleanOperation) AddBooleanOperationNode(booleanOperation);
}
#endregion
#region Methods
public bool DoesInherit(UssStyle style) => inherited.Contains(style);
public void Inherit(UssStyle component)
{
inherited.Add(component);
foreach (KeyValuePair<string, string> keyValue in component.attributes)
{
if (attributes.ContainsKey(keyValue.Key) && attributes[keyValue.Key] == component.attributes[keyValue.Key])
attributes.Remove(keyValue.Key);
if (!attributes.ContainsKey(keyValue.Key) && defaults.TryGetValue(keyValue.Key, out string @default))
attributes.Add(keyValue.Key, @default);
}
}
public void Inherit(IReadOnlyCollection<UssStyle> styles)
{
inherited.AddRange(styles);
foreach (UssStyle style in styles)
{
foreach (KeyValuePair<string, string> keyValue in style.attributes.Where(keyValue => attributes.ContainsKey(keyValue.Key) &&
attributes[keyValue.Key] == style.attributes[keyValue.Key]))
attributes.Remove(keyValue.Key);
}
}
public void Inherit(UssStyle component, IReadOnlyCollection<UssStyle> styles)
{
inherited.Add(component);
inherited.AddRange(styles);
List<string> preserve = (from keyValue in component.attributes
from style in styles
where style.attributes.ContainsKey(keyValue.Key) && style.attributes[keyValue.Key] != keyValue.Value
select keyValue.Key).ToList();
foreach (KeyValuePair<string, string> keyValue in component.attributes)
{
if (attributes.ContainsKey(keyValue.Key) && attributes[keyValue.Key] == component.attributes[keyValue.Key])
attributes.Remove(keyValue.Key);
if (!attributes.ContainsKey(keyValue.Key) && defaults.TryGetValue(keyValue.Key, out string @default))
attributes.Add(keyValue.Key, @default);
}
foreach (UssStyle style in styles)
{
foreach (KeyValuePair<string, string> keyValue in style.attributes.Where(keyValue => attributes.ContainsKey(keyValue.Key) && attributes[keyValue.Key] == style.attributes[keyValue.Key] && !preserve.Contains(keyValue.Key)))
attributes.Remove(keyValue.Key);
}
}
public string ResolveClassList(string component) => attributes.Count > 0 ? $"{Name} {component}" : component;
public string ResolveClassList(IEnumerable<string> styles) => attributes.Count > 0 ? $"{Name} {string.Join(" ", styles)}" : $"{string.Join(" ", styles)}";
public string ResolveClassList(string component, IEnumerable<string> styles) => attributes.Count > 0 ? $"{Name} {component} {string.Join(" ", styles)}" : $"{component} {string.Join(" ", styles)}";
public string ResolveClassList() => attributes.Count > 0 ? $"{Name}" : "";
public void Write(StreamWriter stream)
{
stream.WriteLine($".{Name} {{");
if (Has("--unity-font-missing")) attributes.Remove("--unity-font-missing");
foreach (KeyValuePair<string, string> keyValue in attributes) stream.WriteLine($" {keyValue.Key}: {keyValue.Value};");
stream.Write("}");
}
void AddDefaultFrameNode(DefaultFrameNode node)
{
AddCorner(node, node);
AddFrame(node);
AddDefaultShapeNode(node);
if (node.clipsContent.HasValueAndTrue()) overflow = Visibility.Hidden;
}
void AddDefaultShapeNode(DefaultShapeNode node)
{
AddBoxModel(node, node, node, node);
AddLayout(node, node);
AddBlend(node);
AddGeometry(node, node, node);
}
void AddFrameNode(FrameNode node)
{
AddDefaultFrameNode(node);
}
void AddGroupNode(GroupNode node)
{
AddDefaultFrameNode(node);
}
void AddSliceNode(SliceNode node)
{
AddBoxModel(node, node, default, node);
AddLayout(node, node);
}
void AddRectangleNode(RectangleNode node)
{
AddCorner(node, node);
AddDefaultShapeNode(node);
}
void AddLineNode(LineNode node)
{
AddDefaultShapeNode(node);
}
void AddEllipseNode(EllipseNode node)
{
AddDefaultShapeNode(node);
}
void AddRegularPolygonNode(RegularPolygonNode node)
{
AddCorner(node, node);
AddDefaultShapeNode(node);
}
void AddStarNode(StarNode node)
{
AddCorner(node, node);
AddDefaultShapeNode(node);
}
void AddVectorNode(VectorNode node)
{
AddCorner(node, node);
AddDefaultShapeNode(node);
}
void AddTextNode(TextNode node)
{
void FixWhiteSpace() => whiteSpace = node.absoluteBoundingBox.height / node.style.fontSize < 2 ? Wrap.Nowrap : Wrap.Normal;
AddDefaultShapeNode(node);
FixWhiteSpace();
AddTextStyle(node.style);
}
void AddComponentSetNode(ComponentSetNode node)
{
AddDefaultFrameNode(node);
}
void AddComponentNode(ComponentNode node)
{
AddDefaultFrameNode(node);
}
void AddInstanceNode(InstanceNode node)
{
AddDefaultFrameNode(node);
}
void AddBooleanOperationNode(BooleanOperationNode node)
{
AddDefaultFrameNode(node);
}
void AddFrame(DefaultFrameMixin mixin)
{
void AddPadding()
{
number[] padding = { mixin.paddingTop ?? 0, mixin.paddingRight ?? 0, mixin.paddingBottom ?? 0, mixin.paddingLeft ?? 0 };
if (padding.Any(x => x != 0)) this.padding = padding;
}
void AddAutoLayout()
{
switch (mixin.layoutMode)
{
case LayoutMode.HORIZONTAL:
flexDirection = FlexDirection.Row;
justifyContent = JustifyContent.FlexStart;
alignItems = Align.FlexStart;
if (mixin.layoutAlign != LayoutAlign.STRETCH && mixin.primaryAxisSizingMode.IsValue(PrimaryAxisSizingMode.FIXED)) flexWrap = FlexWrap.Wrap;
break;
case LayoutMode.VERTICAL:
flexDirection = FlexDirection.Column;
justifyContent = JustifyContent.FlexStart;
alignItems = Align.FlexStart;
if (mixin.layoutAlign != LayoutAlign.STRETCH && mixin.primaryAxisSizingMode.IsValue(PrimaryAxisSizingMode.FIXED)) flexWrap = FlexWrap.Wrap;
break;
}
if (mixin.primaryAxisAlignItems.HasValue)
{
justifyContent = mixin.primaryAxisAlignItems.Value switch
{
PrimaryAxisAlignItems.MIN => JustifyContent.FlexStart,
PrimaryAxisAlignItems.CENTER => JustifyContent.Center,
PrimaryAxisAlignItems.MAX => JustifyContent.FlexEnd,
PrimaryAxisAlignItems.SPACE_BETWEEN => JustifyContent.SpaceBetween,
_ => throw new NotSupportedException()
};
}
if (mixin.counterAxisAlignItems.HasValue)
{
alignItems = mixin.counterAxisAlignItems.Value switch
{
CounterAxisAlignItems.MIN => Align.FlexStart,
CounterAxisAlignItems.CENTER => Align.Center,
CounterAxisAlignItems.MAX => Align.FlexEnd,
CounterAxisAlignItems.BASELINE => Align.Stretch,
_ => throw new NotSupportedException()
};
}
if (mixin.itemSpacing.HasPositive()) itemSpacing = mixin.itemSpacing;
}
AddPadding();
if (mixin.layoutMode.HasValue) AddAutoLayout();
}
void AddScene(BaseNodeMixin @base)
{
void HandleVisibility()
{
if (IsVisible(@base) || IsStateNode(@base)) defaults.Add("display", "flex");
else display = Display.None;
}
HandleVisibility();
}
void AddLayout(LayoutMixin mixin, BaseNodeMixin @base)
{
if (@base is DefaultFrameMixin frame && IsMostlyHorizontal(frame)) flexDirection = FlexDirection.Row;
if (@base.parent is DefaultFrameMixin { layoutMode: not null } && mixin.layoutAlign == LayoutAlign.STRETCH) alignSelf = Align.Stretch;
}
void AddBlend(BlendMixin mixin)
{
void AddOpacity()
{
if (mixin.opacity.HasValue)
{
if (mixin.opacity == 1) defaults.Add("opacity", "1");
else opacity = mixin.opacity;
}
}
AddOpacity();
if (mixin is TextNode) AddTextNodeEffects(mixin.effects);
else AddNodeEffects(mixin.effects);
}
void AddGeometry(GeometryMixin mixin, LayoutMixin layout, BaseNodeMixin @base)
{
void AddBackgroundImageForVectorNode()
{
if (HasImageFill(@base))
{
(bool valid, string url) = getAssetPath(@base.id, "png");
if (valid) backgroundImage = $"url('{url}')";
}
else
{
(bool valid, string url) = getAssetPath(@base.id, "svg");
if (valid) backgroundImage = $"url('{url}')";
}
}
void AddBorderWidth()
{
bool state = IsStateNode(mixin.As<BaseNodeMixin>());
if (mixin.individualStrokeWeights is not null)
{
if (mixin.individualStrokeWeights.left > 0 || state) borderLeftWidth = mixin.individualStrokeWeights.left;
if (mixin.individualStrokeWeights.right > 0 || state) borderRightWidth = mixin.individualStrokeWeights.right;
if (mixin.individualStrokeWeights.top > 0 || state) borderTopWidth = mixin.individualStrokeWeights.top;
if (mixin.individualStrokeWeights.bottom > 0 || state) borderBottomWidth = mixin.individualStrokeWeights.bottom;
}
else if (mixin.strokeWeight > 0 || state) borderWidth = mixin.strokeWeight;
}
void AddBorderRadius(RectangleCornerMixin rectangleCornerMixin, CornerMixin cornerMixin)
{
void AddRadius(number minValue, number value)
{
if (rectangleCornerMixin.rectangleCornerRadii is null)
{
if (cornerMixin.cornerRadius.HasPositive()) borderRadius = Math.Min(minValue, cornerMixin!.cornerRadius!.Value) + value;
}
else
{
for (int i = 0; i < rectangleCornerMixin.rectangleCornerRadii.Length; ++i) rectangleCornerMixin.rectangleCornerRadii[i] = Math.Min(minValue, rectangleCornerMixin.rectangleCornerRadii[i]) + value;
borderRadius = rectangleCornerMixin.rectangleCornerRadii;