blitz-pdf 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +26 -0
  2. package/THIRD_PARTY_NOTICES.md +5 -2
  3. package/docs/layout-regressions.md +65 -0
  4. package/docs/pagination-regressions.md +89 -0
  5. package/package.json +2 -1
  6. package/vendor/README.md +35 -0
  7. package/vendor/blitz-dom/Cargo.toml +113 -0
  8. package/vendor/blitz-dom/LICENSE-APACHE +176 -0
  9. package/vendor/blitz-dom/LICENSE-MIT +23 -0
  10. package/vendor/blitz-dom/assets/default.css +1142 -0
  11. package/vendor/blitz-dom/assets/moz-bullet-font.otf +0 -0
  12. package/vendor/blitz-dom/src/accessibility.rs +255 -0
  13. package/vendor/blitz-dom/src/config.rs +97 -0
  14. package/vendor/blitz-dom/src/cssom.rs +971 -0
  15. package/vendor/blitz-dom/src/debug.rs +206 -0
  16. package/vendor/blitz-dom/src/document.rs +3395 -0
  17. package/vendor/blitz-dom/src/events/driver.rs +427 -0
  18. package/vendor/blitz-dom/src/events/focus.rs +40 -0
  19. package/vendor/blitz-dom/src/events/ime.rs +31 -0
  20. package/vendor/blitz-dom/src/events/keyboard.rs +174 -0
  21. package/vendor/blitz-dom/src/events/mod.rs +315 -0
  22. package/vendor/blitz-dom/src/events/pointer.rs +849 -0
  23. package/vendor/blitz-dom/src/font_metrics.rs +177 -0
  24. package/vendor/blitz-dom/src/form.rs +463 -0
  25. package/vendor/blitz-dom/src/html.rs +38 -0
  26. package/vendor/blitz-dom/src/iframe.rs +186 -0
  27. package/vendor/blitz-dom/src/layout/construct.rs +1328 -0
  28. package/vendor/blitz-dom/src/layout/damage.rs +642 -0
  29. package/vendor/blitz-dom/src/layout/inline.rs +1160 -0
  30. package/vendor/blitz-dom/src/layout/list.rs +237 -0
  31. package/vendor/blitz-dom/src/layout/mod.rs +969 -0
  32. package/vendor/blitz-dom/src/layout/paint_tree.rs +462 -0
  33. package/vendor/blitz-dom/src/layout/replaced.rs +439 -0
  34. package/vendor/blitz-dom/src/layout/table.rs +967 -0
  35. package/vendor/blitz-dom/src/layout/text_transform.rs +979 -0
  36. package/vendor/blitz-dom/src/layout/writing_mode.rs +437 -0
  37. package/vendor/blitz-dom/src/lib.rs +160 -0
  38. package/vendor/blitz-dom/src/mutator.rs +1818 -0
  39. package/vendor/blitz-dom/src/net.rs +649 -0
  40. package/vendor/blitz-dom/src/node/attributes.rs +60 -0
  41. package/vendor/blitz-dom/src/node/custom_widget.rs +178 -0
  42. package/vendor/blitz-dom/src/node/element.rs +1106 -0
  43. package/vendor/blitz-dom/src/node/mod.rs +30 -0
  44. package/vendor/blitz-dom/src/node/node.rs +2036 -0
  45. package/vendor/blitz-dom/src/node/scrollbar.rs +237 -0
  46. package/vendor/blitz-dom/src/node/serialize.rs +225 -0
  47. package/vendor/blitz-dom/src/node/stylo_data.rs +142 -0
  48. package/vendor/blitz-dom/src/node/svg.rs +265 -0
  49. package/vendor/blitz-dom/src/node/text.rs +804 -0
  50. package/vendor/blitz-dom/src/query_selector.rs +275 -0
  51. package/vendor/blitz-dom/src/resolve.rs +474 -0
  52. package/vendor/blitz-dom/src/resolved_style.rs +797 -0
  53. package/vendor/blitz-dom/src/scrolling.rs +780 -0
  54. package/vendor/blitz-dom/src/selection.rs +122 -0
  55. package/vendor/blitz-dom/src/stylo.rs +1518 -0
  56. package/vendor/blitz-dom/src/stylo_device.rs +88 -0
  57. package/vendor/blitz-dom/src/stylo_to_cursor_icon.rs +49 -0
  58. package/vendor/blitz-dom/src/stylo_to_kurbo.rs +129 -0
  59. package/vendor/blitz-dom/src/stylo_to_parley.rs +655 -0
  60. package/vendor/blitz-dom/src/traversal.rs +600 -0
  61. package/vendor/blitz-dom/src/tree.rs +136 -0
  62. package/vendor/blitz-dom/src/url.rs +63 -0
  63. package/vendor/blitz-dom/src/util.rs +256 -0
  64. package/wasm/blitz_pdf_bg.wasm +0 -0
@@ -0,0 +1,2036 @@
1
+ use crate::Document;
2
+ use crate::layout::paint_tree::{HoistedPaintChild, StackingContext};
3
+ use bitflags::bitflags;
4
+ use blitz_traits::events::{
5
+ BlitzPointerEvent, BlitzPointerId, DomEventData, HitResult, PointerCoords,
6
+ };
7
+ use blitz_traits::node_id::NodeId;
8
+ use blitz_traits::shell::ShellProvider;
9
+ use euclid::{Point2D, Rect, Size2D};
10
+ use keyboard_types::Modifiers;
11
+ use kurbo::{Affine, Rect as KurboRect};
12
+ use markup5ever::{LocalName, local_name};
13
+ use parley::{BreakReason, Cluster, ClusterSide};
14
+ use selectors::matching::ElementSelectorFlags;
15
+ use std::cell::{Cell, RefCell};
16
+ use std::fmt::Write;
17
+ use std::ops::Deref;
18
+ use std::sync::Arc;
19
+ use std::sync::atomic::{AtomicBool, Ordering};
20
+ #[cfg(feature = "writing-mode")]
21
+ use style::computed_values::flex_direction::T as FlexDirection;
22
+ use style::computed_values::isolation::T as Isolation;
23
+ use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
24
+ use style::invalidation::element::restyle_hints::RestyleHint;
25
+ use style::properties::ComputedValues;
26
+ use style::properties::generated::longhands::position::computed_value::T as Position;
27
+ use style::selector_parser::RestyleDamage;
28
+ use style::servo_arc::Arc as ServoArc;
29
+ use style::shared_lock::SharedRwLock;
30
+ use style::stylesheets::UrlExtraData;
31
+ use style::values::computed::CSSPixelLength;
32
+ use style::values::computed::Display as StyloDisplay;
33
+ use style::values::computed::Rotate;
34
+ use style::values::generics::transform::{Scale, Translate};
35
+ use style::values::specified::box_::{DisplayInside, DisplayOutside};
36
+ use style_dom::ElementState;
37
+ use style_traits::values::ToCss;
38
+ use taffy::{Cache, prelude::Layout};
39
+ use thin_vec::ThinVec;
40
+
41
+ use super::stylo_data::{ComputedStyleRef, StyloData};
42
+ use super::{Attribute, DocumentData, ElementData, LayoutData};
43
+
44
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
45
+ pub enum DisplayOuter {
46
+ Block,
47
+ Inline,
48
+ None,
49
+ }
50
+
51
+ bitflags! {
52
+ #[derive(Clone, Copy, PartialEq)]
53
+ pub struct NodeFlags: u32 {
54
+ /// Whether the node is the root node of an Inline Formatting Context
55
+ const IS_INLINE_ROOT = 0b00000001;
56
+ /// Whether the node is the root node of an Table formatting context
57
+ const IS_TABLE_ROOT = 0b00000010;
58
+ /// Whether the node is "in the document" (~= has a parent and isn't a template node)
59
+ const IS_IN_DOCUMENT = 0b00000100;
60
+ }
61
+ }
62
+
63
+ impl NodeFlags {
64
+ #[inline(always)]
65
+ pub fn is_inline_root(&self) -> bool {
66
+ self.contains(Self::IS_INLINE_ROOT)
67
+ }
68
+
69
+ #[inline(always)]
70
+ pub fn is_table_root(&self) -> bool {
71
+ self.contains(Self::IS_TABLE_ROOT)
72
+ }
73
+
74
+ #[inline(always)]
75
+ pub fn is_in_document(&self) -> bool {
76
+ self.contains(Self::IS_IN_DOCUMENT)
77
+ }
78
+
79
+ #[inline(always)]
80
+ pub fn reset_construction_flags(&mut self) {
81
+ self.remove(Self::IS_INLINE_ROOT);
82
+ self.remove(Self::IS_TABLE_ROOT);
83
+ }
84
+ }
85
+
86
+ pub struct Node {
87
+ // The actual tree we belong to. This is unsafe!!
88
+ tree: *mut crate::NodeTree,
89
+
90
+ /// Our Id
91
+ pub id: NodeId,
92
+ /// Our parent's ID
93
+ pub parent: Option<NodeId>,
94
+ // What are our children?
95
+ pub children: ThinVec<NodeId>,
96
+ /// Our parent in the layout hierachy: a separate list that includes anonymous collections of inline elements
97
+ pub layout_parent: Cell<Option<NodeId>>,
98
+ /// A separate child list that includes anonymous collections of inline elements
99
+ pub layout_children: RefCell<Option<ThinVec<NodeId>>>,
100
+ /// Out-of-flow (absolutely/fixed positioned) boxes for which this node is the
101
+ /// containing block. Recorded by Taffy's out-of-flow positioning pass. The
102
+ /// `Layout.location` of these boxes is relative to this node's border box.
103
+ pub hoisted_children: RefCell<ThinVec<NodeId>>,
104
+ /// For an out-of-flow box that was hoisted by Taffy's out-of-flow positioning
105
+ /// pass, the node whose `hoisted_children` list contains it (its containing
106
+ /// block). The box's `Layout.location` is relative to this node rather than
107
+ /// to its `layout_parent`. `None` for in-flow boxes.
108
+ pub oof_containing_block: Cell<Option<NodeId>>,
109
+ /// Anonymous block boxes created for this node during layout construction.
110
+ ///
111
+ /// Anonymous blocks live only in the slab (they are not part of the DOM
112
+ /// `children` list), so we track the ones we own here to be able to
113
+ /// deallocate them when this node is reconstructed.
114
+ pub anonymous_blocks: ThinVec<NodeId>,
115
+ /// The same as layout_children, but sorted by z-index
116
+ pub paint_children: RefCell<Option<ThinVec<NodeId>>>,
117
+ pub stacking_context: Option<Box<StackingContext>>,
118
+ /// The hoisted entries this node's subtree pushed into the enclosing
119
+ /// stacking context on its last (non-skipped) paint-tree build. Replayed
120
+ /// when the subtree is skipped as clean. Empty for stacking-context roots.
121
+ pub sc_contribution_cache: RefCell<ThinVec<HoistedPaintChild>>,
122
+
123
+ // Flags
124
+ pub flags: NodeFlags,
125
+
126
+ /// Node type (Element, TextNode, etc) specific data.
127
+ ///
128
+ /// For element nodes this holds the [`ElementData`], which stores most of
129
+ /// the per-node style/layout state. For the document node it holds the
130
+ /// [`DocumentData`]. Access the moved fields through the forwarding methods
131
+ /// on [`Node`] (e.g. [`Node::style`], [`Node::final_layout`]).
132
+ pub data: NodeData,
133
+ }
134
+
135
+ unsafe impl Send for Node {}
136
+ unsafe impl Sync for Node {}
137
+
138
+ /// Generates forwarding accessors for fields that live on both [`ElementData`]
139
+ /// (element / anonymous block nodes) and [`DocumentData`] (the document node).
140
+ macro_rules! universal_accessors {
141
+ ($($(#[$meta:meta])* $field:ident / $field_mut:ident : $ty:ty),* $(,)?) => {
142
+ impl Node {
143
+ $(
144
+ $(#[$meta])*
145
+ #[inline]
146
+ pub fn $field(&self) -> &$ty {
147
+ match &self.data {
148
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.$field,
149
+ NodeData::Document(data) => &data.$field,
150
+ _ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
151
+ }
152
+ }
153
+
154
+ $(#[$meta])*
155
+ #[inline]
156
+ pub fn $field_mut(&mut self) -> &mut $ty {
157
+ match &mut self.data {
158
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.$field,
159
+ NodeData::Document(data) => &mut data.$field,
160
+ _ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
161
+ }
162
+ }
163
+ )*
164
+ }
165
+ };
166
+ }
167
+
168
+ universal_accessors! {
169
+ stylo_element_data / stylo_element_data_mut: StyloData,
170
+ transform / transform_mut: Option<Box<Affine>>,
171
+ display_constructed_as / display_constructed_as_mut: StyloDisplay,
172
+ // The document node is styled/snapshotted like an element, so it also
173
+ // carries these:
174
+ element_state / element_state_mut: ElementState,
175
+ snapshot_handled / snapshot_handled_mut: AtomicBool,
176
+ // `apply_selector_flags` deposits `for_parent()` flags on the parent node,
177
+ // and the parent of the root <html> element is the document -- so the
178
+ // document has to be able to hold selector flags too.
179
+ selector_flags / selector_flags_mut: Cell<ElementSelectorFlags>,
180
+ }
181
+
182
+ impl Node {
183
+ /// This node's layout output state, or a shared default if layout has
184
+ /// never written to this node.
185
+ ///
186
+ /// Panics for node kinds which do not participate in layout (text and
187
+ /// comment nodes).
188
+ #[inline]
189
+ pub fn layout_data(&self) -> &LayoutData {
190
+ match &self.data {
191
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.layout_data(),
192
+ NodeData::Document(data) => data.layout_data(),
193
+ _ => panic!("`layout_data` is not available on this node kind"),
194
+ }
195
+ }
196
+
197
+ /// Mutable access to this node's layout output state, allocating it if it
198
+ /// does not yet exist.
199
+ ///
200
+ /// Panics for node kinds which do not participate in layout (text and
201
+ /// comment nodes).
202
+ #[inline]
203
+ pub fn layout_data_mut(&mut self) -> &mut LayoutData {
204
+ match &mut self.data {
205
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.layout_data_mut(),
206
+ NodeData::Document(data) => data.layout_data_mut(),
207
+ _ => panic!("`layout_data` is not available on this node kind"),
208
+ }
209
+ }
210
+
211
+ /// Mutable access to this node's layout output state, if it has been
212
+ /// allocated. Never allocates. Returns `None` for node kinds which do not
213
+ /// participate in layout.
214
+ #[inline]
215
+ pub fn try_layout_data_mut(&mut self) -> Option<&mut LayoutData> {
216
+ match &mut self.data {
217
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
218
+ data.layout_data.as_deref_mut()
219
+ }
220
+ NodeData::Document(data) => data.layout_data.as_deref_mut(),
221
+ _ => None,
222
+ }
223
+ }
224
+
225
+ /// Clear this node's taffy layout cache without allocating `LayoutData`
226
+ /// for nodes that have never been laid out.
227
+ #[inline]
228
+ pub fn clear_layout_cache(&mut self) {
229
+ if let Some(layout_data) = self.try_layout_data_mut() {
230
+ layout_data.cache.clear();
231
+ }
232
+ }
233
+
234
+ /// Clear this node's taffy layout cache and any cached inline
235
+ /// `content_widths`, forcing a full relayout of it on the next pass.
236
+ pub fn invalidate_layout_cache(&mut self) {
237
+ self.clear_layout_cache();
238
+ if let Some(inline_layout) = self
239
+ .data
240
+ .downcast_element_mut()
241
+ .and_then(|el| el.inline_layout_data.as_mut())
242
+ {
243
+ inline_layout.content_widths = None;
244
+ }
245
+ }
246
+
247
+ #[inline]
248
+ pub fn cache(&self) -> &Cache {
249
+ &self.layout_data().cache
250
+ }
251
+
252
+ #[inline]
253
+ pub fn cache_mut(&mut self) -> &mut Cache {
254
+ &mut self.layout_data_mut().cache
255
+ }
256
+
257
+ #[inline]
258
+ pub fn unrounded_layout(&self) -> &Layout {
259
+ &self.layout_data().unrounded_layout
260
+ }
261
+
262
+ #[inline]
263
+ pub fn unrounded_layout_mut(&mut self) -> &mut Layout {
264
+ &mut self.layout_data_mut().unrounded_layout
265
+ }
266
+
267
+ #[inline]
268
+ pub fn final_layout(&self) -> &Layout {
269
+ &self.layout_data().final_layout
270
+ }
271
+
272
+ #[inline]
273
+ pub fn final_layout_mut(&mut self) -> &mut Layout {
274
+ &mut self.layout_data_mut().final_layout
275
+ }
276
+
277
+ #[inline]
278
+ pub fn scroll_offset(&self) -> &crate::Point<f64> {
279
+ &self.layout_data().scroll_offset
280
+ }
281
+
282
+ #[inline]
283
+ pub fn scroll_offset_mut(&mut self) -> &mut crate::Point<f64> {
284
+ &mut self.layout_data_mut().scroll_offset
285
+ }
286
+
287
+ #[inline]
288
+ pub fn scrollable_overflow(&self) -> &KurboRect {
289
+ &self.layout_data().scrollable_overflow
290
+ }
291
+
292
+ #[inline]
293
+ pub fn scrollable_overflow_mut(&mut self) -> &mut KurboRect {
294
+ &mut self.layout_data_mut().scrollable_overflow
295
+ }
296
+
297
+ /// Style data from stylo, if this node kind carries it (element or document
298
+ /// nodes). Returns `None` for text/comment nodes.
299
+ #[inline]
300
+ pub fn try_stylo_element_data(&self) -> Option<&StyloData> {
301
+ match &self.data {
302
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
303
+ Some(&data.stylo_element_data)
304
+ }
305
+ NodeData::Document(data) => Some(&data.stylo_element_data),
306
+ _ => None,
307
+ }
308
+ }
309
+
310
+ #[inline]
311
+ pub fn try_stylo_element_data_mut(&mut self) -> Option<&mut StyloData> {
312
+ match &mut self.data {
313
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
314
+ Some(&mut data.stylo_element_data)
315
+ }
316
+ NodeData::Document(data) => Some(&mut data.stylo_element_data),
317
+ _ => None,
318
+ }
319
+ }
320
+
321
+ /// The `dirty_descendants` flag, if this node kind carries it (element or
322
+ /// document nodes). Returns `None` for text/comment nodes.
323
+ #[inline]
324
+ fn dirty_descendants_flag(&self) -> Option<&AtomicBool> {
325
+ match &self.data {
326
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
327
+ Some(&data.dirty_descendants)
328
+ }
329
+ NodeData::Document(data) => Some(&data.dirty_descendants),
330
+ _ => None,
331
+ }
332
+ }
333
+
334
+ /// The `damaged_descendants` flag, if this node kind carries it (element or
335
+ /// document nodes). Returns `None` for text/comment nodes.
336
+ #[inline]
337
+ fn damaged_descendants_flag(&self) -> Option<&AtomicBool> {
338
+ match &self.data {
339
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
340
+ Some(&data.damaged_descendants)
341
+ }
342
+ NodeData::Document(data) => Some(&data.damaged_descendants),
343
+ _ => None,
344
+ }
345
+ }
346
+
347
+ /// The document's shared style lock. Only available on element and
348
+ /// document nodes.
349
+ #[inline]
350
+ pub fn guard(&self) -> &SharedRwLock {
351
+ let guard = match &self.data {
352
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.guard.as_ref(),
353
+ NodeData::Document(data) => data.guard.as_ref(),
354
+ _ => None,
355
+ };
356
+ guard.expect("`guard` is not available on this node kind")
357
+ }
358
+
359
+ #[inline]
360
+ pub fn has_snapshot(&self) -> bool {
361
+ match &self.data {
362
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot,
363
+ NodeData::Document(data) => data.has_snapshot,
364
+ _ => false,
365
+ }
366
+ }
367
+
368
+ #[inline]
369
+ pub fn set_has_snapshot(&mut self, value: bool) {
370
+ match &mut self.data {
371
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot = value,
372
+ NodeData::Document(data) => data.has_snapshot = value,
373
+ _ => {}
374
+ }
375
+ }
376
+
377
+ #[inline]
378
+ pub fn before(&self) -> Option<NodeId> {
379
+ self.element_data().and_then(|data| data.before)
380
+ }
381
+
382
+ #[inline]
383
+ pub fn after(&self) -> Option<NodeId> {
384
+ self.element_data().and_then(|data| data.after)
385
+ }
386
+ }
387
+
388
+ impl Node {
389
+ pub(crate) fn new(
390
+ tree: *mut crate::NodeTree,
391
+ id: NodeId,
392
+ guard: SharedRwLock,
393
+ mut data: NodeData,
394
+ ) -> Self {
395
+ // Store a handle to the document's shared style lock on the node data.
396
+ // Both element and document nodes are styled by stylo and so need it.
397
+ match &mut data {
398
+ NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
399
+ data.guard = Some(guard);
400
+ }
401
+ NodeData::Document(data) => data.guard = Some(guard),
402
+ _ => {}
403
+ }
404
+
405
+ Self {
406
+ tree,
407
+
408
+ id,
409
+ parent: None,
410
+ children: ThinVec::new(),
411
+ layout_parent: Cell::new(None),
412
+ oof_containing_block: Cell::new(None),
413
+ layout_children: RefCell::new(None),
414
+ hoisted_children: RefCell::new(ThinVec::new()),
415
+ anonymous_blocks: ThinVec::new(),
416
+ paint_children: RefCell::new(None),
417
+ stacking_context: None,
418
+ sc_contribution_cache: RefCell::new(ThinVec::new()),
419
+
420
+ flags: NodeFlags::empty(),
421
+ data,
422
+ }
423
+ }
424
+
425
+ pub fn set_transform(&mut self, scale: f32) -> Option<Affine> {
426
+ let transform = self.primary_styles().and_then(|s| {
427
+ let size = self.final_layout().size;
428
+ let reference_box = Rect::new(
429
+ Point2D::new(CSSPixelLength::new(0.0), CSSPixelLength::new(0.0)),
430
+ Size2D::new(
431
+ CSSPixelLength::new(size.width),
432
+ CSSPixelLength::new(size.height),
433
+ ),
434
+ );
435
+ // Resolve the transform in CSS pixels, then convert it to device-pixel space
436
+ // (S * T * S^-1): translation components are scaled, linear components are not.
437
+ crate::resolve_2d_transform(s.get_box(), reference_box).map(|t| {
438
+ let scale = scale as f64;
439
+ let [m11, m12, m21, m22, m41, m42] = t.as_coeffs();
440
+ Affine::new([m11, m12, m21, m22, m41 * scale, m42 * scale])
441
+ })
442
+ });
443
+
444
+ let slot = self.transform_mut();
445
+ match (slot.as_deref_mut(), transform) {
446
+ (Some(existing), Some(new)) => *existing = new,
447
+ (None, Some(new)) => *slot = Some(Box::new(new)),
448
+ (_, None) => *slot = None,
449
+ }
450
+ transform
451
+ }
452
+
453
+ pub fn pe_by_index(&self, index: usize) -> Option<NodeId> {
454
+ match index {
455
+ 0 => self.after(),
456
+ 1 => self.before(),
457
+ _ => panic!("Invalid pseudo element index"),
458
+ }
459
+ }
460
+
461
+ pub fn set_pe_by_index(&mut self, index: usize, value: Option<NodeId>) {
462
+ let Some(data) = self.element_data_mut() else {
463
+ return;
464
+ };
465
+ match index {
466
+ 0 => data.after = value,
467
+ 1 => data.before = value,
468
+ _ => panic!("Invalid pseudo element index"),
469
+ }
470
+ }
471
+
472
+ pub(crate) fn display_style(&self) -> Option<StyloDisplay> {
473
+ let display = self.primary_styles().as_ref()?.clone_display();
474
+ Some(
475
+ if self.element_data().is_some_and(|el| el.is_button_input()) {
476
+ stylo_taffy::convert::button_input_display(display)
477
+ } else {
478
+ display
479
+ },
480
+ )
481
+ }
482
+
483
+ pub fn is_or_contains_block(&self) -> bool {
484
+ let style = self.primary_styles();
485
+ let style = style.as_ref();
486
+
487
+ // Ignore out-of-flow items
488
+ let position = style
489
+ .map(|s| s.clone_position())
490
+ .unwrap_or(Position::Relative);
491
+ let is_in_flow = matches!(
492
+ position,
493
+ Position::Static | Position::Relative | Position::Sticky
494
+ );
495
+ if !is_in_flow {
496
+ return false;
497
+ }
498
+ // Floated boxes do not break up the inline flow: they participate in the
499
+ // inline formatting context as out-of-flow inline boxes
500
+ let is_floating = style
501
+ .map(|s| s.clone_float().is_floating())
502
+ .unwrap_or(false);
503
+ if is_floating {
504
+ return false;
505
+ }
506
+ let display = self.display_style().unwrap_or(StyloDisplay::inline());
507
+ match display.outside() {
508
+ DisplayOutside::None => false,
509
+ DisplayOutside::Block => true,
510
+ _ => {
511
+ if display.inside() == DisplayInside::Flow {
512
+ self.children
513
+ .iter()
514
+ .copied()
515
+ .any(|child_id| self.tree()[child_id].is_or_contains_block())
516
+ } else {
517
+ false
518
+ }
519
+ }
520
+ }
521
+ }
522
+
523
+ pub fn is_whitespace_node(&self) -> bool {
524
+ match &self.data {
525
+ NodeData::Text(data) => data.content.chars().all(|c| c.is_ascii_whitespace()),
526
+ _ => false,
527
+ }
528
+ }
529
+
530
+ /// Whether this is an empty or whitespace-only text node whose whitespace may be collapsed
531
+ /// away under the `white-space-collapse` it inherits from its parent.
532
+ pub fn is_collapsible_whitespace_node(&self) -> bool {
533
+ let NodeData::Text(data) = &self.data else {
534
+ return false;
535
+ };
536
+ if data.content.is_empty() {
537
+ return true;
538
+ }
539
+ if !data.content.chars().all(|c| c.is_ascii_whitespace()) {
540
+ return false;
541
+ }
542
+ let white_space_collapse = self
543
+ .parent
544
+ .and_then(|parent_id| self.with(parent_id).primary_styles())
545
+ .map(|style| style.clone_white_space_collapse());
546
+ match white_space_collapse {
547
+ Some(WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces) => false,
548
+ Some(WhiteSpaceCollapse::PreserveBreaks) => !data.content.contains('\n'),
549
+ Some(WhiteSpaceCollapse::Collapse) | None => true,
550
+ }
551
+ }
552
+
553
+ pub fn is_focussable(&self) -> bool {
554
+ self.data
555
+ .downcast_element()
556
+ .map(|el| el.is_focussable)
557
+ .unwrap_or(false)
558
+ }
559
+
560
+ pub fn set_restyle_hint(&mut self, hint: RestyleHint) {
561
+ if let Some(stylo_element_data) = self.try_stylo_element_data_mut() {
562
+ if let Some(mut element_data) = stylo_element_data.get_mut() {
563
+ element_data.hint.insert(hint);
564
+ }
565
+ }
566
+ // Mark all ancestors as having dirty descendants so the style traversal
567
+ // will visit this node's subtree
568
+ self.mark_ancestors_dirty();
569
+ }
570
+
571
+ /// Returns whether this node has any descendants that need restyling.
572
+ pub fn has_dirty_descendants(&self) -> bool {
573
+ self.dirty_descendants_flag()
574
+ .is_some_and(|flag| flag.load(Ordering::Relaxed))
575
+ }
576
+
577
+ /// Sets the dirty_descendants flag on this node.
578
+ pub fn set_dirty_descendants(&self) {
579
+ if let Some(flag) = self.dirty_descendants_flag() {
580
+ flag.store(true, Ordering::Relaxed);
581
+ }
582
+ }
583
+
584
+ /// Clears the dirty_descendants flag on this node.
585
+ pub fn unset_dirty_descendants(&self) {
586
+ if let Some(flag) = self.dirty_descendants_flag() {
587
+ flag.store(false, Ordering::Relaxed);
588
+ }
589
+ }
590
+
591
+ /// Marks all ancestors of this node as having dirty descendants.
592
+ /// This propagates the dirty flag up the tree so that the style traversal
593
+ /// knows to visit the subtree containing this node.
594
+ pub fn mark_ancestors_dirty(&self) {
595
+ let mut current_id = self.parent;
596
+ while let Some(parent_id) = current_id {
597
+ let parent = &self.tree()[parent_id];
598
+ // If this ancestor already has dirty_descendants set, we can stop
599
+ // because all further ancestors must also have it set
600
+ if let Some(flag) = parent.dirty_descendants_flag() {
601
+ if flag.swap(true, Ordering::Relaxed) {
602
+ break;
603
+ }
604
+ }
605
+ current_id = parent.parent;
606
+ }
607
+ }
608
+
609
+ /// Returns whether this node or any of its descendants may carry damage.
610
+ pub fn has_damaged_descendants(&self) -> bool {
611
+ self.damaged_descendants_flag()
612
+ .is_some_and(|flag| flag.load(Ordering::Relaxed))
613
+ }
614
+
615
+ /// Clears the damaged_descendants flag on this node.
616
+ pub fn unset_damaged_descendants(&self) {
617
+ if let Some(flag) = self.damaged_descendants_flag() {
618
+ flag.store(false, Ordering::Relaxed);
619
+ }
620
+ }
621
+
622
+ /// Marks this node and all of its ancestors as (potentially) carrying
623
+ /// damage, so that the damage propagation pass visits this node's subtree.
624
+ ///
625
+ /// The invariant is: if a node carries damage (or needs damage-phase
626
+ /// processing such as pseudo-element style syncing), then it and all of
627
+ /// its ancestors have `damaged_descendants` set.
628
+ pub fn mark_damaged(&self) {
629
+ if let Some(flag) = self.damaged_descendants_flag() {
630
+ if flag.swap(true, Ordering::Relaxed) {
631
+ return;
632
+ }
633
+ }
634
+ let mut current_id = self.parent;
635
+ while let Some(parent_id) = current_id {
636
+ let parent = &self.tree()[parent_id];
637
+ // If this ancestor already has damaged_descendants set, we can stop
638
+ // because all further ancestors must also have it set
639
+ if let Some(flag) = parent.damaged_descendants_flag() {
640
+ if flag.swap(true, Ordering::Relaxed) {
641
+ break;
642
+ }
643
+ }
644
+ current_id = parent.parent;
645
+ }
646
+ }
647
+
648
+ // pub fn damage_mut(&mut self) -> Option<&mut RestyleDamage> {
649
+ // self.stylo_element_data
650
+ // .get_mut()
651
+ // .map(|mut data: ElementDataMut<'a>| &'a mut data.damage)
652
+ // }
653
+
654
+ pub fn damage(&self) -> Option<RestyleDamage> {
655
+ self.try_stylo_element_data()
656
+ .and_then(|stylo| stylo.get().map(|data| data.damage))
657
+ }
658
+
659
+ pub fn set_damage(&mut self, damage: RestyleDamage) {
660
+ if let Some(stylo) = self.try_stylo_element_data_mut() {
661
+ if let Some(mut data) = stylo.get_mut() {
662
+ data.damage = damage;
663
+ }
664
+ }
665
+ }
666
+
667
+ pub fn insert_damage(&mut self, damage: RestyleDamage) {
668
+ if let Some(stylo) = self.try_stylo_element_data_mut() {
669
+ if let Some(mut data) = stylo.get_mut() {
670
+ data.damage |= damage;
671
+ }
672
+ }
673
+ if !damage.is_empty() {
674
+ self.mark_damaged();
675
+ }
676
+ }
677
+
678
+ pub fn remove_damage(&mut self, damage: RestyleDamage) {
679
+ if let Some(stylo) = self.try_stylo_element_data_mut() {
680
+ if let Some(mut data) = stylo.get_mut() {
681
+ data.damage.remove(damage);
682
+ }
683
+ }
684
+ }
685
+
686
+ pub fn clear_damage_mut(&mut self) {
687
+ if let Some(stylo) = self.try_stylo_element_data_mut() {
688
+ if let Some(mut data) = stylo.get_mut() {
689
+ data.damage = RestyleDamage::empty();
690
+ }
691
+ }
692
+ }
693
+
694
+ // State changes (hover/focus/active/disabled) do not set a restyle hint.
695
+ // Invalidation is driven by element snapshots: the style traversal diffs the
696
+ // snapshotted (pre-change) state against the current state and invalidates
697
+ // only the elements matched by selectors that depend on the changed state
698
+ // bits. Ancestors are marked dirty so the traversal reaches this node.
699
+ pub fn hover(&mut self) {
700
+ if let Some(data) = self.element_data_mut() {
701
+ data.element_state.insert(ElementState::HOVER);
702
+ }
703
+ self.mark_ancestors_dirty();
704
+ }
705
+
706
+ pub fn unhover(&mut self) {
707
+ if let Some(data) = self.element_data_mut() {
708
+ data.element_state.remove(ElementState::HOVER);
709
+ }
710
+ self.mark_ancestors_dirty();
711
+ }
712
+
713
+ pub fn is_hovered(&self) -> bool {
714
+ self.element_data()
715
+ .is_some_and(|data| data.element_state.contains(ElementState::HOVER))
716
+ }
717
+
718
+ pub fn focus(&mut self, shell_provider: Arc<dyn ShellProvider>) {
719
+ if let Some(data) = self.element_data_mut() {
720
+ data.element_state
721
+ .insert(ElementState::FOCUS | ElementState::FOCUSRING);
722
+ }
723
+ self.mark_ancestors_dirty();
724
+
725
+ // If focussing a text input, enable IME and set IME area
726
+ if self
727
+ .element_data()
728
+ .and_then(|elem| elem.text_input_data())
729
+ .is_some()
730
+ {
731
+ shell_provider.set_ime_enabled(true);
732
+ let mut pos = self.absolute_position(0.0, 0.0);
733
+ pos.x += self.final_layout().content_box_x();
734
+ pos.y += self.final_layout().content_box_y();
735
+ let width = self.final_layout().content_box_width();
736
+ let height = self.final_layout().content_box_height();
737
+ shell_provider.set_ime_cursor_area(pos.x, pos.y, width, height);
738
+ }
739
+ }
740
+
741
+ pub fn blur(&mut self, shell_provider: Arc<dyn ShellProvider>) {
742
+ if let Some(data) = self.element_data_mut() {
743
+ data.element_state
744
+ .remove(ElementState::FOCUS | ElementState::FOCUSRING);
745
+ }
746
+ self.mark_ancestors_dirty();
747
+
748
+ // If blurring a text input, disable IME
749
+ if self
750
+ .element_data()
751
+ .and_then(|elem| elem.text_input_data())
752
+ .is_some()
753
+ {
754
+ shell_provider.set_ime_enabled(false);
755
+ }
756
+ }
757
+
758
+ pub fn is_focussed(&self) -> bool {
759
+ self.element_data()
760
+ .is_some_and(|data| data.element_state.contains(ElementState::FOCUS))
761
+ }
762
+
763
+ pub fn active(&mut self) {
764
+ if let Some(data) = self.element_data_mut() {
765
+ data.element_state.insert(ElementState::ACTIVE);
766
+ }
767
+ self.mark_ancestors_dirty();
768
+ }
769
+
770
+ pub fn unactive(&mut self) {
771
+ if let Some(data) = self.element_data_mut() {
772
+ data.element_state.remove(ElementState::ACTIVE);
773
+ }
774
+ self.mark_ancestors_dirty();
775
+ }
776
+
777
+ pub fn is_active(&self) -> bool {
778
+ self.element_data()
779
+ .is_some_and(|data| data.element_state.contains(ElementState::ACTIVE))
780
+ }
781
+
782
+ // Marks the node as disabled if it can be.
783
+ // It does not disable any children which should be disabled as well (relevant for the `select` element).
784
+ pub fn disable(&mut self) {
785
+ if let Some(data) = self.element_data_mut() {
786
+ if data.can_be_disabled() {
787
+ data.element_state.insert(ElementState::DISABLED);
788
+ data.element_state.remove(ElementState::ENABLED);
789
+ }
790
+ }
791
+ self.mark_ancestors_dirty();
792
+ }
793
+
794
+ // Marks the node as enabled if it can be.
795
+ // It does not enable any children which should be enabled as well (relevant for the `select` element).
796
+ pub fn enable(&mut self) {
797
+ if let Some(data) = self.element_data_mut() {
798
+ if data.can_be_disabled() {
799
+ data.element_state.insert(ElementState::ENABLED);
800
+ data.element_state.remove(ElementState::DISABLED);
801
+ }
802
+ }
803
+ self.mark_ancestors_dirty();
804
+ }
805
+
806
+ pub fn subdoc(&self) -> Option<&dyn Document> {
807
+ self.element_data().and_then(|el| el.sub_doc_data())
808
+ }
809
+
810
+ pub fn subdoc_mut(&mut self) -> Option<&mut dyn Document> {
811
+ self.element_data_mut().and_then(|el| el.sub_doc_data_mut())
812
+ }
813
+
814
+ pub fn text_input_v_centering_offset(&self, scale: f64) -> f64 {
815
+ // For single-line inputs, add an offset to vertically center the text input layout
816
+ // within the content box of it's node.
817
+ if let Some(input_data) = self
818
+ .data
819
+ .downcast_element()
820
+ .and_then(|el| el.text_input_data())
821
+ {
822
+ if !input_data.is_multiline {
823
+ let content_box_height = self.final_layout().content_box_height();
824
+ let input_height = input_data.editor.try_layout().unwrap().height() / scale as f32;
825
+ let y_offset = ((content_box_height - input_height) / 2.0).max(0.0);
826
+
827
+ return y_offset as f64;
828
+ }
829
+ }
830
+
831
+ 0.0
832
+ }
833
+ }
834
+
835
+ #[derive(Debug, Clone, Copy, PartialEq)]
836
+ pub enum NodeKind {
837
+ Document,
838
+ Element,
839
+ AnonymousBlock,
840
+ Text,
841
+ Comment,
842
+ }
843
+
844
+ /// The different kinds of nodes in the DOM.
845
+ #[derive(Debug, Clone)]
846
+ pub enum NodeData {
847
+ /// The `Document` itself - the root node of a HTML document.
848
+ Document(Box<DocumentData>),
849
+
850
+ /// An element with attributes.
851
+ Element(Box<ElementData>),
852
+
853
+ /// An anonymous block box
854
+ AnonymousBlock(Box<ElementData>),
855
+
856
+ /// A text node.
857
+ Text(TextNodeData),
858
+
859
+ /// A comment.
860
+ Comment {
861
+ /// The textual content of the comment
862
+ contents: String,
863
+ },
864
+ // /// A `DOCTYPE` with name, public id, and system id. See
865
+ // /// [document type declaration on wikipedia][https://en.wikipedia.org/wiki/Document_type_declaration]
866
+ // Doctype { name: String, public_id: String, system_id: String },
867
+
868
+ // /// A Processing instruction.
869
+ // ProcessingInstruction { target: String, contents: String },
870
+ }
871
+
872
+ impl NodeData {
873
+ pub fn downcast_element(&self) -> Option<&ElementData> {
874
+ match self {
875
+ Self::Element(data) => Some(data),
876
+ Self::AnonymousBlock(data) => Some(data),
877
+ _ => None,
878
+ }
879
+ }
880
+
881
+ pub fn downcast_element_mut(&mut self) -> Option<&mut ElementData> {
882
+ match self {
883
+ Self::Element(data) => Some(data),
884
+ Self::AnonymousBlock(data) => Some(data),
885
+ _ => None,
886
+ }
887
+ }
888
+
889
+ pub fn is_element_with_tag_name(&self, name: &impl PartialEq<LocalName>) -> bool {
890
+ let Some(elem) = self.downcast_element() else {
891
+ return false;
892
+ };
893
+ *name == elem.name.local
894
+ }
895
+
896
+ pub fn attrs(&self) -> Option<&[Attribute]> {
897
+ Some(&self.downcast_element()?.attrs)
898
+ }
899
+
900
+ pub fn attr(&self, name: impl PartialEq<LocalName>) -> Option<&str> {
901
+ self.downcast_element()?.attr(name)
902
+ }
903
+
904
+ pub fn has_attr(&self, name: impl PartialEq<LocalName>) -> bool {
905
+ self.downcast_element()
906
+ .is_some_and(|elem| elem.has_attr(name))
907
+ }
908
+
909
+ pub fn kind(&self) -> NodeKind {
910
+ match self {
911
+ NodeData::Document(_) => NodeKind::Document,
912
+ NodeData::Element(_) => NodeKind::Element,
913
+ NodeData::AnonymousBlock(_) => NodeKind::AnonymousBlock,
914
+ NodeData::Text(_) => NodeKind::Text,
915
+ NodeData::Comment { .. } => NodeKind::Comment,
916
+ }
917
+ }
918
+ }
919
+
920
+ #[derive(Debug, Clone)]
921
+ pub struct TextNodeData {
922
+ /// The textual content of the text node
923
+ pub content: String,
924
+ }
925
+
926
+ impl TextNodeData {
927
+ pub fn new(content: String) -> Self {
928
+ Self { content }
929
+ }
930
+ }
931
+
932
+ /*
933
+ -> Computed styles
934
+ -> Layout
935
+ -----> Needs to happen only when styles are computed
936
+ */
937
+
938
+ // type DomRefCell<T> = RefCell<T>;
939
+
940
+ // pub struct DomData {
941
+ // // ... we can probs just get away with using the html5ever types directly. basically just using the servo dom, but without the bindings
942
+ // local_name: html5ever::LocalName,
943
+ // tag_name: html5ever::QualName,
944
+ // namespace: html5ever::Namespace,
945
+ // prefix: DomRefCell<Option<html5ever::Prefix>>,
946
+ // attrs: DomRefCell<Vec<Attr>>,
947
+ // // attrs: DomRefCell<Vec<Dom<Attr>>>,
948
+ // id_attribute: DomRefCell<Option<Atom>>,
949
+ // is: DomRefCell<Option<LocalName>>,
950
+ // // style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
951
+ // // attr_list: MutNullableDom<NamedNodeMap>,
952
+ // // class_list: MutNullableDom<DOMTokenList>,
953
+ // state: Cell<ElementState>,
954
+ // }
955
+
956
+ impl Node {
957
+ pub fn tree(&self) -> &crate::NodeTree {
958
+ unsafe { &*self.tree }
959
+ }
960
+
961
+ #[track_caller]
962
+ pub fn with(&self, id: NodeId) -> &Node {
963
+ self.tree().get(id).unwrap()
964
+ }
965
+
966
+ pub fn print_tree(&self, level: usize) {
967
+ println!(
968
+ "{} {} {:?} {} {:?}",
969
+ " ".repeat(level),
970
+ self.id,
971
+ self.parent,
972
+ self.node_debug_str().replace('\n', ""),
973
+ self.children
974
+ );
975
+ // println!("{} {:?}", " ".repeat(level), self.children);
976
+ for child_id in self.children.iter() {
977
+ let child = self.with(*child_id);
978
+ child.print_tree(level + 1)
979
+ }
980
+ }
981
+
982
+ // Get the index of the current node in the parents child list
983
+ pub fn index_of_child(&self, child_id: NodeId) -> Option<usize> {
984
+ self.children.iter().position(|id| *id == child_id)
985
+ }
986
+
987
+ // Get the index of the current node in the parents child list
988
+ pub fn child_index(&self) -> Option<usize> {
989
+ self.tree()[self.parent?]
990
+ .children
991
+ .iter()
992
+ .position(|id| *id == self.id)
993
+ }
994
+
995
+ // Get the nth node in the parents child list
996
+ pub fn forward(&self, n: usize) -> Option<&Node> {
997
+ let child_idx = self.child_index().unwrap_or(0);
998
+ self.tree()[self.parent?]
999
+ .children
1000
+ .get(child_idx + n)
1001
+ .map(|id| self.with(*id))
1002
+ }
1003
+
1004
+ pub fn backward(&self, n: usize) -> Option<&Node> {
1005
+ let child_idx = self.child_index().unwrap_or(0);
1006
+ if child_idx < n {
1007
+ return None;
1008
+ }
1009
+
1010
+ self.tree()[self.parent?]
1011
+ .children
1012
+ .get(child_idx - n)
1013
+ .map(|id| self.with(*id))
1014
+ }
1015
+
1016
+ pub fn is_element(&self) -> bool {
1017
+ matches!(self.data, NodeData::Element { .. })
1018
+ }
1019
+
1020
+ pub fn is_anonymous(&self) -> bool {
1021
+ matches!(self.data, NodeData::AnonymousBlock { .. })
1022
+ }
1023
+
1024
+ pub fn is_text_node(&self) -> bool {
1025
+ matches!(self.data, NodeData::Text { .. })
1026
+ }
1027
+
1028
+ pub fn element_data(&self) -> Option<&ElementData> {
1029
+ match self.data {
1030
+ NodeData::Element(ref data) => Some(data),
1031
+ NodeData::AnonymousBlock(ref data) => Some(data),
1032
+ _ => None,
1033
+ }
1034
+ }
1035
+
1036
+ pub fn element_data_mut(&mut self) -> Option<&mut ElementData> {
1037
+ match self.data {
1038
+ NodeData::Element(ref mut data) => Some(data),
1039
+ NodeData::AnonymousBlock(ref mut data) => Some(data),
1040
+ _ => None,
1041
+ }
1042
+ }
1043
+
1044
+ pub fn text_data(&self) -> Option<&TextNodeData> {
1045
+ match self.data {
1046
+ NodeData::Text(ref data) => Some(data),
1047
+ _ => None,
1048
+ }
1049
+ }
1050
+
1051
+ pub fn text_data_mut(&mut self) -> Option<&mut TextNodeData> {
1052
+ match self.data {
1053
+ NodeData::Text(ref mut data) => Some(data),
1054
+ _ => None,
1055
+ }
1056
+ }
1057
+
1058
+ pub fn node_debug_str(&self) -> String {
1059
+ let mut s = String::new();
1060
+
1061
+ match &self.data {
1062
+ NodeData::Document(_) => write!(s, "DOCUMENT"),
1063
+ // NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
1064
+ NodeData::Text(data) => {
1065
+ let bytes = data.content.as_bytes();
1066
+ write!(
1067
+ s,
1068
+ "TEXT {}",
1069
+ std::str::from_utf8(bytes.split_at(10.min(bytes.len())).0)
1070
+ .unwrap_or("INVALID UTF8")
1071
+ )
1072
+ }
1073
+ NodeData::Comment { .. } => write!(s, "COMMENT"),
1074
+ NodeData::AnonymousBlock(_) => write!(s, "AnonymousBlock"),
1075
+ NodeData::Element(data) => {
1076
+ let name = &data.name;
1077
+ let class = self.attr(local_name!("class")).unwrap_or("");
1078
+ let id = self.attr(local_name!("id")).unwrap_or("");
1079
+ let display = self.display_constructed_as().to_css_string();
1080
+ write!(s, "<{}", name.local).unwrap();
1081
+ if !id.is_empty() {
1082
+ write!(s, " #{id}").unwrap();
1083
+ }
1084
+ if !class.is_empty() {
1085
+ if class.contains(' ') {
1086
+ write!(s, " class=\"{class}\"").unwrap()
1087
+ } else {
1088
+ write!(s, " .{class}").unwrap()
1089
+ }
1090
+ }
1091
+ write!(s, "> ({display})")
1092
+ } // NodeData::ProcessingInstruction { .. } => write!(s, "ProcessingInstruction"),
1093
+ }
1094
+ .unwrap();
1095
+ s
1096
+ }
1097
+
1098
+ pub fn attrs(&self) -> Option<&[Attribute]> {
1099
+ Some(&self.element_data()?.attrs)
1100
+ }
1101
+
1102
+ pub fn attr(&self, name: LocalName) -> Option<&str> {
1103
+ let attr = self.attrs()?.iter().find(|id| id.name.local == name)?;
1104
+ Some(&attr.value)
1105
+ }
1106
+
1107
+ pub fn primary_styles(&self) -> Option<impl Deref<Target = ServoArc<ComputedValues>>> {
1108
+ self.try_stylo_element_data()
1109
+ .and_then(|stylo| stylo.primary_styles())
1110
+ }
1111
+
1112
+ /// A lazy Taffy style backed by this node's primary stylo style.
1113
+ ///
1114
+ /// Panics if the node has no computed styles: layout always runs after
1115
+ /// styling, and the only unstyled nodes (text, comments, descendants of
1116
+ /// `display: none`) are never queried by Taffy.
1117
+ pub fn layout_style(&self) -> stylo_taffy::TaffyStyloStyle<ComputedStyleRef<'_>> {
1118
+ let styles = self
1119
+ .try_stylo_element_data()
1120
+ .and_then(|stylo| stylo.computed_styles())
1121
+ .expect("layout_style() called on a node without computed styles");
1122
+
1123
+ let mut flags = stylo_taffy::StyleFlags::empty();
1124
+ if let Some(el) = self.data.downcast_element() {
1125
+ if crate::layout::replaced::is_replaced_element(&el.name.local) {
1126
+ flags |= stylo_taffy::StyleFlags::IS_REPLACED;
1127
+ }
1128
+ if el.name.local == local_name!("button") {
1129
+ flags |= stylo_taffy::StyleFlags::IS_BUTTON;
1130
+ }
1131
+ if el.is_button_input() {
1132
+ flags |= stylo_taffy::StyleFlags::IS_BUTTON_INPUT;
1133
+ }
1134
+ if let Some(inline_layout) = el.inline_layout_data.as_deref() {
1135
+ flags |= inline_layout.span_cb_flags;
1136
+ }
1137
+ }
1138
+
1139
+ #[cfg(feature = "writing-mode")]
1140
+ {
1141
+ // Own-layout_wm by default: the node's own algorithm reads its style in its own axes
1142
+ let layout_wm = styles.writing_mode;
1143
+ stylo_taffy::TaffyStyloStyle::new_in(styles, flags, layout_wm)
1144
+ }
1145
+ #[cfg(not(feature = "writing-mode"))]
1146
+ {
1147
+ stylo_taffy::TaffyStyloStyle::new(styles, flags)
1148
+ }
1149
+ }
1150
+
1151
+ /// The node's style for Taffy, expressed in the axes of the writing mode `layout_wm` (the writing
1152
+ /// mode of the box laying this node out). Used for the child-style getters.
1153
+ #[cfg(feature = "writing-mode")]
1154
+ pub fn layout_style_in(
1155
+ &self,
1156
+ layout_wm: stylo_taffy::WritingMode,
1157
+ ) -> stylo_taffy::TaffyStyloStyle<ComputedStyleRef<'_>> {
1158
+ let mut style = self.layout_style();
1159
+ style.layout_wm = layout_wm;
1160
+ style
1161
+ }
1162
+
1163
+ /// Whether the node has any `contain` value, which blocks `writing-mode` propagation from
1164
+ /// `<body>` to the root (css-writing-modes-3 §8).
1165
+ #[cfg(feature = "writing-mode")]
1166
+ pub(crate) fn has_containment(&self) -> bool {
1167
+ self.primary_styles()
1168
+ .is_some_and(|style| !style.clone_contain().is_empty())
1169
+ }
1170
+
1171
+ /// Whether the node is a flex container with a column `flex-direction`, i.e. aligns its
1172
+ /// children's `align-self` in its inline axis.
1173
+ #[cfg(feature = "writing-mode")]
1174
+ pub(crate) fn is_column_flex_container(&self) -> bool {
1175
+ self.primary_styles().is_some_and(|s| {
1176
+ s.clone_display().inside() == DisplayInside::Flex
1177
+ && !self.element_data().is_some_and(|el| el.is_button_input())
1178
+ && matches!(
1179
+ s.get_position().flex_direction,
1180
+ FlexDirection::Column | FlexDirection::ColumnReverse
1181
+ )
1182
+ })
1183
+ }
1184
+
1185
+ /// The node's computed `writing-mode` (horizontal-tb for nodes without styles)
1186
+ #[cfg(feature = "writing-mode")]
1187
+ pub fn writing_mode(&self) -> stylo_taffy::WritingMode {
1188
+ self.primary_styles()
1189
+ .map(|s| s.writing_mode)
1190
+ .unwrap_or(stylo_taffy::WritingMode::empty())
1191
+ }
1192
+
1193
+ /// The node's `display` as a [`taffy::Display`]. Returns [`taffy::Display::Block`]
1194
+ /// for nodes without computed styles (e.g. text nodes).
1195
+ pub fn taffy_display(&self) -> taffy::Display {
1196
+ self.primary_styles()
1197
+ .map(|style| {
1198
+ let display = style.clone_display();
1199
+ if self.element_data().is_some_and(|el| el.is_button_input())
1200
+ && !matches!(
1201
+ display.inside(),
1202
+ DisplayInside::None | DisplayInside::Contents
1203
+ )
1204
+ {
1205
+ taffy::Display::FlowRoot
1206
+ } else {
1207
+ stylo_taffy::convert::display(display)
1208
+ }
1209
+ })
1210
+ .unwrap_or(taffy::Display::Block)
1211
+ }
1212
+
1213
+ /// The node's `position` as a [`taffy::Position`]. Returns [`taffy::Position::Static`]
1214
+ /// for nodes without computed styles (e.g. text nodes).
1215
+ pub fn taffy_position(&self) -> taffy::Position {
1216
+ self.primary_styles()
1217
+ .map(|s| stylo_taffy::convert::position(s.get_box().position))
1218
+ .unwrap_or(taffy::Position::Static)
1219
+ }
1220
+
1221
+ /// Whether the node is an out-of-flow box that Taffy positions from its containing
1222
+ /// block's hoisted child list rather than from its parent (`display: none` boxes
1223
+ /// generate no box and are never hoisted).
1224
+ pub fn is_out_of_flow(&self) -> bool {
1225
+ self.primary_styles().is_some_and(|s| {
1226
+ let box_style = s.get_box();
1227
+ stylo_taffy::convert::position(box_style.position).is_out_of_flow()
1228
+ && stylo_taffy::convert::display(box_style.display) != taffy::Display::None
1229
+ })
1230
+ }
1231
+
1232
+ pub fn text_content(&self) -> String {
1233
+ let mut out = String::new();
1234
+ self.write_text_content(&mut out);
1235
+ out
1236
+ }
1237
+
1238
+ fn write_text_content(&self, out: &mut String) {
1239
+ match &self.data {
1240
+ NodeData::Text(data) => {
1241
+ out.push_str(&data.content);
1242
+ }
1243
+ NodeData::Element(..) | NodeData::AnonymousBlock(..) => {
1244
+ for child_id in self.children.iter() {
1245
+ self.with(*child_id).write_text_content(out);
1246
+ }
1247
+ }
1248
+ _ => {}
1249
+ }
1250
+ }
1251
+
1252
+ pub fn flush_style_attribute(&mut self, url_extra_data: &UrlExtraData) {
1253
+ if let NodeData::Element(ref mut elem_data) = self.data {
1254
+ if let Some(guard) = elem_data.guard.clone() {
1255
+ elem_data.flush_style_attribute(&guard, url_extra_data);
1256
+ }
1257
+ }
1258
+ }
1259
+
1260
+ /// The `order` sort key of this node within a flex/grid container's
1261
+ /// `layout_children`. The list is stable-sorted by this key when the
1262
+ /// container's children are constructed (`collect_layout_children`) and
1263
+ /// re-collected when a child's `order` changes (`REORDER_CHILDREN` damage).
1264
+ ///
1265
+ /// ::before/::after pseudos are flex/grid items and honor `order`. They
1266
+ /// sit first/last in the constructed list, and the sort is stable, so
1267
+ /// ties keep ::before first and ::after last. Out-of-flow children are
1268
+ /// not flex/grid items, so they key as 0 and keep source order.
1269
+ pub fn order(&self) -> i32 {
1270
+ self.primary_styles()
1271
+ .filter(|s| !matches!(s.get_box().position, Position::Absolute | Position::Fixed))
1272
+ .map(|s| s.clone_order())
1273
+ .unwrap_or(0)
1274
+ }
1275
+
1276
+ pub fn z_index(&self) -> i32 {
1277
+ self.primary_styles()
1278
+ .map(|s| s.clone_z_index().integer_or(0))
1279
+ .unwrap_or(0)
1280
+ }
1281
+
1282
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Stacking_context#features_creating_stacking_contexts
1283
+ pub fn is_stacking_context_root(&self, is_flex_or_grid_item: bool) -> bool {
1284
+ let Some(style) = self.primary_styles() else {
1285
+ return false;
1286
+ };
1287
+
1288
+ let position = style.clone_position();
1289
+ let has_z_index = !style.clone_z_index().is_auto();
1290
+
1291
+ if style.clone_opacity() != 1.0 {
1292
+ return true;
1293
+ }
1294
+
1295
+ let position_based = match position {
1296
+ Position::Fixed | Position::Sticky => true,
1297
+ Position::Relative | Position::Absolute => has_z_index,
1298
+ Position::Static => has_z_index && is_flex_or_grid_item,
1299
+ };
1300
+ if position_based {
1301
+ return true;
1302
+ }
1303
+
1304
+ let box_style = style.get_box();
1305
+ if !box_style.transform.0.is_empty()
1306
+ || !matches!(box_style.rotate, Rotate::None)
1307
+ || !matches!(box_style.scale, Scale::None)
1308
+ || !matches!(box_style.translate, Translate::None)
1309
+ {
1310
+ return true;
1311
+ }
1312
+
1313
+ if self.applies_atomic_paint_effect() {
1314
+ return true;
1315
+ }
1316
+
1317
+ if style.get_box().isolation == Isolation::Isolate {
1318
+ return true;
1319
+ }
1320
+
1321
+ // TODO: mix-blend-mode
1322
+ // TODO: contain
1323
+
1324
+ false
1325
+ }
1326
+
1327
+ /// Whether this node's styles apply an atomic paint effect (opacity, filter,
1328
+ /// clip-path, mask) to its subtree.
1329
+ pub(crate) fn applies_atomic_paint_effect(&self) -> bool {
1330
+ use style::values::computed::basic_shape::ClipPath;
1331
+ use style::values::generics::image::GenericImage;
1332
+
1333
+ let Some(style) = self.primary_styles() else {
1334
+ return false;
1335
+ };
1336
+
1337
+ if style.clone_opacity() != 1.0 {
1338
+ return true;
1339
+ }
1340
+
1341
+ let effects = style.get_effects();
1342
+ if !effects.filter.0.is_empty() {
1343
+ return true;
1344
+ }
1345
+
1346
+ if !matches!(style.clone_clip_path(), ClipPath::None) {
1347
+ return true;
1348
+ }
1349
+
1350
+ style
1351
+ .get_svg()
1352
+ .mask_image
1353
+ .0
1354
+ .iter()
1355
+ .any(|image| !matches!(image, GenericImage::None))
1356
+ }
1357
+
1358
+ /// Takes an (x, y) position (relative to the *parent's* top-left corner) and returns:
1359
+ /// - None if the position is outside of this node's bounds
1360
+ /// - Some(HitResult) if the position is within the node but doesn't match any children
1361
+ /// - The result of recursively calling child.hit() on the the child element that is
1362
+ /// positioned at that position if there is one.
1363
+ ///
1364
+ /// TODO: z-index
1365
+ /// (If multiple children are positioned at the position then a random one will be recursed into)
1366
+ pub fn hit(&self, x: f32, y: f32, scale: f64) -> Option<HitResult> {
1367
+ self.hit_inner(x, y, scale, &mut None)
1368
+ }
1369
+
1370
+ /// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
1371
+ /// thumb under the point into `scrollbar` during the same descent (so
1372
+ /// thumb hit-testing shares the exact coordinate handling — transforms
1373
+ /// included — of every other hit test).
1374
+ pub(crate) fn hit_inner(
1375
+ &self,
1376
+ x: f32,
1377
+ y: f32,
1378
+ scale: f64,
1379
+ scrollbar: &mut Option<crate::node::ScrollbarRef>,
1380
+ ) -> Option<HitResult> {
1381
+ use style::computed_values::pointer_events::T as PointerEvents;
1382
+ use style::computed_values::visibility::T as Visibility;
1383
+
1384
+ // Don't hit on visbility:hidden elements
1385
+ if let Some(style) = self.primary_styles() {
1386
+ if matches!(
1387
+ style.clone_visibility(),
1388
+ Visibility::Hidden | Visibility::Collapse
1389
+ ) {
1390
+ return None;
1391
+ }
1392
+ }
1393
+
1394
+ // pointer-events:none makes this element transparent to hits, but its
1395
+ // descendants are still tested (one may restore pointer-events:auto).
1396
+ let pointer_events_none = self
1397
+ .primary_styles()
1398
+ .is_some_and(|style| style.clone_pointer_events() == PointerEvents::None);
1399
+
1400
+ let mut x = x - self.final_layout().location.x + self.scroll_offset().x as f32;
1401
+ let mut y = y - self.final_layout().location.y + self.scroll_offset().y as f32;
1402
+
1403
+ if let Some(t) = self.transform().as_deref() {
1404
+ let p = t.inverse() * kurbo::Point::new(x as f64 * scale, y as f64 * scale);
1405
+ x = (p.x / scale) as f32;
1406
+ y = (p.y / scale) as f32;
1407
+ }
1408
+
1409
+ let size = self.final_layout().size;
1410
+ let matches_self = !(x < 0.0
1411
+ || x > size.width + self.scroll_offset().x as f32
1412
+ || y < 0.0
1413
+ || y > size.height + self.scroll_offset().y as f32);
1414
+
1415
+ let overflow_rect = self.final_layout().scrollable_overflow_rect;
1416
+ let matches_content = !(x < 0.0
1417
+ || x > overflow_rect.right + self.scroll_offset().x as f32
1418
+ || y < 0.0
1419
+ || y > overflow_rect.bottom + self.scroll_offset().y as f32);
1420
+
1421
+ let matches_hoisted_content = match &self.stacking_context {
1422
+ Some(sc) => {
1423
+ // Both the point (after the scroll adjustment above) and the
1424
+ // bbox are in this node's unscrolled content coordinates.
1425
+ let bbox = sc.hoisted_content_bbox(self.tree(), self.id, scale);
1426
+ x >= bbox.left && x <= bbox.right && y >= bbox.top && y <= bbox.bottom
1427
+ }
1428
+ None => false,
1429
+ };
1430
+
1431
+ // `scrollable_overflow` is stored in device (scaled) pixels, whereas the
1432
+ // coordinates here are in CSS pixels, so unscale it before comparing.
1433
+ let overflow = *self.scrollable_overflow();
1434
+
1435
+ let matches_overflow = x >= (overflow.x0 / scale) as f32
1436
+ && x <= (overflow.x1 / scale) as f32
1437
+ && y >= (overflow.y0 / scale) as f32
1438
+ && y <= (overflow.y1 / scale) as f32;
1439
+
1440
+ if !matches_self && !matches_content && !matches_hoisted_content && !matches_overflow {
1441
+ return None;
1442
+ }
1443
+
1444
+ // Descendants overwrite, so the innermost scroll container's thumb
1445
+ // wins. Thumb coords are border-box relative (unscrolled).
1446
+ if matches_self
1447
+ && let Some(sb) = self.scrollbar_at_local(
1448
+ (x - self.scroll_offset().x as f32) as f64,
1449
+ (y - self.scroll_offset().y as f32) as f64,
1450
+ )
1451
+ {
1452
+ *scrollbar = Some(sb);
1453
+ }
1454
+
1455
+ let content_box_offset = taffy::Point {
1456
+ x: self.final_layout().padding.left + self.final_layout().border.left,
1457
+ y: self.final_layout().padding.top + self.final_layout().border.top,
1458
+ };
1459
+ if self.flags.is_inline_root() {
1460
+ x -= content_box_offset.x;
1461
+ y -= content_box_offset.y;
1462
+ }
1463
+
1464
+ // Positive z_index hoisted children
1465
+ if matches_hoisted_content {
1466
+ if let Some(hoisted) = &self.stacking_context {
1467
+ for hoisted_child in hoisted.pos_z_hoisted_children().rev() {
1468
+ let pos = hoisted_child.position(self.tree(), self.id);
1469
+ let x = x - pos.x;
1470
+ let y = y - pos.y;
1471
+ if let Some(hit) = self
1472
+ .with(hoisted_child.node_id)
1473
+ .hit_inner(x, y, scale, scrollbar)
1474
+ {
1475
+ return Some(hit);
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+
1481
+ // Call `.hit()` on each child in turn. If any return `Some` then return that value. Else return `Some(self.id).
1482
+ for child_id in self.paint_children.borrow().iter().flatten().rev() {
1483
+ let child = self.with(*child_id);
1484
+ let child_position = child.taffy_position();
1485
+ let mut child_x = x;
1486
+ let mut child_y = y;
1487
+ if child_position.is_out_of_flow() {
1488
+ // Out-of-flow children's layout location is relative to this node's
1489
+ // border box, so undo the inline-root content-box offset applied above
1490
+ if self.flags.is_inline_root() {
1491
+ child_x += content_box_offset.x;
1492
+ child_y += content_box_offset.y;
1493
+ }
1494
+ // Fixed-position children of the root element are positioned
1495
+ // against the viewport and do not scroll with it. (A fixed box
1496
+ // whose containing block is a transformed ancestor scrolls with
1497
+ // that ancestor like any other out-of-flow box.)
1498
+ if child_position == taffy::Position::Fixed && self.containing_block().is_none() {
1499
+ child_x -= self.scroll_offset().x as f32;
1500
+ child_y -= self.scroll_offset().y as f32;
1501
+ let viewport_scroll = self.tree().viewport_scroll();
1502
+ child_x -= viewport_scroll.x as f32;
1503
+ child_y -= viewport_scroll.y as f32;
1504
+ }
1505
+ }
1506
+ if let Some(hit) = child.hit_inner(child_x, child_y, scale, scrollbar) {
1507
+ return Some(hit);
1508
+ }
1509
+ }
1510
+
1511
+ // Negative z_index hoisted children
1512
+ if matches_hoisted_content {
1513
+ if let Some(hoisted) = &self.stacking_context {
1514
+ for hoisted_child in hoisted.neg_z_hoisted_children().rev() {
1515
+ let pos = hoisted_child.position(self.tree(), self.id);
1516
+ let x = x - pos.x;
1517
+ let y = y - pos.y;
1518
+ if let Some(hit) = self
1519
+ .with(hoisted_child.node_id)
1520
+ .hit_inner(x, y, scale, scrollbar)
1521
+ {
1522
+ return Some(hit);
1523
+ }
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ // Inline children
1529
+ if self.flags.is_inline_root() {
1530
+ let element_data = &self.element_data().unwrap();
1531
+ if let Some(ild) = element_data.inline_layout_data.as_ref() {
1532
+ let layout = &ild.layout;
1533
+ let scale = layout.scale();
1534
+ let y = y - ild.block_offset;
1535
+
1536
+ if let Some((cluster, _side)) =
1537
+ Cluster::from_point_exact(layout, x * scale, y * scale)
1538
+ {
1539
+ let node_id = cluster.style().brush.id;
1540
+ let text_pointer_events_none = self
1541
+ .with(node_id)
1542
+ .primary_styles()
1543
+ .is_some_and(|style| style.clone_pointer_events() == PointerEvents::None);
1544
+ if !text_pointer_events_none {
1545
+ return Some(HitResult {
1546
+ node_id,
1547
+ x,
1548
+ y,
1549
+ is_text: true,
1550
+ });
1551
+ }
1552
+ }
1553
+ }
1554
+ }
1555
+
1556
+ // Self (this node)
1557
+ if matches_self && !pointer_events_none {
1558
+ return Some(HitResult {
1559
+ node_id: self.id,
1560
+ x,
1561
+ y,
1562
+ is_text: false,
1563
+ });
1564
+ }
1565
+
1566
+ None
1567
+ }
1568
+
1569
+ /// Find the inline root ancestor of this node (or self if this is an inline root).
1570
+ /// Returns None if no inline root ancestor exists.
1571
+ pub fn inline_root_ancestor(&self) -> Option<&Node> {
1572
+ let mut node = self;
1573
+ loop {
1574
+ if node.flags.is_inline_root() {
1575
+ return Some(node);
1576
+ }
1577
+ let id = node.layout_parent.get()?;
1578
+ node = self.with(id);
1579
+ }
1580
+ }
1581
+
1582
+ /// Get the text byte offset at a given point, using coordinates already transformed
1583
+ /// to be relative to this inline root's content box.
1584
+ /// Returns Some(byte_offset) if the point hits text, None otherwise.
1585
+ pub fn text_offset_at_point(&self, x: f32, y: f32) -> Option<usize> {
1586
+ if !self.flags.is_inline_root() {
1587
+ return None;
1588
+ }
1589
+
1590
+ let element_data = self.element_data()?;
1591
+ let inline_layout = element_data.inline_layout_data.as_ref()?;
1592
+ let layout = &inline_layout.layout;
1593
+ let scale = layout.scale();
1594
+ let y = y - inline_layout.block_offset;
1595
+
1596
+ // Use Parley's cluster hit testing (from_point is more forgiving than from_point_exact)
1597
+ let (cluster, side) = Cluster::from_point(layout, x * scale, y * scale)?;
1598
+
1599
+ // Determine byte offset based on which side of the cluster was clicked
1600
+ // For LTR text: left side = start of cluster, right side = end of cluster
1601
+ // For RTL text: left side = end of cluster, right side = start of cluster
1602
+ // Also, explicit line breaks should always use start to avoid cursor appearing on next line
1603
+ let is_leading = side == ClusterSide::Left;
1604
+ let offset = if cluster.is_rtl() {
1605
+ if is_leading {
1606
+ cluster.text_range().end
1607
+ } else {
1608
+ cluster.text_range().start
1609
+ }
1610
+ } else {
1611
+ // LTR text
1612
+ if is_leading || cluster.is_line_break() == Some(BreakReason::Explicit) {
1613
+ cluster.text_range().start
1614
+ } else {
1615
+ cluster.text_range().end
1616
+ }
1617
+ };
1618
+
1619
+ Some(offset)
1620
+ }
1621
+
1622
+ /// Whether this node is a non-atomic inline element: one that has no layout box of its
1623
+ /// own because it is flattened into the containing inline root's text layout as a style
1624
+ /// span.
1625
+ pub fn is_non_atomic_inline(&self) -> bool {
1626
+ let Some(element) = self.element_data() else {
1627
+ return false;
1628
+ };
1629
+ if self.flags.is_inline_root()
1630
+ || crate::layout::replaced::is_inline_box_element(&element.name.local)
1631
+ {
1632
+ return false;
1633
+ }
1634
+ self.primary_styles().is_some_and(|styles| {
1635
+ let display = styles.clone_display();
1636
+ display.outside() == DisplayOutside::Inline && display.inside() == DisplayInside::Flow
1637
+ })
1638
+ }
1639
+
1640
+ /// The node whose box this node's `Layout.location` is relative to: the
1641
+ /// `oof_containing_block` for a hoisted out-of-flow box, otherwise the
1642
+ /// `layout_parent`.
1643
+ pub fn containing_block(&self) -> Option<NodeId> {
1644
+ self.oof_containing_block
1645
+ .get()
1646
+ .or_else(|| self.layout_parent.get())
1647
+ }
1648
+
1649
+ /// Computes the Document-relative coordinates of the `Node`
1650
+ pub fn absolute_position(&self, x: f32, y: f32) -> crate::util::Point<f32> {
1651
+ let x = x + self.final_layout().location.x - self.scroll_offset().x as f32;
1652
+ let y = y + self.final_layout().location.y - self.scroll_offset().y as f32;
1653
+
1654
+ // Recurse up the positioning hierarchy
1655
+ self.containing_block()
1656
+ .map(|i| self.with(i).absolute_position(x, y))
1657
+ .unwrap_or(crate::util::Point { x, y })
1658
+ }
1659
+
1660
+ /// Whether this node can act as an [`offset_parent`](Self::offset_parent): a positioned
1661
+ /// element, or one of the elements that always qualify (`body`, `td`, `th`).
1662
+ pub(crate) fn is_offset_parent(&self) -> bool {
1663
+ let Some(styles) = self.primary_styles() else {
1664
+ return false;
1665
+ };
1666
+ if styles.get_box().position != Position::Static {
1667
+ return true;
1668
+ }
1669
+ self.data.is_element_with_tag_name(&local_name!("body"))
1670
+ || self.data.is_element_with_tag_name(&local_name!("td"))
1671
+ || self.data.is_element_with_tag_name(&local_name!("th"))
1672
+ }
1673
+
1674
+ /// Whether this node is a non-positioned `body` element. When such an element is the
1675
+ /// `offsetParent`, `offsetLeft`/`offsetTop` are measured from the initial containing
1676
+ /// block origin rather than from the `body`'s padding edge.
1677
+ pub(crate) fn is_static_body(&self) -> bool {
1678
+ self.data.is_element_with_tag_name(&local_name!("body"))
1679
+ && self
1680
+ .primary_styles()
1681
+ .is_some_and(|styles| styles.get_box().position == Position::Static)
1682
+ }
1683
+
1684
+ /// The nearest layout ancestor that [is an offset parent](Self::is_offset_parent), as in
1685
+ /// CSSOM View's `offsetParent`.
1686
+ pub fn offset_parent(&self) -> Option<&Node> {
1687
+ let mut node = self;
1688
+ loop {
1689
+ node = self.with(node.containing_block()?);
1690
+ if node.is_offset_parent() {
1691
+ return Some(node);
1692
+ }
1693
+ }
1694
+ }
1695
+
1696
+ /// The per-line-box fragment boxes of a non-atomic inline element, in CSS pixels relative
1697
+ /// to the border box of its inline root.
1698
+ ///
1699
+ /// Returns `None` for nodes that have their own layout box.
1700
+ pub fn inline_fragment_boxes(&self) -> Option<impl Iterator<Item = taffy::Rect<f32>> + '_> {
1701
+ use parley::PositionedLayoutItem;
1702
+
1703
+ if !self.is_non_atomic_inline() {
1704
+ return None;
1705
+ }
1706
+
1707
+ let inline_root = self.inline_root_ancestor()?;
1708
+ let inline_layout = inline_root.element_data()?.inline_layout_data.as_ref()?;
1709
+ let layout = &inline_layout.layout;
1710
+ let scale = layout.scale();
1711
+
1712
+ // Walk up the DOM parent chain from `id` to check whether it is (or is
1713
+ // inside) the target node, stopping at the inline root.
1714
+ let inline_root_id = inline_root.id;
1715
+ let is_in_target = move |mut id: NodeId| -> bool {
1716
+ loop {
1717
+ if id == self.id {
1718
+ return true;
1719
+ }
1720
+ if id == inline_root_id {
1721
+ return false;
1722
+ }
1723
+ match self.with(id).parent {
1724
+ Some(parent) => id = parent,
1725
+ None => return false,
1726
+ }
1727
+ }
1728
+ };
1729
+
1730
+ let root_layout = inline_root.unrounded_layout();
1731
+ let content_box_inset = root_layout.padding + root_layout.border;
1732
+ let origin_x = content_box_inset.left;
1733
+ let origin_y = content_box_inset.top + inline_layout.block_offset;
1734
+
1735
+ fn union(acc: &mut Option<taffy::Rect<f32>>, left: f32, top: f32, right: f32, bottom: f32) {
1736
+ *acc = Some(match *acc {
1737
+ Some(rect) => taffy::Rect {
1738
+ left: rect.left.min(left),
1739
+ top: rect.top.min(top),
1740
+ right: rect.right.max(right),
1741
+ bottom: rect.bottom.max(bottom),
1742
+ },
1743
+ None => taffy::Rect {
1744
+ left,
1745
+ top,
1746
+ right,
1747
+ bottom,
1748
+ },
1749
+ });
1750
+ }
1751
+
1752
+ // One rect per line box: the union of all of the target's fragments on that line
1753
+ Some(layout.lines().filter_map(move |line| {
1754
+ let line_metrics = line.metrics();
1755
+ let mut line_rect: Option<taffy::Rect<f32>> = None;
1756
+
1757
+ for item in line.items() {
1758
+ match item {
1759
+ PositionedLayoutItem::GlyphRun(glyph_run) => {
1760
+ if !is_in_target(glyph_run.style().brush.id) {
1761
+ continue;
1762
+ }
1763
+ let x0 = glyph_run.offset();
1764
+ let x1 = x0 + glyph_run.advance();
1765
+ // Use the line box's block extent rather than the
1766
+ // run's font ascent/descent: fonts with small
1767
+ // typographic metrics would otherwise produce rects
1768
+ // that clip the rendered glyphs. This matches the
1769
+ // geometry used for text selection highlights.
1770
+ let y0 = line_metrics.block_min_coord;
1771
+ let y1 = line_metrics.block_max_coord;
1772
+ union(&mut line_rect, x0, y0, x1, y1);
1773
+ }
1774
+ PositionedLayoutItem::InlineBox(inline_box) => {
1775
+ if !is_in_target(NodeId::from_u64(inline_box.id)) {
1776
+ continue;
1777
+ }
1778
+ let x0 = inline_box.x;
1779
+ let y0 = inline_box.y;
1780
+ union(
1781
+ &mut line_rect,
1782
+ x0,
1783
+ y0,
1784
+ x0 + inline_box.width,
1785
+ y0 + inline_box.height,
1786
+ );
1787
+ }
1788
+ }
1789
+ }
1790
+
1791
+ line_rect.map(|rect| taffy::Rect {
1792
+ left: origin_x + rect.left / scale,
1793
+ top: origin_y + rect.top / scale,
1794
+ right: origin_x + rect.right / scale,
1795
+ bottom: origin_y + rect.bottom / scale,
1796
+ })
1797
+ }))
1798
+ }
1799
+
1800
+ /// CSSOM View's `offsetLeft`/`offsetTop`: the offset of this node's border box from the
1801
+ /// padding edge of its [`offset_parent`](Self::offset_parent).
1802
+ pub fn offset_top_left(&self) -> crate::util::Point<f32> {
1803
+ let mut x = 0.0;
1804
+ let mut y = 0.0;
1805
+ let mut current = self;
1806
+
1807
+ // Non-atomic inlines have no layout box of their own: start from the first
1808
+ // fragment box (relative to the inline root's border box) and continue the
1809
+ // walk from the inline root.
1810
+ if let Some(mut fragments) = self.inline_fragment_boxes() {
1811
+ if let Some(first) = fragments.next() {
1812
+ x += first.left;
1813
+ y += first.top;
1814
+ }
1815
+ let Some(inline_root) = self.inline_root_ancestor() else {
1816
+ return crate::util::Point { x, y };
1817
+ };
1818
+ if inline_root.is_offset_parent() && !inline_root.is_static_body() {
1819
+ let border = inline_root.final_layout().border;
1820
+ return crate::util::Point {
1821
+ x: x - border.left,
1822
+ y: y - border.top,
1823
+ };
1824
+ }
1825
+ current = inline_root;
1826
+ }
1827
+
1828
+ loop {
1829
+ let layout = current.final_layout();
1830
+ x += layout.location.x;
1831
+ y += layout.location.y;
1832
+
1833
+ let Some(parent_id) = current.containing_block() else {
1834
+ break;
1835
+ };
1836
+ let parent = self.with(parent_id);
1837
+ if parent.is_offset_parent() && !parent.is_static_body() {
1838
+ let border = parent.final_layout().border;
1839
+ x -= border.left;
1840
+ y -= border.top;
1841
+ break;
1842
+ }
1843
+ current = parent;
1844
+ }
1845
+ crate::util::Point { x, y }
1846
+ }
1847
+
1848
+ /// CSSOM View's `clientWidth`: the width of the padding box (border box minus
1849
+ /// borders and scrollbar)
1850
+ pub fn client_width(&self) -> f32 {
1851
+ let layout = self.final_layout();
1852
+ layout.size.width - layout.border.left - layout.border.right - layout.scrollbar_size.width
1853
+ }
1854
+
1855
+ /// CSSOM View's `clientHeight`: the height of the padding box (border box minus
1856
+ /// borders and scrollbar)
1857
+ pub fn client_height(&self) -> f32 {
1858
+ let layout = self.final_layout();
1859
+ layout.size.height - layout.border.top - layout.border.bottom - layout.scrollbar_size.height
1860
+ }
1861
+
1862
+ /// CSSOM View's `scrollWidth`: the width of the node's content, including
1863
+ /// content not visible due to overflow
1864
+ pub fn scroll_width(&self) -> f32 {
1865
+ self.client_width()
1866
+ .max(self.final_layout().scrollable_overflow_rect.right)
1867
+ }
1868
+
1869
+ /// CSSOM View's `scrollHeight`: the height of the node's content, including
1870
+ /// content not visible due to overflow
1871
+ pub fn scroll_height(&self) -> f32 {
1872
+ self.client_height()
1873
+ .max(self.final_layout().scrollable_overflow_rect.bottom)
1874
+ }
1875
+
1876
+ /// Does the node generate any boxes? (e.g. `getClientRects()` returns an empty
1877
+ /// list for boxless nodes, such as `display: none`, `display: contents`, or
1878
+ /// detached elements)
1879
+ pub fn has_boxes(&self) -> bool {
1880
+ self.flags.is_in_document()
1881
+ && !self.display_style().is_some_and(|display| {
1882
+ matches!(
1883
+ display.inside(),
1884
+ style::values::specified::box_::DisplayInside::None
1885
+ | style::values::specified::box_::DisplayInside::Contents
1886
+ )
1887
+ })
1888
+ }
1889
+
1890
+ /// Creates a synthetic click event
1891
+ pub fn synthetic_click_event(&self, mods: Modifiers) -> DomEventData {
1892
+ DomEventData::Click(self.synthetic_click_event_data(mods))
1893
+ }
1894
+
1895
+ pub fn synthetic_click_event_data(&self, mods: Modifiers) -> BlitzPointerEvent {
1896
+ let absolute_position = self.absolute_position(0.0, 0.0);
1897
+ let x = absolute_position.x + (self.final_layout().size.width / 2.0);
1898
+ let y = absolute_position.y + (self.final_layout().size.height / 2.0);
1899
+
1900
+ BlitzPointerEvent {
1901
+ id: BlitzPointerId::Mouse,
1902
+ is_primary: true,
1903
+ coords: PointerCoords {
1904
+ page_x: x,
1905
+ page_y: y,
1906
+
1907
+ // TODO: should these be different?
1908
+ screen_x: x,
1909
+ screen_y: y,
1910
+ client_x: x,
1911
+ client_y: y,
1912
+ },
1913
+ mods,
1914
+ button: Default::default(),
1915
+ buttons: Default::default(),
1916
+ details: Default::default(),
1917
+ element: Default::default(),
1918
+ active_pointers: Default::default(),
1919
+ }
1920
+ }
1921
+ }
1922
+
1923
+ /// It might be wrong to expose this since what does *equality* mean outside the dom?
1924
+ impl PartialEq for Node {
1925
+ fn eq(&self, other: &Self) -> bool {
1926
+ self.id == other.id
1927
+ }
1928
+ }
1929
+
1930
+ impl Eq for Node {}
1931
+
1932
+ impl std::fmt::Debug for Node {
1933
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1934
+ // FIXME: update to reflect changes to fields
1935
+ f.debug_struct("NodeData")
1936
+ .field("parent", &self.parent)
1937
+ .field("id", &self.id)
1938
+ .field("is_inline_root", &self.flags.is_inline_root())
1939
+ .field("children", &self.children)
1940
+ .field("layout_children", &self.layout_children.borrow())
1941
+ // .field("style", &self.style)
1942
+ .field("node", &self.data)
1943
+ .field("stylo_element_data", &self.try_stylo_element_data())
1944
+ // .field("unrounded_layout", &self.unrounded_layout)
1945
+ // .field("final_layout", &self.final_layout)
1946
+ .finish()
1947
+ }
1948
+ }
1949
+
1950
+ #[cfg(test)]
1951
+ mod test {
1952
+ use style_dom::ElementState;
1953
+
1954
+ use crate::{Attribute, BaseDocument, DocumentConfig, ElementData, NodeData, qual_name};
1955
+
1956
+ #[test]
1957
+ fn create_node_with_disabled_attr() {
1958
+ let mut document = BaseDocument::new(DocumentConfig::default());
1959
+ let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
1960
+ qual_name!("button"),
1961
+ vec![Attribute {
1962
+ name: qual_name!("disabled"),
1963
+ value: "".into(),
1964
+ }],
1965
+ ))));
1966
+ let node = document.get_node(node).unwrap();
1967
+
1968
+ assert!(
1969
+ node.element_state().contains(ElementState::DISABLED),
1970
+ "form node is disabled"
1971
+ );
1972
+ assert!(
1973
+ !node.element_state().contains(ElementState::ENABLED),
1974
+ "form node is not enabled"
1975
+ );
1976
+ }
1977
+
1978
+ #[test]
1979
+ fn ignore_disabled_attr_content() {
1980
+ let mut document = BaseDocument::new(DocumentConfig::default());
1981
+ let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
1982
+ qual_name!("button"),
1983
+ vec![Attribute {
1984
+ name: qual_name!("disabled"),
1985
+ value: "false".into(),
1986
+ }],
1987
+ ))));
1988
+ let node = document.get_node(node).unwrap();
1989
+
1990
+ assert!(
1991
+ node.element_state().contains(ElementState::DISABLED),
1992
+ "form node is disabled"
1993
+ );
1994
+ assert!(
1995
+ !node.element_state().contains(ElementState::ENABLED),
1996
+ "form node is not enabled"
1997
+ );
1998
+ }
1999
+
2000
+ #[test]
2001
+ fn create_node_with_ignored_disable() {
2002
+ let mut document = BaseDocument::new(DocumentConfig::default());
2003
+ let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
2004
+ qual_name!("a"),
2005
+ vec![Attribute {
2006
+ name: qual_name!("disabled"),
2007
+ value: "".into(),
2008
+ }],
2009
+ ))));
2010
+ let node = document.get_node(node).unwrap();
2011
+
2012
+ assert!(
2013
+ !node.element_state().contains(ElementState::DISABLED),
2014
+ "Non form node cannot be disabled"
2015
+ );
2016
+ assert!(
2017
+ !node.element_state().contains(ElementState::ENABLED),
2018
+ "Non form node cannot be enabled"
2019
+ );
2020
+ }
2021
+
2022
+ #[test]
2023
+ fn create_empty_enabled_node() {
2024
+ let mut document = BaseDocument::new(DocumentConfig::default());
2025
+ let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
2026
+ qual_name!("button"),
2027
+ vec![],
2028
+ ))));
2029
+ let node = document.get_node(node).unwrap();
2030
+
2031
+ assert!(
2032
+ node.element_state().contains(ElementState::ENABLED),
2033
+ "Button should be enabled by default"
2034
+ );
2035
+ }
2036
+ }