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,1818 @@
1
+ use blitz_traits::node_id::NodeId;
2
+ use std::collections::HashSet;
3
+ use std::mem;
4
+ use std::ops::{Deref, DerefMut};
5
+
6
+ use crate::layout::damage::ALL_DAMAGE;
7
+ use crate::net::{ImageHandler, ResourceHandler, StylesheetHandler};
8
+ use crate::node::{CanvasData, NodeFlags, SpecialElementData};
9
+ use crate::stylo_device::DeviceChanges;
10
+ use crate::util::ImageType;
11
+ use crate::{
12
+ Attribute, BaseDocument, Document, ElementData, Node, NodeData, QualName, local_name, qual_name,
13
+ };
14
+ use blitz_traits::shell::Viewport;
15
+ use style::Atom;
16
+ use style::invalidation::element::restyle_hints::RestyleHint;
17
+ use style::stylesheets::OriginSet;
18
+ use thin_vec::ThinVec;
19
+
20
+ macro_rules! tag_and_attr {
21
+ ($tag:tt, $attr:tt) => {
22
+ (&local_name!($tag), &local_name!($attr))
23
+ };
24
+ }
25
+
26
+ #[derive(Debug, Clone)]
27
+ pub enum AppendTextErr {
28
+ /// The node is not a text node
29
+ NotTextNode,
30
+ }
31
+
32
+ /// Operations that happen almost immediately, but are deferred within a
33
+ /// function for borrow-checker reasons.
34
+ enum SpecialOp {
35
+ LoadImage(NodeId),
36
+ LoadIframe(NodeId),
37
+ LoadStylesheet(NodeId),
38
+ UnloadStylesheet(NodeId),
39
+ LoadCustomPaintSource(NodeId),
40
+ ProcessButtonInput(NodeId),
41
+ UnloadSubDocument(NodeId),
42
+ #[cfg(feature = "custom-widget")]
43
+ UnloadCustomWidget(NodeId),
44
+ }
45
+
46
+ pub struct DocumentMutator<'doc> {
47
+ /// Document is public as an escape hatch, but users of this API should ideally avoid using it
48
+ /// and prefer exposing additional functionality in DocumentMutator.
49
+ pub doc: &'doc mut BaseDocument,
50
+
51
+ eager_op_queue: Vec<SpecialOp>,
52
+
53
+ // Tracked nodes for deferred processing when mutations have completed
54
+ title_node: Option<NodeId>,
55
+ style_nodes: HashSet<NodeId>,
56
+ form_nodes: HashSet<NodeId>,
57
+
58
+ /// Whether an element/attribute that affect animation status has been seen
59
+ recompute_is_animating: bool,
60
+
61
+ /// Whether any mutation that affects rendered output has been performed
62
+ mutations_occurred: bool,
63
+
64
+ /// The (latest) node which has been mounted in and had autofocus=true, if any
65
+ #[cfg(feature = "autofocus")]
66
+ node_to_autofocus: Option<NodeId>,
67
+ }
68
+
69
+ impl Drop for DocumentMutator<'_> {
70
+ fn drop(&mut self) {
71
+ self.flush(); // Defined at bottom of file
72
+ if self.mutations_occurred {
73
+ self.doc.shell_provider.request_redraw();
74
+ }
75
+ }
76
+ }
77
+
78
+ impl DocumentMutator<'_> {
79
+ pub fn new<'doc>(doc: &'doc mut BaseDocument) -> DocumentMutator<'doc> {
80
+ DocumentMutator {
81
+ doc,
82
+ eager_op_queue: Vec::new(),
83
+ title_node: None,
84
+ style_nodes: HashSet::new(),
85
+ form_nodes: HashSet::new(),
86
+ recompute_is_animating: false,
87
+ mutations_occurred: false,
88
+ #[cfg(feature = "autofocus")]
89
+ node_to_autofocus: None,
90
+ }
91
+ }
92
+
93
+ // Query methods
94
+
95
+ pub fn node_has_parent(&self, node_id: NodeId) -> bool {
96
+ self.doc.nodes[node_id].parent.is_some()
97
+ }
98
+
99
+ pub fn previous_sibling_id(&self, node_id: NodeId) -> Option<NodeId> {
100
+ self.doc.nodes[node_id].backward(1).map(|node| node.id)
101
+ }
102
+
103
+ pub fn next_sibling_id(&self, node_id: NodeId) -> Option<NodeId> {
104
+ self.doc.nodes[node_id].forward(1).map(|node| node.id)
105
+ }
106
+
107
+ pub fn parent_id(&self, node_id: NodeId) -> Option<NodeId> {
108
+ self.doc.nodes[node_id].parent
109
+ }
110
+
111
+ pub fn last_child_id(&self, node_id: NodeId) -> Option<NodeId> {
112
+ self.doc.nodes[node_id].children.last().copied()
113
+ }
114
+
115
+ pub fn child_ids(&self, node_id: NodeId) -> ThinVec<NodeId> {
116
+ self.doc.nodes[node_id].children.clone()
117
+ }
118
+
119
+ pub fn element_name(&self, node_id: NodeId) -> Option<&QualName> {
120
+ self.doc.nodes[node_id].element_data().map(|el| &el.name)
121
+ }
122
+
123
+ pub fn node_at_path(&self, start_node_id: NodeId, path: &[u8]) -> NodeId {
124
+ let mut current = &self.doc.nodes[start_node_id];
125
+ for i in path {
126
+ let new_id = current.children[*i as usize];
127
+ current = &self.doc.nodes[new_id];
128
+ }
129
+ current.id
130
+ }
131
+
132
+ // Node creation methods
133
+
134
+ pub fn create_comment_node(&mut self, contents: &str) -> NodeId {
135
+ self.doc.create_node(NodeData::Comment {
136
+ contents: contents.to_string(),
137
+ })
138
+ }
139
+
140
+ pub fn create_text_node(&mut self, text: &str) -> NodeId {
141
+ self.doc.create_text_node(text)
142
+ }
143
+
144
+ pub fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> NodeId {
145
+ let mut data = ElementData::new(name, attrs);
146
+ data.flush_style_attribute(self.doc.guard(), &self.doc.url.url_extra_data());
147
+
148
+ let id = self.doc.create_node(NodeData::Element(Box::new(data)));
149
+ let node = self.doc.get_node_mut(id).unwrap();
150
+
151
+ // Initialise style data
152
+ *node.stylo_element_data_mut().ensure_init_mut() = style::data::ElementData {
153
+ damage: ALL_DAMAGE,
154
+ ..Default::default()
155
+ };
156
+
157
+ id
158
+ }
159
+
160
+ pub fn deep_clone_node(&mut self, node_id: NodeId) -> NodeId {
161
+ self.doc.deep_clone_node(node_id)
162
+ }
163
+
164
+ /// Create (or return the existing) "template contents" fragment node for a
165
+ /// `<template>` element. The contents node is detached from the tree (so it
166
+ /// is inert: never styled or rendered) and is exposed to JavaScript as the
167
+ /// template's `content` DocumentFragment.
168
+ pub fn template_contents(&mut self, template_id: NodeId) -> NodeId {
169
+ if let Some(contents_id) = self.try_template_contents(template_id) {
170
+ return contents_id;
171
+ }
172
+ let name = QualName::new(
173
+ None,
174
+ markup5ever::ns!(html),
175
+ markup5ever::LocalName::from("#document-fragment"),
176
+ );
177
+ let contents_id = self.create_element(name, Vec::new());
178
+ if let Some(element) = self
179
+ .doc
180
+ .get_node_mut(template_id)
181
+ .and_then(|node| node.element_data_mut())
182
+ {
183
+ element.template_contents = Some(contents_id);
184
+ }
185
+ contents_id
186
+ }
187
+
188
+ /// The "template contents" fragment node of a `<template>` element (if any)
189
+ pub fn try_template_contents(&self, template_id: NodeId) -> Option<NodeId> {
190
+ self.doc
191
+ .get_node(template_id)
192
+ .and_then(|node| node.element_data())
193
+ .and_then(|element| element.template_contents)
194
+ }
195
+
196
+ // Node mutation methods
197
+
198
+ pub fn set_node_text(&mut self, node_id: NodeId, value: &str) {
199
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
200
+ let node = &mut self.doc.nodes[node_id];
201
+
202
+ let text = match node.data {
203
+ NodeData::Text(ref mut text) => text,
204
+ // TODO: otherwise this is basically element.textContent which is a bit different - need to parse as html
205
+ _ => return,
206
+ };
207
+
208
+ let changed = text.content != value;
209
+ if changed {
210
+ self.mutations_occurred |= node_is_in_document;
211
+ text.content.clear();
212
+ text.content.push_str(value);
213
+ node.insert_damage(ALL_DAMAGE);
214
+ // Mark ancestors dirty so the style traversal visits this subtree.
215
+ // Without this, the traversal may skip nodes with pending damage.
216
+ node.mark_ancestors_dirty();
217
+ let parent_id = node.parent;
218
+
219
+ // Also insert damage on the parent element, since text content changes
220
+ // affect the parent's layout (text may wrap differently, change size, etc.)
221
+ if let Some(parent_id) = parent_id {
222
+ let parent = &mut self.doc.nodes[parent_id];
223
+ parent.insert_damage(ALL_DAMAGE);
224
+ }
225
+
226
+ self.maybe_record_node(parent_id);
227
+ }
228
+ }
229
+
230
+ pub fn append_text_to_node(
231
+ &mut self,
232
+ node_id: NodeId,
233
+ text: &str,
234
+ ) -> Result<(), AppendTextErr> {
235
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
236
+ let node = &mut self.doc.nodes[node_id];
237
+ node.insert_damage(ALL_DAMAGE);
238
+ node.mark_ancestors_dirty();
239
+ match node.text_data_mut() {
240
+ Some(data) => {
241
+ data.content += text;
242
+ self.mutations_occurred |= node_is_in_document;
243
+ Ok(())
244
+ }
245
+ None => Err(AppendTextErr::NotTextNode),
246
+ }
247
+ }
248
+
249
+ pub fn add_attrs_if_missing(&mut self, node_id: NodeId, attrs: Vec<Attribute>) {
250
+ let node = &mut self.doc.nodes[node_id];
251
+ node.insert_damage(ALL_DAMAGE);
252
+ let element_data = node.element_data_mut().expect("Not an element");
253
+
254
+ let existing_names = element_data
255
+ .attrs
256
+ .iter()
257
+ .map(|e| e.name.clone())
258
+ .collect::<HashSet<_>>();
259
+
260
+ for attr in attrs
261
+ .into_iter()
262
+ .filter(|attr| !existing_names.contains(&attr.name))
263
+ {
264
+ self.set_attribute(node_id, attr.name, &attr.value);
265
+ }
266
+ }
267
+
268
+ pub fn set_attribute(&mut self, node_id: NodeId, name: QualName, value: &str) {
269
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
270
+ if node_is_in_document {
271
+ self.doc.snapshot_node(node_id);
272
+
273
+ let node = &mut self.doc.nodes[node_id];
274
+ if let Some(mut data) = node.try_stylo_element_data_mut().and_then(|s| s.get_mut()) {
275
+ data.hint |= RestyleHint::restyle_subtree();
276
+ data.damage.insert(ALL_DAMAGE);
277
+ }
278
+ node.mark_damaged();
279
+
280
+ // TODO: make this fine grained / conditional based on ElementSelectorFlags
281
+ let parent = node.parent;
282
+ if let Some(parent_id) = parent {
283
+ let parent = &mut self.doc.nodes[parent_id];
284
+ if let Some(mut data) = parent
285
+ .try_stylo_element_data_mut()
286
+ .and_then(|s| s.get_mut())
287
+ {
288
+ data.hint |= RestyleHint::restyle_subtree();
289
+ }
290
+ }
291
+
292
+ // Mark ancestors dirty so the style traversal visits this subtree.
293
+ // Without this, the traversal may skip nodes with pending RestyleHint/damage
294
+ // because it uses dirty_descendants flags to determine which subtrees to visit.
295
+ self.doc.nodes[node_id].mark_ancestors_dirty();
296
+ }
297
+
298
+ if name.local == local_name!("id") && node_is_in_document {
299
+ if let Some(old_id) = self.doc.nodes[node_id]
300
+ .element_data()
301
+ .map(|element| element.id.clone())
302
+ {
303
+ if let Some(old_id) = old_id {
304
+ self.doc.remove_from_id_map(&old_id, node_id);
305
+ }
306
+ self.doc.add_to_id_map(value, node_id);
307
+ }
308
+ }
309
+
310
+ let node = &mut self.doc.nodes[node_id];
311
+
312
+ let NodeData::Element(ref mut element) = node.data else {
313
+ return;
314
+ };
315
+
316
+ self.mutations_occurred |= node_is_in_document;
317
+ // If element is a CustomWidget, then Ccall attribute_changed on it
318
+ #[cfg(feature = "custom-widget")]
319
+ if let SpecialElementData::CustomWidget(widget_data) = &mut element.special_data {
320
+ let old_value = element.attrs.get(&name).as_ref().map(|attr| &*attr.value);
321
+ widget_data
322
+ .widget
323
+ .attribute_changed(&name.local, old_value, Some(value));
324
+ }
325
+
326
+ element.attrs.set(name.clone(), value);
327
+
328
+ // Focusability is cached on the element and comes from these
329
+ // attributes, so it has to follow a change to one of them: a widget
330
+ // that hands the focus around its own children - a menu, a grid -
331
+ // sets their tabindex after creating them.
332
+ if name.local == local_name!("tabindex")
333
+ || name.local == local_name!("href")
334
+ || name.local == local_name!("disabled")
335
+ {
336
+ element.flush_is_focussable();
337
+ }
338
+
339
+ if name.local == local_name!("href") {
340
+ element.flush_link_state();
341
+ }
342
+
343
+ let tag = &element.name.local;
344
+ let attr = &name.local;
345
+
346
+ if *attr == local_name!("id") {
347
+ element.id = Some(Atom::from(value))
348
+ }
349
+
350
+ if *attr == local_name!("value") {
351
+ if let Some(input_data) = element.text_input_data_mut() {
352
+ // Update text input value
353
+ input_data.set_text(
354
+ &mut self.doc.font_ctx.lock().unwrap(),
355
+ &mut self.doc.layout_ctx,
356
+ value,
357
+ );
358
+ }
359
+ return;
360
+ }
361
+
362
+ if *attr == local_name!("style") {
363
+ element.flush_style_attribute(&self.doc.guard, &self.doc.url.url_extra_data());
364
+ node.set_restyle_hint(RestyleHint::RESTYLE_STYLE_ATTRIBUTE);
365
+ return;
366
+ }
367
+
368
+ if *attr == local_name!("disabled") && element.can_be_disabled() {
369
+ node.disable();
370
+ return;
371
+ }
372
+
373
+ // If node if not in the document, then don't apply any special behaviours
374
+ // and simply set the attribute value
375
+ if !node.flags.is_in_document() {
376
+ return;
377
+ }
378
+
379
+ // Custom widgets replace the element's built-in tag-specific behaviour
380
+ #[cfg(feature = "custom-widget")]
381
+ if element.custom_widget_data().is_some() {
382
+ return;
383
+ }
384
+
385
+ if (tag, attr) == tag_and_attr!("input", "checked") {
386
+ set_input_checked_state(element, value.to_string());
387
+ } else if (tag, attr) == tag_and_attr!("img", "src") {
388
+ self.load_image(node_id);
389
+ } else if (tag, attr) == tag_and_attr!("canvas", "src") {
390
+ self.load_custom_paint_src(node_id);
391
+ } else if (tag, attr) == tag_and_attr!("link", "href")
392
+ || (tag, attr) == tag_and_attr!("link", "rel")
393
+ {
394
+ self.load_linked_stylesheet(node_id);
395
+ } else if (tag, attr) == tag_and_attr!("iframe", "src")
396
+ || (tag, attr) == tag_and_attr!("iframe", "srcdoc")
397
+ {
398
+ self.load_iframe(node_id);
399
+ }
400
+ }
401
+
402
+ pub fn clear_attribute(&mut self, node_id: NodeId, name: QualName) {
403
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
404
+ if node_is_in_document {
405
+ self.doc.snapshot_node(node_id);
406
+
407
+ let node = &mut self.doc.nodes[node_id];
408
+
409
+ if let Some(mut data) = node.try_stylo_element_data_mut().and_then(|s| s.get_mut()) {
410
+ data.hint |= RestyleHint::restyle_subtree();
411
+ data.damage.insert(ALL_DAMAGE);
412
+ }
413
+ node.mark_damaged();
414
+
415
+ // Mark ancestors dirty so the style traversal visits this subtree.
416
+ // Without this, the traversal may skip nodes with pending RestyleHint/damage.
417
+ node.mark_ancestors_dirty();
418
+ }
419
+
420
+ if name.local == local_name!("id") && node_is_in_document {
421
+ if let Some(old_id) = self.doc.nodes[node_id]
422
+ .element_data()
423
+ .and_then(|element| element.id.clone())
424
+ {
425
+ self.doc.remove_from_id_map(&old_id, node_id);
426
+ }
427
+ }
428
+
429
+ let node = &mut self.doc.nodes[node_id];
430
+
431
+ let Some(element) = node.element_data_mut() else {
432
+ return;
433
+ };
434
+
435
+ let removed_attr = element.attrs.remove(&name);
436
+ let had_attr = removed_attr.is_some();
437
+ if !had_attr {
438
+ return;
439
+ }
440
+ self.mutations_occurred |= node_is_in_document;
441
+
442
+ // If element is a CustomWidget, then call attribute_changed on it
443
+ #[cfg(feature = "custom-widget")]
444
+ if let SpecialElementData::CustomWidget(widget_data) = &mut element.special_data {
445
+ let old_value = removed_attr.as_ref().map(|attr| &*attr.value);
446
+ widget_data
447
+ .widget
448
+ .attribute_changed(&name.local, old_value, None);
449
+ }
450
+
451
+ if name.local == local_name!("id") {
452
+ element.id = None;
453
+ }
454
+
455
+ // As in `set_attribute`: taking one of these away can make the element
456
+ // unfocusable again.
457
+ if name.local == local_name!("tabindex")
458
+ || name.local == local_name!("href")
459
+ || name.local == local_name!("disabled")
460
+ {
461
+ element.flush_is_focussable();
462
+ }
463
+
464
+ if name.local == local_name!("href") {
465
+ element.flush_link_state();
466
+ }
467
+
468
+ // Update text input value
469
+ if name.local == local_name!("value") {
470
+ if let Some(input_data) = element.text_input_data_mut() {
471
+ input_data.set_text(
472
+ &mut self.doc.font_ctx.lock().unwrap(),
473
+ &mut self.doc.layout_ctx,
474
+ "",
475
+ );
476
+ }
477
+ }
478
+
479
+ let tag = &element.name.local;
480
+ let attr = &name.local;
481
+
482
+ if *attr == local_name!("disabled") && element.can_be_disabled() {
483
+ node.enable();
484
+ return;
485
+ }
486
+
487
+ if *attr == local_name!("style") {
488
+ element.flush_style_attribute(&self.doc.guard, &self.doc.url.url_extra_data());
489
+ node.set_restyle_hint(RestyleHint::RESTYLE_STYLE_ATTRIBUTE);
490
+ } else if (tag, attr) == tag_and_attr!("input", "checked") {
491
+ element.set_checkbox_input_checked(false);
492
+ } else if (tag, attr) == tag_and_attr!("canvas", "src") {
493
+ self.recompute_is_animating = true;
494
+ } else if (tag, attr) == tag_and_attr!("link", "href") {
495
+ self.unload_stylesheet(node_id);
496
+ } else if (tag, attr) == tag_and_attr!("iframe", "srcdoc") && node_is_in_document {
497
+ // Fall back to loading from the `src` attribute (if any)
498
+ self.load_iframe(node_id);
499
+ }
500
+ }
501
+
502
+ pub fn set_style_property(&mut self, node_id: NodeId, name: &str, value: &str) {
503
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
504
+ self.doc.set_style_property(node_id, name, value);
505
+ self.mutations_occurred |= node_is_in_document;
506
+ }
507
+
508
+ pub fn remove_style_property(&mut self, node_id: NodeId, name: &str) {
509
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
510
+ self.doc.remove_style_property(node_id, name);
511
+ self.mutations_occurred |= node_is_in_document;
512
+ }
513
+
514
+ pub fn set_sub_document(&mut self, node_id: NodeId, sub_document: Box<dyn Document>) {
515
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
516
+ self.doc.set_sub_document(node_id, sub_document);
517
+ self.mutations_occurred |= node_is_in_document;
518
+ }
519
+
520
+ pub fn remove_sub_document(&mut self, node_id: NodeId) {
521
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
522
+ self.doc.remove_sub_document(node_id);
523
+ self.mutations_occurred |= node_is_in_document;
524
+ }
525
+
526
+ #[cfg(feature = "custom-widget")]
527
+ pub fn set_custom_widget(&mut self, node_id: NodeId, widget: Box<dyn crate::Widget>) {
528
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
529
+ self.doc.set_custom_widget(node_id, widget);
530
+ self.mutations_occurred |= node_is_in_document;
531
+ }
532
+
533
+ #[cfg(feature = "custom-widget")]
534
+ pub fn remove_custom_widget(&mut self, node_id: NodeId) {
535
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
536
+ self.doc.remove_custom_widget(node_id);
537
+ self.mutations_occurred |= node_is_in_document;
538
+ }
539
+
540
+ /// Remove the node from it's parent but don't drop it
541
+ pub fn remove_node(&mut self, node_id: NodeId) {
542
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
543
+ // Process the subtree *before* severing the parent link so that
544
+ // interaction state referencing removed nodes can retarget to the
545
+ // nearest surviving ancestor.
546
+ self.process_removed_subtree(node_id);
547
+
548
+ let node = &mut self.doc.nodes[node_id];
549
+
550
+ // Update child_idx values
551
+ if let Some(parent_id) = node.parent.take() {
552
+ self.mutations_occurred |= node_is_in_document;
553
+ let parent = &mut self.doc.nodes[parent_id];
554
+ parent.insert_damage(ALL_DAMAGE);
555
+ // Mark ancestors dirty so the style traversal visits this subtree.
556
+ parent.mark_ancestors_dirty();
557
+ parent.children.retain(|id| *id != node_id);
558
+ self.maybe_record_node(parent_id);
559
+ }
560
+ }
561
+
562
+ pub fn remove_and_drop_node(&mut self, node_id: NodeId) -> Option<Node> {
563
+ self.remove_and_drop_node_with(node_id, &mut |_| {})
564
+ }
565
+
566
+ /// Like [`Self::remove_and_drop_node`], but calls `on_drop` with the id of
567
+ /// every dropped node (the node itself and all of its descendants).
568
+ pub fn remove_and_drop_node_with(
569
+ &mut self,
570
+ node_id: NodeId,
571
+ on_drop: &mut dyn FnMut(NodeId),
572
+ ) -> Option<Node> {
573
+ let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();
574
+ self.process_removed_subtree(node_id);
575
+
576
+ let node = self.doc.drop_node_ignoring_parent_with(node_id, on_drop);
577
+ self.mutations_occurred |= node_is_in_document;
578
+
579
+ // Update child_idx values
580
+ if let Some(parent_id) = node.as_ref().and_then(|node| node.parent) {
581
+ let parent = &mut self.doc.nodes[parent_id];
582
+ parent.insert_damage(ALL_DAMAGE);
583
+ let parent_is_in_doc = parent.flags.is_in_document();
584
+
585
+ // TODO: make this fine grained / conditional based on ElementSelectorFlags
586
+ if parent_is_in_doc {
587
+ if let Some(mut data) = parent
588
+ .try_stylo_element_data_mut()
589
+ .and_then(|s| s.get_mut())
590
+ {
591
+ data.hint |= RestyleHint::restyle_subtree();
592
+ }
593
+ // Mark ancestors dirty so the style traversal visits this subtree.
594
+ parent.mark_ancestors_dirty();
595
+ }
596
+
597
+ parent.children.retain(|id| *id != node_id);
598
+ self.maybe_record_node(parent_id);
599
+ }
600
+
601
+ node
602
+ }
603
+
604
+ pub fn remove_and_drop_all_children(&mut self, node_id: NodeId) {
605
+ let parent = &mut self.doc.nodes[node_id];
606
+ let parent_is_in_doc = parent.flags.is_in_document();
607
+
608
+ // TODO: make this fine grained / conditional based on ElementSelectorFlags
609
+ if parent_is_in_doc {
610
+ if let Some(mut data) = parent
611
+ .try_stylo_element_data_mut()
612
+ .and_then(|s| s.get_mut())
613
+ {
614
+ data.hint |= RestyleHint::restyle_subtree();
615
+ }
616
+ // Mark ancestors dirty so the style traversal visits this subtree.
617
+ parent.mark_ancestors_dirty();
618
+ }
619
+
620
+ let children = mem::take(&mut parent.children);
621
+ self.mutations_occurred |= parent_is_in_doc && !children.is_empty();
622
+ for child_id in children {
623
+ self.process_removed_subtree(child_id);
624
+ let _ = self.doc.drop_node_ignoring_parent(child_id);
625
+ }
626
+ self.maybe_record_node(node_id);
627
+ }
628
+
629
+ // Tree mutation methods
630
+ pub fn remove_node_if_unparented(&mut self, node_id: NodeId) {
631
+ self.remove_node_if_unparented_with(node_id, &mut |_| {});
632
+ }
633
+
634
+ /// Like [`Self::remove_node_if_unparented`], but calls `on_drop` with the id of
635
+ /// every dropped node (the node itself and all of its descendants).
636
+ pub fn remove_node_if_unparented_with(
637
+ &mut self,
638
+ node_id: NodeId,
639
+ on_drop: &mut dyn FnMut(NodeId),
640
+ ) {
641
+ if let Some(node) = self.doc.get_node(node_id) {
642
+ if node.parent.is_none() {
643
+ self.remove_and_drop_node_with(node_id, on_drop);
644
+ }
645
+ }
646
+ }
647
+
648
+ /// Remove all of the children from old_parent_id and append them to new_parent_id
649
+ pub fn append_children(&mut self, parent_id: NodeId, child_ids: &[NodeId]) {
650
+ self.add_children_to_parent(parent_id, child_ids, &|parent, child_ids| {
651
+ parent.children.extend_from_slice(child_ids);
652
+ });
653
+ }
654
+
655
+ pub fn insert_nodes_before(&mut self, anchor_node_id: NodeId, new_node_ids: &[NodeId]) {
656
+ let parent_id = self.doc.nodes[anchor_node_id].parent.unwrap();
657
+ self.add_children_to_parent(parent_id, new_node_ids, &|parent, child_ids| {
658
+ let node_child_idx = parent.index_of_child(anchor_node_id).unwrap();
659
+ parent
660
+ .children
661
+ .splice(node_child_idx..node_child_idx, child_ids.iter().copied());
662
+ });
663
+ }
664
+
665
+ fn add_children_to_parent(
666
+ &mut self,
667
+ parent_id: NodeId,
668
+ child_ids: &[NodeId],
669
+ insert_children_fn: &dyn Fn(&mut Node, &[NodeId]),
670
+ ) {
671
+ let new_parent_is_in_document = self.doc.nodes[parent_id].flags.is_in_document();
672
+ self.mutations_occurred |= new_parent_is_in_document && !child_ids.is_empty();
673
+ // Detach the children from their old parents *before* inserting them into
674
+ // the new parent (matching DOM `insertBefore` semantics). If a child is
675
+ // being moved within the same parent then detaching it after insertion
676
+ // would remove both the old and the newly-inserted entries from the
677
+ // parent's child list, and anchor indices would be computed against a
678
+ // child list that still contains the moved nodes.
679
+ for child_id in child_ids.iter().copied() {
680
+ let child = &mut self.doc.nodes[child_id];
681
+ let child_was_in_doc = child.flags.is_in_document();
682
+ self.mutations_occurred |= child_was_in_doc;
683
+ let Some(old_parent_id) = child.parent.take() else {
684
+ continue;
685
+ };
686
+
687
+ let old_parent = &mut self.doc.nodes[old_parent_id];
688
+ old_parent.insert_damage(ALL_DAMAGE);
689
+
690
+ // TODO: make this fine grained / conditional based on ElementSelectorFlags
691
+ if child_was_in_doc {
692
+ if let Some(mut data) = old_parent
693
+ .try_stylo_element_data_mut()
694
+ .and_then(|s| s.get_mut())
695
+ {
696
+ data.hint |= RestyleHint::restyle_subtree();
697
+ }
698
+ // Mark ancestors dirty so the style traversal visits this subtree.
699
+ old_parent.mark_ancestors_dirty();
700
+ }
701
+
702
+ old_parent.children.retain(|id| *id != child_id);
703
+ self.maybe_record_node(old_parent_id);
704
+ }
705
+
706
+ let new_parent = &mut self.doc.nodes[parent_id];
707
+ new_parent.insert_damage(ALL_DAMAGE);
708
+
709
+ // TODO: make this fine grained / conditional based on ElementSelectorFlags
710
+ if new_parent_is_in_document {
711
+ if let Some(mut data) = new_parent
712
+ .try_stylo_element_data_mut()
713
+ .and_then(|s| s.get_mut())
714
+ {
715
+ data.hint |= RestyleHint::restyle_subtree();
716
+ }
717
+ // Mark ancestors dirty so the style traversal visits this subtree.
718
+ new_parent.mark_ancestors_dirty();
719
+ }
720
+
721
+ insert_children_fn(new_parent, child_ids);
722
+
723
+ for child_id in child_ids.iter().copied() {
724
+ let child = &mut self.doc.nodes[child_id];
725
+ let child_was_in_doc = child.flags.is_in_document();
726
+ child.parent = Some(parent_id);
727
+
728
+ if new_parent_is_in_document && !child_was_in_doc {
729
+ self.process_added_subtree(child_id);
730
+ } else if !new_parent_is_in_document && child_was_in_doc {
731
+ self.process_removed_subtree(child_id);
732
+ }
733
+ }
734
+
735
+ self.maybe_record_node(parent_id);
736
+ }
737
+
738
+ // Tree mutation methods (that defer to other methods)
739
+ pub fn insert_nodes_after(&mut self, anchor_node_id: NodeId, new_node_ids: &[NodeId]) {
740
+ match self.next_sibling_id(anchor_node_id) {
741
+ Some(id) => self.insert_nodes_before(id, new_node_ids),
742
+ None => {
743
+ let parent_id = self.parent_id(anchor_node_id).unwrap();
744
+ self.append_children(parent_id, new_node_ids)
745
+ }
746
+ }
747
+ }
748
+
749
+ pub fn reparent_children(&mut self, old_parent_id: NodeId, new_parent_id: NodeId) {
750
+ let child_ids = std::mem::take(&mut self.doc.nodes[old_parent_id].children);
751
+ self.maybe_record_node(old_parent_id);
752
+ self.append_children(new_parent_id, &child_ids);
753
+ }
754
+
755
+ pub fn replace_node_with(&mut self, anchor_node_id: NodeId, new_node_ids: &[NodeId]) {
756
+ self.insert_nodes_before(anchor_node_id, new_node_ids);
757
+ self.remove_node(anchor_node_id);
758
+ }
759
+
760
+ // === ParentNode / ChildNode mixin mutation methods ===
761
+ //
762
+ // These implement the DOM spec's mutation semantics for the ParentNode and
763
+ // ChildNode mixins (`append`/`prepend`/`replaceChildren` and
764
+ // `before`/`after`/`replaceWith`). Callers pass lists of node ids with
765
+ // string arguments already converted to (detached) text nodes and
766
+ // DocumentFragment arguments already expanded into their children (per the
767
+ // DOM spec's "insert a node" steps).
768
+
769
+ /// Detach (rather than drop) any already-parented nodes, so that references
770
+ /// to them (and their descendants) remain valid
771
+ fn detach_all(&mut self, node_ids: &[NodeId]) {
772
+ for node_id in node_ids {
773
+ if self.node_has_parent(*node_id) {
774
+ self.remove_node(*node_id);
775
+ }
776
+ }
777
+ }
778
+
779
+ /// The nearest sibling of `anchor_id` (in the direction given by `offset`:
780
+ /// +1 = following, -1 = preceding) which is not in `excluded` — the spec's
781
+ /// "viable next/previous sibling" for ChildNode mutation methods
782
+ fn viable_sibling(
783
+ &self,
784
+ anchor_id: NodeId,
785
+ offset: isize,
786
+ excluded: &[NodeId],
787
+ ) -> Option<NodeId> {
788
+ let node = self.doc.get_node(anchor_id)?;
789
+ let parent = self.doc.get_node(node.parent?)?;
790
+ let mut index = parent.index_of_child(anchor_id)?;
791
+ loop {
792
+ index = index.checked_add_signed(offset)?;
793
+ let sibling_id = *parent.children.get(index)?;
794
+ if !excluded.contains(&sibling_id) {
795
+ return Some(sibling_id);
796
+ }
797
+ }
798
+ }
799
+
800
+ /// ParentNode's `prepend()`: insert the nodes at the start of `parent_id`'s
801
+ /// children (ParentNode's `append()` is [`append_children`](Self::append_children))
802
+ pub fn prepend_nodes(&mut self, parent_id: NodeId, node_ids: &[NodeId]) {
803
+ self.detach_all(node_ids);
804
+ match self.child_ids(parent_id).first().copied() {
805
+ Some(first_child_id) => self.insert_nodes_before(first_child_id, node_ids),
806
+ None => self.append_children(parent_id, node_ids),
807
+ }
808
+ }
809
+
810
+ /// ParentNode's `replaceChildren()`: replace all of `parent_id`'s children
811
+ /// with the given nodes. The existing children are detached rather than
812
+ /// dropped, so that references to them remain valid.
813
+ pub fn replace_children(&mut self, parent_id: NodeId, node_ids: &[NodeId]) {
814
+ self.detach_all(node_ids);
815
+ for child_id in self.child_ids(parent_id) {
816
+ self.remove_node(child_id);
817
+ }
818
+ self.append_children(parent_id, node_ids);
819
+ }
820
+
821
+ /// ChildNode's `before()`: insert the nodes before `anchor_id`. The
822
+ /// insertion point is after the nearest preceding sibling which isn't
823
+ /// itself being inserted (or at the start of the parent if there is none).
824
+ /// Does nothing if the anchor has no parent.
825
+ pub fn before_node(&mut self, anchor_id: NodeId, node_ids: &[NodeId]) {
826
+ let Some(parent_id) = self.parent_id(anchor_id) else {
827
+ return;
828
+ };
829
+ let viable_prev = self.viable_sibling(anchor_id, -1, node_ids);
830
+ self.detach_all(node_ids);
831
+ match viable_prev {
832
+ Some(prev_id) => self.insert_nodes_after(prev_id, node_ids),
833
+ None => match self.child_ids(parent_id).first().copied() {
834
+ Some(first_child_id) => self.insert_nodes_before(first_child_id, node_ids),
835
+ None => self.append_children(parent_id, node_ids),
836
+ },
837
+ }
838
+ }
839
+
840
+ /// ChildNode's `after()`: insert the nodes after `anchor_id`. The insertion
841
+ /// point is before the nearest following sibling which isn't itself being
842
+ /// inserted (or at the end of the parent if there is none). Does nothing if
843
+ /// the anchor has no parent.
844
+ pub fn after_node(&mut self, anchor_id: NodeId, node_ids: &[NodeId]) {
845
+ let Some(parent_id) = self.parent_id(anchor_id) else {
846
+ return;
847
+ };
848
+ let viable_next = self.viable_sibling(anchor_id, 1, node_ids);
849
+ self.detach_all(node_ids);
850
+ match viable_next {
851
+ Some(next_id) => self.insert_nodes_before(next_id, node_ids),
852
+ None => self.append_children(parent_id, node_ids),
853
+ }
854
+ }
855
+
856
+ /// ChildNode's `replaceWith()`: replace `anchor_id` with the nodes in its
857
+ /// parent's child list. If the anchor is itself one of the inserted nodes,
858
+ /// they are inserted at its old position (the spec's "viable next sibling"
859
+ /// handling). The anchor is detached rather than dropped, so references to
860
+ /// it remain valid. Does nothing if the anchor has no parent.
861
+ pub fn replace_with_nodes(&mut self, anchor_id: NodeId, node_ids: &[NodeId]) {
862
+ let Some(parent_id) = self.parent_id(anchor_id) else {
863
+ return;
864
+ };
865
+ let viable_next = self.viable_sibling(anchor_id, 1, node_ids);
866
+ self.detach_all(node_ids);
867
+ if self.node_has_parent(anchor_id) {
868
+ self.replace_node_with(anchor_id, node_ids);
869
+ } else {
870
+ match viable_next {
871
+ Some(next_id) => self.insert_nodes_before(next_id, node_ids),
872
+ None => self.append_children(parent_id, node_ids),
873
+ }
874
+ }
875
+ }
876
+ }
877
+
878
+ impl<'doc> DocumentMutator<'doc> {
879
+ pub fn flush(&mut self) {
880
+ if self.recompute_is_animating {
881
+ self.doc.has_canvas = self.doc.compute_has_canvas();
882
+ }
883
+
884
+ if let Some(id) = self.title_node {
885
+ let title = self.doc.nodes[id].text_content();
886
+ self.doc.shell_provider.set_window_title(title);
887
+ }
888
+
889
+ // Add/Update inline stylesheets (<style> elements)
890
+ for id in self.style_nodes.drain() {
891
+ self.doc.process_style_element(id);
892
+ }
893
+
894
+ for id in self.form_nodes.drain() {
895
+ self.doc.reset_form_owner(id);
896
+ }
897
+
898
+ #[cfg(feature = "autofocus")]
899
+ if let Some(node_id) = self.node_to_autofocus.take() {
900
+ if self.doc.get_node(node_id).is_some() {
901
+ self.doc.set_focus_to(node_id);
902
+ }
903
+ }
904
+ }
905
+
906
+ pub fn set_inner_html(&mut self, node_id: NodeId, html: &str) {
907
+ self.remove_and_drop_all_children(node_id);
908
+ self.doc
909
+ .html_parser_provider
910
+ .clone()
911
+ .parse_inner_html(self, node_id, html);
912
+ }
913
+
914
+ fn flush_eager_ops(&mut self) {
915
+ let mut ops = mem::take(&mut self.eager_op_queue);
916
+ for op in ops.drain(0..) {
917
+ match op {
918
+ SpecialOp::LoadImage(node_id) => self.load_image(node_id),
919
+ SpecialOp::LoadIframe(node_id) => self.load_iframe(node_id),
920
+ SpecialOp::LoadStylesheet(node_id) => self.load_linked_stylesheet(node_id),
921
+ SpecialOp::UnloadStylesheet(node_id) => self.unload_stylesheet(node_id),
922
+ SpecialOp::LoadCustomPaintSource(node_id) => self.load_custom_paint_src(node_id),
923
+ SpecialOp::ProcessButtonInput(node_id) => self.process_button_input(node_id),
924
+ SpecialOp::UnloadSubDocument(node_id) => self.remove_sub_document(node_id),
925
+ #[cfg(feature = "custom-widget")]
926
+ SpecialOp::UnloadCustomWidget(node_id) => self.remove_custom_widget(node_id),
927
+ }
928
+ }
929
+
930
+ // Queue is empty, but put Vec back anyway so allocation can be reused.
931
+ self.eager_op_queue = ops;
932
+ }
933
+
934
+ fn process_added_subtree(&mut self, node_id: NodeId) {
935
+ self.doc.iter_subtree_mut(node_id, |node_id, doc| {
936
+ let node = &mut doc.nodes[node_id];
937
+ node.flags.set(NodeFlags::IS_IN_DOCUMENT, true);
938
+ node.insert_damage(ALL_DAMAGE);
939
+
940
+ // If the node has an "id" attribute, store it in the ID map.
941
+ if let Some(id_attr) = node.attr(local_name!("id")).map(ToString::to_string) {
942
+ doc.add_to_id_map(&id_attr, node_id);
943
+ }
944
+
945
+ let node = &mut doc.nodes[node_id];
946
+ let NodeData::Element(ref mut element) = node.data else {
947
+ return;
948
+ };
949
+
950
+ // Custom widgets replace the element's built-in tag-specific behaviour
951
+ #[cfg(feature = "custom-widget")]
952
+ let has_custom_widget = element.custom_widget_data().is_some();
953
+ #[cfg(not(feature = "custom-widget"))]
954
+ let has_custom_widget = false;
955
+
956
+ // Custom post-processing by element tag name
957
+ let tag = element.name.local.as_ref();
958
+ match tag {
959
+ "title" => self.title_node = Some(node_id),
960
+ "style" => {
961
+ self.style_nodes.insert(node_id);
962
+ }
963
+ _ if has_custom_widget => {}
964
+ "link" => self.eager_op_queue.push(SpecialOp::LoadStylesheet(node_id)),
965
+ "img" => self.eager_op_queue.push(SpecialOp::LoadImage(node_id)),
966
+ "iframe" => self.eager_op_queue.push(SpecialOp::LoadIframe(node_id)),
967
+ "canvas" => self
968
+ .eager_op_queue
969
+ .push(SpecialOp::LoadCustomPaintSource(node_id)),
970
+ "button" | "fieldset" | "input" | "select" | "textarea" | "object" | "output" => {
971
+ self.eager_op_queue
972
+ .push(SpecialOp::ProcessButtonInput(node_id));
973
+ self.form_nodes.insert(node_id);
974
+ }
975
+ _ => {}
976
+ }
977
+
978
+ #[cfg(feature = "autofocus")]
979
+ if node.is_focussable() {
980
+ if let NodeData::Element(ref element) = node.data {
981
+ // `autofocus` is a boolean attribute, so presence alone enables it
982
+ // (`<input autofocus>`). "false" is still ignored, because Dioxus
983
+ // writes `autofocus: false` as the string "false".
984
+ if let Some(value) = element.attr(local_name!("autofocus")) {
985
+ if value != "false" {
986
+ self.node_to_autofocus = Some(node_id);
987
+ }
988
+ }
989
+ }
990
+ }
991
+ });
992
+
993
+ self.flush_eager_ops();
994
+ }
995
+
996
+ fn process_removed_subtree(&mut self, node_id: NodeId) {
997
+ self.doc.iter_subtree_mut(node_id, |node_id, doc| {
998
+ doc.nodes[node_id]
999
+ .flags
1000
+ .set(NodeFlags::IS_IN_DOCUMENT, false);
1001
+
1002
+ // Clear any interaction state that references this node, running
1003
+ // the usual teardown steps (unhover/unactive the surviving
1004
+ // ancestor chain, IME disable on blur of a focused input).
1005
+ doc.clear_interaction_state_for_removed_node(node_id);
1006
+
1007
+ let node = &mut doc.nodes[node_id];
1008
+
1009
+ // Clear the text selection if one of its endpoints references this node.
1010
+ // This prevents stale selection endpoint references.
1011
+ if doc.text_selection.anchor.node_or_parent == Some(node_id)
1012
+ || doc.text_selection.focus.node_or_parent == Some(node_id)
1013
+ {
1014
+ doc.text_selection.clear();
1015
+ }
1016
+
1017
+ // Remove any snapshot for this node to prevent stale snapshot references
1018
+ // during style invalidation.
1019
+ if node.has_snapshot() {
1020
+ let opaque_id = style::dom::TNode::opaque(&&*node);
1021
+ doc.snapshots.remove(&opaque_id);
1022
+ node.set_has_snapshot(false);
1023
+ }
1024
+
1025
+ // If the node has an "id" attribute remove it from the ID map.
1026
+ if let Some(id_attr) = node.attr(local_name!("id")).map(ToString::to_string) {
1027
+ doc.remove_from_id_map(&id_attr, node_id);
1028
+ }
1029
+
1030
+ let node = &mut doc.nodes[node_id];
1031
+ let NodeData::Element(ref mut element) = node.data else {
1032
+ return;
1033
+ };
1034
+
1035
+ match &element.special_data {
1036
+ SpecialElementData::SubDocument(_) => {
1037
+ self.eager_op_queue
1038
+ .push(SpecialOp::UnloadSubDocument(node_id));
1039
+ }
1040
+ #[cfg(feature = "custom-widget")]
1041
+ SpecialElementData::CustomWidget(_) => {
1042
+ self.eager_op_queue
1043
+ .push(SpecialOp::UnloadCustomWidget(node_id));
1044
+ }
1045
+ SpecialElementData::Stylesheet(_) => self
1046
+ .eager_op_queue
1047
+ .push(SpecialOp::UnloadStylesheet(node_id)),
1048
+ SpecialElementData::Image(_) => {}
1049
+ SpecialElementData::Canvas(_) => {
1050
+ self.recompute_is_animating = true;
1051
+ }
1052
+ SpecialElementData::TableRoot(_) => {}
1053
+ SpecialElementData::TextInput(_) => {}
1054
+ SpecialElementData::CheckboxInput(_) => {}
1055
+ #[cfg(feature = "file-input")]
1056
+ SpecialElementData::FileInput(_) => {}
1057
+ SpecialElementData::None => {}
1058
+ }
1059
+ });
1060
+
1061
+ self.flush_eager_ops();
1062
+ }
1063
+
1064
+ fn maybe_record_node(&mut self, node_id: impl Into<Option<NodeId>>) {
1065
+ let Some(node_id) = node_id.into() else {
1066
+ return;
1067
+ };
1068
+
1069
+ let Some(tag_name) = self.doc.nodes[node_id]
1070
+ .data
1071
+ .downcast_element()
1072
+ .map(|elem| &elem.name.local)
1073
+ else {
1074
+ return;
1075
+ };
1076
+
1077
+ match tag_name.as_ref() {
1078
+ "title" => self.title_node = Some(node_id),
1079
+ "style" => {
1080
+ self.style_nodes.insert(node_id);
1081
+ }
1082
+ _ => {}
1083
+ }
1084
+ }
1085
+
1086
+ fn load_linked_stylesheet(&mut self, target_id: NodeId) {
1087
+ let node = &self.doc.nodes[target_id];
1088
+
1089
+ let mut is_in_head = false;
1090
+ let mut parent_id = node.parent;
1091
+ while let Some(id) = parent_id
1092
+ && !is_in_head
1093
+ {
1094
+ let parent = &self.doc.nodes[id];
1095
+ is_in_head |= parent.data.is_element_with_tag_name(&local_name!("head"));
1096
+ parent_id = parent.parent;
1097
+ }
1098
+
1099
+ let rel_attr = node.attr(local_name!("rel"));
1100
+ let href_attr = node.attr(local_name!("href"));
1101
+
1102
+ let (Some(rels), Some(href)) = (rel_attr, href_attr) else {
1103
+ return;
1104
+ };
1105
+ if !rels.split_ascii_whitespace().any(|rel| rel == "stylesheet") {
1106
+ return;
1107
+ }
1108
+
1109
+ let url = self.doc.resolve_url(href);
1110
+ let handler = ResourceHandler::new(
1111
+ self.doc.tx.clone(),
1112
+ self.doc.id(),
1113
+ Some(node.id),
1114
+ self.doc.shell_provider.clone(),
1115
+ StylesheetHandler {
1116
+ source_url: url.clone(),
1117
+ guard: self.doc.guard.clone(),
1118
+ net_provider: self.doc.net_provider.clone(),
1119
+ abort_signal: self.doc.abort_signal.clone(),
1120
+ },
1121
+ );
1122
+
1123
+ if is_in_head && !self.doc.net_provider.is_noop() {
1124
+ self.doc
1125
+ .pending_critical_resources
1126
+ .insert(handler.request_id());
1127
+ }
1128
+
1129
+ self.doc.net_provider.fetch(
1130
+ self.doc.id(),
1131
+ self.doc.build_request(url),
1132
+ Box::new(handler),
1133
+ );
1134
+ }
1135
+
1136
+ fn unload_stylesheet(&mut self, node_id: NodeId) {
1137
+ let node = &mut self.doc.nodes[node_id];
1138
+ let Some(element) = node.element_data_mut() else {
1139
+ unreachable!();
1140
+ };
1141
+ let SpecialElementData::Stylesheet(stylesheet) = element.special_data.take() else {
1142
+ unreachable!();
1143
+ };
1144
+
1145
+ let guard = self.doc.guard.read();
1146
+ self.doc.stylist.remove_stylesheet(stylesheet, &guard);
1147
+ self.doc
1148
+ .stylist
1149
+ .force_stylesheet_origins_dirty(OriginSet::all());
1150
+
1151
+ self.doc.nodes_to_stylesheet.remove(&node_id);
1152
+ self.doc.stylesheet_generation += 1;
1153
+ }
1154
+
1155
+ fn load_image(&mut self, target_id: NodeId) {
1156
+ let node = &self.doc.nodes[target_id];
1157
+ if let Some(raw_src) = node.attr(local_name!("src")) {
1158
+ if !raw_src.is_empty() {
1159
+ let src = self.doc.resolve_url(raw_src);
1160
+ let src_string = src.as_str();
1161
+
1162
+ // Check cache first
1163
+ if let Some(cached_image) = self.doc.image_cache.get(src_string) {
1164
+ #[cfg(feature = "tracing")]
1165
+ tracing::info!("Loading image {src_string} from cache");
1166
+ let node = &mut self.doc.nodes[target_id];
1167
+ node.element_data_mut().unwrap().special_data =
1168
+ SpecialElementData::Image(Box::new(cached_image.clone()));
1169
+ node.clear_layout_cache();
1170
+ node.insert_damage(ALL_DAMAGE);
1171
+ return;
1172
+ }
1173
+
1174
+ // Check if there's already a pending request for this URL
1175
+ if let Some(waiting_list) = self.doc.pending_images.get_mut(src_string) {
1176
+ #[cfg(feature = "tracing")]
1177
+ tracing::info!("Image {src_string} already pending, queueing node {target_id}");
1178
+ waiting_list.push((target_id, ImageType::Image));
1179
+ return;
1180
+ }
1181
+
1182
+ // Start fetch and track as pending
1183
+ #[cfg(feature = "tracing")]
1184
+ tracing::info!("Fetching image {src_string}");
1185
+ self.doc
1186
+ .pending_images
1187
+ .insert(src_string.to_string(), vec![(target_id, ImageType::Image)]);
1188
+
1189
+ self.doc.net_provider.fetch(
1190
+ self.doc.id(),
1191
+ self.doc.build_request(src),
1192
+ ResourceHandler::boxed(
1193
+ self.doc.tx.clone(),
1194
+ self.doc.id(),
1195
+ None, // Don't pass node_id, we'll handle it via pending_images
1196
+ self.doc.shell_provider.clone(),
1197
+ ImageHandler::new(ImageType::Image),
1198
+ ),
1199
+ );
1200
+ }
1201
+ }
1202
+ }
1203
+
1204
+ fn load_iframe(&mut self, target_id: NodeId) {
1205
+ if self.doc.subdocument_depth >= crate::iframe::MAX_SUBDOCUMENT_DEPTH {
1206
+ #[cfg(feature = "tracing")]
1207
+ tracing::warn!(
1208
+ "Not loading iframe: max sub-document nesting depth ({}) reached",
1209
+ crate::iframe::MAX_SUBDOCUMENT_DEPTH
1210
+ );
1211
+ return;
1212
+ }
1213
+
1214
+ let node = &self.doc.nodes[target_id];
1215
+ let Some(element) = node.element_data() else {
1216
+ return;
1217
+ };
1218
+
1219
+ // `srcdoc` takes precedence over `src`
1220
+ if let Some(srcdoc) = element.attr(local_name!("srcdoc")) {
1221
+ let srcdoc = srcdoc.to_string();
1222
+ self.doc.load_iframe_srcdoc(target_id, &srcdoc);
1223
+ return;
1224
+ }
1225
+
1226
+ let Some(raw_src) = element.attr(local_name!("src")) else {
1227
+ return;
1228
+ };
1229
+ if raw_src.is_empty() {
1230
+ return;
1231
+ }
1232
+ let Some(url) = self.doc.url.resolve_relative(raw_src) else {
1233
+ #[cfg(feature = "tracing")]
1234
+ tracing::warn!("Not loading iframe: could not resolve url {raw_src}");
1235
+ return;
1236
+ };
1237
+ self.doc.start_iframe_load(target_id, url);
1238
+ }
1239
+
1240
+ fn load_custom_paint_src(&mut self, target_id: NodeId) {
1241
+ let node = &mut self.doc.nodes[target_id];
1242
+ if let Some(raw_src) = node.attr(local_name!("src")) {
1243
+ if let Ok(custom_paint_source_id) = raw_src.parse::<u64>() {
1244
+ self.recompute_is_animating = true;
1245
+ let canvas_data = SpecialElementData::Canvas(CanvasData {
1246
+ custom_paint_source_id,
1247
+ });
1248
+ node.element_data_mut().unwrap().special_data = canvas_data;
1249
+ }
1250
+ }
1251
+ }
1252
+
1253
+ fn process_button_input(&mut self, target_id: NodeId) {
1254
+ let node = &self.doc.nodes[target_id];
1255
+ let Some(data) = node.element_data() else {
1256
+ return;
1257
+ };
1258
+
1259
+ let tagname = data.name.local.as_ref();
1260
+ let type_attr = data.attr(local_name!("type"));
1261
+ let value = data.attr(local_name!("value"));
1262
+
1263
+ // Add content of "value" attribute as a text node child if:
1264
+ // - Tag name is
1265
+ if let ("input", Some("button" | "submit" | "reset"), Some(value)) =
1266
+ (tagname, type_attr, value)
1267
+ {
1268
+ let value = value.to_string();
1269
+ let id = self.create_text_node(&value);
1270
+ self.append_children(target_id, &[id]);
1271
+ return;
1272
+ }
1273
+ #[cfg(feature = "file-input")]
1274
+ if let ("input", Some("file")) = (tagname, type_attr) {
1275
+ let button_id = self.create_element(
1276
+ qual_name!("button", html),
1277
+ vec![
1278
+ Attribute {
1279
+ name: qual_name!("type", html),
1280
+ value: "button".to_string(),
1281
+ },
1282
+ Attribute {
1283
+ name: qual_name!("tabindex", html),
1284
+ value: "-1".to_string(),
1285
+ },
1286
+ ],
1287
+ );
1288
+ let label_id = self.create_element(qual_name!("label", html), vec![]);
1289
+ let text_id = self.create_text_node("No File Selected");
1290
+ let button_text_id = self.create_text_node("Browse");
1291
+ self.append_children(target_id, &[button_id, label_id]);
1292
+ self.append_children(label_id, &[text_id]);
1293
+ self.append_children(button_id, &[button_text_id]);
1294
+ }
1295
+ }
1296
+ }
1297
+
1298
+ /// Set 'checked' state on an input based on given attributevalue
1299
+ fn set_input_checked_state(element: &mut ElementData, value: String) {
1300
+ let Ok(checked) = value.parse() else {
1301
+ return;
1302
+ };
1303
+ match element.special_data {
1304
+ SpecialElementData::CheckboxInput(_) => element.set_checkbox_input_checked(checked),
1305
+ // If we have just constructed the element, set the node attribute,
1306
+ // and NodeSpecificData will be created from that later
1307
+ // this simulates the checked attribute being set in html,
1308
+ // and the element's checked property being set from that
1309
+ SpecialElementData::None => element.attrs.push(Attribute {
1310
+ name: qual_name!("checked", html),
1311
+ value: checked.to_string(),
1312
+ }),
1313
+ _ => {}
1314
+ }
1315
+ }
1316
+
1317
+ /// Type that allows mutable access to the viewport
1318
+ /// And syncs it back to stylist on drop.
1319
+ pub struct ViewportMut<'doc> {
1320
+ doc: &'doc mut BaseDocument,
1321
+ initial_viewport: Viewport,
1322
+ }
1323
+ impl ViewportMut<'_> {
1324
+ pub fn new(doc: &mut BaseDocument) -> ViewportMut<'_> {
1325
+ let initial_viewport = doc.viewport.clone();
1326
+ ViewportMut {
1327
+ doc,
1328
+ initial_viewport,
1329
+ }
1330
+ }
1331
+ }
1332
+ impl Deref for ViewportMut<'_> {
1333
+ type Target = Viewport;
1334
+
1335
+ fn deref(&self) -> &Self::Target {
1336
+ &self.doc.viewport
1337
+ }
1338
+ }
1339
+ impl DerefMut for ViewportMut<'_> {
1340
+ fn deref_mut(&mut self) -> &mut Self::Target {
1341
+ &mut self.doc.viewport
1342
+ }
1343
+ }
1344
+ impl Drop for ViewportMut<'_> {
1345
+ fn drop(&mut self) {
1346
+ if self.doc.viewport == self.initial_viewport {
1347
+ return;
1348
+ }
1349
+
1350
+ let changes = DeviceChanges::from_viewports(&self.initial_viewport, &self.doc.viewport);
1351
+ self.doc.queue_device_changes(changes);
1352
+ }
1353
+ }
1354
+
1355
+ #[cfg(test)]
1356
+ mod test {
1357
+ use style::media_queries::MediaType;
1358
+ use style::servo_arc::Arc as ServoArc;
1359
+ use style_dom::ElementState;
1360
+
1361
+ use std::sync::{
1362
+ Arc,
1363
+ atomic::{AtomicUsize, Ordering},
1364
+ };
1365
+
1366
+ use blitz_traits::shell::{ColorScheme, ShellProvider, Viewport};
1367
+
1368
+ use crate::{Attribute, BaseDocument, DocumentConfig, ElementData, NodeData, qual_name};
1369
+
1370
+ #[test]
1371
+ fn media_type_defaults_to_screen() {
1372
+ let mut document = BaseDocument::new(DocumentConfig::default());
1373
+ assert_eq!(*document.media_type(), MediaType::screen());
1374
+ assert_eq!(document.stylist_device().media_type(), MediaType::screen());
1375
+ }
1376
+
1377
+ #[test]
1378
+ fn media_type_honors_config() {
1379
+ let mut document = BaseDocument::new(DocumentConfig {
1380
+ media_type: Some(MediaType::print()),
1381
+ ..Default::default()
1382
+ });
1383
+ assert_eq!(*document.media_type(), MediaType::print());
1384
+ assert_eq!(document.stylist_device().media_type(), MediaType::print());
1385
+ }
1386
+
1387
+ #[test]
1388
+ fn set_media_type_updates_stylist_device() {
1389
+ let mut document = BaseDocument::new(DocumentConfig::default());
1390
+ assert_eq!(document.stylist_device().media_type(), MediaType::screen());
1391
+
1392
+ document.set_media_type(MediaType::print());
1393
+ assert_eq!(*document.media_type(), MediaType::print());
1394
+ assert_eq!(document.stylist_device().media_type(), MediaType::print());
1395
+ }
1396
+
1397
+ #[test]
1398
+ fn mutator_remove_disabled() {
1399
+ let mut document = BaseDocument::new(DocumentConfig::default());
1400
+ let id = document.create_node(NodeData::Element(Box::new(ElementData::new(
1401
+ qual_name!("button"),
1402
+ vec![Attribute {
1403
+ name: qual_name!("disabled"),
1404
+ value: "".into(),
1405
+ }],
1406
+ ))));
1407
+
1408
+ let node = document.get_node(id).unwrap();
1409
+ assert!(
1410
+ node.element_state().contains(ElementState::DISABLED),
1411
+ "form node is disabled"
1412
+ );
1413
+ assert!(
1414
+ !node.element_state().contains(ElementState::ENABLED),
1415
+ "form node is not enabled yet"
1416
+ );
1417
+
1418
+ let mut mutator = document.mutate();
1419
+ mutator.clear_attribute(id, qual_name!("disabled"));
1420
+ drop(mutator);
1421
+
1422
+ let node = document.get_node(id).unwrap();
1423
+ assert!(
1424
+ !node.element_state().contains(ElementState::DISABLED),
1425
+ "form node is no longer disabled"
1426
+ );
1427
+ assert!(
1428
+ node.element_state().contains(ElementState::ENABLED),
1429
+ "form node is enabled"
1430
+ );
1431
+ }
1432
+
1433
+ #[test]
1434
+ fn mutator_set_disabled() {
1435
+ let mut document = BaseDocument::new(DocumentConfig::default());
1436
+ let id = document.create_node(NodeData::Element(Box::new(ElementData::new(
1437
+ qual_name!("button"),
1438
+ vec![],
1439
+ ))));
1440
+
1441
+ let node = document.get_node(id).unwrap();
1442
+ assert!(
1443
+ !node.element_state().contains(ElementState::DISABLED),
1444
+ "form node is not disabled"
1445
+ );
1446
+ assert!(
1447
+ node.element_state().contains(ElementState::ENABLED),
1448
+ "form node is enabled"
1449
+ );
1450
+
1451
+ let mut mutator = document.mutate();
1452
+ mutator.set_attribute(id, qual_name!("disabled"), "");
1453
+ drop(mutator);
1454
+
1455
+ let node = document.get_node(id).unwrap();
1456
+
1457
+ assert!(
1458
+ node.element_state().contains(ElementState::DISABLED),
1459
+ "form node is disabled"
1460
+ );
1461
+ assert!(
1462
+ !node.element_state().contains(ElementState::ENABLED),
1463
+ "form node is no longer enabled enabled"
1464
+ );
1465
+ }
1466
+
1467
+ #[test]
1468
+ fn mutator_set_disabled_invalid_node() {
1469
+ let mut document = BaseDocument::new(DocumentConfig::default());
1470
+ let id = document.create_node(NodeData::Element(Box::new(ElementData::new(
1471
+ qual_name!("a"),
1472
+ vec![],
1473
+ ))));
1474
+
1475
+ let node = document.get_node(id).unwrap();
1476
+ assert!(
1477
+ !node.element_state().contains(ElementState::DISABLED),
1478
+ "form node is not disabled"
1479
+ );
1480
+ assert!(
1481
+ !node.element_state().contains(ElementState::ENABLED),
1482
+ "form node is enabled"
1483
+ );
1484
+
1485
+ let mut mutator = document.mutate();
1486
+ mutator.set_attribute(id, qual_name!("disabled"), "");
1487
+ drop(mutator);
1488
+
1489
+ let node = document.get_node(id).unwrap();
1490
+ assert!(
1491
+ !node.element_state().contains(ElementState::DISABLED),
1492
+ "form node is not disabled"
1493
+ );
1494
+ assert!(
1495
+ !node.element_state().contains(ElementState::ENABLED),
1496
+ "form node is enabled"
1497
+ );
1498
+ }
1499
+
1500
+ #[test]
1501
+ fn mutator_id_attribute_updates_id_map() {
1502
+ let mut document = BaseDocument::new(DocumentConfig::default());
1503
+ let root_id = document.root_node().id;
1504
+
1505
+ let node_id = {
1506
+ let mut mutator = document.mutate();
1507
+ let node_id = mutator.create_element(
1508
+ qual_name!("div"),
1509
+ vec![Attribute {
1510
+ name: qual_name!("id"),
1511
+ value: "old".into(),
1512
+ }],
1513
+ );
1514
+ mutator.append_children(root_id, &[node_id]);
1515
+ node_id
1516
+ };
1517
+ assert_eq!(document.get_element_by_id("old"), Some(node_id));
1518
+
1519
+ {
1520
+ let mut mutator = document.mutate();
1521
+ mutator.set_attribute(node_id, qual_name!("id"), "new");
1522
+ }
1523
+ assert_eq!(document.get_element_by_id("new"), Some(node_id));
1524
+ assert_eq!(document.get_element_by_id("old"), None);
1525
+
1526
+ {
1527
+ let mut mutator = document.mutate();
1528
+ mutator.clear_attribute(node_id, qual_name!("id"));
1529
+ }
1530
+ assert_eq!(document.get_element_by_id("new"), None);
1531
+ }
1532
+
1533
+ #[test]
1534
+ fn get_element_by_id_duplicate_ids_first_in_tree_order_wins() {
1535
+ let mut document = BaseDocument::new(DocumentConfig::default());
1536
+ let root_id = document.root_node().id;
1537
+
1538
+ let (first_id, second_id) = {
1539
+ let mut mutator = document.mutate();
1540
+ let first_id = mutator.create_element(qual_name!("div"), vec![]);
1541
+ let second_id = mutator.create_element(qual_name!("div"), vec![]);
1542
+ mutator.append_children(root_id, &[first_id, second_id]);
1543
+ // Assign the id to the later node first so that insertion order
1544
+ // differs from tree order
1545
+ mutator.set_attribute(second_id, qual_name!("id"), "dup");
1546
+ mutator.set_attribute(first_id, qual_name!("id"), "dup");
1547
+ (first_id, second_id)
1548
+ };
1549
+ assert_eq!(document.get_element_by_id("dup"), Some(first_id));
1550
+
1551
+ {
1552
+ let mut mutator = document.mutate();
1553
+ mutator.remove_node(first_id);
1554
+ }
1555
+ assert_eq!(document.get_element_by_id("dup"), Some(second_id));
1556
+ }
1557
+
1558
+ #[derive(Default)]
1559
+ struct RedrawShell {
1560
+ redraw_requests: AtomicUsize,
1561
+ }
1562
+
1563
+ impl ShellProvider for RedrawShell {
1564
+ fn request_redraw(&self) {
1565
+ self.redraw_requests.fetch_add(1, Ordering::Relaxed);
1566
+ }
1567
+ }
1568
+
1569
+ #[test]
1570
+ fn mutator_requests_redraw_only_after_mutation() {
1571
+ let shell = Arc::new(RedrawShell::default());
1572
+ let mut document = BaseDocument::new(DocumentConfig {
1573
+ shell_provider: Some(shell.clone()),
1574
+ ..Default::default()
1575
+ });
1576
+ let root_id = document.root_node().id;
1577
+
1578
+ {
1579
+ let mut mutator = document.mutate();
1580
+ let parent_id = mutator.create_element(qual_name!("div"), vec![]);
1581
+ let child_id = mutator.create_element(qual_name!("span"), vec![]);
1582
+ mutator.append_children(parent_id, &[child_id]);
1583
+ mutator.remove_and_drop_all_children(parent_id);
1584
+ mutator.set_attribute(parent_id, qual_name!("id"), "detached");
1585
+ }
1586
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 0);
1587
+
1588
+ {
1589
+ let mutator = document.mutate();
1590
+ assert_eq!(mutator.child_ids(root_id).len(), 0);
1591
+ }
1592
+
1593
+ {
1594
+ let mut mutator = document.mutate();
1595
+ let node_id = mutator.create_element(qual_name!("div"), vec![]);
1596
+ mutator.append_children(root_id, &[node_id]);
1597
+ mutator.set_attribute(node_id, qual_name!("id"), "in-document");
1598
+ }
1599
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 1);
1600
+
1601
+ {
1602
+ let mut mutator = document.mutate();
1603
+ let parent_id = mutator.create_element(qual_name!("div"), vec![]);
1604
+ let child_id = mutator.create_element(qual_name!("span"), vec![]);
1605
+ mutator.append_children(root_id, &[parent_id]);
1606
+ mutator.append_children(parent_id, &[child_id]);
1607
+ mutator.remove_and_drop_all_children(parent_id);
1608
+ }
1609
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 2);
1610
+
1611
+ {
1612
+ let mut mutator = document.mutate();
1613
+ let parent_id = mutator.create_element(qual_name!("div"), vec![]);
1614
+ let child_id = mutator.create_element(qual_name!("span"), vec![]);
1615
+ let detached_target_id = mutator.create_element(qual_name!("div"), vec![]);
1616
+ mutator.append_children(root_id, &[parent_id]);
1617
+ mutator.append_children(parent_id, &[child_id]);
1618
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 2);
1619
+ mutator.append_children(detached_target_id, &[child_id]);
1620
+ }
1621
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 3);
1622
+ }
1623
+
1624
+ #[test]
1625
+ fn moving_subtree_out_of_document_clears_in_document_flag() {
1626
+ let shell = Arc::new(RedrawShell::default());
1627
+ let mut document = BaseDocument::new(DocumentConfig {
1628
+ shell_provider: Some(shell.clone()),
1629
+ ..Default::default()
1630
+ });
1631
+ let root_id = document.root_node().id;
1632
+ let (child_id, grandchild_id, detached_parent_id) = {
1633
+ let mut mutator = document.mutate();
1634
+ let in_document_parent_id = mutator.create_element(qual_name!("div"), vec![]);
1635
+ let child_id = mutator.create_element(qual_name!("div"), vec![]);
1636
+ let grandchild_id = mutator.create_element(qual_name!("span"), vec![]);
1637
+ let detached_parent_id = mutator.create_element(qual_name!("section"), vec![]);
1638
+ mutator.append_children(root_id, &[in_document_parent_id]);
1639
+ mutator.append_children(in_document_parent_id, &[child_id]);
1640
+ mutator.append_children(child_id, &[grandchild_id]);
1641
+ (child_id, grandchild_id, detached_parent_id)
1642
+ };
1643
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 1);
1644
+ assert!(document.get_node(child_id).unwrap().flags.is_in_document());
1645
+ assert!(
1646
+ document
1647
+ .get_node(grandchild_id)
1648
+ .unwrap()
1649
+ .flags
1650
+ .is_in_document()
1651
+ );
1652
+
1653
+ {
1654
+ let mut mutator = document.mutate();
1655
+ mutator.append_children(detached_parent_id, &[child_id]);
1656
+ }
1657
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 2);
1658
+ assert!(!document.get_node(child_id).unwrap().flags.is_in_document());
1659
+ assert!(
1660
+ !document
1661
+ .get_node(grandchild_id)
1662
+ .unwrap()
1663
+ .flags
1664
+ .is_in_document()
1665
+ );
1666
+
1667
+ {
1668
+ let mut mutator = document.mutate();
1669
+ mutator.set_attribute(child_id, qual_name!("id"), "detached");
1670
+ }
1671
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 2);
1672
+
1673
+ {
1674
+ let mut mutator = document.mutate();
1675
+ mutator.append_children(root_id, &[child_id]);
1676
+ }
1677
+ assert_eq!(shell.redraw_requests.load(Ordering::Relaxed), 3);
1678
+ assert!(document.get_node(child_id).unwrap().flags.is_in_document());
1679
+ assert!(
1680
+ document
1681
+ .get_node(grandchild_id)
1682
+ .unwrap()
1683
+ .flags
1684
+ .is_in_document()
1685
+ );
1686
+ }
1687
+
1688
+ #[test]
1689
+ fn style_property_updates_nested_layout() {
1690
+ let mut document = BaseDocument::new(DocumentConfig {
1691
+ viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
1692
+ ..Default::default()
1693
+ });
1694
+ let root_id = document.root_node().id;
1695
+
1696
+ let mover_id = {
1697
+ let mut mutator = document.mutate();
1698
+ let parent_id = mutator.create_element(qual_name!("div"), vec![]);
1699
+ let mover_id = mutator.create_element(qual_name!("div"), vec![]);
1700
+ mutator.set_style_property(parent_id, "position", "relative");
1701
+ mutator.set_style_property(parent_id, "width", "800px");
1702
+ mutator.set_style_property(parent_id, "height", "600px");
1703
+ mutator.set_style_property(mover_id, "position", "absolute");
1704
+ mutator.set_style_property(mover_id, "left", "0px");
1705
+ mutator.set_style_property(mover_id, "top", "0px");
1706
+ mutator.append_children(parent_id, &[mover_id]);
1707
+ mutator.append_children(root_id, &[parent_id]);
1708
+ mover_id
1709
+ };
1710
+
1711
+ document.resolve(0.0);
1712
+ assert_eq!(
1713
+ document
1714
+ .get_node(mover_id)
1715
+ .unwrap()
1716
+ .final_layout()
1717
+ .location
1718
+ .x,
1719
+ 0.0
1720
+ );
1721
+
1722
+ {
1723
+ let mut mutator = document.mutate();
1724
+ mutator.set_style_property(mover_id, "left", "120px");
1725
+ }
1726
+
1727
+ document.resolve(0.0);
1728
+ assert_eq!(
1729
+ document
1730
+ .get_node(mover_id)
1731
+ .unwrap()
1732
+ .final_layout()
1733
+ .location
1734
+ .x,
1735
+ 120.0
1736
+ );
1737
+ }
1738
+
1739
+ #[test]
1740
+ fn style_property_mutation_copies_blocks_in_rule_tree() {
1741
+ let mut document = BaseDocument::new(DocumentConfig {
1742
+ viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
1743
+ ..Default::default()
1744
+ });
1745
+ let root_id = document.root_node().id;
1746
+
1747
+ let div_id = {
1748
+ let mut mutator = document.mutate();
1749
+ let div_id = mutator.create_element(qual_name!("div"), vec![]);
1750
+ mutator.set_style_property(div_id, "width", "100px");
1751
+ mutator.set_style_property(div_id, "height", "50px");
1752
+ mutator.append_children(root_id, &[div_id]);
1753
+ div_id
1754
+ };
1755
+
1756
+ let style_block = |document: &BaseDocument| {
1757
+ document
1758
+ .get_node(div_id)
1759
+ .unwrap()
1760
+ .element_data()
1761
+ .unwrap()
1762
+ .style_attribute
1763
+ .clone()
1764
+ .unwrap()
1765
+ };
1766
+
1767
+ let before_resolve = style_block(&document);
1768
+ {
1769
+ let mut mutator = document.mutate();
1770
+ mutator.set_style_property(div_id, "height", "60px");
1771
+ }
1772
+ // Not yet in the rule tree: mutated in place.
1773
+ assert!(ServoArc::ptr_eq(&before_resolve, &style_block(&document)));
1774
+
1775
+ document.resolve(0.0);
1776
+ let in_rule_tree = style_block(&document);
1777
+ assert!(
1778
+ in_rule_tree
1779
+ .read_with(&document.guard.read())
1780
+ .immutable
1781
+ .load(Ordering::Relaxed)
1782
+ );
1783
+
1784
+ {
1785
+ let mut mutator = document.mutate();
1786
+ mutator.set_style_property(div_id, "width", "200px");
1787
+ }
1788
+ let after_set = style_block(&document);
1789
+ assert!(!ServoArc::ptr_eq(&in_rule_tree, &after_set));
1790
+ {
1791
+ let guard = document.guard.read();
1792
+ let old = in_rule_tree.read_with(&guard);
1793
+ let new = after_set.read_with(&guard);
1794
+ assert_eq!(old.declarations().len(), 2);
1795
+ assert_eq!(new.declarations().len(), 2);
1796
+ assert_ne!(old, new);
1797
+ }
1798
+
1799
+ document.resolve(0.0);
1800
+ assert_eq!(
1801
+ document.get_node(div_id).unwrap().final_layout().size.width,
1802
+ 200.0
1803
+ );
1804
+
1805
+ let in_rule_tree = style_block(&document);
1806
+ {
1807
+ let mut mutator = document.mutate();
1808
+ mutator.remove_style_property(div_id, "height");
1809
+ }
1810
+ let after_remove = style_block(&document);
1811
+ assert!(!ServoArc::ptr_eq(&in_rule_tree, &after_remove));
1812
+ {
1813
+ let guard = document.guard.read();
1814
+ assert_eq!(in_rule_tree.read_with(&guard).declarations().len(), 2);
1815
+ assert_eq!(after_remove.read_with(&guard).declarations().len(), 1);
1816
+ }
1817
+ }
1818
+ }