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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
|
import std/algorithm
import std/macros
import std/math
import std/options
import std/strutils
import std/tables
import css/cssparser
import css/lunit
import css/selectorparser
import html/catom
import types/bitmap
import types/color
import types/opt
import types/refstring
import types/winattrs
import utils/twtstr
type
CSSPropertyType* = enum
# primitive/enum properties: stored as byte
# (when adding a new property, sort the individual lists, and update
# LastBitPropType/LastWordPropType if needed.)
cptBgcolorIsCanvas = "-cha-bgcolor-is-canvas"
cptBorderCollapse = "border-collapse"
cptBoxSizing = "box-sizing"
cptCaptionSide = "caption-side"
cptClear = "clear"
cptDisplay = "display"
cptFlexDirection = "flex-direction"
cptFlexWrap = "flex-wrap"
cptFloat = "float"
cptFontStyle = "font-style"
cptListStylePosition = "list-style-position"
cptListStyleType = "list-style-type"
cptOverflowX = "overflow-x"
cptOverflowY = "overflow-y"
cptPosition = "position"
cptTextAlign = "text-align"
cptTextDecoration = "text-decoration"
cptTextTransform = "text-transform"
cptVisibility = "visibility"
cptWhiteSpace = "white-space"
cptWordBreak = "word-break"
# word properties: stored as (64-bit) word
cptBackgroundColor = "background-color"
cptBottom = "bottom"
cptChaColspan = "-cha-colspan"
cptChaRowspan = "-cha-rowspan"
cptColor = "color"
cptFlexBasis = "flex-basis"
cptFlexGrow = "flex-grow"
cptFlexShrink = "flex-shrink"
cptFontSize = "font-size"
cptFontWeight = "font-weight"
cptHeight = "height"
cptLeft = "left"
cptMarginBottom = "margin-bottom"
cptMarginLeft = "margin-left"
cptMarginRight = "margin-right"
cptMarginTop = "margin-top"
cptMaxHeight = "max-height"
cptMaxWidth = "max-width"
cptMinHeight = "min-height"
cptMinWidth = "min-width"
cptOpacity = "opacity"
cptPaddingBottom = "padding-bottom"
cptPaddingLeft = "padding-left"
cptPaddingRight = "padding-right"
cptPaddingTop = "padding-top"
cptRight = "right"
cptTop = "top"
cptVerticalAlign = "vertical-align"
cptWidth = "width"
cptZIndex = "z-index"
# object properties: stored as a tagged ref object
cptBackgroundImage = "background-image"
cptBorderSpacing = "border-spacing"
cptContent = "content"
cptCounterReset = "counter-reset"
cptQuotes = "quotes"
const LastBitPropType = cptWordBreak
const FirstWordPropType = LastBitPropType.succ
const LastWordPropType = cptZIndex
const FirstObjPropType = LastWordPropType.succ
type
CSSShorthandType = enum
cstNone = ""
cstAll = "all"
cstMargin = "margin"
cstPadding = "padding"
cstBackground = "background"
cstListStyle = "list-style"
cstFlex = "flex"
cstFlexFlow = "flex-flow"
cstOverflow = "overflow"
CSSUnit* = enum
cuAuto = ""
cuCap = "cap"
cuCh = "ch"
cuCm = "cm"
cuDvmax = "dvmax"
cuDvmin = "dvmin"
cuEm = "em"
cuEx = "ex"
cuIc = "ic"
cuIn = "in"
cuLh = "lh"
cuLvmax = "lvmax"
cuLvmin = "lvmin"
cuMm = "mm"
cuPc = "pc"
cuPerc = "%"
cuPt = "pt"
cuPx = "px"
cuRcap = "rcap"
cuRch = "rch"
cuRem = "rem"
cuRex = "rex"
cuRic = "ric"
cuRlh = "rlh"
cuSvmax = "svmax"
cuSvmin = "svmin"
cuVb = "vb"
cuVh = "vh"
cuVi = "vi"
cuVmax = "vmax"
cuVmin = "vmin"
cuVw = "vw"
CSSValueType* = enum
cvtLength = "length"
cvtColor = "color"
cvtContent = "content"
cvtDisplay = "display"
cvtFontStyle = "fontStyle"
cvtWhiteSpace = "whiteSpace"
cvtInteger = "integer"
cvtTextDecoration = "textDecoration"
cvtWordBreak = "wordBreak"
cvtListStyleType = "listStyleType"
cvtVerticalAlign = "verticalAlign"
cvtTextAlign = "textAlign"
cvtListStylePosition = "listStylePosition"
cvtPosition = "position"
cvtCaptionSide = "captionSide"
cvtLength2 = "length2"
cvtBorderCollapse = "borderCollapse"
cvtQuotes = "quotes"
cvtCounterReset = "counterReset"
cvtImage = "image"
cvtFloat = "float"
cvtVisibility = "visibility"
cvtBoxSizing = "boxSizing"
cvtClear = "clear"
cvtTextTransform = "textTransform"
cvtBgcolorIsCanvas = "bgcolorIsCanvas"
cvtFlexDirection = "flexDirection"
cvtFlexWrap = "flexWrap"
cvtNumber = "number"
cvtOverflow = "overflow"
CSSGlobalType* = enum
cgtInitial = "initial"
cgtInherit = "inherit"
cgtRevert = "revert"
cgtUnset = "unset"
CSSDisplay* = enum
DisplayInline = "inline"
DisplayNone = "none"
DisplayBlock = "block"
DisplayListItem = "list-item"
DisplayInlineBlock = "inline-block"
DisplayTable = "table"
DisplayInlineTable = "inline-table"
DisplayTableRowGroup = "table-row-group"
DisplayTableHeaderGroup = "table-header-group"
DisplayTableFooterGroup = "table-footer-group"
DisplayTableColumnGroup = "table-column-group"
DisplayTableRow = "table-row"
DisplayTableColumn = "table-column"
DisplayTableCell = "table-cell"
DisplayTableCaption = "table-caption"
DisplayFlowRoot = "flow-root"
DisplayFlex = "flex"
DisplayInlineFlex = "inline-flex"
# internal, for layout
DisplayTableWrapper = ""
CSSWhiteSpace* = enum
WhitespaceNormal = "normal"
WhitespaceNowrap = "nowrap"
WhitespacePre = "pre"
WhitespacePreLine = "pre-line"
WhitespacePreWrap = "pre-wrap"
CSSFontStyle* = enum
FontStyleNormal = "normal"
FontStyleItalic = "italic"
FontStyleOblique = "oblique"
CSSPosition* = enum
PositionStatic = "static"
PositionRelative = "relative"
PositionAbsolute = "absolute"
PositionFixed = "fixed"
PositionSticky = "sticky"
CSSTextDecoration* = enum
TextDecorationNone = "none"
TextDecorationUnderline = "underline"
TextDecorationOverline = "overline"
TextDecorationLineThrough = "line-through"
TextDecorationBlink = "blink"
TextDecorationReverse = "-cha-reverse"
CSSWordBreak* = enum
WordBreakNormal = "normal"
WordBreakBreakAll = "break-all"
WordBreakKeepAll = "keep-all"
CSSListStyleType* = enum
ListStyleTypeDisc = "disc"
ListStyleTypeNone = "none"
ListStyleTypeCircle = "circle"
ListStyleTypeSquare = "square"
ListStyleTypeDecimal = "decimal"
ListStyleTypeDisclosureClosed = "disclosure-closed"
ListStyleTypeDisclosureOpen = "disclosure-open"
ListStyleTypeCjkEarthlyBranch = "cjk-earthly-branch"
ListStyleTypeCjkHeavenlyStem = "cjk-heavenly-stem"
ListStyleTypeLowerRoman = "lower-roman"
ListStyleTypeUpperRoman = "upper-roman"
ListStyleTypeLowerAlpha = "lower-alpha"
ListStyleTypeUpperAlpha = "upper-alpha"
ListStyleTypeLowerGreek = "lower-greek"
ListStyleTypeHiragana = "hiragana"
ListStyleTypeHiraganaIroha = "hiragana-iroha"
ListStyleTypeKatakana = "katakana"
ListStyleTypeKatakanaIroha = "katakana-iroha"
ListStyleTypeJapaneseInformal = "japanese-informal"
CSSVerticalAlign2* = enum
VerticalAlignBaseline = "baseline"
VerticalAlignSub = "sub"
VerticalAlignSuper = "super"
VerticalAlignTextTop = "text-top"
VerticalAlignTextBottom = "text-bottom"
VerticalAlignMiddle = "middle"
VerticalAlignTop = "top"
VerticalAlignBottom = "bottom"
CSSTextAlign* = enum
TextAlignStart = "start"
TextAlignEnd = "end"
TextAlignLeft = "left"
TextAlignRight = "right"
TextAlignCenter = "center"
TextAlignJustify = "justify"
TextAlignChaCenter = "-cha-center"
TextAlignChaLeft = "-cha-left"
TextAlignChaRight = "-cha-right"
CSSListStylePosition* = enum
ListStylePositionOutside = "outside"
ListStylePositionInside = "inside"
CSSCaptionSide* = enum
CaptionSideTop = "top"
CaptionSideBottom = "bottom"
CaptionSideBlockStart = "block-start"
CaptionSideBlockEnd = "block-end"
CSSBorderCollapse* = enum
BorderCollapseSeparate = "separate"
BorderCollapseCollapse = "collapse"
CSSContentType* = enum
ContentString, ContentOpenQuote, ContentCloseQuote, ContentNoOpenQuote,
ContentNoCloseQuote
CSSFloat* = enum
FloatNone = "none"
FloatLeft = "left"
FloatRight = "right"
CSSVisibility* = enum
VisibilityVisible = "visible"
VisibilityHidden = "hidden"
VisibilityCollapse = "collapse"
CSSBoxSizing* = enum
BoxSizingContentBox = "content-box"
BoxSizingBorderBox = "border-box"
CSSClear* = enum
ClearNone = "none"
ClearLeft = "left"
ClearRight = "right"
ClearBoth = "both"
ClearInlineStart = "inline-start"
ClearInlineEnd = "inline-end"
CSSTextTransform* = enum
TextTransformNone = "none"
TextTransformCapitalize = "capitalize"
TextTransformUppercase = "uppercase"
TextTransformLowercase = "lowercase"
TextTransformFullWidth = "full-width"
TextTransformFullSizeKana = "full-size-kana"
TextTransformChaHalfWidth = "-cha-half-width"
CSSFlexDirection* = enum
FlexDirectionRow = "row"
FlexDirectionRowReverse = "row-reverse"
FlexDirectionColumn = "column"
FlexDirectionColumnReverse = "column-reverse"
CSSFlexWrap* = enum
FlexWrapNowrap = "nowrap"
FlexWrapWrap = "wrap"
FlexWrapWrapReverse = "wrap-reverse"
CSSOverflow* = enum
OverflowVisible = "visible"
OverflowHidden = "hidden"
OverflowClip = "clip"
OverflowScroll = "scroll"
OverflowAuto = "auto"
OverflowOverlay = "overlay"
type
CSSLengthType* = enum
clPx = "px"
clAuto = "auto"
clPerc = "%"
CSSLength* = object
u*: CSSLengthType
# hack to support simple function calls like calc(100% - 10px).
addpx*: int16
num*: float32
CSSVerticalAlign* = object
keyword*: CSSVerticalAlign2
# inlined CSSLength so that this object fits into 1 word
u*: CSSLengthType
num*: float32
CSSContent* = object
t*: CSSContentType
s*: RefString
# nil -> auto
CSSQuotes* = ref object
qs*: seq[tuple[s, e: RefString]]
CSSCounterReset* = object
name*: string
num*: int
CSSLength2* = ref object
a*: CSSLength
b*: CSSLength
CSSValueBit* {.union.} = object
dummy*: uint8
bgcolorIsCanvas*: bool
borderCollapse*: CSSBorderCollapse
boxSizing*: CSSBoxSizing
captionSide*: CSSCaptionSide
clear*: CSSClear
display*: CSSDisplay
flexDirection*: CSSFlexDirection
flexWrap*: CSSFlexWrap
float*: CSSFloat
fontStyle*: CSSFontStyle
listStylePosition*: CSSListStylePosition
listStyleType*: CSSListStyleType
overflow*: CSSOverflow
position*: CSSPosition
textAlign*: CSSTextAlign
textDecoration*: set[CSSTextDecoration]
textTransform*: CSSTextTransform
visibility*: CSSVisibility
whiteSpace*: CSSWhiteSpace
wordBreak*: CSSWordBreak
CSSValueWord* {.union.} = object
dummy: uint64
color*: CSSColor
integer*: int32
length*: CSSLength
number*: float32
verticalAlign*: CSSVerticalAlign
CSSValue* = ref object
case v*: CSSValueType
of cvtContent:
content*: seq[CSSContent]
of cvtQuotes:
quotes*: CSSQuotes
of cvtLength2:
length2*: CSSLength2
of cvtCounterReset:
counterReset*: seq[CSSCounterReset]
of cvtImage:
image*: NetworkBitmap
else: discard
# Linked list of variable maps, except empty maps are skipped.
CSSVariableMap* = ref object
parent*: CSSVariableMap
table*: Table[CAtom, CSSVariable]
CSSValues* = ref object
bits*: array[CSSPropertyType.low..LastBitPropType, CSSValueBit]
words*: array[FirstWordPropType..LastWordPropType, CSSValueWord]
objs*: array[FirstObjPropType..CSSPropertyType.high, CSSValue]
vars*: CSSVariableMap
CSSOrigin* = enum
coUserAgent
coUser
coAuthor
CSSEntryType* = enum
ceBit, ceObject, ceWord, ceVar, ceGlobal
CSSComputedEntry* = object
# put it here, so ComputedEntry remains 2 words wide
cvar*: CAtom
t*: CSSPropertyType
case et*: CSSEntryType
of ceBit:
bit*: uint8
of ceWord:
word*: CSSValueWord
of ceObject:
obj*: CSSValue
of ceVar:
fallback*: ref CSSComputedEntry
of ceGlobal:
global*: CSSGlobalType
CSSVariable* = ref object
name*: CAtom
cvals*: seq[CSSComponentValue]
resolved*: seq[tuple[v: CSSValueType; entry: CSSComputedEntry]]
static:
doAssert sizeof(CSSValueBit) == 1
doAssert sizeof(CSSValueWord) <= 8
doAssert sizeof(CSSValue()[]) <= 16
doAssert sizeof(CSSComputedEntry()) <= 16
const ValueTypes = [
# bits
cptBgcolorIsCanvas: cvtBgcolorIsCanvas,
cptBorderCollapse: cvtBorderCollapse,
cptBoxSizing: cvtBoxSizing,
cptCaptionSide: cvtCaptionSide,
cptClear: cvtClear,
cptDisplay: cvtDisplay,
cptFlexDirection: cvtFlexDirection,
cptFlexWrap: cvtFlexWrap,
cptFloat: cvtFloat,
cptFontStyle: cvtFontStyle,
cptListStylePosition: cvtListStylePosition,
cptListStyleType: cvtListStyleType,
cptOverflowX: cvtOverflow,
cptOverflowY: cvtOverflow,
cptPosition: cvtPosition,
cptTextAlign: cvtTextAlign,
cptTextDecoration: cvtTextDecoration,
cptTextTransform: cvtTextTransform,
cptVisibility: cvtVisibility,
cptWhiteSpace: cvtWhiteSpace,
cptWordBreak: cvtWordBreak,
# words
cptBackgroundColor: cvtColor,
cptBottom: cvtLength,
cptChaColspan: cvtInteger,
cptChaRowspan: cvtInteger,
cptColor: cvtColor,
cptFlexBasis: cvtLength,
cptFlexGrow: cvtNumber,
cptFlexShrink: cvtNumber,
cptFontSize: cvtLength,
cptFontWeight: cvtInteger,
cptHeight: cvtLength,
cptLeft: cvtLength,
cptMarginBottom: cvtLength,
cptMarginLeft: cvtLength,
cptMarginRight: cvtLength,
cptMarginTop: cvtLength,
cptMaxHeight: cvtLength,
cptMaxWidth: cvtLength,
cptMinHeight: cvtLength,
cptMinWidth: cvtLength,
cptOpacity: cvtNumber,
cptPaddingBottom: cvtLength,
cptPaddingLeft: cvtLength,
cptPaddingRight: cvtLength,
cptPaddingTop: cvtLength,
cptRight: cvtLength,
cptTop: cvtLength,
cptVerticalAlign: cvtVerticalAlign,
cptWidth: cvtLength,
cptZIndex: cvtInteger,
# pointers
cptBackgroundImage: cvtImage,
cptBorderSpacing: cvtLength2,
cptContent: cvtContent,
cptCounterReset: cvtCounterReset,
cptQuotes: cvtQuotes,
]
const InheritedProperties = {
cptColor, cptFontStyle, cptWhiteSpace, cptFontWeight, cptTextDecoration,
cptWordBreak, cptListStyleType, cptTextAlign, cptListStylePosition,
cptCaptionSide, cptBorderSpacing, cptBorderCollapse, cptQuotes,
cptVisibility, cptTextTransform
}
const OverflowScrollLike* = {OverflowScroll, OverflowAuto, OverflowOverlay}
const OverflowHiddenLike* = {OverflowHidden, OverflowClip}
const FlexReverse* = {FlexDirectionRowReverse, FlexDirectionColumnReverse}
const DisplayInlineBlockLike* = {
DisplayInlineTable, DisplayInlineBlock, DisplayInlineFlex
}
const DisplayOuterInline* = DisplayInlineBlockLike + {DisplayInline}
const DisplayInnerFlex* = {DisplayFlex, DisplayInlineFlex}
const RowGroupBox* = {
# Note: caption is not included here
DisplayTableRowGroup, DisplayTableHeaderGroup, DisplayTableFooterGroup
}
const ProperTableChild* = RowGroupBox + {
DisplayTableRow, DisplayTableColumn, DisplayTableColumnGroup
}
const DisplayInnerTable* = {DisplayTable, DisplayInlineTable}
const DisplayInternalTable* = {
DisplayTableCell, DisplayTableRow, DisplayTableCaption
} + RowGroupBox
const ProperTableRowParent* = RowGroupBox + {DisplayTableWrapper} #TODO remove
const PositionAbsoluteFixed* = {PositionAbsolute, PositionFixed}
const WhiteSpacePreserve* = {
WhitespacePre, WhitespacePreLine, WhitespacePreWrap
}
# Forward declarations
proc parseValue(cvals: openArray[CSSComponentValue]; t: CSSPropertyType;
entry: var CSSComputedEntry; attrs: WindowAttributes): Opt[void]
proc newCSSVariableMap*(parent: CSSVariableMap): CSSVariableMap =
return CSSVariableMap(parent: parent)
proc putIfAbsent*(map: CSSVariableMap; name: CAtom; cvar: CSSVariable) =
discard map.table.hasKeyOrPut(name, cvar)
type CSSPropertyReprType* = enum
cprtBit, cprtWord, cprtObject
func reprType*(t: CSSPropertyType): CSSPropertyReprType =
if t <= LastBitPropType:
return cprtBit
if t <= LastWordPropType:
return cprtWord
return cprtObject
func shorthandType(s: string): CSSShorthandType =
return parseEnumNoCase[CSSShorthandType](s).get(cstNone)
func propertyType(s: string): Opt[CSSPropertyType] =
return parseEnumNoCase[CSSPropertyType](s)
func valueType*(prop: CSSPropertyType): CSSValueType =
return ValueTypes[prop]
func isSupportedProperty*(s: string): bool =
return propertyType(s).isSome
func `$`*(length: CSSLength): string =
if length.u == clAuto:
return "auto"
return $length.num & $length.u
func `$`*(bmp: NetworkBitmap): string =
return "" #TODO
func `$`*(content: CSSContent): string =
if content.s != "":
return content.s
return "none"
func `$`(quotes: CSSQuotes): string =
if quotes == nil:
return "auto"
result = ""
for (s, e) in quotes.qs:
result &= "'" & ($s).cssEscape() & "' '" & ($e).cssEscape() & "'"
func `$`(counterreset: seq[CSSCounterReset]): string =
result = ""
for it in counterreset:
result &= it.name
result &= ' '
result &= $it.num
func serialize(val: CSSValue): string =
case val.v
of cvtImage: return $val.image
of cvtLength2:
if val.length2 == nil:
return "0px 0px"
return $val.length2.a & " " & $val.length2.b
of cvtContent:
result = ""
for x in val.content:
if result.len > 0:
result &= ' '
result &= $x
of cvtQuotes: return $val.quotes
of cvtCounterReset: return $val.counterReset
else: assert false
func serialize(val: CSSValueWord; t: CSSValueType): string =
case t
of cvtColor: return $val.color
of cvtInteger: return $val.integer
of cvtLength: return $val.length
of cvtNumber: return $val.number
of cvtVerticalAlign: return $val.verticalAlign
else: assert false
func serialize(val: CSSValueBit; t: CSSValueType): string =
case t
of cvtBgcolorIsCanvas: return $val.bgcolorIsCanvas
of cvtBorderCollapse: return $val.borderCollapse
of cvtBoxSizing: return $val.boxSizing
of cvtCaptionSide: return $val.captionSide
of cvtClear: return $val.clear
of cvtDisplay: return $val.display
of cvtFlexDirection: return $val.flexDirection
of cvtFlexWrap: return $val.flexWrap
of cvtFloat: return $val.float
of cvtFontStyle: return $val.fontStyle
of cvtListStylePosition: return $val.listStylePosition
of cvtListStyleType: return $val.listStyleType
of cvtOverflow: return $val.overflow
of cvtPosition: return $val.position
of cvtTextAlign: return $val.textAlign
of cvtTextDecoration: return $val.textDecoration
of cvtTextTransform: return $val.textTransform
of cvtVisibility: return $val.visibility
of cvtWhiteSpace: return $val.whiteSpace
of cvtWordBreak: return $val.wordBreak
else: assert false
func serialize*(computed: CSSValues; p: CSSPropertyType): string =
case p.reprType
of cprtBit: return computed.bits[p].serialize(valueType(p))
of cprtWord: return computed.words[p].serialize(valueType(p))
of cprtObject: return computed.objs[p].serialize()
func `$`*(computed: CSSValues): string =
result = ""
for p in CSSPropertyType:
result &= $p & ':'
result &= computed.serialize(p)
result &= ';'
when defined(debug):
func `$`*(val: CSSValue): string =
return val.serialize()
macro `{}`*(vals: CSSValues; s: static string): untyped =
let t = propertyType(s).get
let vs = ident($valueType(t))
case t.reprType
of cprtBit:
return quote do:
`vals`.bits[CSSPropertyType(`t`)].`vs`
of cprtWord:
return quote do:
`vals`.words[CSSPropertyType(`t`)].`vs`
of cprtObject:
return quote do:
`vals`.objs[CSSPropertyType(`t`)].`vs`
macro `{}=`*(vals: CSSValues; s: static string, val: typed) =
let t = propertyType(s).get
let v = valueType(t)
let vs = ident($v)
case t.reprType
of cprtBit:
return quote do:
`vals`.bits[CSSPropertyType(`t`)] = CSSValueBit(`vs`: `val`)
of cprtWord:
return quote do:
`vals`.words[CSSPropertyType(`t`)] = CSSValueWord(`vs`: `val`)
of cprtObject:
return quote do:
`vals`.objs[CSSPropertyType(`t`)] = CSSValue(
v: CSSValueType(`v`),
`vs`: `val`
)
func inherited*(t: CSSPropertyType): bool =
return t in InheritedProperties
func blockify*(display: CSSDisplay): CSSDisplay =
case display
of DisplayBlock, DisplayTable, DisplayListItem, DisplayNone, DisplayFlowRoot,
DisplayFlex, DisplayTableWrapper:
#TODO grid
return display
of DisplayInline, DisplayInlineBlock, DisplayTableRow,
DisplayTableRowGroup, DisplayTableColumn,
DisplayTableColumnGroup, DisplayTableCell, DisplayTableCaption,
DisplayTableHeaderGroup, DisplayTableFooterGroup:
return DisplayBlock
of DisplayInlineTable:
return DisplayTable
of DisplayInlineFlex:
return DisplayFlex
func bfcify*(overflow: CSSOverflow): CSSOverflow =
if overflow == OverflowVisible:
return OverflowAuto
if overflow == OverflowClip:
return OverflowHidden
return overflow
const UpperAlphaMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toPoints()
const LowerAlphaMap = "abcdefghijklmnopqrstuvwxyz".toPoints()
const LowerGreekMap = "αβγδεζηθικλμνξοπρστυφχψω".toPoints()
const HiraganaMap = ("あいうえおかきくけこさしすせそたちつてとなにぬねの" &
"はひふへほまみむめもやゆよらりるれろわゐゑをん").toPoints()
const HiraganaIrohaMap = ("いろはにほへとちりぬるをわかよたれそつねならむ" &
"うゐのおくやまけふこえてあさきゆめみしゑひもせす").toPoints()
const KatakanaMap = ("アイウエオカキクケコサシスセソタチツテトナニヌネノ" &
"ハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン").toPoints()
const KatakanaIrohaMap = ("イロハニホヘトチリヌルヲワカヨタレソツネナラム" &
"ウヰノオクヤマケフコエテアサキユメミシヱヒモセス").toPoints()
const EarthlyBranchMap = "子丑寅卯辰巳午未申酉戌亥".toPoints()
const HeavenlyStemMap = "甲乙丙丁戊己庚辛壬癸".toPoints()
func numToBase(n: int; map: openArray[uint32]): string =
if n <= 0:
return $n
var tmp: seq[uint32] = @[]
var n = n
while n != 0:
n -= 1
tmp &= map[n mod map.len]
n = n div map.len
var res = ""
for i in countdown(tmp.high, 0):
res.addUTF8(tmp[i])
return res
func numToFixed(n: int; map: openArray[uint32]): string =
let n = n - 1
if n notin 0 .. map.high:
return $n
return $map[n]
func numberAdditive(i: int; range: HSlice[int, int];
symbols: openArray[(int, string)]): string =
if i notin range:
return $i
var n = i
var at = 0
while n > 0:
if n >= symbols[at][0]:
n -= symbols[at][0]
result &= symbols[at][1]
continue
inc at
return result
const romanNumbers = [
(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"),
(50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")
]
const romanNumbersLower = block:
var res: seq[(int, string)] = @[]
for (n, s) in romanNumbers:
res.add((n, s.toLowerAscii()))
res
func romanNumber(i: int): string =
return numberAdditive(i, 1..3999, romanNumbers)
func romanNumberLower(i: int): string =
return numberAdditive(i, 1..3999, romanNumbersLower)
func japaneseNumber(i: int): string =
if i == 0:
return "〇"
var n = i
var s = ""
if i < 0:
s &= "マイナス"
n *= -1
let o = n
var ss: seq[string] = @[]
var d = 0
while n > 0:
let m = n mod 10
if m != 0:
case d
of 1: ss.add("十")
of 2: ss.add("百")
of 3: ss.add("千")
of 4:
ss.add("万")
ss.add("一")
of 5:
ss.add("万")
ss.add("十")
of 6:
ss.add("万")
ss.add("百")
of 7:
ss.add("万")
ss.add("千")
ss.add("一")
of 8:
ss.add("億")
ss.add("一")
of 9:
ss.add("億")
ss.add("十")
else: discard
case m
of 0:
inc d
n = n div 10
of 1:
if o == n:
ss.add("一")
of 2: ss.add("二")
of 3: ss.add("三")
of 4: ss.add("四")
of 5: ss.add("五")
of 6: ss.add("六")
of 7: ss.add("七")
of 8: ss.add("八")
of 9: ss.add("九")
else: discard
n -= m
for j in countdown(ss.high, 0):
s &= ss[j]
return s
func listMarker*(t: CSSListStyleType; i: int): string =
case t
of ListStyleTypeNone: return ""
of ListStyleTypeDisc: return "• " # U+2022
of ListStyleTypeCircle: return "○ " # U+25CB
of ListStyleTypeSquare: return "□ " # U+25A1
of ListStyleTypeDisclosureOpen: return "▶ " # U+25B6
of ListStyleTypeDisclosureClosed: return "▼ " # U+25BC
of ListStyleTypeDecimal: return $i & ". "
of ListStyleTypeUpperRoman: return romanNumber(i) & ". "
of ListStyleTypeLowerRoman: return romanNumberLower(i) & ". "
of ListStyleTypeUpperAlpha: return numToBase(i, UpperAlphaMap) & ". "
of ListStyleTypeLowerAlpha: return numToBase(i, LowerAlphaMap) & ". "
of ListStyleTypeLowerGreek: return numToBase(i, LowerGreekMap) & ". "
of ListStyleTypeHiragana: return numToBase(i, HiraganaMap) & "、"
of ListStyleTypeHiraganaIroha: return numToBase(i, HiraganaIrohaMap) & "、"
of ListStyleTypeKatakana: return numToBase(i, KatakanaMap) & "、"
of ListStyleTypeKatakanaIroha: return numToBase(i, KatakanaIrohaMap) & "、"
of ListStyleTypeCjkEarthlyBranch:
return numToFixed(i, EarthlyBranchMap) & "、"
of ListStyleTypeCjkHeavenlyStem: return numToFixed(i, HeavenlyStemMap) & "、"
of ListStyleTypeJapaneseInformal: return japaneseNumber(i) & "、"
func quoteStart*(level: int): string =
if level == 0:
return "“"
return "‘"
func quoteEnd*(level: int): string =
if level == 0:
return "“"
return "‘"
func parseIdent(map: openArray[IdentMapItem]; cval: CSSComponentValue): int =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok.t == cttIdent:
return map.parseEnumNoCase0(tok.value)
return -1
func parseIdent[T: enum](cval: CSSComponentValue): Opt[T] =
const IdentMap = getIdentMap(T)
let i = IdentMap.parseIdent(cval)
if i != -1:
return ok(T(i))
return err()
template cssLength*(n: float32): CSSLength =
CSSLength(u: clPx, num: n)
func resolveLength*(u: CSSUnit; val: float32; attrs: WindowAttributes):
CSSLength =
return case u
of cuAuto: CSSLength(u: clAuto)
of cuEm, cuRem, cuCap, cuRcap, cuLh, cuRlh:
cssLength(val * float32(attrs.ppl))
of cuCh, cuRch: cssLength(val * float32(attrs.ppc))
of cuIc, cuRic: cssLength(val * float32(attrs.ppc) * 2)
of cuEx, cuRex: cssLength(val * float32(attrs.ppc) / 2)
of cuPerc: CSSLength(u: clPerc, num: val)
of cuPx: cssLength(val)
of cuCm: cssLength(val * 37.8)
of cuMm: cssLength(val * 3.78)
of cuIn: cssLength(val * 96)
of cuPc: cssLength(val * 16)
of cuPt: cssLength(val * 4 / 3)
of cuVw, cuVi: cssLength(float32(attrs.widthPx) * val / 100)
of cuVh, cuVb: cssLength(float32(attrs.heightPx) * val / 100)
of cuVmin, cuSvmin, cuLvmin, cuDvmin:
cssLength(min(attrs.widthPx, attrs.heightPx) / 100 * val)
of cuVmax, cuSvmax, cuLvmax, cuDvmax:
cssLength(max(attrs.widthPx, attrs.heightPx) / 100 * val)
func parseLength(val: float32; u: string; attrs: WindowAttributes):
Opt[CSSLength] =
let u = ?parseEnumNoCase[CSSUnit](u)
return ok(resolveLength(u, val, attrs))
const CSSLengthAuto* = CSSLength(u: clAuto)
func parseDimensionValues*(s: string): Option[CSSLength] =
var i = s.skipBlanks(0)
if i >= s.len or s[i] notin AsciiDigit:
return none(CSSLength)
var n = 0f64
while s[i] in AsciiDigit:
n *= 10
n += float32(decValue(s[i]))
inc i
if i >= s.len:
return some(cssLength(n))
if s[i] == '.':
inc i
if i >= s.len:
return some(cssLength(n))
var d = 1
while i < s.len and s[i] in AsciiDigit:
n += float32(decValue(s[i])) / float32(d)
inc d
inc i
if i < s.len and s[i] == '%':
return some(CSSLength(num: n, u: clPerc))
return some(cssLength(n))
func skipBlanks*(vals: openArray[CSSComponentValue]; i: int): int =
var i = i
while i < vals.len:
if vals[i] != cttWhitespace:
break
inc i
return i
func findBlank(vals: openArray[CSSComponentValue]; i: int): int =
var i = i
while i < vals.len:
if vals[i] == cttWhitespace:
break
inc i
return i
func getToken(cvals: openArray[CSSComponentValue]; i: int): Opt[CSSToken] =
if i < cvals.len:
let cval = cvals[i]
if cval of CSSToken:
return ok(CSSToken(cval))
return err()
func getToken(cvals: openArray[CSSComponentValue]; i: int;
tt: set[CSSTokenType]): Opt[CSSToken] =
let tok = ?cvals.getToken(i)
if tok.t in tt:
return ok(tok)
return err()
func getToken(cvals: openArray[CSSComponentValue]; i: int; t: CSSTokenType):
Opt[CSSToken] =
let tok = ?cvals.getToken(i)
if t == tok.t:
return ok(tok)
return err()
func getColorToken(cvals: openArray[CSSComponentValue]; i: int;
legacy = false): Opt[CSSToken] =
let tok = ?cvals.getToken(i)
if tok.t in {cttNumber, cttINumber, cttDimension, cttIDimension,
cttPercentage}:
return ok(tok)
if not legacy and tok.t == cttIdent and tok.value == "none":
return ok(tok)
return err()
# For rgb(), rgba(), hsl(), hsla().
proc parseLegacyColorFun(value: openArray[CSSComponentValue]):
Opt[tuple[v1, v2, v3: CSSToken; a: uint8; legacy: bool]] =
var i = value.skipBlanks(0)
let v1 = ?value.getColorToken(i)
i = value.skipBlanks(i + 1)
let legacy = ?value.getToken(i) == cttComma
if legacy:
if v1.t == cttIdent:
return err() # legacy doesn't accept "none"
inc i
i = value.skipBlanks(i)
let v2 = ?value.getColorToken(i, legacy)
if legacy:
i = value.skipBlanks(i + 1)
discard ?value.getToken(i, cttComma)
i = value.skipBlanks(i + 1)
let v3 = ?value.getColorToken(i, legacy)
i = value.skipBlanks(i + 1)
if i == value.len:
return ok((v1, v2, v3, 255u8, legacy))
if legacy:
discard ?value.getToken(i, cttComma)
else:
if (?value.getToken(i, cttDelim)).cvalue != '/':
return err()
i = value.skipBlanks(i + 1)
let v4 = ?value.getToken(i, {cttPercentage, cttNumber, cttINumber})
if value.skipBlanks(i + 1) < value.len:
return err()
return ok((v1, v2, v3, uint8(clamp(v4.nvalue, 0, 1) * 255), legacy))
# syntax: -cha-ansi( number | ident )
# where number is an ANSI color (0..255)
# and ident is in NameTable and may start with "bright-"
func parseANSI(value: openArray[CSSComponentValue]): Opt[CSSColor] =
var i = value.skipBlanks(0)
if i != value.high or not (value[i] of CSSToken): # only 1 param is valid
#TODO numeric functions
return err()
let tok = CSSToken(value[i])
if tok.t == cttINumber:
if int(tok.nvalue) notin 0..255:
return err() # invalid numeric ANSI color
return ok(ANSIColor(tok.nvalue).cssColor())
elif tok.t == cttIdent:
var name = tok.value
if name.equalsIgnoreCase("default"):
return ok(defaultColor.cssColor())
var bright = false
if name.startsWithIgnoreCase("bright-"):
bright = true
name = name.substr("bright-".len)
const NameTable = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white"
]
for i, it in NameTable.mypairs:
if it.equalsIgnoreCase(name):
var i = int(i)
if bright:
i += 8
return ok(ANSIColor(i).cssColor())
return err()
proc parseRGBComponent(tok: CSSToken): uint8 =
if tok.t == cttIdent: # none
return 0u8
var res = tok.nvalue
if tok.t == cttPercentage:
res *= 2.55
return uint8(clamp(res, 0, 255)) # number
type CSSAngleType = enum
catDeg = "deg"
catGrad = "grad"
catRad = "rad"
catTurn = "turn"
# The return value is in degrees.
proc parseAngle(tok: CSSToken): Opt[float32] =
if tok.t in {cttDimension, cttIDimension}:
case ?parseEnumNoCase[CSSAngleType](tok.unit)
of catDeg: return ok(tok.nvalue)
of catGrad: return ok(tok.nvalue * 0.9f32)
of catRad: return ok(radToDeg(tok.nvalue))
of catTurn: return ok(tok.nvalue * 360f32)
return err()
proc parseHue(tok: CSSToken): Opt[float32] =
if tok.t in {cttNumber, cttINumber}:
return ok(tok.nvalue)
if tok.t == cttIdent: # none
return ok(0)
return parseAngle(tok)
proc parseSatOrLight(tok: CSSToken): Opt[float32] =
if tok.t in {cttNumber, cttINumber, cttPercentage}:
return ok(clamp(tok.nvalue, 0f32, 100f32))
return err()
proc parseColor*(val: CSSComponentValue): Opt[CSSColor] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.t
of cttHash:
let c = parseHexColor(tok.value)
if c.isSome:
return ok(c.get.cssColor())
of cttIdent:
if tok.value.equalsIgnoreCase("transparent"):
return ok(rgba(0, 0, 0, 0).cssColor())
let x = namedRGBColor(tok.value)
if x.isSome:
return ok(x.get.cssColor())
else: discard
elif val of CSSFunction:
let f = CSSFunction(val)
case f.name
of cftRgb, cftRgba:
let (r, g, b, a, legacy) = ?parseLegacyColorFun(f.value)
if r.t == g.t and g.t == b.t or not legacy:
let r = parseRGBComponent(r)
let g = parseRGBComponent(g)
let b = parseRGBComponent(b)
return ok(rgba(r, g, b, a).cssColor())
of cftHsl, cftHsla:
let (h, s, l, a, legacy) = ?parseLegacyColorFun(f.value)
if h.t != cttIdent and s.t == cttPercentage and l.t == cttPercentage or
not legacy:
let h = ?parseHue(h)
let s = ?parseSatOrLight(s)
let l = ?parseSatOrLight(l)
return ok(hsla(h, s, l, a).cssColor())
return err()
of cftChaAnsi:
return parseANSI(f.value)
else: discard
return err()
func parseLength*(val: CSSComponentValue; attrs: WindowAttributes;
hasAuto = true; allowNegative = true): Opt[CSSLength] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.t
of cttNumber, cttINumber:
if tok.nvalue == 0:
return ok(cssLength(0))
of cttPercentage:
if not allowNegative and tok.nvalue < 0:
return err()
return parseLength(tok.nvalue, "%", attrs)
of cttDimension, cttIDimension:
if not allowNegative and tok.nvalue < 0:
return err()
return parseLength(tok.nvalue, tok.unit, attrs)
of cttIdent:
if hasAuto and tok.value.equalsIgnoreCase("auto"):
return ok(CSSLengthAuto)
else: discard
elif val of CSSFunction:
#TODO obviously this is a horrible solution...
let fun = CSSFunction(val)
if fun.name == cftCalc and allowNegative:
var i = fun.value.skipBlanks(0)
if i >= fun.value.len:
return err()
var length = ?parseLength(fun.value[i], attrs, hasAuto, allowNegative)
i = fun.value.skipBlanks(i + 1)
let dtok = ?fun.value.getToken(i, cttDelim)
let sign = if dtok.cvalue == '+':
1f32
elif dtok.cvalue == '-':
-1f32
else:
return err()
i = fun.value.skipBlanks(i + 1)
if i >= fun.value.len:
return err()
var length2 = ?parseLength(fun.value[i], attrs, hasAuto, allowNegative)
length2.num *= sign
if length2.u == clAuto or fun.value.skipBlanks(i + 1) < fun.value.len:
return err()
if length.u == length2.u:
return ok(CSSLength(u: length.u, num: length.num + length2.num))
if length2.u == clPerc:
swap(length, length2)
length2.num += float32(length.addpx)
if length2.num notin float32(int16.low)..float32(int16.high):
return err()
return ok(CSSLength(
u: clPerc,
num: length.num,
addpx: int16(length2.num)
))
return err()
func cssAbsoluteLength(val: CSSComponentValue; attrs: WindowAttributes):
Opt[CSSLength] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.t
of cttNumber, cttINumber:
if tok.nvalue == 0:
return ok(cssLength(0))
of cttDimension, cttIDimension:
if tok.nvalue >= 0:
return parseLength(tok.nvalue, tok.unit, attrs)
else: discard
return err()
func parseGlobal(cval: CSSComponentValue): Opt[CSSGlobalType] =
return parseIdent[CSSGlobalType](cval)
func parseQuotes(cvals: openArray[CSSComponentValue]): Opt[CSSQuotes] =
var i = cvals.skipBlanks(0)
let tok = ?cvals.getToken(i)
i = cvals.skipBlanks(i + 1)
case tok.t
of cttIdent:
if i < cvals.len:
return err()
if tok.value.equalsIgnoreCase("auto"):
return ok(nil)
elif tok.value.equalsIgnoreCase("none"):
return ok(CSSQuotes())
return err()
of cttString:
var res = CSSQuotes()
var otok = tok
while i < cvals.len:
let cval = cvals[i]
if not (cval of CSSToken):
return err()
let tok = CSSToken(cval)
if tok.t != cttString:
return err()
if otok != nil:
res.qs.add((newRefString(otok.value), newRefString(tok.value)))
otok = nil
else:
otok = tok
i = cvals.skipBlanks(i + 1)
if otok != nil:
return err()
return ok(move(res))
else:
return err()
func cssContent(cvals: openArray[CSSComponentValue]): seq[CSSContent] =
result = @[]
for cval in cvals:
if cval of CSSToken:
let tok = CSSToken(cval)
case tok.t
of cttIdent:
if tok.value == "/":
break
elif tok.value.equalsIgnoreCase("open-quote"):
result.add(CSSContent(t: ContentOpenQuote))
elif tok.value.equalsIgnoreCase("no-open-quote"):
result.add(CSSContent(t: ContentNoOpenQuote))
elif tok.value.equalsIgnoreCase("close-quote"):
result.add(CSSContent(t: ContentCloseQuote))
elif tok.value.equalsIgnoreCase("no-close-quote"):
result.add(CSSContent(t: ContentNoCloseQuote))
of cttString:
result.add(CSSContent(t: ContentString, s: newRefString(tok.value)))
else: return
func parseFontWeight(cval: CSSComponentValue): Opt[int32] =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok.t == cttIdent:
const FontWeightMap = {
"bold": 700,
"bolder": 700,
"lighter": 400,
"normal": 400
}
let i = FontWeightMap.parseIdent(cval)
if i != -1:
return ok(int32(i))
elif tok.t in {cttNumber, cttINumber}:
if tok.nvalue in 1f64..1000f64:
return ok(int32(tok.nvalue))
return err()
func cssTextDecoration(cvals: openArray[CSSComponentValue]):
Opt[set[CSSTextDecoration]] =
var s: set[CSSTextDecoration] = {}
for cval in cvals:
if not (cval of CSSToken):
continue
let tok = CSSToken(cval)
if tok.t == cttIdent:
let td = ?parseIdent[CSSTextDecoration](tok)
if td == TextDecorationNone:
if cvals.len != 1:
return err()
return ok(s)
s.incl(td)
return ok(s)
func cssVerticalAlign(cval: CSSComponentValue; attrs: WindowAttributes):
Opt[CSSVerticalAlign] =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok.t == cttIdent:
let va2 = ?parseIdent[CSSVerticalAlign2](cval)
return ok(CSSVerticalAlign(keyword: va2))
else:
let length = ?parseLength(tok, attrs, hasAuto = false)
return ok(CSSVerticalAlign(
keyword: VerticalAlignBaseline,
u: length.u,
num: length.num
))
return err()
func cssCounterReset(cvals: openArray[CSSComponentValue]):
Opt[seq[CSSCounterReset]] =
template die =
return err()
var r = CSSCounterReset()
var s = false
var res: seq[CSSCounterReset] = @[]
for cval in cvals:
if cval of CSSToken:
let tok = CSSToken(cval)
case tok.t
of cttWhitespace: discard
of cttIdent:
if s:
die
r.name = tok.value
s = true
of cttNumber, cttINumber:
if not s:
die
r.num = int(tok.nvalue)
res.add(r)
s = false
else:
die
return ok(res)
func cssMaxSize(cval: CSSComponentValue; attrs: WindowAttributes):
Opt[CSSLength] =
if cval of CSSToken:
let tok = CSSToken(cval)
case tok.t
of cttIdent:
if tok.value.equalsIgnoreCase("none"):
return ok(CSSLengthAuto)
of cttNumber, cttINumber, cttDimension, cttIDimension, cttPercentage:
return parseLength(tok, attrs, allowNegative = false)
else: discard
return err()
#TODO should be URL (parsed with baseurl of document...)
func cssURL*(cval: CSSComponentValue; src = false): Option[string] =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok == cttUrl:
return some(tok.value)
elif not src and tok == cttString:
return some(tok.value)
elif cval of CSSFunction:
let fun = CSSFunction(cval)
if fun.name == cftUrl or src and fun.name == cftSrc:
for x in fun.value:
if not (x of CSSToken):
break
let x = CSSToken(x)
if x == cttWhitespace:
discard
elif x == cttString:
return some(x.value)
else:
break
return none(string)
#TODO this should be bg-image, add gradient, etc etc
func parseImage(cval: CSSComponentValue): Opt[NetworkBitmap] =
if cval of CSSToken:
#TODO bg-image only
let tok = CSSToken(cval)
if tok.t == cttIdent and tok.value.equalsIgnoreCase("none"):
return ok(nil)
let url = cssURL(cval, src = true)
if url.isSome:
#TODO do something with the URL
return ok(NetworkBitmap(cacheId: -1, imageId: -1))
return err()
func parseInteger(cval: CSSComponentValue; range: Slice[int32]): Opt[int32] =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok.t in {cttNumber, cttINumber}:
if tok.nvalue in float32(range.a)..float32(range.b):
return ok(int32(tok.nvalue))
return err()
func parseNumber(cval: CSSComponentValue; range: Slice[float32]): Opt[float32] =
if cval of CSSToken:
let tok = CSSToken(cval)
if tok.t in {cttNumber, cttINumber}:
if tok.nvalue in range:
return ok(tok.nvalue)
return err()
proc makeEntry*(t: CSSPropertyType; obj: CSSValue): CSSComputedEntry =
return CSSComputedEntry(et: ceObject, t: t, obj: obj)
proc makeEntry*(t: CSSPropertyType; word: CSSValueWord): CSSComputedEntry =
return CSSComputedEntry(et: ceWord, t: t, word: word)
proc makeEntry*(t: CSSPropertyType; bit: CSSValueBit): CSSComputedEntry =
return CSSComputedEntry(et: ceBit, t: t, bit: bit.dummy)
proc makeEntry*(t: CSSPropertyType; global: CSSGlobalType): CSSComputedEntry =
return CSSComputedEntry(et: ceGlobal, t: t, global: global)
proc parseVariable(fun: CSSFunction; t: CSSPropertyType;
entry: var CSSComputedEntry; attrs: WindowAttributes): Opt[void] =
var i = fun.value.skipBlanks(0)
if i >= fun.value.len:
return err()
let cval = fun.value[i]
if not (cval of CSSToken):
return err()
let tok = CSSToken(fun.value[i])
if tok.t != cttIdent:
return err()
entry = CSSComputedEntry(
et: ceVar,
t: t,
cvar: tok.value.substr(2).toAtom()
)
i = fun.value.skipBlanks(i + 1)
if i < fun.value.len:
if fun.value[i] != cttComma:
return err()
i = fun.value.skipBlanks(i + 1)
if i < fun.value.len:
entry.fallback = (ref CSSComputedEntry)()
if fun.value.toOpenArray(i, fun.value.high).parseValue(t,
entry.fallback[], attrs).isNone:
entry.fallback = nil
return ok()
proc parseValue(cvals: openArray[CSSComponentValue]; t: CSSPropertyType;
entry: var CSSComputedEntry; attrs: WindowAttributes): Opt[void] =
var i = cvals.skipBlanks(0)
if i >= cvals.len:
return err()
let cval = cvals[i]
inc i
if cval of CSSFunction:
let fun = CSSFunction(cval)
if fun.name == cftVar:
if cvals.skipBlanks(i) < cvals.len:
return err()
return fun.parseVariable(t, entry, attrs)
let v = valueType(t)
template set_new(prop, val: untyped) =
entry = CSSComputedEntry(
t: t,
et: ceObject,
obj: CSSValue(v: v, prop: val)
)
template set_word(prop, val: untyped) =
entry = CSSComputedEntry(
t: t,
et: ceWord,
word: CSSValueWord(prop: val)
)
template set_bit(prop, val: untyped) =
entry = CSSComputedEntry(t: t, et: ceBit, bit: cast[uint8](val))
case v
of cvtDisplay: set_bit display, ?parseIdent[CSSDisplay](cval)
of cvtWhiteSpace: set_bit whiteSpace, ?parseIdent[CSSWhiteSpace](cval)
of cvtWordBreak: set_bit wordBreak, ?parseIdent[CSSWordBreak](cval)
of cvtListStyleType:
set_bit listStyleType, ?parseIdent[CSSListStyleType](cval)
of cvtFontStyle: set_bit fontStyle, ?parseIdent[CSSFontStyle](cval)
of cvtColor: set_word color, ?parseColor(cval)
of cvtLength:
case t
of cptMinWidth, cptMinHeight:
set_word length, ?parseLength(cval, attrs, allowNegative = false)
of cptMaxWidth, cptMaxHeight:
set_word length, ?cssMaxSize(cval, attrs)
of cptPaddingLeft, cptPaddingRight, cptPaddingTop, cptPaddingBottom:
set_word length, ?parseLength(cval, attrs, hasAuto = false)
#TODO content for flex-basis
else:
set_word length, ?parseLength(cval, attrs)
of cvtContent: set_new content, cssContent(cvals)
of cvtInteger:
case t
of cptFontWeight: set_word integer, ?parseFontWeight(cval)
of cptChaColspan: set_word integer, ?parseInteger(cval, 1i32 .. 1000i32)
of cptChaRowspan: set_word integer, ?parseInteger(cval, 0i32 .. 65534i32)
of cptZIndex: set_word integer, ?parseInteger(cval, -65534i32 .. 65534i32)
else: assert false
of cvtTextDecoration: set_bit textDecoration, ?cssTextDecoration(cvals)
of cvtVerticalAlign: set_word verticalAlign, ?cssVerticalAlign(cval, attrs)
of cvtTextAlign: set_bit textAlign, ?parseIdent[CSSTextAlign](cval)
of cvtListStylePosition:
set_bit listStylePosition, ?parseIdent[CSSListStylePosition](cval)
of cvtPosition: set_bit position, ?parseIdent[CSSPosition](cval)
of cvtCaptionSide: set_bit captionSide, ?parseIdent[CSSCaptionSide](cval)
of cvtBorderCollapse:
set_bit borderCollapse, ?parseIdent[CSSBorderCollapse](cval)
of cvtLength2:
let a = ?cssAbsoluteLength(cval, attrs)
i = cvals.skipBlanks(i)
let b = if i >= cvals.len: a else: ?cssAbsoluteLength(cvals[i], attrs)
set_new length2, CSSLength2(a: a, b: b)
of cvtQuotes: set_new quotes, ?parseQuotes(cvals)
of cvtCounterReset: set_new counterReset, ?cssCounterReset(cvals)
of cvtImage: set_new image, ?parseImage(cval)
of cvtFloat: set_bit float, ?parseIdent[CSSFloat](cval)
of cvtVisibility: set_bit visibility, ?parseIdent[CSSVisibility](cval)
of cvtBoxSizing: set_bit boxSizing, ?parseIdent[CSSBoxSizing](cval)
of cvtClear: set_bit clear, ?parseIdent[CSSClear](cval)
of cvtTextTransform:
set_bit textTransform, ?parseIdent[CSSTextTransform](cval)
of cvtBgcolorIsCanvas: return err() # internal value
of cvtFlexDirection:
set_bit flexDirection, ?parseIdent[CSSFlexDirection](cval)
of cvtFlexWrap: set_bit flexWrap, ?parseIdent[CSSFlexWrap](cval)
of cvtNumber:
case t
of cptFlexGrow, cptFlexShrink:
set_word number, ?parseNumber(cval, 0f32..float32.high)
of cptOpacity: set_word number, ?parseNumber(cval, 0f32..1f32)
else: assert false
of cvtOverflow: set_bit overflow, ?parseIdent[CSSOverflow](cval)
return ok()
func getInitialColor(t: CSSPropertyType): CSSColor =
if t == cptBackgroundColor:
return rgba(0, 0, 0, 0).cssColor()
return defaultColor.cssColor()
func getInitialLength(t: CSSPropertyType): CSSLength =
case t
of cptWidth, cptHeight, cptLeft, cptRight, cptTop, cptBottom, cptMaxWidth,
cptMaxHeight, cptMinWidth, cptMinHeight, cptFlexBasis:
return CSSLengthAuto
of cptFontSize:
return cssLength(16)
else:
return cssLength(0)
func getInitialInteger(t: CSSPropertyType): int32 =
case t
of cptChaColspan, cptChaRowspan:
return 1
of cptFontWeight:
return 400 # normal
else:
return 0
func getInitialNumber(t: CSSPropertyType): float32 =
if t in {cptFlexShrink, cptOpacity}:
return 1
return 0
func getInitialTable(): array[CSSPropertyType, CSSValue] =
for t in CSSPropertyType:
result[t] = CSSValue(v: valueType(t))
let defaultTable = getInitialTable()
template getDefault*(t: CSSPropertyType): CSSValue =
{.cast(noSideEffect).}:
defaultTable[t]
proc getDefaultWord(t: CSSPropertyType): CSSValueWord =
case valueType(t)
of cvtColor: return CSSValueWord(color: getInitialColor(t))
of cvtInteger: return CSSValueWord(integer: getInitialInteger(t))
of cvtLength: return CSSValueWord(length: getInitialLength(t))
of cvtNumber: return CSSValueWord(number: getInitialNumber(t))
else: return CSSValueWord(dummy: 0)
func lengthShorthand(cvals: openArray[CSSComponentValue];
props: array[4, CSSPropertyType]; global: Opt[CSSGlobalType];
attrs: WindowAttributes; hasAuto = true): Opt[seq[CSSComputedEntry]] =
var res: seq[CSSComputedEntry] = @[]
if global.isSome:
let global = global.get
for t in props:
res.add(makeEntry(t, global))
return ok(res)
var lengths: seq[CSSValueWord] = @[]
var i = 0
while i < cvals.len:
i = cvals.skipBlanks(i)
let length = ?parseLength(cvals[i], attrs, hasAuto = hasAuto)
let val = CSSValueWord(length: length)
lengths.add(val)
inc i
case lengths.len
of 1: # top, bottom, left, right
for i, t in props.mypairs:
res.add(makeEntry(t, lengths[0]))
of 2: # top, bottom | left, right
for i, t in props.mypairs:
res.add(makeEntry(t, lengths[i mod 2]))
of 3: # top | left, right | bottom
for i, t in props.mypairs:
let j = if i == 0:
0 # top
elif i == 2:
2 # bottom
else:
1 # left, right
res.add(makeEntry(t, lengths[j]))
of 4: # top | right | bottom | left
for i, t in props.mypairs:
res.add(makeEntry(t, lengths[i]))
else:
return err()
return ok(res)
const PropertyMarginSpec = [
cptMarginTop, cptMarginRight, cptMarginBottom, cptMarginLeft
]
const PropertyPaddingSpec = [
cptPaddingTop, cptPaddingRight, cptPaddingBottom, cptPaddingLeft
]
proc addGlobals(res: var seq[CSSComputedEntry]; ps: openArray[CSSPropertyType];
global: CSSGlobalType) =
for p in ps:
res.add(makeEntry(p, global))
proc parseComputedValues*(res: var seq[CSSComputedEntry]; name: string;
cvals: openArray[CSSComponentValue]; attrs: WindowAttributes): Err[void] =
var i = cvals.skipBlanks(0)
if i >= cvals.len:
return err()
let global = parseGlobal(cvals[i])
case shorthandType(name)
of cstNone:
let t = propertyType(name)
if t.isSome:
let t = t.get
if global.isSome:
res.add(makeEntry(t, global.get))
else:
var entry = CSSComputedEntry()
?cvals.parseValue(t, entry, attrs)
res.add(entry)
of cstAll:
let global = ?global
for t in CSSPropertyType:
res.add(makeEntry(t, global))
of cstMargin:
res.add(?lengthShorthand(cvals, PropertyMarginSpec, global, attrs))
of cstPadding:
res.add(?lengthShorthand(cvals, PropertyPaddingSpec, global, attrs,
hasAuto = false))
of cstBackground:
if global.isSome:
res.addGlobals([cptBackgroundColor, cptBackgroundImage], global.get)
else:
var bgcolor = makeEntry(cptBackgroundColor,
getDefaultWord(cptBackgroundColor))
var bgimage = makeEntry(cptBackgroundImage,
getDefault(cptBackgroundImage))
var valid = true
var i = cvals.skipBlanks(0)
while i < cvals.len:
let j = cvals.findBlank(i)
if cvals.toOpenArray(i, j - 1).parseValue(bgcolor.t, bgcolor,
attrs).isSome:
discard
elif cvals.toOpenArray(i, j - 1).parseValue(bgimage.t, bgimage,
attrs).isSome:
discard
else:
#TODO when we implement the other shorthands too
#valid = false
discard
i = cvals.skipBlanks(j)
if valid:
res.add(bgcolor)
res.add(bgimage)
of cstListStyle:
if global.isSome:
res.addGlobals([cptListStylePosition, cptListStyleType], global.get)
else:
var valid = true
var typeVal = CSSValueBit()
var positionVal = CSSValueBit()
for tok in cvals:
if tok == cttWhitespace:
continue
if (let r = parseIdent[CSSListStylePosition](tok); r.isSome):
positionVal.listStylePosition = r.get
elif (let r = parseIdent[CSSListStyleType](tok); r.isSome):
typeVal.listStyleType = r.get
else:
#TODO list-style-image
#valid = false
discard
if valid:
res.add(makeEntry(cptListStylePosition, positionVal))
res.add(makeEntry(cptListStyleType, typeVal))
of cstFlex:
if global.isSome:
res.addGlobals([cptFlexGrow, cptFlexShrink, cptFlexBasis], global.get)
else:
var i = cvals.skipBlanks(0)
if i >= cvals.len:
return err()
if (let r = parseNumber(cvals[i], 0f32..float32.high); r.isSome):
# flex-grow
let val = CSSValueWord(number: r.get)
res.add(makeEntry(cptFlexGrow, val))
i = cvals.skipBlanks(i + 1)
if i < cvals.len:
if not (cvals[i] of CSSToken):
return err()
if (let r = parseNumber(cvals[i], 0f32..float32.high); r.isSome):
# flex-shrink
let val = CSSValueWord(number: r.get)
res.add(makeEntry(cptFlexShrink, val))
i = cvals.skipBlanks(i + 1)
if res.len < 1: # flex-grow omitted, default to 1
let val = CSSValueWord(number: 1)
res.add(makeEntry(cptFlexGrow, val))
if res.len < 2: # flex-shrink omitted, default to 1
let val = CSSValueWord(number: 1)
res.add(makeEntry(cptFlexShrink, val))
if i < cvals.len:
# flex-basis
let val = CSSValueWord(length: ?parseLength(cvals[i], attrs))
res.add(makeEntry(cptFlexBasis, val))
else: # omitted, default to 0px
let val = CSSValueWord(length: cssLength(0))
res.add(makeEntry(cptFlexBasis, val))
of cstFlexFlow:
if global.isSome:
res.addGlobals([cptFlexDirection, cptFlexWrap], global.get)
else:
var i = cvals.skipBlanks(0)
if i >= cvals.len:
return err()
if (let dir = parseIdent[CSSFlexDirection](cvals[i]); dir.isSome):
# flex-direction
var val = CSSValueBit(flexDirection: dir.get)
res.add(makeEntry(cptFlexDirection, val))
i = cvals.skipBlanks(i + 1)
if i < cvals.len:
let wrap = ?parseIdent[CSSFlexWrap](cvals[i])
var val = CSSValueBit(flexWrap: wrap)
res.add(makeEntry(cptFlexWrap, val))
of cstOverflow:
if global.isSome:
res.addGlobals([cptOverflowX, cptOverflowY], global.get)
else:
var i = cvals.skipBlanks(0)
if i >= cvals.len:
return err()
if (let xx = parseIdent[CSSOverflow](cvals[i]); xx.isSome):
var x = CSSValueBit(overflow: xx.get)
var y = x
i = cvals.skipBlanks(i + 1)
if i < cvals.len:
y.overflow = ?parseIdent[CSSOverflow](cvals[i])
res.add(makeEntry(cptOverflowX, x))
res.add(makeEntry(cptOverflowY, y))
return ok()
proc parseComputedValues*(name: string; value: seq[CSSComponentValue];
attrs: WindowAttributes): seq[CSSComputedEntry] =
var res: seq[CSSComputedEntry] = @[]
if res.parseComputedValues(name, value, attrs).isSome:
return res
return @[]
proc copyFrom*(a, b: CSSValues; t: CSSPropertyType) =
case t.reprType
of cprtBit: a.bits[t] = b.bits[t]
of cprtWord: a.words[t] = b.words[t]
of cprtObject: a.objs[t] = b.objs[t]
proc setInitial*(a: CSSValues; t: CSSPropertyType) =
case t.reprType
of cprtBit: a.bits[t].dummy = 0
of cprtWord: a.words[t] = getDefaultWord(t)
of cprtObject: a.objs[t] = getDefault(t)
proc initialOrInheritFrom*(a, b: CSSValues; t: CSSPropertyType) =
if t.inherited and b != nil:
a.copyFrom(b, t)
else:
a.setInitial(t)
proc initialOrCopyFrom*(a, b: CSSValues; t: CSSPropertyType) =
if b != nil:
a.copyFrom(b, t)
else:
a.setInitial(t)
func inheritProperties*(parent: CSSValues): CSSValues =
result = CSSValues()
for t in CSSPropertyType:
if t.inherited:
result.copyFrom(parent, t)
else:
result.setInitial(t)
func copyProperties*(props: CSSValues): CSSValues =
result = CSSValues()
result[] = props[]
func rootProperties*(): CSSValues =
result = CSSValues()
for t in CSSPropertyType:
result.setInitial(t)
# Separate CSSValues of a table into those of the wrapper and the actual
# table.
func splitTable*(computed: CSSValues): tuple[outer, innner: CSSValues] =
var outer = CSSValues()
var inner = CSSValues()
const props = {
cptPosition, cptFloat, cptMarginLeft, cptMarginRight, cptMarginTop,
cptMarginBottom, cptTop, cptRight, cptBottom, cptLeft,
# Note: the standard does not ask us to include padding or sizing, but the
# wrapper & actual table layouts share the same sizing from the wrapper,
# so we must add them here.
cptPaddingLeft, cptPaddingRight, cptPaddingTop, cptPaddingBottom,
cptWidth, cptHeight, cptBoxSizing,
# no clue why this isn't included in the standard
cptClear
}
for t in CSSPropertyType:
if t in props:
outer.copyFrom(computed, t)
inner.setInitial(t)
else:
inner.copyFrom(computed, t)
outer.setInitial(t)
outer{"display"} = computed{"display"}
inner{"display"} = DisplayTableWrapper
return (outer, inner)
when defined(debug):
func `serializeEmpty`*(computed: CSSValues): string =
let default = rootProperties()
result = ""
for p in CSSPropertyType:
let a = computed.serialize(p)
let b = default.serialize(p)
if a != b:
result &= $p & ':'
result &= a
result &= ';'
|