ps-blitz-dom 0.3.0-beta.4

Blitz DOM implementation
Documentation
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
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::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;
    }
}

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>,
    // 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>>,

    // 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 / cache_mut: 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.
    selector_flags / selector_flags_mut: Cell<ElementSelectorFlags>,
}

impl Node {
    /// 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,
            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,

            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.
    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() {
            if let Some(mut element_data) = stylo_element_data.get_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) {
        let mut current_id = self.parent;
        while let Some(parent_id) = current_id {
            let parent = &self.tree()[parent_id];
            // If this ancestor already has dirty_descendants set, we can stop
            // because all further ancestors must also have it set
            if let Some(flag) = parent.dirty_descendants_flag() {
                if flag.swap(true, Ordering::Relaxed) {
                    break;
                }
            }
            current_id = parent.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,
    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(Debug, 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,
    /// Node ids of `<style>` elements within this shadow root, in document
    /// order. Used to build the scoped stylesheet set for this shadow tree.
    pub stylesheet_nodes: Vec<NodeId>,
}

impl ShadowRootData {
    pub fn new(host: NodeId, mode: ShadowRootMode) -> Self {
        Self {
            host,
            mode,
            stylesheet_nodes: Vec::new(),
        }
    }
}

/// 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,
    },

    /// 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::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 }
    }

    #[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> {
        self.tree()[self.parent?]
            .children
            .iter()
            .position(|id| *id == self.id)
    }

    // Get the nth node in the parents child list
    pub fn forward(&self, n: usize) -> Option<&Node> {
        let child_idx = self.child_index().unwrap_or(0);
        self.tree()[self.parent?]
            .children
            .get(child_idx + n)
            .map(|id| self.with(*id))
    }

    pub fn backward(&self, n: usize) -> Option<&Node> {
        let child_idx = self.child_index().unwrap_or(0);
        if child_idx < n {
            return None;
        }

        self.tree()[self.parent?]
            .children
            .get(child_idx - n)
            .map(|id| self.with(*id))
    }

    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 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::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));
    }

    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>,
    ) {
        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(_) => {}
            // 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);
                    }
                }
                writer.push('<');
                writer.push_str(&data.name.local);

                for attr in data.attrs() {
                    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(
                            writer,
                            style,
                            nesting + 1,
                            current_color_override,
                        );
                    }

                    if matches!(style, OutputStyle::Pretty) {
                        for _ in 0..nesting {
                            writer.push_str(INDENT);
                        }
                    }
                    writer.push_str("</");
                    writer.push_str(&data.name.local);
                    writer.push('>');
                    if matches!(style, OutputStyle::Pretty) {
                        writer.push('\n');
                    }
                }
            }
        }
    }

    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(|id| id.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
    }

    /// 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(..) => {
                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;
        }

        if self.transform().is_some() {
            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 style.get_box().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> {
        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);
        }

        if self.flags.is_inline_root() {
            let content_box_offset = taffy::Point {
                x: self.final_layout().padding.left + self.final_layout().border.left,
                y: self.final_layout().padding.top + self.final_layout().border.top,
            };
            x -= content_box_offset.x;
            y -= content_box_offset.y;
        }

        // 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() {
                    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(x, y, scale, scrollbar)
                    {
                        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(x, y, scale, scrollbar) {
                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() {
                    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(x, y, scale, scrollbar)
                    {
                        return Some(hit);
                    }
                }
            }
        }

        // Inline children
        if self.flags.is_inline_root() {
            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 {
                        return Some(HitResult {
                            node_id,
                            x,
                            y,
                            is_text: true,
                        });
                    }
                }
            }
        }

        // Self (this node)
        if matches_self && !pointer_events_none {
            return Some(HitResult {
                node_id: self.id,
                x,
                y,
                is_text: false,
            });
        }

        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()
            .map(|i| {
                let parent = self.with(i);
                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](Self::is_offset_parent), as in
    /// CSSOM View's `offsetParent`.
    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()
    }
}

#[cfg(test)]
mod test {
    use style_dom::ElementState;

    use crate::{Attribute, BaseDocument, DocumentConfig, ElementData, NodeData, qual_name};

    #[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"
        );
    }
}