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
|
import std/algorithm
import std/macros
import std/options
import std/strutils
import std/tables
import std/unicode
import css/cssparser
import css/selectorparser
import img/bitmap
import layout/layoutunit
import types/color
import types/opt
import types/winattrs
import utils/twtstr
export selectorparser.PseudoElem
type
CSSShorthandType = enum
cstNone = ""
cstAll = "all"
cstMargin = "margin"
cstPadding = "padding"
cstBackground = "background"
cstListStyle = "list-style"
cstFlex = "flex"
cstFlexFlow = "flex-flow"
CSSUnit* = enum
cuCm = "cm"
cuMm = "mm"
cuIn = "in"
cuPx = "px"
cuPt = "pt"
cuPc = "pc"
cuEm = "em"
cuEx = "ex"
cuCh = "ch"
cuRem = "rem"
cuVw = "vw"
cuVh = "vh"
cuVmin = "vmin"
cuVmax = "vmax"
cuPerc = "%"
cuIc = "ic"
CSSPropertyType* = enum
cptNone = ""
cptColor = "color"
cptMarginTop = "margin-top"
cptMarginLeft = "margin-left"
cptMarginRight = "margin-right"
cptMarginBottom = "margin-bottom"
cptFontStyle = "font-style"
cptDisplay = "display"
cptContent = "content"
cptWhiteSpace = "white-space"
cptFontWeight = "font-weight"
cptTextDecoration = "text-decoration"
cptWordBreak = "word-break"
cptWidth = "width"
cptHeight = "height"
cptListStyleType = "list-style-type"
cptPaddingTop = "padding-top"
cptPaddingLeft = "padding-left"
cptPaddingRight = "padding-right"
cptPaddingBottom = "padding-bottom"
cptVerticalAlign = "vertical-align"
cptLineHeight = "line-height"
cptTextAlign = "text-align"
cptListStylePosition = "list-style-position"
cptBackgroundColor = "background-color"
cptPosition = "position"
cptLeft = "left"
cptRight = "right"
cptTop = "top"
cptBottom = "bottom"
cptCaptionSide = "caption-side"
cptBorderSpacing = "border-spacing"
cptBorderCollapse = "border-collapse"
cptQuotes = "quotes"
cptCounterReset = "counter-reset"
cptMaxWidth = "max-width"
cptMaxHeight = "max-height"
cptMinWidth = "min-width"
cptMinHeight = "min-height"
cptBackgroundImage = "background-image"
cptChaColspan = "-cha-colspan"
cptChaRowspan = "-cha-rowspan"
cptFloat = "float"
cptVisibility = "visibility"
cptBoxSizing = "box-sizing"
cptClear = "clear"
cptTextTransform = "text-transform"
cptBgcolorIsCanvas = "-cha-bgcolor-is-canvas"
cptFlexDirection = "flex-direction"
cptFlexWrap = "flex-wrap"
cptFlexGrow = "flex-grow"
cptFlexShrink = "flex-shrink"
cptFlexBasis = "flex-basis"
cptOverflow = "overflow"
CSSValueType* = enum
cvtNone = ""
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
cgtNoglobal = ""
cgtInitial = "initial"
cgtInherit = "inherit"
cgtRevert = "revert"
cgtUnset = "unset"
CSSDisplay* = enum
DisplayNone = "none"
DisplayInline = "inline"
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 = ""
DisplayInlineTableWrapper = ""
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"
CSSWordBreak* = enum
WordBreakNormal = "normal"
WordBreakBreakAll = "break-all"
WordBreakKeepAll = "keep-all"
CSSListStyleType* = enum
ListStyleTypeNone = "none"
ListStyleTypeDisc = "disc"
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, ContentImage,
ContentVideo, ContentAudio, ContentNewline
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"
type
CSSLength* = object
num*: float64
unit*: CSSUnit
auto*: bool
CSSVerticalAlign* = object
length*: CSSLength
keyword*: CSSVerticalAlign2
CSSContent* = object
t*: CSSContentType
s*: string
bmp*: Bitmap
CSSQuotes* = object
auto*: bool
qs*: seq[tuple[s, e: string]]
CSSCounterReset* = object
name*: string
num*: int
CSSComputedValue* = ref object
case v*: CSSValueType
of cvtColor:
color*: CellColor
of cvtLength:
length*: CSSLength
of cvtFontStyle:
fontStyle*: CSSFontStyle
of cvtDisplay:
display*: CSSDisplay
of cvtContent:
content*: seq[CSSContent]
of cvtQuotes:
quotes*: CSSQuotes
of cvtWhiteSpace:
whiteSpace*: CSSWhiteSpace
of cvtInteger:
integer*: int
of cvtNumber:
number*: float64
of cvtTextDecoration:
textDecoration*: set[CSSTextDecoration]
of cvtWordBreak:
wordBreak*: CSSWordBreak
of cvtListStyleType:
listStyleType*: CSSListStyleType
of cvtVerticalAlign:
verticalAlign*: CSSVerticalAlign
of cvtTextAlign:
textAlign*: CSSTextAlign
of cvtListStylePosition:
listStylePosition*: CSSListStylePosition
of cvtPosition:
position*: CSSPosition
of cvtCaptionSide:
captionSide*: CSSCaptionSide
of cvtLength2:
length2*: tuple[a, b: CSSLength]
of cvtBorderCollapse:
borderCollapse*: CSSBorderCollapse
of cvtCounterReset:
counterReset*: seq[CSSCounterReset]
of cvtImage:
image*: CSSContent
of cvtFloat:
float*: CSSFloat
of cvtVisibility:
visibility*: CSSVisibility
of cvtBoxSizing:
boxSizing*: CSSBoxSizing
of cvtClear:
clear*: CSSClear
of cvtTextTransform:
textTransform*: CSSTextTransform
of cvtBgcolorIsCanvas:
bgcolorIsCanvas*: bool
of cvtFlexDirection:
flexDirection*: CSSFlexDirection
of cvtFlexWrap:
flexWrap*: CSSFlexWrap
of cvtOverflow:
overflow*: CSSOverflow
of cvtNone: discard
CSSComputedValues* = ref array[CSSPropertyType, CSSComputedValue]
CSSOrigin* = enum
coUserAgent
coUser
coAuthor
CSSComputedEntry* = tuple
t: CSSPropertyType
val: CSSComputedValue
global: CSSGlobalType
const ShorthandNames = block:
var tab = initTable[string, CSSShorthandType]()
for t in CSSShorthandType:
if $t != "":
tab[$t] = t
tab
const PropertyNames = block:
var tab = initTable[string, CSSPropertyType]()
for t in CSSPropertyType:
if $t != "":
tab[$t] = t
tab
const ValueTypes = [
cptNone: cvtNone,
cptColor: cvtColor,
cptMarginTop: cvtLength,
cptMarginLeft: cvtLength,
cptMarginRight: cvtLength,
cptMarginBottom: cvtLength,
cptFontStyle: cvtFontStyle,
cptDisplay: cvtDisplay,
cptContent: cvtContent,
cptWhiteSpace: cvtWhiteSpace,
cptFontWeight: cvtInteger,
cptTextDecoration: cvtTextDecoration,
cptWordBreak: cvtWordBreak,
cptWidth: cvtLength,
cptHeight: cvtLength,
cptListStyleType: cvtListStyleType,
cptPaddingTop: cvtLength,
cptPaddingLeft: cvtLength,
cptPaddingRight: cvtLength,
cptPaddingBottom: cvtLength,
cptVerticalAlign: cvtVerticalAlign,
cptLineHeight: cvtLength,
cptTextAlign: cvtTextAlign,
cptListStylePosition: cvtListStylePosition,
cptBackgroundColor: cvtColor,
cptPosition: cvtPosition,
cptLeft: cvtLength,
cptRight: cvtLength,
cptTop: cvtLength,
cptBottom: cvtLength,
cptCaptionSide: cvtCaptionSide,
cptBorderSpacing: cvtLength2,
cptBorderCollapse: cvtBorderCollapse,
cptQuotes: cvtQuotes,
cptCounterReset: cvtCounterReset,
cptMaxWidth: cvtLength,
cptMaxHeight: cvtLength,
cptMinWidth: cvtLength,
cptMinHeight: cvtLength,
cptBackgroundImage: cvtImage,
cptChaColspan: cvtInteger,
cptChaRowspan: cvtInteger,
cptFloat: cvtFloat,
cptVisibility: cvtVisibility,
cptBoxSizing: cvtBoxSizing,
cptClear: cvtClear,
cptTextTransform: cvtTextTransform,
cptBgcolorIsCanvas: cvtBgcolorIsCanvas,
cptFlexDirection: cvtFlexDirection,
cptFlexWrap: cvtFlexWrap,
cptFlexGrow: cvtNumber,
cptFlexShrink: cvtNumber,
cptFlexBasis: cvtLength,
cptOverflow: cvtOverflow
]
const InheritedProperties = {
cptColor, cptFontStyle, cptWhiteSpace, cptFontWeight, cptTextDecoration,
cptWordBreak, cptListStyleType, cptLineHeight, cptTextAlign,
cptListStylePosition, cptCaptionSide, cptBorderSpacing, cptBorderCollapse,
cptQuotes, cptVisibility, cptTextTransform
}
func shorthandType(s: string): CSSShorthandType =
return ShorthandNames.getOrDefault(s.toLowerAscii(), cstNone)
func propertyType(s: string): CSSPropertyType =
return PropertyNames.getOrDefault(s.toLowerAscii(), cptNone)
func valueType(prop: CSSPropertyType): CSSValueType =
return ValueTypes[prop]
func isSupportedProperty*(s: string): bool =
return s in PropertyNames
func `$`*(length: CSSLength): string =
if length.auto:
return "auto"
return $length.num & $length.unit
func `$`*(content: CSSContent): string =
if content.s != "":
return "url(" & content.s & ")"
return "none"
func `$`(quotes: CSSQuotes): string =
if quotes.auto:
return "auto"
return "auto" #TODO
func `$`(counterreset: seq[CSSCounterReset]): string =
result = ""
for it in counterreset:
result &= $it.name
result &= ' '
result &= $it.num
func `$`*(val: CSSComputedValue): string =
case val.v
of cvtNone: return "none"
of cvtColor: return $val.color
of cvtImage: return $val.image
of cvtLength: return $val.length
of cvtDisplay: return $val.display
of cvtFontStyle: return $val.fontStyle
of cvtWhiteSpace: return $val.whiteSpace
of cvtInteger: return $val.integer
of cvtTextDecoration: return $val.textDecoration
of cvtWordBreak: return $val.wordBreak
of cvtListStyleType: return $val.listStyleType
of cvtVerticalAlign: return $val.verticalAlign
of cvtTextAlign: return $val.textAlign
of cvtListStylePosition: return $val.listStylePosition
of cvtPosition: return $val.position
of cvtCaptionSide: return $val.captionSide
of cvtLength2: return $val.length2.a & " " & $val.length2.b
of cvtBorderCollapse: return $val.borderCollapse
of cvtContent: return $val.content
of cvtQuotes: return $val.quotes
of cvtCounterReset: return $val.counterReset
of cvtFloat: return $val.float
of cvtVisibility: return $val.visibility
of cvtBoxSizing: return $val.boxSizing
of cvtClear: return $val.clear
of cvtTextTransform: return $val.textTransform
of cvtBgcolorIsCanvas: return $val.bgcolorIsCanvas
of cvtFlexDirection: return $val.flexDirection
of cvtFlexWrap: return $val.flexWrap
of cvtOverflow: return $val.overflow
of cvtNumber: return $val.number
macro `{}`*(vals: CSSComputedValues; s: static string): untyped =
let t = propertyType(s)
let vs = ident($valueType(t))
return quote do:
`vals`[CSSPropertyType(`t`)].`vs`
macro `{}=`*(vals: CSSComputedValues; s: static string, val: typed) =
let t = propertyType(s)
let v = valueType(t)
let vs = ident($v)
return quote do:
`vals`[CSSPropertyType(`t`)] = CSSComputedValue(
v: CSSValueType(`v`),
`vs`: `val`
)
func inherited*(t: CSSPropertyType): bool =
return t in InheritedProperties
func em_to_px(em: float64; window: WindowAttributes): LayoutUnit =
(em * float64(window.ppl)).toLayoutUnit()
func ch_to_px(ch: float64; window: WindowAttributes): LayoutUnit =
(ch * float64(window.ppc)).toLayoutUnit()
# 水 width, we assume it's 2 chars
func ic_to_px(ic: float64; window: WindowAttributes): LayoutUnit =
(ic * float64(window.ppc) * 2).toLayoutUnit()
# x-letter height, we assume it's em/2
func ex_to_px(ex: float64; window: WindowAttributes): LayoutUnit =
(ex * float64(window.ppc) / 2).toLayoutUnit()
func px*(l: CSSLength; window: WindowAttributes; p: LayoutUnit): LayoutUnit =
case l.unit
of cuEm, cuRem: em_to_px(l.num, window)
of cuCh: ch_to_px(l.num, window)
of cuIc: ic_to_px(l.num, window)
of cuEx: ex_to_px(l.num, window)
of cuPerc: toLayoutUnit(toFloat64(p) * l.num / 100)
of cuPx: toLayoutUnit(l.num)
of cuCm: toLayoutUnit(l.num * 37.8)
of cuMm: toLayoutUnit(l.num * 3.78)
of cuIn: toLayoutUnit(l.num * 96)
of cuPc: toLayoutUnit(l.num * 16)
of cuPt: toLayoutUnit(l.num * 4 / 3)
of cuVw: toLayoutUnit(float64(window.width_px) * l.num / 100)
of cuVh: toLayoutUnit(float64(window.height_px) * l.num / 100)
of cuVmin:
toLayoutUnit(min(window.width_px, window.width_px) / 100 * l.num)
of cuVmax:
toLayoutUnit(max(window.width_px, window.width_px) / 100 * l.num)
func blockify*(display: CSSDisplay): CSSDisplay =
case display
of DisplayBlock, DisplayTable, DisplayListItem, DisplayNone, DisplayFlowRoot,
DisplayFlex, DisplayTableWrapper, DisplayInlineTableWrapper:
#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
const UpperAlphaMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toRunes()
const LowerAlphaMap = "abcdefghijklmnopqrstuvwxyz".toRunes()
const LowerGreekMap = "αβγδεζηθικλμνξοπρστυφχψω".toRunes()
const HiraganaMap = ("あいうえおかきくけこさしすせそたちつてとなにぬねの" &
"はひふへほまみむめもやゆよらりるれろわゐゑをん").toRunes()
const HiraganaIrohaMap = ("いろはにほへとちりぬるをわかよたれそつねならむ" &
"うゐのおくやまけふこえてあさきゆめみしゑひもせす").toRunes()
const KatakanaMap = ("アイウエオカキクケコサシスセソタチツテトナニヌネノ" &
"ハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン").toRunes()
const KatakanaIrohaMap = ("イロハニホヘトチリヌルヲワカヨタレソツネナラム" &
"ウヰノオクヤマケフコエテアサキユメミシヱヒモセス").toRunes()
const EarthlyBranchMap = "子丑寅卯辰巳午未申酉戌亥".toRunes()
const HeavenlyStemMap = "甲乙丙丁戊己庚辛壬癸".toRunes()
func numToBase(n: int; map: openArray[Rune]): string =
if n <= 0:
return $n
var tmp: seq[Rune]
var n = n
while n != 0:
n -= 1
tmp &= map[n mod map.len]
n = n div map.len
result = ""
for i in countdown(tmp.high, 0):
result &= $tmp[i]
func numToFixed(n: int; map: openArray[Rune]): 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
if i < 0:
result &= "マイナス"
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
n = ss.len - 1
while n >= 0:
result &= ss[n]
dec n
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) & "、"
#TODO this should change by language
func quoteStart*(level: int): string =
if level == 0:
return "“"
return "‘"
func quoteEnd*(level: int): string =
if level == 0:
return "“"
return "‘"
const Colors: Table[string, ARGBColor] = ((func (): Table[string, ARGBColor] =
for name, rgb in ColorsRGB:
result[name] = rgb
result["transparent"] = rgba(0x00, 0x00, 0x00, 0x00)
)())
template isToken(cval: CSSComponentValue): bool =
cval of CSSToken
template getToken(cval: CSSComponentValue): CSSToken =
CSSToken(cval)
func parseIdent(map: openArray[IdentMapItem]; cval: CSSComponentValue):
Opt[int] =
if isToken(cval):
let tok = getToken(cval)
if tok.tokenType == cttIdent:
return map.parseEnumNoCase0(tok.value)
return err()
func parseIdent[T: enum](cval: CSSComponentValue): Opt[T] =
const IdentMap = getIdentMap(T)
return ok(cast[T](?IdentMap.parseIdent(cval)))
func cssLength(val: float64; unit: string): Opt[CSSLength] =
let u = ?parseEnumNoCase[CSSUnit](unit)
return ok(CSSLength(num: val, unit: u))
const CSSLengthAuto* = CSSLength(auto: true)
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 += float64(decValue(s[i]))
inc i
if i >= s.len:
return some(CSSLength(num: n, unit: cuPx))
if s[i] == '.':
inc i
if i >= s.len:
return some(CSSLength(num: n, unit: cuPx))
var d = 1
while i < s.len and s[i] in AsciiDigit:
n += float64(decValue(s[i])) / float64(d)
inc d
inc i
if i < s.len and s[i] == '%':
return some(CSSLength(num: n, unit: cuPerc))
return some(CSSLength(num: n, unit: cuPx))
func skipWhitespace(vals: openArray[CSSComponentValue]; i: var int) =
while i < vals.len:
if vals[i] != cttWhitespace:
break
inc i
func parseARGB(value: openArray[CSSComponentValue]): Opt[CellColor] =
var i = 0
var commaMode = false
template check_err(slash: bool) =
#TODO calc, percentages, etc (cssnumber function or something)
if not slash and i >= value.len or i < value.len and
value[i] != cttNumber:
return err()
template next_value(first = false, slash = false) =
inc i
value.skipWhitespace(i)
if i < value.len:
if value[i] == cttComma and (commaMode or first):
# legacy compatibility
inc i
value.skipWhitespace(i)
commaMode = true
elif commaMode:
return err()
elif slash:
let tok = value[i]
if tok != cttDelim or CSSToken(tok).cvalue != '/':
return err()
inc i
value.skipWhitespace(i)
check_err slash
value.skipWhitespace(i)
check_err false
let r = clamp(CSSToken(value[i]).nvalue, 0, 255)
next_value true
let g = clamp(CSSToken(value[i]).nvalue, 0, 255)
next_value
let b = clamp(CSSToken(value[i]).nvalue, 0, 255)
next_value false, true
let a = if i < value.len:
clamp(CSSToken(value[i]).nvalue, 0, 1)
else:
1
value.skipWhitespace(i)
if i < value.len:
return err()
return ok(rgba(int(r), int(g), int(b), int(a * 255)).cellColor())
# 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[CellColor] =
var i = 0
value.skipWhitespace(i)
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.tokenType == cttNumber:
if tok.tflagb != tflagbInteger or int(tok.nvalue) notin 0..255:
return err() # invalid numeric ANSI color
return ok(ANSIColor(tok.nvalue).cellColor())
elif tok.tokenType == cttIdent:
var name = tok.value
if name.equalsIgnoreCase("default"):
return ok(defaultColor)
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:
if it.equalsIgnoreCase(name):
var i = int(i)
if bright:
i += 8
return ok(ANSIColor(i).cellColor())
return err()
func cssColor*(val: CSSComponentValue): Opt[CellColor] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.tokenType
of cttHash:
let c = parseHexColor(tok.value)
if c.isSome:
return ok(c.get.cellColor())
of cttIdent:
let s = tok.value.toLowerAscii()
if s in Colors:
return ok(Colors[s].cellColor())
else: discard
elif val of CSSFunction:
let f = CSSFunction(val)
if f.name.equalsIgnoreCase("rgb") or f.name.equalsIgnoreCase("rgba"):
return parseARGB(f.value)
elif f.name.equalsIgnoreCase("-cha-ansi"):
return parseANSI(f.value)
return err()
func cssLength*(val: CSSComponentValue; has_auto = true; allow_negative = true):
Opt[CSSLength] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.tokenType
of cttNumber:
if tok.nvalue == 0:
return ok(CSSLength(num: 0, unit: cuPx))
of cttPercentage:
if not allow_negative:
if tok.nvalue < 0:
return err()
return cssLength(tok.nvalue, "%")
of cttDimension:
if not allow_negative:
if tok.nvalue < 0:
return err()
return cssLength(tok.nvalue, tok.unit)
of cttIdent:
if has_auto:
if tok.value.equalsIgnoreCase("auto"):
return ok(CSSLengthAuto)
else: discard
return err()
func cssAbsoluteLength(val: CSSComponentValue): Opt[CSSLength] =
if val of CSSToken:
let tok = CSSToken(val)
case tok.tokenType
of cttNumber:
if tok.nvalue == 0:
return ok(CSSLength(num: 0, unit: cuPx))
of cttDimension:
if tok.nvalue >= 0:
return cssLength(tok.nvalue, tok.unit)
else: discard
return err()
func cssGlobal(cval: CSSComponentValue): CSSGlobalType =
return parseIdent[CSSGlobalType](cval).get(cgtNoglobal)
func cssQuotes(cvals: openArray[CSSComponentValue]): Opt[CSSQuotes] =
template die =
return err()
if cvals.len == 0:
die
var res: CSSQuotes
var sa = false
var pair: tuple[s, e: string]
for cval in cvals:
if res.auto: die
if isToken(cval):
let tok = getToken(cval)
case tok.tokenType
of cttIdent:
if res.qs.len > 0: die
if tok.value.equalsIgnoreCase("auto"):
res.auto = true
elif tok.value.equalsIgnoreCase("none"):
if cvals.len != 1:
die
die
of cttString:
if sa:
pair.e = tok.value
res.qs.add(pair)
sa = false
else:
pair.s = tok.value
sa = true
of cttWhitespace: discard
else: die
if sa:
die
return ok(res)
func cssContent(cvals: openArray[CSSComponentValue]): seq[CSSContent] =
for cval in cvals:
if isToken(cval):
let tok = getToken(cval)
case tok.tokenType
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: tok.value))
else: return
func cssFontWeight(cval: CSSComponentValue): Opt[int] =
if isToken(cval):
let tok = getToken(cval)
if tok.tokenType == cttIdent:
const FontWeightMap = {
"normal": 400,
"bold": 700,
"lighter": 400,
"bolder": 700
}
return FontWeightMap.parseIdent(cval)
elif tok.tokenType == cttNumber:
if tok.nvalue in 1f64..1000f64:
return ok(int(tok.nvalue))
return err()
func cssTextDecoration(cvals: openArray[CSSComponentValue]):
Opt[set[CSSTextDecoration]] =
var s: set[CSSTextDecoration] = {}
for cval in cvals:
if not isToken(cval):
continue
let tok = getToken(cval)
if tok.tokenType == 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): Opt[CSSVerticalAlign] =
if isToken(cval):
let tok = getToken(cval)
if tok.tokenType == cttIdent:
let va2 = ?parseIdent[CSSVerticalAlign2](cval)
return ok(CSSVerticalAlign(keyword: va2))
else:
return ok(CSSVerticalAlign(
keyword: VerticalAlignBaseline,
length: ?cssLength(tok, has_auto = false)
))
return err()
func cssLineHeight(cval: CSSComponentValue): Opt[CSSLength] =
if cval of CSSToken:
let tok = CSSToken(cval)
case tok.tokenType
of cttNumber:
return cssLength(tok.nvalue * 100, "%")
of cttIdent:
if tok.value == "normal":
return ok(CSSLengthAuto)
else:
return cssLength(tok, has_auto = false)
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 isToken(cval):
let tok = getToken(cval)
case tok.tokenType
of cttWhitespace: discard
of cttIdent:
if s:
die
r.name = tok.value
s = true
of cttNumber:
if not s:
die
r.num = int(tok.nvalue)
res.add(r)
s = false
else:
die
return ok(res)
func cssMaxMinSize(cval: CSSComponentValue): Opt[CSSLength] =
if isToken(cval):
let tok = getToken(cval)
case tok.tokenType
of cttIdent:
if tok.value.equalsIgnoreCase("none"):
return ok(CSSLengthAuto)
of cttNumber, cttDimension, cttPercentage:
return cssLength(tok, allow_negative = false)
else: discard
return err()
#TODO should be URL (parsed with baseurl of document...)
func cssURL(cval: CSSComponentValue): Option[string] =
if isToken(cval):
let tok = getToken(cval)
if tok == cttUrl:
return some(tok.value)
elif cval of CSSFunction:
let fun = CSSFunction(cval)
if fun.name.equalsIgnoreCase("url") or fun.name.equalsIgnoreCase("src"):
for x in fun.value:
if not isToken(x):
break
let x = getToken(x)
if x == cttWhitespace:
discard
elif x == cttString:
return some(x.value)
else:
break
#TODO this should be bg-image, add gradient, etc etc
func cssImage(cval: CSSComponentValue): Opt[CSSContent] =
if isToken(cval):
#TODO bg-image only
let tok = getToken(cval)
if tok.tokenType == cttIdent and tok.value == "none":
return ok(CSSContent(t: ContentImage, s: ""))
let url = cssURL(cval)
if url.isSome:
return ok(CSSContent(t: ContentImage, s: url.get))
return err()
func cssInteger(cval: CSSComponentValue; range: Slice[int]): Opt[int] =
if isToken(cval):
let tok = getToken(cval)
if tok.tokenType == cttNumber:
if tok.nvalue in float64(range.a)..float64(range.b):
return ok(int(tok.nvalue))
return err()
func cssNumber(cval: CSSComponentValue; positive: bool): Opt[float64] =
if isToken(cval):
let tok = getToken(cval)
if tok.tokenType == cttNumber:
if not positive or tok.nvalue >= 0:
return ok(tok.nvalue)
return err()
proc parseValue(cvals: openArray[CSSComponentValue]; t: CSSPropertyType):
Opt[CSSComputedValue] =
var i = 0
cvals.skipWhitespace(i)
if i >= cvals.len:
return err()
let cval = cvals[i]
inc i
let v = valueType(t)
template return_new(prop, val: untyped) =
return ok(CSSComputedValue(v: v, prop: val))
case v
of cvtColor: return_new color, ?cssColor(cval)
of cvtLength:
case t
of cptLineHeight:
return_new length, ?cssLineHeight(cval)
of cptMaxWidth, cptMaxHeight, cptMinWidth, cptMinHeight:
return_new length, ?cssMaxMinSize(cval)
of cptPaddingLeft, cptPaddingRight, cptPaddingTop, cptPaddingBottom:
return_new length, ?cssLength(cval, has_auto = false)
#TODO content for flex-basis
else:
return_new length, ?cssLength(cval)
of cvtFontStyle: return_new fontStyle, ?parseIdent[CSSFontStyle](cval)
of cvtDisplay: return_new display, ?parseIdent[CSSDisplay](cval)
of cvtContent: return_new content, cssContent(cvals)
of cvtWhiteSpace: return_new whiteSpace, ?parseIdent[CSSWhiteSpace](cval)
of cvtInteger:
case t
of cptFontWeight: return_new integer, ?cssFontWeight(cval)
of cptChaColspan: return_new integer, ?cssInteger(cval, 1 .. 1000)
of cptChaRowspan: return_new integer, ?cssInteger(cval, 0 .. 65534)
else: assert false
of cvtTextDecoration: return_new textdecoration, ?cssTextDecoration(cvals)
of cvtWordBreak: return_new wordBreak, ?parseIdent[CSSWordBreak](cval)
of cvtListStyleType:
return_new liststyletype, ?parseIdent[CSSListStyleType](cval)
of cvtVerticalAlign: return_new verticalAlign, ?cssVerticalAlign(cval)
of cvtTextAlign: return_new textAlign, ?parseIdent[CSSTextAlign](cval)
of cvtListStylePosition:
return_new listStylePosition, ?parseIdent[CSSListStylePosition](cval)
of cvtPosition: return_new position, ?parseIdent[CSSPosition](cval)
of cvtCaptionSide: return_new captionSide, ?parseIdent[CSSCaptionSide](cval)
of cvtBorderCollapse:
return_new borderCollapse, ?parseIdent[CSSBorderCollapse](cval)
of cvtLength2:
let a = ?cssAbsoluteLength(cval)
cvals.skipWhitespace(i)
let b = if i >= cvals.len: a else: ?cssAbsoluteLength(cvals[i])
return_new length2, (a, b)
of cvtQuotes: return_new quotes, ?cssQuotes(cvals)
of cvtCounterReset: return_new counterReset, ?cssCounterReset(cvals)
of cvtImage: return_new image, ?cssImage(cval)
of cvtFloat: return_new float, ?parseIdent[CSSFloat](cval)
of cvtVisibility: return_new visibility, ?parseIdent[CSSVisibility](cval)
of cvtBoxSizing: return_new boxSizing, ?parseIdent[CSSBoxSizing](cval)
of cvtClear: return_new clear, ?parseIdent[CSSClear](cval)
of cvtTextTransform:
return_new textTransform, ?parseIdent[CSSTextTransform](cval)
of cvtBgcolorIsCanvas: return err() # internal value
of cvtFlexDirection:
return_new flexDirection, ?parseIdent[CSSFlexDirection](cval)
of cvtFlexWrap: return_new flexWrap, ?parseIdent[CSSFlexWrap](cval)
of cvtNumber: return_new number, ?cssNumber(cval, t == cptFlexGrow)
of cvtOverflow: return_new overflow, ?parseIdent[CSSOverflow](cval)
of cvtNone: return err()
func getInitialColor(t: CSSPropertyType): CellColor =
if t == cptBackgroundColor:
return Colors["transparent"].cellColor()
return defaultColor
func getInitialLength(t: CSSPropertyType): CSSLength =
case t
of cptWidth, cptHeight, cptLineHeight, cptLeft, cptRight, cptTop, cptBottom,
cptMaxWidth, cptMaxHeight, cptMinWidth, cptMinHeight, cptFlexBasis:
return CSSLengthAuto
else:
return CSSLength(auto: false, unit: cuPx, num: 0)
func getInitialInteger(t: CSSPropertyType): int =
case t
of cptChaColspan, cptChaRowspan:
return 1
of cptFontWeight:
return 400 # normal
else:
return 0
func getInitialNumber(t: CSSPropertyType): float64 =
if t == cptFlexShrink:
return 1
return 0
func calcInitial(t: CSSPropertyType): CSSComputedValue =
let v = valueType(t)
var nv: CSSComputedValue
case v
of cvtColor:
nv = CSSComputedValue(v: v, color: getInitialColor(t))
of cvtDisplay:
nv = CSSComputedValue(v: v, display: DisplayInline)
of cvtWordBreak:
nv = CSSComputedValue(v: v, wordbreak: WordBreakNormal)
of cvtLength:
nv = CSSComputedValue(v: v, length: getInitialLength(t))
of cvtInteger:
nv = CSSComputedValue(v: v, integer: getInitialInteger(t))
of cvtQuotes:
nv = CSSComputedValue(v: v, quotes: CSSQuotes(auto: true))
of cvtNumber:
nv = CSSComputedValue(v: v, number: getInitialNumber(t))
else:
nv = CSSComputedValue(v: v)
return nv
func getInitialTable(): array[CSSPropertyType, CSSComputedValue] =
for t in CSSPropertyType:
result[t] = calcInitial(t)
let defaultTable = getInitialTable()
template getDefault*(t: CSSPropertyType): CSSComputedValue =
{.cast(noSideEffect).}:
defaultTable[t]
func lengthShorthand(cvals: openArray[CSSComponentValue];
props: array[4, CSSPropertyType]; global: CSSGlobalType; has_auto = true):
Opt[seq[CSSComputedEntry]] =
var res: seq[CSSComputedEntry] = @[]
if global != cgtNoglobal:
for t in props:
res.add((t, nil, global))
return ok(res)
var lengths: seq[CSSComputedValue] = @[]
var i = 0
while i < cvals.len:
cvals.skipWhitespace(i)
let length = ?cssLength(cvals[i], has_auto = has_auto)
let val = CSSComputedValue(v: cvtLength, length: length)
lengths.add(val)
inc i
case lengths.len
of 1: # top, bottom, left, right
for i, t in props:
res.add((t, lengths[0], cgtNoglobal))
of 2: # top, bottom | left, right
for i, t in props:
res.add((t, lengths[i mod 2], cgtNoglobal))
of 3: # top | left, right | bottom
for i, t in props:
let j = if i == 0:
0 # top
elif i == 3:
2 # bottom
else:
1 # left, right
res.add((t, lengths[j], cgtNoglobal))
of 4: # top | right | bottom | left
for i, t in props:
res.add((t, lengths[i], cgtNoglobal))
else:
return err()
return ok(res)
const PropertyMarginSpec = [
cptMarginTop, cptMarginRight, cptMarginBottom, cptMarginLeft
]
const PropertyPaddingSpec = [
cptPaddingTop, cptPaddingRight, cptPaddingBottom, cptPaddingLeft
]
proc parseComputedValues*(res: var seq[CSSComputedEntry]; name: string;
cvals: openArray[CSSComponentValue]): Err[void] =
var i = 0
cvals.skipWhitespace(i)
if i >= cvals.len:
return err()
let global = cssGlobal(cvals[i])
case shorthandType(name)
of cstNone:
let t = propertyType(name)
if global != cgtNoglobal:
res.add((t, nil, global))
else:
res.add((t, ?cvals.parseValue(t), global))
of cstAll:
if global == cgtNoglobal:
return err()
for t in CSSPropertyType:
res.add((t, nil, global))
of cstMargin:
res.add(?lengthShorthand(cvals, PropertyMarginSpec, global))
of cstPadding:
res.add(?lengthShorthand(cvals, PropertyPaddingSpec, global,
has_auto = false))
of cstBackground:
var bgcolorval = getDefault(cptBackgroundColor)
var bgimageval = getDefault(cptBackgroundImage)
var valid = true
if global == cgtNoglobal:
for tok in cvals:
if tok == cttWhitespace:
continue
if (let r = cssImage(tok); r.isSome):
bgimageval = CSSComputedValue(v: cvtImage, image: r.get)
elif (let r = cssColor(tok); r.isSome):
bgcolorval = CSSComputedValue(v: cvtColor, color: r.get)
else:
#TODO when we implement the other shorthands too
#valid = false
discard
if valid:
res.add((cptBackgroundColor, bgcolorval, global))
res.add((cptBackgroundImage, bgimageval, global))
of cstListStyle:
var positionVal = getDefault(cptListStylePosition)
var typeVal = getDefault(cptListStyleType)
var valid = true
if global == cgtNoglobal:
for tok in cvals:
if tok == cttWhitespace:
continue
if (let r = parseIdent[CSSListStylePosition](tok); r.isSome):
positionVal = CSSComputedValue(
v: cvtListStylePosition,
liststyleposition: r.get
)
elif (let r = parseIdent[CSSListStyleType](tok); r.isSome):
typeVal = CSSComputedValue(
v: cvtListStyleType,
liststyletype: r.get
)
else:
#TODO list-style-image
#valid = false
discard
if valid:
res.add((cptListStylePosition, positionVal, global))
res.add((cptListStyleType, typeVal, global))
of cstFlex:
if global == cgtNoglobal:
var i = 0
cvals.skipWhitespace(i)
if i >= cvals.len:
return err()
if (let r = cssNumber(cvals[i], positive = true); r.isSome):
# flex-grow
let val = CSSComputedValue(v: cvtNumber, number: r.get)
res.add((cptFlexGrow, val, global))
inc i
cvals.skipWhitespace(i)
if i < cvals.len:
if not cvals[i].isToken:
return err()
if (let r = cssNumber(cvals[i], positive = true); r.isSome):
# flex-shrink
let val = CSSComputedValue(v: cvtNumber, number: r.get)
res.add((cptFlexShrink, val, global))
inc i
cvals.skipWhitespace(i)
if res.len < 1: # flex-grow omitted, default to 1
let val = CSSComputedValue(v: cvtNumber, number: 1)
res.add((cptFlexGrow, val, global))
if res.len < 2: # flex-shrink omitted, default to 1
let val = CSSComputedValue(v: cvtNumber, number: 1)
res.add((cptFlexShrink, val, global))
if i < cvals.len:
# flex-basis
let val = CSSComputedValue(v: cvtLength, length: ?cssLength(cvals[i]))
res.add((cptFlexBasis, val, global))
else: # omitted, default to 0px
let val = CSSComputedValue(
v: cvtLength,
length: CSSLength(unit: cuPx, num: 0)
)
res.add((cptFlexBasis, val, global))
else:
res.add((cptFlexGrow, getDefault(cptFlexGrow), global))
res.add((cptFlexShrink, getDefault(cptFlexShrink), global))
res.add((cptFlexBasis, getDefault(cptFlexBasis), global))
of cstFlexFlow:
if global == cgtNoglobal:
var i = 0
cvals.skipWhitespace(i)
if i >= cvals.len:
return err()
if (let dir = parseIdent[CSSFlexDirection](cvals[i]); dir.isSome):
# flex-direction
let val = CSSComputedValue(v: cvtFlexDirection, flexdirection: dir.get)
res.add((cptFlexDirection, val, global))
inc i
cvals.skipWhitespace(i)
if i < cvals.len:
let wrap = ?parseIdent[CSSFlexWrap](cvals[i])
let val = CSSComputedValue(v: cvtFlexWrap, flexwrap: wrap)
res.add((cptFlexWrap, val, global))
else:
res.add((cptFlexDirection, getDefault(cptFlexDirection), global))
res.add((cptFlexWrap, getDefault(cptFlexWrap), global))
return ok()
proc parseComputedValues*(name: string; value: seq[CSSComponentValue]):
seq[CSSComputedEntry] =
var res: seq[CSSComputedEntry] = @[]
if res.parseComputedValues(name, value).isSome:
return res
return @[]
proc applyValue*(vals: CSSComputedValues; entry: CSSComputedEntry;
parent, previousOrigin: CSSComputedValues) =
let parentVal = if parent != nil:
parent[entry.t]
else:
nil
case entry.global
of cgtInherit:
if parentVal != nil:
vals[entry.t] = parentVal
else:
vals[entry.t] = getDefault(entry.t)
of cgtInitial:
vals[entry.t] = getDefault(entry.t)
of cgtUnset:
if inherited(entry.t):
# inherit
if parentVal != nil:
vals[entry.t] = parentVal
else:
vals[entry.t] = getDefault(entry.t)
else:
# initial
vals[entry.t] = getDefault(entry.t)
of cgtRevert:
if previousOrigin != nil:
vals[entry.t] = previousOrigin[entry.t]
else:
vals[entry.t] = getDefault(entry.t)
of cgtNoglobal:
vals[entry.t] = entry.val
func inheritProperties*(parent: CSSComputedValues): CSSComputedValues =
new(result)
for prop in CSSPropertyType:
if inherited(prop) and parent[prop] != nil:
result[prop] = parent[prop]
else:
result[prop] = getDefault(prop)
func copyProperties*(props: CSSComputedValues): CSSComputedValues =
new(result)
result[] = props[]
func rootProperties*(): CSSComputedValues =
new(result)
for prop in CSSPropertyType:
result[prop] = getDefault(prop)
# Separate CSSComputedValues of a table into those of the wrapper and the actual
# table.
func splitTable*(computed: CSSComputedValues):
tuple[outerComputed, innnerComputed: CSSComputedValues] =
var outerComputed, innerComputed: CSSComputedValues
new(outerComputed)
new(innerComputed)
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 prop in CSSPropertyType:
if prop in props:
outerComputed[prop] = computed[prop]
innerComputed[prop] = getDefault(prop)
else:
outerComputed[prop] = getDefault(prop)
innerComputed[prop] = computed[prop]
outerComputed{"display"} = computed{"display"}
return (outerComputed, innerComputed)
|