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
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
use crate::Document;
use crate::layout::damage::HoistedPaintChildren;
use bitflags::bitflags;
use blitz_traits::events::{
BlitzPointerEvent, BlitzPointerId, DomEventData, HitResult, PointerCoords,
};
use blitz_traits::node_id::NodeId;
use blitz_traits::shell::ShellProvider;
use euclid::{Point2D, Rect, Size2D};
use html_escape::encode_quoted_attribute_to_string;
use keyboard_types::Modifiers;
use kurbo::{Affine, Rect as KurboRect};
use markup5ever::{LocalName, local_name};
use parley::{BreakReason, Cluster, ClusterSide, Selection};
use selectors::matching::ElementSelectorFlags;
use std::cell::{Cell, RefCell};
use std::fmt::Write;
use std::ops::{Deref, Range};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use style::Atom;
use style::computed_values::isolation::T as Isolation;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::properties::ComputedValues;
use style::properties::generated::longhands::position::computed_value::T as Position;
use style::selector_parser::{PseudoElement, RestyleDamage};
use style::servo_arc::Arc as ServoArc;
use style::shared_lock::SharedRwLock;
use style::stylesheets::UrlExtraData;
use style::values::computed::CSSPixelLength;
use style::values::computed::Display as StyloDisplay;
use style::values::computed::Rotate;
use style::values::generics::transform::{Scale, Translate};
use style::values::specified::box_::{DisplayInside, DisplayOutside};
use style_dom::ElementState;
use style_traits::values::ToCss;
use taffy::{
Cache,
prelude::{Layout, Style},
};
use thin_vec::ThinVec;
use super::stylo_data::StyloData;
use super::{Attribute, DocumentData, ElementData};
#[derive(Clone, Copy)]
enum OutputStyle {
Normal,
Pretty,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisplayOuter {
Block,
Inline,
None,
}
bitflags! {
#[derive(Clone, Copy, PartialEq)]
pub struct NodeFlags: u32 {
/// Whether the node is the root node of an Inline Formatting Context
const IS_INLINE_ROOT = 0b00000001;
/// Whether the node is the root node of an Table formatting context
const IS_TABLE_ROOT = 0b00000010;
/// Whether the node is "in the document" (~= has a parent and isn't a template node)
const IS_IN_DOCUMENT = 0b00000100;
/// Parser-created scripts remain inert after cloning or adoption.
const IS_PARSER_INERT_SCRIPT = 0b00001000;
}
}
impl NodeFlags {
#[inline(always)]
pub fn is_inline_root(&self) -> bool {
self.contains(Self::IS_INLINE_ROOT)
}
#[inline(always)]
pub fn is_table_root(&self) -> bool {
self.contains(Self::IS_TABLE_ROOT)
}
#[inline(always)]
pub fn is_in_document(&self) -> bool {
self.contains(Self::IS_IN_DOCUMENT)
}
#[inline(always)]
pub fn reset_construction_flags(&mut self) {
self.remove(Self::IS_INLINE_ROOT);
self.remove(Self::IS_TABLE_ROOT);
}
}
pub struct Node {
// The actual tree we belong to. This is unsafe!!
tree: *mut crate::NodeTree,
/// Our Id
pub id: NodeId,
/// Our parent's ID
pub parent: Option<NodeId>,
/// A validated hint into the parent's DOM child list.
///
/// Adjacent traversal seeds the next node's hint, avoiding repeated linear
/// searches while walking an unchanged sibling list. Mutations need not
/// maintain this field: readers always validate it against the child list.
child_index_hint: Cell<usize>,
/// The owning document, including when this node is detached.
/// Document nodes themselves have no owner.
pub owner_document: Option<NodeId>,
/// Non-rendering document syntax, stored independently of layout data.
pub markup: Option<Arc<MarkupNode>>,
/// Script custom element candidates in this shadow-including subtree.
pub custom_element_subtree_count: usize,
// What are our children?
pub children: ThinVec<NodeId>,
/// Our parent in the layout hierachy: a separate list that includes anonymous collections of inline elements
pub layout_parent: Cell<Option<NodeId>>,
/// A separate child list that includes anonymous collections of inline elements
pub layout_children: RefCell<Option<ThinVec<NodeId>>>,
/// Anonymous block boxes created for this node during layout construction.
///
/// Anonymous blocks live only in the slab (they are not part of the DOM
/// `children` list), so we track the ones we own here to be able to
/// deallocate them when this node is reconstructed.
pub anonymous_blocks: ThinVec<NodeId>,
/// The same as layout_children, but sorted by z-index
pub paint_children: RefCell<Option<ThinVec<NodeId>>>,
pub stacking_context: Option<Box<HoistedPaintChildren>>,
/// The "flattened tree" children of this node used for layout and painting,
/// if it differs from [`children`](Self::children). This is set for shadow
/// hosts (where it holds the shadow root's children) and `<slot>` elements
/// (where it holds the light-DOM nodes assigned to the slot). When `None`,
/// [`children`](Self::children) is used directly.
#[cfg(feature = "shadow-dom")]
pub flattened_children: Option<Vec<NodeId>>,
/// Slot assignment belongs to slottable nodes, including text nodes.
#[cfg(feature = "shadow-dom")]
pub assigned_slot: Option<NodeId>,
/// Present only on slots. An empty list is distinct from fallback children.
#[cfg(feature = "shadow-dom")]
pub assigned_nodes: Option<Vec<NodeId>>,
pub(crate) children_to_process: std::sync::atomic::AtomicIsize,
// Flags
pub flags: NodeFlags,
/// Node type (Element, TextNode, etc) specific data.
///
/// For element nodes this holds the [`ElementData`], which stores most of
/// the per-node style/layout state. For the document node it holds the
/// [`DocumentData`]. Access the moved fields through the forwarding methods
/// on [`Node`] (e.g. [`Node::style`], [`Node::final_layout`]).
pub data: NodeData,
}
unsafe impl Send for Node {}
unsafe impl Sync for Node {}
/// Generates forwarding accessors for fields that live on both [`ElementData`]
/// (element / anonymous block nodes) and [`DocumentData`] (the document node).
macro_rules! universal_accessors {
($($(#[$meta:meta])* $field:ident / $field_mut:ident : $ty:ty),* $(,)?) => {
impl Node {
$(
$(#[$meta])*
#[inline]
pub fn $field(&self) -> &$ty {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.$field,
NodeData::Document(data) => &data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
$(#[$meta])*
#[inline]
pub fn $field_mut(&mut self) -> &mut $ty {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.$field,
NodeData::Document(data) => &mut data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
)*
}
};
}
universal_accessors! {
stylo_element_data / stylo_element_data_mut: StyloData,
style / style_mut: Style<Atom>,
style_source / style_source_mut: Option<ServoArc<ComputedValues>>,
subtree_hoists / subtree_hoists_mut: bool,
// `cache` is not here: it is stored as `Option<Box<Cache>>` and reached
// through hand-written accessors below, because the read side has to be
// able to answer without allocating. See `ElementData::cache`.
unrounded_layout / unrounded_layout_mut: Layout,
final_layout / final_layout_mut: Layout,
scroll_offset / scroll_offset_mut: crate::Point<f64>,
scrollable_overflow / scrollable_overflow_mut: KurboRect,
transform / transform_mut: Option<Affine>,
display_constructed_as / display_constructed_as_mut: StyloDisplay,
// The document node is styled/snapshotted like an element, so it also
// carries these:
element_state / element_state_mut: ElementState,
snapshot_handled / snapshot_handled_mut: AtomicBool,
// `apply_selector_flags` deposits `for_parent()` flags on the parent node,
// and the parent of the root <html> element is the document -- so the
// document has to be able to hold selector flags too.
}
impl Node {
pub fn selector_flags(&self) -> &Cell<ElementSelectorFlags> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.selector_flags,
NodeData::Document(data) => &data.selector_flags,
NodeData::ShadowRoot(data) => &data.selector_flags,
_ => panic!("selector flags require a parent node"),
}
}
pub fn selector_flags_mut(&mut self) -> &mut Cell<ElementSelectorFlags> {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.selector_flags,
NodeData::Document(data) => &mut data.selector_flags,
NodeData::ShadowRoot(data) => &mut data.selector_flags,
_ => panic!("selector flags require a parent node"),
}
}
/// This node's taffy layout cache.
///
/// Hand-written rather than generated by `universal_accessors!` because
/// the cache is `Option<Box<Cache>>`: a node that has never been laid out
/// borrows a shared empty one instead of owning 1616 bytes. See the
/// [`cache`](super::ElementData::cache) field for the measurement behind
/// that. The signature is unchanged, so callers cannot tell.
#[inline]
pub fn cache(&self) -> &Cache {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.cache(),
NodeData::Document(data) => data.cache(),
_ => panic!("`cache` is not available on this node kind"),
}
}
/// This node's taffy layout cache, allocating on first use.
#[inline]
pub fn cache_mut(&mut self) -> &mut Cache {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.cache_mut(),
NodeData::Document(data) => data.cache_mut(),
_ => panic!("`cache_mut` is not available on this node kind"),
}
}
/// Release this node's layout cache, returning its memory.
#[inline]
pub fn cache_release(&mut self) {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.cache_release(),
NodeData::Document(data) => data.cache_release(),
_ => {}
}
}
/// Style data from stylo, if this node kind carries it (element or document
/// nodes). Returns `None` for text/comment nodes.
/// The computed values the cached taffy style was built from, for node
/// kinds that carry one. `None` for text and comment nodes, which are never
/// styled, so a caller can ask without knowing the kind.
#[inline]
pub fn style_source_opt(&self) -> Option<&ServoArc<ComputedValues>> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.style_source.as_ref(),
NodeData::Document(data) => data.style_source.as_ref(),
_ => None,
}
}
#[inline]
pub fn stylo_element_data_opt(&self) -> Option<&StyloData> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.stylo_element_data)
}
NodeData::Document(data) => Some(&data.stylo_element_data),
_ => None,
}
}
#[inline]
pub fn stylo_element_data_opt_mut(&mut self) -> Option<&mut StyloData> {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&mut data.stylo_element_data)
}
NodeData::Document(data) => Some(&mut data.stylo_element_data),
_ => None,
}
}
/// The `dirty_descendants` flag, if this node kind carries it (element or
/// document nodes). Returns `None` for text/comment nodes.
#[inline]
fn dirty_descendants_flag(&self) -> Option<&AtomicBool> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.dirty_descendants)
}
NodeData::Document(data) => Some(&data.dirty_descendants),
_ => None,
}
}
/// The document's shared style lock. Only available on element and
/// document nodes.
#[inline]
pub fn guard(&self) -> &SharedRwLock {
let guard = match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.guard.as_ref(),
NodeData::Document(data) => data.guard.as_ref(),
_ => None,
};
guard.expect("`guard` is not available on this node kind")
}
#[inline]
pub fn has_snapshot(&self) -> bool {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot,
NodeData::Document(data) => data.has_snapshot,
_ => false,
}
}
#[inline]
pub fn set_has_snapshot(&mut self, value: bool) {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot = value,
NodeData::Document(data) => data.has_snapshot = value,
_ => {}
}
}
#[inline]
pub fn before(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.before)
}
#[inline]
pub fn after(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.after)
}
}
impl Node {
pub(crate) fn new(
tree: *mut crate::NodeTree,
id: NodeId,
guard: SharedRwLock,
mut data: NodeData,
) -> Self {
// Store a handle to the document's shared style lock on the node data.
// Both element and document nodes are styled by stylo and so need it.
match &mut data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
data.guard = Some(guard);
}
NodeData::Document(data) => data.guard = Some(guard),
_ => {}
}
Self {
tree,
id,
parent: None,
child_index_hint: Cell::new(0),
owner_document: None,
markup: None,
custom_element_subtree_count: 0,
children: ThinVec::new(),
layout_parent: Cell::new(None),
layout_children: RefCell::new(None),
anonymous_blocks: ThinVec::new(),
paint_children: RefCell::new(None),
stacking_context: None,
#[cfg(feature = "shadow-dom")]
flattened_children: None,
#[cfg(feature = "shadow-dom")]
assigned_slot: None,
#[cfg(feature = "shadow-dom")]
assigned_nodes: None,
children_to_process: std::sync::atomic::AtomicIsize::new(0),
flags: NodeFlags::empty(),
data,
}
}
pub fn set_transform(&mut self, scale: f32) -> Option<Affine> {
let transform = self.primary_styles().and_then(|s| {
let size = self.final_layout().size;
let reference_box = Rect::new(
Point2D::new(CSSPixelLength::new(0.0), CSSPixelLength::new(0.0)),
Size2D::new(
CSSPixelLength::new(size.width),
CSSPixelLength::new(size.height),
),
);
// Resolve the transform in CSS pixels, then convert it to device-pixel space
// (S * T * S^-1): translation components are scaled, linear components are not.
crate::resolve_2d_transform(s.get_box(), reference_box).map(|t| {
let scale = scale as f64;
let [m11, m12, m21, m22, m41, m42] = t.as_coeffs();
Affine::new([m11, m12, m21, m22, m41 * scale, m42 * scale])
})
});
*self.transform_mut() = transform;
transform
}
pub fn pe_by_index(&self, index: usize) -> Option<NodeId> {
match index {
0 => self.after(),
1 => self.before(),
_ => panic!("Invalid pseudo element index"),
}
}
pub fn set_pe_by_index(&mut self, index: usize, value: Option<NodeId>) {
let Some(data) = self.element_data_mut() else {
return;
};
match index {
0 => data.after = value,
1 => data.before = value,
_ => panic!("Invalid pseudo element index"),
}
}
pub(crate) fn display_style(&self) -> Option<StyloDisplay> {
Some(self.primary_styles().as_ref()?.clone_display())
}
/// A compact computed-style view for renderer diagnostics.
/// Computed values for the properties a page is most likely to read.
///
/// Deliberately a fixed set rather than every property stylo computes.
/// `getComputedStyle` in a real browser answers for all of them, and this
/// does not; a caller asking for something outside this list gets an empty
/// string, which is what an unsupported property returns anyway.
///
/// The alternative was to keep throwing `getComputedStyle is not defined`,
/// which stops the whole script. Measured over a hundred-site corpus, three
/// sites died on exactly that. A page that reads `display` and gets the
/// right answer is strictly better off, and one that reads something absent
/// is no worse off than before.
///
/// Grow the list when a page is found needing more. It is cheap: every
/// entry is one `clone_*` call stylo already provides.
pub fn computed_style_properties(&self) -> Option<Vec<(&'static str, String)>> {
let style = self.primary_styles()?;
let layout = *self.final_layout();
let (used_width, used_height) = if matches!(
style.clone_box_sizing(),
style::computed_values::box_sizing::T::BorderBox
) {
(layout.size.width, layout.size.height)
} else {
(
(layout.size.width
- layout.padding.left
- layout.padding.right
- layout.border.left
- layout.border.right)
.max(0.0),
(layout.size.height
- layout.padding.top
- layout.padding.bottom
- layout.border.top
- layout.border.bottom)
.max(0.0),
)
};
Some(vec![
("display", style.clone_display().to_css_string()),
("position", style.clone_position().to_css_string()),
("visibility", style.clone_visibility().to_css_string()),
("opacity", style.clone_opacity().to_css_string()),
("color", style.clone_color().to_css_string()),
(
"background-color",
style.clone_background_color().to_css_string(),
),
(
"font-size",
format!("{}px", style.clone_font_size().computed_size().px()),
),
("font-weight", style.clone_font_weight().to_css_string()),
("font-style", style.clone_font_style().to_css_string()),
("font-family", style.clone_font_family().to_css_string()),
("text-align", style.clone_text_align().to_css_string()),
("overflow-x", style.clone_overflow_x().to_css_string()),
("overflow-y", style.clone_overflow_y().to_css_string()),
("z-index", style.clone_z_index().to_css_string()),
("box-sizing", style.clone_box_sizing().to_css_string()),
(
"flex-direction",
style.clone_flex_direction().to_css_string(),
),
(
"justify-content",
style.clone_justify_content().to_css_string(),
),
("align-items", style.clone_align_items().to_css_string()),
// The used values, not the specified ones. A page reading `width`
// off `getComputedStyle` is nearly always asking how wide the box
// ended up, and `auto` is not an answer it can use.
//
// Which box follows `box-sizing`, as in a browser: the content box
// unless the element is `border-box`. Reporting the border box for
// every element made `width - paddingLeft - paddingRight` (the
// usual content-width arithmetic) subtract the padding twice.
("width", format!("{}px", used_width)),
("height", format!("{}px", used_height)),
// The box model's edges, used values in px. Absent, a read of
// `paddingLeft` came back `undefined`, and `parseFloat(undefined)`
// is `NaN`, which then travelled silently into whatever position or
// size the page was computing: measuring code that subtracts
// padding or margins from a box placed things at NaN.
("padding-top", format!("{}px", layout.padding.top)),
("padding-right", format!("{}px", layout.padding.right)),
("padding-bottom", format!("{}px", layout.padding.bottom)),
("padding-left", format!("{}px", layout.padding.left)),
("border-top-width", format!("{}px", layout.border.top)),
("border-right-width", format!("{}px", layout.border.right)),
("border-bottom-width", format!("{}px", layout.border.bottom)),
("border-left-width", format!("{}px", layout.border.left)),
("margin-top", format!("{}px", layout.margin.top)),
("margin-right", format!("{}px", layout.margin.right)),
("margin-bottom", format!("{}px", layout.margin.bottom)),
("margin-left", format!("{}px", layout.margin.left)),
])
}
pub fn diagnostic_computed_style(&self) -> Option<Vec<(&'static str, String)>> {
let style = self.primary_styles()?;
Some(vec![
("display", style.clone_display().to_css_string()),
("color", style.clone_color().to_css_string()),
(
"background-color",
style.clone_background_color().to_css_string(),
),
(
"font-size",
format!("{}px", style.clone_font_size().computed_size().px()),
),
("width", style.clone_width().to_css_string()),
])
}
/// Whether computed style removes this node from layout.
pub fn is_display_none(&self) -> bool {
self.display_style()
.is_some_and(|display| display.is_none())
}
pub fn is_or_contains_block(&self) -> bool {
let style = self.primary_styles();
let style = style.as_ref();
// Ignore out-of-flow items
let position = style
.map(|s| s.clone_position())
.unwrap_or(Position::Relative);
let is_in_flow = matches!(
position,
Position::Static | Position::Relative | Position::Sticky
);
if !is_in_flow {
return false;
}
// Floated boxes do not break up the inline flow: they participate in the
// inline formatting context as out-of-flow inline boxes
let is_floating = style
.map(|s| s.clone_float().is_floating())
.unwrap_or(false);
if is_floating {
return false;
}
let display = style
.map(|s| s.clone_display())
.unwrap_or(StyloDisplay::inline());
match display.outside() {
DisplayOutside::None => false,
DisplayOutside::Block => true,
_ => {
if display.inside() == DisplayInside::Flow {
self.children
.iter()
.copied()
.any(|child_id| self.tree()[child_id].is_or_contains_block())
} else {
false
}
}
}
}
pub fn is_whitespace_node(&self) -> bool {
match &self.data {
NodeData::Text(data) => data.content.chars().all(|c| c.is_ascii_whitespace()),
_ => false,
}
}
pub fn is_focussable(&self) -> bool {
self.data
.downcast_element()
.map(|el| el.is_focussable)
.unwrap_or(false)
}
pub fn set_restyle_hint(&mut self, hint: RestyleHint) {
if let Some(stylo_element_data) = self.stylo_element_data_opt_mut() {
// A new shadow host or slot can acquire descendants that already
// have styles. Preserve the subtree hint before its first style
// traversal so those descendants also rematch their rules.
let mut element_data = stylo_element_data.ensure_init_mut();
element_data.hint.insert(hint);
}
// Mark all ancestors as having dirty descendants so the style traversal
// will visit this node's subtree
self.mark_ancestors_dirty();
}
/// Returns whether this node has any descendants that need restyling.
pub fn has_dirty_descendants(&self) -> bool {
self.dirty_descendants_flag()
.is_some_and(|flag| flag.load(Ordering::Relaxed))
}
/// Sets the dirty_descendants flag on this node.
pub fn set_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(true, Ordering::Relaxed);
}
}
/// Clears the dirty_descendants flag on this node.
pub fn unset_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(false, Ordering::Relaxed);
}
}
/// Set appropriate damage for Stylo when an element's style attribute is updated
pub(crate) fn mark_style_attr_updated(&mut self) {
if let Some(stylo_element_data) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo_element_data.get_mut() {
data.hint |= RestyleHint::RESTYLE_STYLE_ATTRIBUTE;
}
}
self.set_dirty_descendants();
self.mark_ancestors_dirty();
}
/// Marks all ancestors of this node as having dirty descendants.
/// This propagates the dirty flag up the tree so that the style traversal
/// knows to visit the subtree containing this node.
pub fn mark_ancestors_dirty(&self) {
// Mutating a shadow root must dirty its host even though the root
// itself is omitted from the flattened tree.
let mut current = self
.shadow_root_data()
.map(|root| self.with(root.host))
.or_else(|| self.flattened_parent());
while let Some(parent) = current {
if let Some(flag) = parent.dirty_descendants_flag() {
// New elements start dirty, and insertion or slot assignment
// can change the ancestry of an already-dirty element. Its
// flag does not prove that this ancestor chain is dirty.
flag.store(true, Ordering::Relaxed);
}
current = parent.flattened_parent();
}
}
// pub fn damage_mut(&mut self) -> Option<&mut RestyleDamage> {
// self.stylo_element_data
// .get_mut()
// .map(|mut data: ElementDataMut<'a>| &'a mut data.damage)
// }
pub fn damage(&self) -> Option<RestyleDamage> {
self.stylo_element_data_opt()
.and_then(|stylo| stylo.get().map(|data| data.damage))
}
pub fn set_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = damage;
}
}
}
pub fn insert_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage |= damage;
}
}
}
pub fn remove_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage.remove(damage);
}
}
}
pub fn clear_damage_mut(&mut self) {
if let Some(stylo) = self.stylo_element_data_opt_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = RestyleDamage::empty();
}
}
}
pub fn hover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::HOVER);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn unhover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::HOVER);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn is_hovered(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::HOVER))
}
pub fn focus(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.insert(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
// If focussing a text input, enable IME and set IME area
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(true);
let mut pos = self.absolute_position(0.0, 0.0);
pos.x += self.final_layout().content_box_x();
pos.y += self.final_layout().content_box_y();
let width = self.final_layout().content_box_width();
let height = self.final_layout().content_box_height();
shell_provider.set_ime_cursor_area(pos.x, pos.y, width, height);
}
}
pub fn blur(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.remove(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
// If blurring a text input, disable IME
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(false);
}
}
pub fn is_focussed(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::FOCUS))
}
pub fn active(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::ACTIVE);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn unactive(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::ACTIVE);
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn is_active(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::ACTIVE))
}
// Marks the node as disabled if it can be.
// It does not disable any children which should be disabled as well (relevant for the `select` element).
pub fn disable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::DISABLED);
data.element_state.remove(ElementState::ENABLED);
}
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
// Marks the node as enabled if it can be.
// It does not enable any children which should be enabled as well (relevant for the `select` element).
pub fn enable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::ENABLED);
data.element_state.remove(ElementState::DISABLED);
}
}
self.set_restyle_hint(RestyleHint::restyle_subtree());
}
pub fn subdoc(&self) -> Option<&dyn Document> {
self.element_data().and_then(|el| el.sub_doc_data())
}
pub fn subdoc_mut(&mut self) -> Option<&mut dyn Document> {
self.element_data_mut().and_then(|el| el.sub_doc_data_mut())
}
pub fn text_input_v_centering_offset(&self, scale: f64) -> f64 {
// For single-line inputs, add an offset to vertically center the text input layout
// within the content box of it's node.
if let Some(input_data) = self
.data
.downcast_element()
.and_then(|el| el.text_input_data())
{
if !input_data.is_multiline {
let content_box_height = self.final_layout().content_box_height();
let input_height = input_data.editor.try_layout().unwrap().height() / scale as f32;
let y_offset = ((content_box_height - input_height) / 2.0).max(0.0);
return y_offset as f64;
}
}
0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum NodeKind {
Document,
Element,
AnonymousBlock,
Text,
Comment,
DocumentFragment,
ShadowRoot,
}
/// How much text one click selects.
///
/// Click count decides: a second click takes the word, a third takes the line,
/// matching what a text input does and what every other platform does with the
/// same gesture.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextGranularity {
/// The word under the pointer, by Unicode word segmentation.
Word,
/// The whole hard line, so a soft-wrapped paragraph selects entire.
Line,
}
impl TextGranularity {
/// The granularity a click of this count selects, or `None` for a first
/// click, which places a caret rather than selecting anything.
pub fn from_click_count(count: u16) -> Option<Self> {
match count {
0 | 1 => None,
2 => Some(Self::Word),
_ => Some(Self::Line),
}
}
}
/// The encapsulation mode of a shadow root.
///
/// Mirrors the `ShadowRootMode` enum from the DOM specification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShadowRootMode {
/// Elements of the shadow root are accessible from JavaScript outside the
/// root (e.g. via `Element.shadowRoot`).
Open,
/// Elements of the shadow root are not accessible from JavaScript outside
/// the root.
Closed,
}
/// Data associated with a [`NodeData::ShadowRoot`] node.
///
/// A shadow root is a non-element, non-document node that acts as the root of a
/// shadow tree. Its `children` (on the owning [`Node`]) are the top-level nodes
/// of the shadow tree. The light-DOM children of the host element are
/// distributed into any `<slot>` elements within this tree to form the
/// "flattened tree" that is used for style resolution, layout and painting.
#[derive(Clone)]
pub struct ShadowRootData {
/// The node id of the host element that this shadow root is attached to.
pub host: NodeId,
/// The encapsulation mode of this shadow root.
pub mode: ShadowRootMode,
/// Set when the root was created from a declarative `<template>`.
pub declarative: bool,
/// When set, `cloneNode` copies this shadow root.
pub clonable: bool,
/// Stored for `ShadowRoot.serializable`. Serialization is separate.
pub serializable: bool,
/// Stored for `ShadowRoot.delegatesFocus`.
pub delegates_focus: bool,
/// Stylesheet owners in shadow-tree order.
pub stylesheet_nodes: Vec<NodeId>,
pub(crate) cascade_data: Option<ServoArc<style::stylist::CascadeData>>,
pub(crate) cascade_dirty: bool,
pub(crate) slots: Vec<NodeId>,
pub(crate) slottables: Vec<NodeId>,
pub(crate) selector_flags: Cell<ElementSelectorFlags>,
}
impl std::fmt::Debug for ShadowRootData {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ShadowRootData")
.field("host", &self.host)
.field("mode", &self.mode)
.field("declarative", &self.declarative)
.field("clonable", &self.clonable)
.field("serializable", &self.serializable)
.field("delegates_focus", &self.delegates_focus)
.field("stylesheet_nodes", &self.stylesheet_nodes)
.field("cascade_dirty", &self.cascade_dirty)
.field("slots", &self.slots)
.finish()
}
}
impl ShadowRootData {
pub fn new(host: NodeId, mode: ShadowRootMode) -> Self {
Self {
host,
mode,
declarative: false,
clonable: false,
serializable: false,
delegates_focus: false,
stylesheet_nodes: Vec::new(),
cascade_data: None,
cascade_dirty: true,
slots: Vec::new(),
slottables: Vec::new(),
selector_flags: Cell::new(ElementSelectorFlags::empty()),
}
}
}
/// Document syntax that generates no layout box.
#[derive(Debug, PartialEq, Eq)]
pub enum MarkupNode {
ProcessingInstruction {
target: String,
},
Doctype {
name: String,
public_id: String,
system_id: String,
},
}
/// The different kinds of nodes in the DOM.
#[derive(Debug, Clone)]
pub enum NodeData {
/// The `Document` itself - the root node of a HTML document.
Document(Box<DocumentData>),
/// An element with attributes.
Element(Box<ElementData>),
/// An anonymous block box
AnonymousBlock(Box<ElementData>),
/// A text node.
Text(TextNodeData),
/// A comment.
Comment {
/// The textual content of the comment
contents: String,
},
/// A `DocumentFragment`: a parentless container whose children move when
/// it is inserted, and which never appears in the box tree itself.
DocumentFragment,
/// The root of a shadow tree attached to a host element.
ShadowRoot(ShadowRootData),
// /// A `DOCTYPE` with name, public id, and system id. See
// /// [document type declaration on wikipedia][https://en.wikipedia.org/wiki/Document_type_declaration]
// Doctype { name: String, public_id: String, system_id: String },
// /// A Processing instruction.
// ProcessingInstruction { target: String, contents: String },
}
impl NodeData {
pub fn downcast_element(&self) -> Option<&ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn downcast_element_mut(&mut self) -> Option<&mut ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn is_element_with_tag_name(&self, name: &impl PartialEq<LocalName>) -> bool {
let Some(elem) = self.downcast_element() else {
return false;
};
*name == elem.name.local
}
pub fn attrs(&self) -> Option<&[Attribute]> {
Some(&self.downcast_element()?.attrs)
}
pub fn attr(&self, name: impl PartialEq<LocalName>) -> Option<&str> {
self.downcast_element()?.attr(name)
}
pub fn has_attr(&self, name: impl PartialEq<LocalName>) -> bool {
self.downcast_element()
.is_some_and(|elem| elem.has_attr(name))
}
pub fn kind(&self) -> NodeKind {
match self {
NodeData::Document(_) => NodeKind::Document,
NodeData::Element(_) => NodeKind::Element,
NodeData::AnonymousBlock(_) => NodeKind::AnonymousBlock,
NodeData::Text(_) => NodeKind::Text,
NodeData::Comment { .. } => NodeKind::Comment,
NodeData::DocumentFragment => NodeKind::DocumentFragment,
NodeData::ShadowRoot(_) => NodeKind::ShadowRoot,
}
}
pub fn shadow_root_data(&self) -> Option<&ShadowRootData> {
match self {
Self::ShadowRoot(data) => Some(data),
_ => None,
}
}
pub fn shadow_root_data_mut(&mut self) -> Option<&mut ShadowRootData> {
match self {
Self::ShadowRoot(data) => Some(data),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct TextNodeData {
/// The textual content of the text node
pub content: String,
}
impl TextNodeData {
pub fn new(content: String) -> Self {
Self { content }
}
}
/*
-> Computed styles
-> Layout
-----> Needs to happen only when styles are computed
*/
// type DomRefCell<T> = RefCell<T>;
// pub struct DomData {
// // ... we can probs just get away with using the html5ever types directly. basically just using the servo dom, but without the bindings
// local_name: html5ever::LocalName,
// tag_name: html5ever::QualName,
// namespace: html5ever::Namespace,
// prefix: DomRefCell<Option<html5ever::Prefix>>,
// attrs: DomRefCell<Vec<Attr>>,
// // attrs: DomRefCell<Vec<Dom<Attr>>>,
// id_attribute: DomRefCell<Option<Atom>>,
// is: DomRefCell<Option<LocalName>>,
// // style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
// // attr_list: MutNullableDom<NamedNodeMap>,
// // class_list: MutNullableDom<DOMTokenList>,
// state: Cell<ElementState>,
// }
impl Node {
pub fn tree(&self) -> &crate::NodeTree {
unsafe { &*self.tree }
}
pub fn is_html_document(&self) -> bool {
let document = match &self.data {
NodeData::Document(data) => return data.content_type == "text/html",
_ => self.owner_document.and_then(|id| self.tree().get(id)),
};
match document.map(|node| &node.data) {
Some(NodeData::Document(data)) => data.content_type == "text/html",
_ => true,
}
}
pub fn qualified_element_name(&self) -> Option<String> {
let element = self.element_data()?;
let name = match &element.name.prefix {
Some(prefix) => format!("{prefix}:{}", element.name.local),
None => element.name.local.to_string(),
};
Some(
if self.is_html_document() && element.name.ns == markup5ever::ns!(html) {
name.to_ascii_uppercase()
} else {
name
},
)
}
#[track_caller]
pub fn with(&self, id: NodeId) -> &Node {
self.tree().get(id).unwrap()
}
pub fn print_tree(&self, level: usize) {
println!(
"{} {} {:?} {} {:?}",
" ".repeat(level),
self.id,
self.parent,
self.node_debug_str().replace('\n', ""),
self.children
);
// println!("{} {:?}", " ".repeat(level), self.children);
for child_id in self.children.iter() {
let child = self.with(*child_id);
child.print_tree(level + 1)
}
}
// Get the index of the current node in the parents child list
pub fn index_of_child(&self, child_id: NodeId) -> Option<usize> {
self.children.iter().position(|id| *id == child_id)
}
// Get the index of the current node in the parents child list
pub fn child_index(&self) -> Option<usize> {
let children = &self.tree()[self.parent?].children;
let hint = self.child_index_hint.get();
if children.get(hint) == Some(&self.id) {
return Some(hint);
}
let index = children.iter().position(|id| *id == self.id)?;
self.child_index_hint.set(index);
Some(index)
}
/// Read a DOM child and seed its sibling traversal hint.
pub fn dom_child_at(&self, index: usize) -> Option<NodeId> {
let id = *self.children.get(index)?;
self.with(id).child_index_hint.set(index);
Some(id)
}
// Get the nth node in the parents child list
pub fn forward(&self, n: usize) -> Option<&Node> {
let index = self.child_index()?.checked_add(n)?;
let id = *self.tree()[self.parent?].children.get(index)?;
let node = self.with(id);
node.child_index_hint.set(index);
Some(node)
}
pub fn backward(&self, n: usize) -> Option<&Node> {
let index = self.child_index()?.checked_sub(n)?;
let id = *self.tree()[self.parent?].children.get(index)?;
let node = self.with(id);
node.child_index_hint.set(index);
Some(node)
}
pub fn is_element(&self) -> bool {
matches!(self.data, NodeData::Element { .. })
}
pub fn is_anonymous(&self) -> bool {
matches!(self.data, NodeData::AnonymousBlock { .. })
}
pub fn is_shadow_root(&self) -> bool {
matches!(self.data, NodeData::ShadowRoot { .. })
}
pub fn shadow_root_data(&self) -> Option<&ShadowRootData> {
self.data.shadow_root_data()
}
pub fn shadow_root_data_mut(&mut self) -> Option<&mut ShadowRootData> {
self.data.shadow_root_data_mut()
}
/// If this node is a shadow host (i.e. has an attached shadow root),
/// returns the node id of its shadow root.
pub fn shadow_root_id(&self) -> Option<NodeId> {
self.element_data().and_then(|el| el.shadow_root)
}
/// The parent corresponding to `layout_dom_children`.
///
/// Shadow roots are transparent, assigned nodes inherit through their
/// slot, and undistributed light children and suppressed fallback children
/// have no edge into the flattened tree.
#[inline]
pub(crate) fn flattened_parent(&self) -> Option<&Node> {
#[cfg(feature = "shadow-dom")]
{
if self.is_shadow_root() {
return None;
}
if let Some(slot_id) = self.assigned_slot {
return Some(self.with(slot_id));
}
let parent = self.with(self.parent?);
if let Some(root) = parent.shadow_root_data() {
return Some(self.with(root.host));
}
if parent.shadow_root_id().is_some()
|| parent
.assigned_nodes
.as_ref()
.is_some_and(|nodes| !nodes.is_empty())
{
return None;
}
Some(parent)
}
#[cfg(not(feature = "shadow-dom"))]
{
self.parent.map(|id| self.with(id))
}
}
/// The children to use for layout and painting. For shadow hosts and
/// `<slot>` elements this is the "flattened tree" children; for all other
/// nodes it is the regular DOM [`children`](Self::children).
#[cfg(feature = "shadow-dom")]
pub fn layout_dom_children(&self) -> &[NodeId] {
match &self.flattened_children {
Some(children) => children,
None => &self.children,
}
}
/// The children to use for layout and painting.
#[cfg(not(feature = "shadow-dom"))]
#[inline(always)]
pub fn layout_dom_children(&self) -> &[NodeId] {
&self.children
}
pub fn is_text_node(&self) -> bool {
matches!(self.data, NodeData::Text { .. })
}
pub fn element_data(&self) -> Option<&ElementData> {
match self.data {
NodeData::Element(ref data) => Some(data),
NodeData::AnonymousBlock(ref data) => Some(data),
_ => None,
}
}
pub fn element_data_mut(&mut self) -> Option<&mut ElementData> {
match self.data {
NodeData::Element(ref mut data) => Some(data),
NodeData::AnonymousBlock(ref mut data) => Some(data),
_ => None,
}
}
pub fn text_data(&self) -> Option<&TextNodeData> {
match self.data {
NodeData::Text(ref data) => Some(data),
_ => None,
}
}
pub fn text_data_mut(&mut self) -> Option<&mut TextNodeData> {
match self.data {
NodeData::Text(ref mut data) => Some(data),
_ => None,
}
}
pub fn node_debug_str(&self) -> String {
let mut s = String::new();
match &self.data {
NodeData::Document(_) => write!(s, "DOCUMENT"),
NodeData::DocumentFragment => write!(s, "FRAGMENT"),
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
let bytes = data.content.as_bytes();
write!(
s,
"TEXT {}",
std::str::from_utf8(bytes.split_at(10.min(bytes.len())).0)
.unwrap_or("INVALID UTF8")
)
}
NodeData::Comment { .. } => write!(s, "COMMENT"),
NodeData::AnonymousBlock(_) => write!(s, "AnonymousBlock"),
NodeData::ShadowRoot(data) => write!(s, "#shadow-root ({:?})", data.mode),
NodeData::Element(data) => {
let name = &data.name;
let class = self.attr(local_name!("class")).unwrap_or("");
let id = self.attr(local_name!("id")).unwrap_or("");
let display = self.display_constructed_as().to_css_string();
write!(s, "<{}", name.local).unwrap();
if !id.is_empty() {
write!(s, " #{id}").unwrap();
}
if !class.is_empty() {
if class.contains(' ') {
write!(s, " class=\"{class}\"").unwrap()
} else {
write!(s, " .{class}").unwrap()
}
}
write!(s, "> ({display})")
} // NodeData::ProcessingInstruction { .. } => write!(s, "ProcessingInstruction"),
}
.unwrap();
s
}
/// Renders the HTML of this node and all its children as a `String` without extra whitespace.
///
/// Example output:
///
/// ```text
/// <html><head /><body><main id="main"><div class="arbitrary-class" /></main></body></html>
/// ```
pub fn outer_html(&self) -> String {
let mut output = String::new();
self.write_outer_html(&mut output);
output
}
/// Renders the HTML of this node and all its children as a `String` with whitespace for human
/// readability.
///
/// Example output:
///
/// ```text
/// <html>
/// <head />
/// <body>
/// <main id="main">
/// <div class="arbitrary-class" />
/// </main>
/// </body>
/// </html>
/// ```
pub fn outer_html_pretty(&self) -> String {
let mut output = String::new();
self.write_outer_html_pretty(&mut output);
output
}
pub fn write_outer_html(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, OutputStyle::Normal, 0, None);
}
#[cfg(feature = "svg")]
pub(crate) fn write_outer_html_with_current_color(
&self,
writer: &mut String,
current_color: &str,
) {
self.write_outer_html_in_style(writer, OutputStyle::Normal, 0, Some(current_color));
}
#[cfg(feature = "svg")]
pub(crate) fn write_outer_html_with_svg_ids(
&self,
writer: &mut String,
ids: &std::collections::HashMap<NodeId, String>,
) {
self.write_outer_html_in_style_with_svg_ids(
writer,
OutputStyle::Normal,
0,
None,
Some(ids),
);
}
pub fn write_outer_html_pretty(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, OutputStyle::Pretty, 0, None);
}
fn write_outer_html_in_style(
&self,
writer: &mut String,
style: OutputStyle,
nesting: usize,
current_color_override: Option<&str>,
) {
self.write_outer_html_in_style_with_svg_ids(
writer,
style,
nesting,
current_color_override,
None,
);
}
fn write_outer_html_in_style_with_svg_ids(
&self,
writer: &mut String,
style: OutputStyle,
nesting: usize,
current_color_override: Option<&str>,
svg_ids: Option<&std::collections::HashMap<NodeId, String>>,
) {
const INDENT: &str = " ";
let has_children = !self.children.is_empty();
let computed_current_color = || {
self.primary_styles()
.map(|style| style.clone_color())
.map(|color| crate::util::absolute_color_to_svg_css(&color))
};
let current_color = current_color_override
.map(ToOwned::to_owned)
.or_else(computed_current_color);
match &self.data {
NodeData::Document(_) => {}
NodeData::Comment { .. } => {}
NodeData::AnonymousBlock(_) => {}
NodeData::ShadowRoot(_) => {}
// A fragment serialises as nothing of its own: the spec says its
// children are what gets inserted, and it is never in a document
// to be serialised from in the first place.
NodeData::DocumentFragment => {}
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push_str(data.content.as_str());
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
}
NodeData::Element(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
// A hyperlink is a graphics container in the image source.
// Its live DOM name, attributes and event ancestry stay intact.
let tag_name = if svg_ids.is_some()
&& data.name.ns.as_ref() == "http://www.w3.org/2000/svg"
&& data.name.local == local_name!("a")
{
"g"
} else {
data.name.local.as_ref()
};
let svg_id = svg_ids.and_then(|ids| ids.get(&self.id));
writer.push('<');
writer.push_str(tag_name);
if let Some(id) = svg_id {
writer.push_str(" id=\"");
encode_quoted_attribute_to_string(id, writer);
writer.push('"');
}
for attr in data.attrs() {
if svg_id.is_some()
&& attr.name.ns.as_ref().is_empty()
&& attr.name.local == local_name!("id")
{
continue;
}
writer.push(' ');
if let Some(prefix) = attr
.name
.prefix
.as_ref()
.filter(|prefix| !prefix.is_empty())
{
writer.push_str(prefix);
writer.push(':');
}
writer.push_str(&attr.name.local);
writer.push_str("=\"");
#[allow(clippy::unnecessary_unwrap)] // Convert to if-let chain once stabilised
if current_color.is_some() && attr.value.contains("currentColor") {
let value = attr
.value
.replace("currentColor", current_color.as_ref().unwrap());
encode_quoted_attribute_to_string(&value, writer);
} else {
encode_quoted_attribute_to_string(&attr.value, writer);
}
writer.push('"');
}
if !has_children {
writer.push_str(" /");
}
writer.push('>');
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
if has_children {
for &child_id in &self.children {
self.tree()[child_id].write_outer_html_in_style_with_svg_ids(
writer,
style,
nesting + 1,
current_color_override,
svg_ids,
);
}
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push_str("</");
writer.push_str(tag_name);
writer.push('>');
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
}
}
}
}
/// Serialise this node as the HTML fragment serialisation algorithm does
/// for `outerHTML`: void elements have no end tag, every other element
/// has one, text and attribute values are escaped, comments are kept.
///
/// Unlike [`Self::outer_html`], which is a debug rendering (`<div />`),
/// this output parses back to the same tree, which `innerHTML +=` and
/// templating code depend on.
pub fn write_html(&self, writer: &mut String) {
match &self.data {
NodeData::Text(data) => {
let raw = self
.parent
.and_then(|parent| self.tree()[parent].element_data())
.is_some_and(|parent| is_raw_text_element(&parent.name.local));
if raw {
writer.push_str(&data.content);
} else {
escape_html(&data.content, false, writer);
}
}
NodeData::Comment { contents } => {
writer.push_str("<!--");
writer.push_str(contents);
writer.push_str("-->");
}
NodeData::Element(data) => {
writer.push('<');
writer.push_str(&data.name.local);
for attr in data.attrs() {
writer.push(' ');
if let Some(prefix) = attr
.name
.prefix
.as_ref()
.filter(|prefix| !prefix.is_empty())
{
writer.push_str(prefix);
writer.push(':');
}
writer.push_str(&attr.name.local);
writer.push_str("=\"");
escape_html(&attr.value, true, writer);
writer.push('"');
}
writer.push('>');
if is_void_element(&data.name.local) {
return;
}
self.write_children_html(writer);
writer.push_str("</");
writer.push_str(&data.name.local);
writer.push('>');
}
NodeData::Document(_)
| NodeData::DocumentFragment
| NodeData::ShadowRoot(_)
| NodeData::AnonymousBlock(_) => self.write_children_html(writer),
}
}
/// Serialise this node's children, as `innerHTML` returns them.
pub fn write_children_html(&self, writer: &mut String) {
if let Some(contents) = self
.element_data()
.and_then(|element| element.template_contents)
{
self.tree()[contents].write_children_html(writer);
return;
}
for &child_id in &self.children {
self.tree()[child_id].write_html(writer);
}
}
pub fn attrs(&self) -> Option<&[Attribute]> {
Some(&self.element_data()?.attrs)
}
pub fn attr(&self, name: LocalName) -> Option<&str> {
let attr = self
.attrs()?
.iter()
.find(|attr| attr.name.ns == markup5ever::ns!() && attr.name.local == name)?;
Some(&attr.value)
}
pub fn primary_styles(&self) -> Option<impl Deref<Target = ServoArc<ComputedValues>>> {
self.stylo_element_data_opt()
.and_then(|stylo| stylo.primary_styles())
}
pub fn text_content(&self) -> String {
let mut out = String::new();
self.write_text_content(&mut out);
out
}
/// HTML's rendered-text getter. Text comes from the inline layout's
/// processed buffer, rather than reconstructing whitespace from source.
/// Callers must flush layout before invoking this.
pub fn rendered_inner_text(&self) -> String {
use style::computed_values::visibility::T as Visibility;
enum Piece {
Text(String),
RequiredBreak(usize),
}
fn text(node: &Node) -> String {
let NodeData::Text(data) = &node.data else {
return String::new();
};
// Text that never reached an inline layout is not rendered.
if node.inline_root_ancestor().is_none() {
return String::new();
}
let preserves = node
.parent
.map(|id| node.with(id))
.and_then(Node::primary_styles)
.is_some_and(|style| {
style.get_inherited_text().white_space_collapse
!= style::computed_values::white_space_collapse::T::Collapse
});
if preserves {
return data.content.to_string();
}
// Collapsing white space: every run of spaces, tabs and newlines
// is one space, as the line layout rendered it.
let mut result = String::with_capacity(data.content.len());
let mut space = false;
for ch in data.content.chars() {
if matches!(ch, ' ' | '\t' | '\n' | '\r' | '\u{c}') {
space = true;
} else {
if space {
result.push(' ');
space = false;
}
result.push(ch);
}
}
if space {
result.push(' ');
}
result
}
fn collect(node: &Node, pieces: &mut Vec<Piece>) {
if node.is_element() && node.is_display_none() {
return;
}
let visible = node
.primary_styles()
.is_none_or(|style| style.clone_visibility() == Visibility::Visible);
if node.is_text_node() {
let visible = node
.parent
.map(|id| node.with(id))
.and_then(Node::primary_styles)
.is_none_or(|style| style.clone_visibility() == Visibility::Visible);
if visible {
let value = text(node);
if !value.is_empty() {
pieces.push(Piece::Text(value));
}
}
return;
}
if !node.is_element() {
return;
}
let tag = node.element_data().expect("element").name.local.as_ref();
if tag == "br" {
if visible {
pieces.push(Piece::Text("\n".to_owned()));
}
return;
}
let display = node.primary_styles().map(|style| style.clone_display());
let block = display.is_some_and(|display| {
display.outside() == DisplayOutside::Block && !display.is_contents()
});
let breaks = if tag == "p" { 2 } else { usize::from(block) };
if breaks != 0 {
pieces.push(Piece::RequiredBreak(breaks));
}
for child in &node.children {
collect(node.with(*child), pieces);
}
if visible {
if matches!(tag, "td" | "th") {
let next_cell = node
.parent
.map(|parent| node.with(parent))
.and_then(|parent| {
parent.index_of_child(node.id).map(|index| (parent, index))
})
.is_some_and(|(parent, index)| {
parent.children[index + 1..].iter().any(|id| {
let child = parent.with(*id);
child.data.is_element_with_tag_name(&local_name!("td"))
|| child.data.is_element_with_tag_name(&local_name!("th"))
})
});
if next_cell {
pieces.push(Piece::Text("\t".to_owned()));
}
} else if tag == "tr" {
pieces.push(Piece::RequiredBreak(1));
}
}
if breaks != 0 {
pieces.push(Piece::RequiredBreak(breaks));
}
}
let mut current = Some(self);
while let Some(node) = current {
if !self.flags.is_in_document() || node.is_display_none() {
return self.text_content();
}
current = node.parent.map(|id| node.with(id));
}
if self.primary_styles().is_none() {
return self.text_content();
}
let mut pieces = Vec::new();
collect(self, &mut pieces);
let mut result = String::new();
let mut pending = 0;
for piece in pieces {
match piece {
Piece::RequiredBreak(count) => pending = pending.max(count),
Piece::Text(value) => {
if !result.is_empty() && pending != 0 {
result.truncate(result.trim_end_matches(' ').len());
for _ in 0..pending {
result.push('\n');
}
}
pending = 0;
if result.is_empty() || result.ends_with('\n') || result.ends_with(' ') {
result.push_str(value.trim_start_matches(' '));
} else {
result.push_str(&value);
}
}
}
}
result.truncate(result.trim_end_matches(' ').len());
result
}
/// CSSOM View's offset parent, excluding nodes without CSS boxes and
/// viewport-fixed elements.
pub fn cssom_offset_parent(&self) -> Option<&Node> {
if !self.flags.is_in_document()
|| self.data.is_element_with_tag_name(&local_name!("body"))
|| self.data.is_element_with_tag_name(&local_name!("html"))
{
return None;
}
let style = self.primary_styles()?;
if style.clone_position() == Position::Fixed || style.clone_display().is_contents() {
return None;
}
let mut current = Some(self);
while let Some(node) = current {
if node.is_display_none() {
return None;
}
current = node.parent.map(|id| node.with(id));
}
let static_position = style.clone_position() == Position::Static;
let zoom = style.effective_zoom.zoom(1.0);
let mut parent = self.parent.map(|id| self.with(id));
while let Some(node) = parent {
if let Some(style) = node.primary_styles()
&& !style.clone_display().is_contents()
&& (node.is_offset_parent()
|| style.effective_zoom.zoom(1.0) != zoom
|| (static_position
&& node.data.is_element_with_tag_name(&local_name!("table"))))
{
return Some(node);
}
parent = node.parent.map(|id| node.with(id));
}
None
}
/// Write this subtree's text content into any [`std::fmt::Write`] sink.
///
/// Public and generic so that a caller which does not want a `String` does
/// not have to fork this traversal to avoid one. `blitz-dom-api`'s
/// buffer-writing reader passes a sink that counts, and then one that fills
/// a caller-supplied slice; a private copy of this walk in that crate would
/// silently disagree with this one the first time a `NodeData` variant is
/// added here.
///
/// The sinks callers pass do not fail, and `String`'s never has, so nothing
/// in this crate inspects the `Result`. It is kept in the signature because
/// it is `fmt::Write`'s, not because there is an error to handle.
pub fn write_text_content<W: Write>(&self, out: &mut W) {
match &self.data {
NodeData::Text(data) => {
let _ = out.write_str(&data.content);
}
NodeData::Element(..)
| NodeData::AnonymousBlock(..)
| NodeData::Document(..)
| NodeData::DocumentFragment
| NodeData::ShadowRoot(..) => {
for child_id in self.children.iter() {
self.with(*child_id).write_text_content(out);
}
}
_ => {}
}
}
pub fn flush_style_attribute(&mut self, url_extra_data: &UrlExtraData) {
if let NodeData::Element(ref mut elem_data) = self.data {
if let Some(guard) = elem_data.guard.clone() {
elem_data.flush_style_attribute(&guard, url_extra_data);
}
}
}
pub fn order(&self) -> i32 {
self.primary_styles()
.map(|s| match s.pseudo() {
Some(PseudoElement::Before) => i32::MIN,
Some(PseudoElement::After) => i32::MAX,
_ => s.clone_order(),
})
.unwrap_or(0)
}
pub fn z_index(&self) -> i32 {
self.primary_styles()
.map(|s| s.clone_z_index().integer_or(0))
.unwrap_or(0)
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Stacking_context#features_creating_stacking_contexts
pub fn is_stacking_context_root(&self, is_flex_or_grid_item: bool) -> bool {
let Some(style) = self.primary_styles() else {
return false;
};
let position = style.clone_position();
let has_z_index = !style.clone_z_index().is_auto();
if style.clone_opacity() != 1.0 {
return true;
}
let position_based = match position {
Position::Fixed | Position::Sticky => true,
Position::Relative | Position::Absolute => has_z_index,
Position::Static => has_z_index && is_flex_or_grid_item,
};
if position_based {
return true;
}
// This runs while the stacking-context tree is built, before
// `resolve_transforms` populates the cached device-space matrix. Using
// that cache here makes the first frame treat a transformed node as an
// ordinary box, hoist its painted children into the parent, and only
// repair the tree after the first hover/restyle. The computed CSS value
// is already available and is the source of truth for whether the node
// establishes a stacking context.
let box_styles = style.get_box();
if !box_styles.transform.0.is_empty()
|| !matches!(box_styles.translate, Translate::None)
|| !matches!(box_styles.rotate, Rotate::None)
|| !matches!(box_styles.scale, Scale::None)
{
return true;
}
// `isolation: isolate` exists precisely to create a stacking context
// without any other visual effect. Ignoring it lets a negative z-index
// descendant escape to an ancestor context, where it is painted before
// (and so underneath) the backgrounds of the boxes in between.
if box_styles.isolation == Isolation::Isolate {
return true;
}
// TODO: mix-blend-mode
// TODO: filter
// TODO: clip-path
// TODO: mask
// TODO: contain
false
}
/// Takes an (x, y) position (relative to the *parent's* top-left corner) and returns:
/// - None if the position is outside of this node's bounds
/// - Some(HitResult) if the position is within the node but doesn't match any children
/// - The result of recursively calling child.hit() on the the child element that is
/// positioned at that position if there is one.
///
/// TODO: z-index
/// (If multiple children are positioned at the position then a random one will be recursed into)
pub fn hit(&self, x: f32, y: f32, scale: f64) -> Option<HitResult> {
self.hit_inner(x, y, scale, &mut None)
}
/// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
/// thumb under the point into `scrollbar` during the same descent (so
/// thumb hit-testing shares the exact coordinate handling — transforms
/// included — of every other hit test).
pub(crate) fn hit_inner(
&self,
x: f32,
y: f32,
scale: f64,
scrollbar: &mut Option<crate::node::ScrollbarRef>,
) -> Option<HitResult> {
self.hit_inner_collect(x, y, scale, scrollbar, &mut None)
}
/// Use the input hit traversal either for the foremost hit or for every hit.
pub(crate) fn hit_inner_collect(
&self,
x: f32,
y: f32,
scale: f64,
scrollbar: &mut Option<crate::node::ScrollbarRef>,
hits: &mut Option<Vec<HitResult>>,
) -> Option<HitResult> {
use style::computed_values::pointer_events::T as PointerEvents;
use style::computed_values::visibility::T as Visibility;
// A hidden subtree takes no hits.
//
// This never needed saying while hiding a pane destroyed its boxes: a
// hidden subtree had nothing to test against. It keeps its boxes now,
// and their `final_layout` is whatever it was when the pane was last
// visible — full size, in place, over the tab in front. A retained tab
// measured 331 of its 370 elements still carrying live geometry after
// being hidden, and every one of them was a click target.
if matches!(self.style().display, taffy::Display::None) {
return None;
}
// Don't hit on visbility:hidden elements
if let Some(style) = self.primary_styles() {
if matches!(
style.clone_visibility(),
Visibility::Hidden | Visibility::Collapse
) {
return None;
}
}
// pointer-events:none makes this element transparent to hits, but its
// descendants are still tested (one may restore pointer-events:auto).
let pointer_events_none = self
.primary_styles()
.is_some_and(|style| style.clone_pointer_events() == PointerEvents::None);
let mut x = x - self.final_layout().location.x + self.scroll_offset().x as f32;
let mut y = y - self.final_layout().location.y + self.scroll_offset().y as f32;
if let Some(t) = *self.transform() {
let p = t.inverse() * kurbo::Point::new(x as f64 * scale, y as f64 * scale);
x = (p.x / scale) as f32;
y = (p.y / scale) as f32;
}
let size = self.final_layout().size;
let matches_self = !(x < 0.0
|| x > size.width + self.scroll_offset().x as f32
|| y < 0.0
|| y > size.height + self.scroll_offset().y as f32);
let content_size = self.final_layout().content_size;
let matches_content = !(x < 0.0
|| x > content_size.width + self.scroll_offset().x as f32
|| y < 0.0
|| y > content_size.height + self.scroll_offset().y as f32);
let matches_hoisted_content = match &self.stacking_context {
Some(sc) => {
let content_area = sc.content_area;
x >= content_area.left + self.scroll_offset().x as f32
&& x <= content_area.right + self.scroll_offset().x as f32
&& y >= content_area.top + self.scroll_offset().y as f32
&& y <= content_area.bottom + self.scroll_offset().y as f32
}
None => false,
};
// `scrollable_overflow` is stored in device (scaled) pixels, whereas the
// coordinates here are in CSS pixels, so unscale it before comparing.
let overflow = *self.scrollable_overflow();
let matches_overflow = x >= (overflow.x0 / scale) as f32
&& x <= (overflow.x1 / scale) as f32
&& y >= (overflow.y0 / scale) as f32
&& y <= (overflow.y1 / scale) as f32;
if !matches_self && !matches_content && !matches_hoisted_content && !matches_overflow {
return None;
}
// Descendants overwrite, so the innermost scroll container's thumb
// wins. Thumb coords are border-box relative (unscrolled).
if matches_self
&& let Some(sb) = self.scrollbar_at_local(
(x - self.scroll_offset().x as f32) as f64,
(y - self.scroll_offset().y as f32) as f64,
)
{
*scrollbar = Some(sb);
}
// Child layouts and hoisted offsets use border-box coordinates.
// Only glyph hit testing below uses the inline content-box origin.
// Positive z_index hoisted children
if matches_hoisted_content {
if let Some(hoisted) = &self.stacking_context {
for hoisted_child in hoisted.pos_z_hoisted_children().rev() {
if hoisted_child.clips.iter().any(|clip| {
x < clip.left || x > clip.right || y < clip.top || y > clip.bottom
}) {
continue;
}
let x = x - hoisted_child.position.x;
let y = y - hoisted_child.position.y;
if let Some(hit) = self
.with(hoisted_child.node_id)
.hit_inner_collect(x, y, scale, scrollbar, hits)
{
return Some(hit);
}
}
}
}
// Call `.hit()` on each child in turn. If any return `Some` then return that value. Else return `Some(self.id).
for child_id in self.paint_children.borrow().iter().flatten().rev() {
if let Some(hit) = self
.with(*child_id)
.hit_inner_collect(x, y, scale, scrollbar, hits)
{
return Some(hit);
}
}
// Negative z_index hoisted children
if matches_hoisted_content {
if let Some(hoisted) = &self.stacking_context {
for hoisted_child in hoisted.neg_z_hoisted_children().rev() {
if hoisted_child.clips.iter().any(|clip| {
x < clip.left || x > clip.right || y < clip.top || y > clip.bottom
}) {
continue;
}
let x = x - hoisted_child.position.x;
let y = y - hoisted_child.position.y;
if let Some(hit) = self
.with(hoisted_child.node_id)
.hit_inner_collect(x, y, scale, scrollbar, hits)
{
return Some(hit);
}
}
}
}
// Inline SVG descendants have image geometry instead of layout boxes.
#[cfg(feature = "svg")]
if matches_self && let Some(hit) = self.hit_inline_svg(x, y, hits) {
return Some(hit);
}
// Inline children
if self.flags.is_inline_root() {
x -= self.final_layout().padding.left + self.final_layout().border.left;
y -= self.final_layout().padding.top + self.final_layout().border.top;
let element_data = &self.element_data().unwrap();
if let Some(ild) = element_data.inline_layout_data.as_ref() {
let layout = &ild.layout;
let scale = layout.scale();
if let Some((cluster, _side)) =
Cluster::from_point_exact(layout, x * scale, y * scale)
{
let style_index = cluster.glyphs().next()?.style_index();
let node_id = layout.styles()[style_index].brush.id;
let text_pointer_events_none = self
.with(node_id)
.primary_styles()
.is_some_and(|style| style.clone_pointer_events() == PointerEvents::None);
if !text_pointer_events_none {
let hit = HitResult {
node_id,
x,
y,
is_text: true,
};
if let Some(hits) = hits.as_mut() {
hits.push(hit);
} else {
return Some(hit);
}
}
}
}
}
// Self (this node)
if matches_self && !pointer_events_none {
let hit = HitResult {
node_id: self.id,
x,
y,
is_text: false,
};
if let Some(hits) = hits.as_mut() {
hits.push(hit);
} else {
return Some(hit);
}
}
None
}
/// Find the inline root ancestor of this node (or self if this is an inline root).
/// Returns None if no inline root ancestor exists.
pub fn inline_root_ancestor(&self) -> Option<&Node> {
let mut node = self;
loop {
if node.flags.is_inline_root() {
return Some(node);
}
let id = node.layout_parent.get()?;
node = self.with(id);
}
}
/// Get the text byte offset at a given point, using coordinates already transformed
/// to be relative to this inline root's content box.
/// Returns Some(byte_offset) if the point hits text, None otherwise.
pub fn text_offset_at_point(&self, x: f32, y: f32) -> Option<usize> {
if !self.flags.is_inline_root() {
return None;
}
let element_data = self.element_data()?;
let inline_layout = element_data.inline_layout_data.as_ref()?;
let layout = &inline_layout.layout;
let scale = layout.scale();
// Use Parley's cluster hit testing (from_point is more forgiving than from_point_exact)
let (cluster, side) = Cluster::from_point(layout, x * scale, y * scale)?;
// Determine byte offset based on which side of the cluster was clicked
// For LTR text: left side = start of cluster, right side = end of cluster
// For RTL text: left side = end of cluster, right side = start of cluster
// Also, explicit line breaks should always use start to avoid cursor appearing on next line
let is_leading = side == ClusterSide::Left;
let offset = if cluster.is_rtl() {
if is_leading {
cluster.text_range().end
} else {
cluster.text_range().start
}
} else {
// LTR text
if is_leading || cluster.is_line_break() == Some(BreakReason::Explicit) {
cluster.text_range().start
} else {
cluster.text_range().end
}
};
Some(offset)
}
/// The byte range of the word or line at a point, for a multi-click
/// selection.
///
/// See [`TextGranularity`] for which click count maps to which unit. Coordinates are relative to this inline root's content box,
/// as for [`text_offset_at_point`](Self::text_offset_at_point).
///
/// Parley owns the boundary rules (it is what an `<input>` already selects
/// with), so this asks it rather than scanning for spaces: word breaks are
/// a Unicode segmentation question, not a whitespace one.
pub fn text_range_at_point(
&self,
x: f32,
y: f32,
granularity: TextGranularity,
) -> Option<Range<usize>> {
if !self.flags.is_inline_root() {
return None;
}
let element_data = self.element_data()?;
let inline_layout = element_data.inline_layout_data.as_ref()?;
let layout = &inline_layout.layout;
let scale = layout.scale();
let (x, y) = (x * scale, y * scale);
// Bail when the point misses the text entirely: `Selection` answers an
// out-of-range point with a collapsed cursor at the end of the text,
// which would read as "selected nothing at the very end" rather than
// as a miss.
Cluster::from_point(layout, x, y)?;
let selection = match granularity {
TextGranularity::Word => Selection::word_from_point(layout, x, y),
// The hard line, so a soft-wrapped paragraph selects as the whole
// paragraph. That is what a triple click does elsewhere, and it is
// what `select_hard_line_at_point` gives a text input.
TextGranularity::Line => Selection::hard_line_from_point(layout, x, y),
};
let range = selection.text_range();
if range.is_empty() { None } else { Some(range) }
}
/// Computes the Document-relative coordinates of the `Node`
pub fn absolute_position(&self, x: f32, y: f32) -> crate::util::Point<f32> {
// A scroll offset moves this node's descendants, not its own border
// box. Parent recursion applies each ancestor offset to the child.
let x = x + self.final_layout().location.x;
let y = y + self.final_layout().location.y;
// Recurse up the layout hierarchy
self.layout_parent
.get()
.and_then(|id| self.tree().get(id))
.map(|parent| {
parent.absolute_position(
x - parent.scroll_offset().x as f32,
y - parent.scroll_offset().y as f32,
)
})
.unwrap_or(crate::util::Point { x, y })
}
/// Whether this node can act as an [`offset_parent`](Self::offset_parent): a positioned
/// element, or one of the elements that always qualify (`body`, `td`, `th`).
fn is_offset_parent(&self) -> bool {
let Some(styles) = self.primary_styles() else {
return false;
};
if styles.get_box().position != Position::Static {
return true;
}
self.data.is_element_with_tag_name(&local_name!("body"))
|| self.data.is_element_with_tag_name(&local_name!("td"))
|| self.data.is_element_with_tag_name(&local_name!("th"))
}
/// The nearest layout ancestor that is an offset parent, as in CSSOM View's
/// `offsetParent`.
///
/// The predicate is `is_offset_parent`, which is private, so this is not a
/// link: rustdoc rejects a public item linking to a private one under
/// `-D warnings`, and the alternative is publishing a helper nothing else
/// needs.
pub fn offset_parent(&self) -> Option<&Node> {
let mut node = self;
loop {
node = self.with(node.layout_parent.get()?);
if node.is_offset_parent() {
return Some(node);
}
}
}
/// CSSOM View's `offsetLeft`/`offsetTop`: the offset of this node's border box from the
/// padding edge of its [`offset_parent`](Self::offset_parent).
pub fn offset_top_left(&self) -> crate::util::Point<f32> {
let mut x = 0.0;
let mut y = 0.0;
let mut current = self;
loop {
let layout = current.final_layout();
x += layout.location.x;
y += layout.location.y;
let Some(parent_id) = current.layout_parent.get() else {
break;
};
let parent = self.with(parent_id);
if parent.is_offset_parent() {
let border = parent.final_layout().border;
x -= border.left;
y -= border.top;
break;
}
current = parent;
}
crate::util::Point { x, y }
}
/// Creates a synthetic click event
pub fn synthetic_click_event(&self, mods: Modifiers) -> DomEventData {
DomEventData::Click(self.synthetic_click_event_data(mods))
}
pub fn synthetic_click_event_data(&self, mods: Modifiers) -> BlitzPointerEvent {
let absolute_position = self.absolute_position(0.0, 0.0);
let x = absolute_position.x + (self.final_layout().size.width / 2.0);
let y = absolute_position.y + (self.final_layout().size.height / 2.0);
BlitzPointerEvent {
id: BlitzPointerId::Mouse,
is_primary: true,
coords: PointerCoords {
page_x: x,
page_y: y,
// TODO: should these be different?
screen_x: x,
screen_y: y,
client_x: x,
client_y: y,
},
mods,
button: Default::default(),
buttons: Default::default(),
details: Default::default(),
element: Default::default(),
active_pointers: Default::default(),
}
}
}
/// It might be wrong to expose this since what does *equality* mean outside the dom?
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Node {}
impl std::fmt::Debug for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// FIXME: update to reflect changes to fields
f.debug_struct("NodeData")
.field("parent", &self.parent)
.field("id", &self.id)
.field("is_inline_root", &self.flags.is_inline_root())
.field("children", &self.children)
.field("layout_children", &self.layout_children.borrow())
// .field("style", &self.style)
.field("node", &self.data)
.field("stylo_element_data", &self.stylo_element_data_opt())
// .field("unrounded_layout", &self.unrounded_layout)
// .field("final_layout", &self.final_layout)
.finish()
}
}
/// Elements whose text children serialise verbatim (HTML fragment
/// serialisation, with scripting enabled).
fn is_raw_text_element(name: &LocalName) -> bool {
matches!(
name.as_ref(),
"style" | "script" | "xmp" | "iframe" | "noembed" | "noframes" | "plaintext" | "noscript"
)
}
/// Elements that serialise with no end tag.
fn is_void_element(name: &LocalName) -> bool {
matches!(
name.as_ref(),
"area"
| "base"
| "basefont"
| "bgsound"
| "br"
| "col"
| "embed"
| "frame"
| "hr"
| "img"
| "input"
| "keygen"
| "link"
| "meta"
| "param"
| "source"
| "track"
| "wbr"
)
}
/// Escape a string as the HTML serialiser does: `&` and no-break space
/// always, `"` in attribute mode, `<` and `>` otherwise.
fn escape_html(text: &str, attribute: bool, writer: &mut String) {
for ch in text.chars() {
match ch {
'&' => writer.push_str("&"),
'\u{a0}' => writer.push_str(" "),
'"' if attribute => writer.push_str("""),
'<' if !attribute => writer.push_str("<"),
'>' if !attribute => writer.push_str(">"),
_ => writer.push(ch),
}
}
}
#[cfg(test)]
mod test {
use style_dom::ElementState;
use crate::{Attribute, BaseDocument, DocumentConfig, ElementData, NodeData, qual_name};
#[test]
fn absolute_position_tolerates_a_detached_layout_parent() {
let mut document = BaseDocument::new(DocumentConfig::default());
let parent = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("section"),
vec![],
))));
let child = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![],
))));
document
.get_node(child)
.unwrap()
.layout_parent
.set(Some(parent));
// An event handler may detach its own ancestor before the renderer's
// default-action tail finishes computing event-relative coordinates.
// The child object can still be alive through that dispatch even though
// its recorded layout parent has already left the slot map.
document.remove_node_from_tree(parent);
assert_eq!(
document
.get_node(child)
.unwrap()
.absolute_position(4.0, 7.0),
crate::util::Point { x: 4.0, y: 7.0 },
);
}
#[test]
fn create_node_with_disabled_attr() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![Attribute {
name: qual_name!("disabled"),
value: "".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::DISABLED),
"form node is disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"form node is not enabled"
);
}
#[test]
fn ignore_disabled_attr_content() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![Attribute {
name: qual_name!("disabled"),
value: "false".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::DISABLED),
"form node is disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"form node is not enabled"
);
}
#[test]
fn create_node_with_ignored_disable() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("a"),
vec![Attribute {
name: qual_name!("disabled"),
value: "".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
!node.element_state().contains(ElementState::DISABLED),
"Non form node cannot be disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"Non form node cannot be enabled"
);
}
#[test]
fn create_empty_enabled_node() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::ENABLED),
"Button should be enabled by default"
);
}
}