blitz_dom/
mutator.rs

1use std::collections::HashSet;
2use std::mem;
3use std::ops::{Deref, DerefMut};
4
5use crate::document::make_device;
6use crate::layout::damage::ALL_DAMAGE;
7use crate::net::{CssHandler, ImageHandler};
8use crate::node::{CanvasData, NodeFlags, SpecialElementData};
9use crate::util::ImageType;
10use crate::{
11    Attribute, BaseDocument, ElementData, Node, NodeData, QualName, local_name, qual_name,
12};
13use blitz_traits::net::Request;
14use blitz_traits::shell::Viewport;
15use style::Atom;
16use style::invalidation::element::restyle_hints::RestyleHint;
17use style::stylesheets::OriginSet;
18
19macro_rules! tag_and_attr {
20    ($tag:tt, $attr:tt) => {
21        (&local_name!($tag), &local_name!($attr))
22    };
23}
24
25#[derive(Debug, Clone)]
26pub enum AppendTextErr {
27    /// The node is not a text node
28    NotTextNode,
29}
30
31/// Operations that happen almost immediately, but are deferred within a
32/// function for borrow-checker reasons.
33enum SpecialOp {
34    LoadImage(usize),
35    LoadStylesheet(usize),
36    UnloadStylesheet(usize),
37    LoadCustomPaintSource(usize),
38    ProcessButtonInput(usize),
39}
40
41pub struct DocumentMutator<'doc> {
42    /// Document is public as an escape hatch, but users of this API should ideally avoid using it
43    /// and prefer exposing additional functionality in DocumentMutator.
44    pub doc: &'doc mut BaseDocument,
45
46    eager_op_queue: Vec<SpecialOp>,
47
48    // Tracked nodes for deferred processing when mutations have completed
49    title_node: Option<usize>,
50    style_nodes: HashSet<usize>,
51    form_nodes: HashSet<usize>,
52
53    /// Whether an element/attribute that affect animation status has been seen
54    recompute_is_animating: bool,
55
56    /// The (latest) node which has been mounted in and had autofocus=true, if any
57    #[cfg(feature = "autofocus")]
58    node_to_autofocus: Option<usize>,
59}
60
61impl Drop for DocumentMutator<'_> {
62    fn drop(&mut self) {
63        self.flush(); // Defined at bottom of file
64    }
65}
66
67impl DocumentMutator<'_> {
68    pub fn new<'doc>(doc: &'doc mut BaseDocument) -> DocumentMutator<'doc> {
69        DocumentMutator {
70            doc,
71            eager_op_queue: Vec::new(),
72            title_node: None,
73            style_nodes: HashSet::new(),
74            form_nodes: HashSet::new(),
75            recompute_is_animating: false,
76            #[cfg(feature = "autofocus")]
77            node_to_autofocus: None,
78        }
79    }
80
81    // Query methods
82
83    pub fn node_has_parent(&self, node_id: usize) -> bool {
84        self.doc.nodes[node_id].parent.is_some()
85    }
86
87    pub fn previous_sibling_id(&self, node_id: usize) -> Option<usize> {
88        self.doc.nodes[node_id].backward(1).map(|node| node.id)
89    }
90
91    pub fn next_sibling_id(&self, node_id: usize) -> Option<usize> {
92        self.doc.nodes[node_id].forward(1).map(|node| node.id)
93    }
94
95    pub fn parent_id(&self, node_id: usize) -> Option<usize> {
96        self.doc.nodes[node_id].parent
97    }
98
99    pub fn last_child_id(&self, node_id: usize) -> Option<usize> {
100        self.doc.nodes[node_id].children.last().copied()
101    }
102
103    pub fn child_ids(&self, node_id: usize) -> Vec<usize> {
104        self.doc.nodes[node_id].children.clone()
105    }
106
107    pub fn element_name(&self, node_id: usize) -> Option<&QualName> {
108        self.doc.nodes[node_id].element_data().map(|el| &el.name)
109    }
110
111    pub fn node_at_path(&self, start_node_id: usize, path: &[u8]) -> usize {
112        let mut current = &self.doc.nodes[start_node_id];
113        for i in path {
114            let new_id = current.children[*i as usize];
115            current = &self.doc.nodes[new_id];
116        }
117        current.id
118    }
119
120    // Node creation methods
121
122    pub fn create_comment_node(&mut self) -> usize {
123        self.doc.create_node(NodeData::Comment)
124    }
125
126    pub fn create_text_node(&mut self, text: &str) -> usize {
127        self.doc.create_text_node(text)
128    }
129
130    pub fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) -> usize {
131        let mut data = ElementData::new(name, attrs);
132        data.flush_style_attribute(self.doc.guard(), &self.doc.url.url_extra_data());
133
134        let id = self.doc.create_node(NodeData::Element(data));
135        let node = self.doc.get_node(id).unwrap();
136
137        // Initialise style data
138        *node.stylo_element_data.borrow_mut() = Some(style::data::ElementData {
139            damage: ALL_DAMAGE,
140            ..Default::default()
141        });
142
143        id
144    }
145
146    pub fn deep_clone_node(&mut self, node_id: usize) -> usize {
147        self.doc.deep_clone_node(node_id)
148    }
149
150    // Node mutation methods
151
152    pub fn set_node_text(&mut self, node_id: usize, value: &str) {
153        let node = self.doc.get_node_mut(node_id).unwrap();
154
155        let text = match node.data {
156            NodeData::Text(ref mut text) => text,
157            // TODO: otherwise this is basically element.textContent which is a bit different - need to parse as html
158            _ => return,
159        };
160
161        let changed = text.content != value;
162        if changed {
163            text.content.clear();
164            text.content.push_str(value);
165            node.insert_damage(ALL_DAMAGE);
166            let parent = node.parent;
167            self.maybe_record_node(parent);
168        }
169    }
170
171    pub fn append_text_to_node(&mut self, node_id: usize, text: &str) -> Result<(), AppendTextErr> {
172        match self.doc.nodes[node_id].text_data_mut() {
173            Some(data) => {
174                data.content += text;
175                Ok(())
176            }
177            None => Err(AppendTextErr::NotTextNode),
178        }
179    }
180
181    pub fn add_attrs_if_missing(&mut self, node_id: usize, attrs: Vec<Attribute>) {
182        let node = &mut self.doc.nodes[node_id];
183        node.insert_damage(ALL_DAMAGE);
184        let element_data = node.element_data_mut().expect("Not an element");
185
186        let existing_names = element_data
187            .attrs
188            .iter()
189            .map(|e| e.name.clone())
190            .collect::<HashSet<_>>();
191
192        for attr in attrs
193            .into_iter()
194            .filter(|attr| !existing_names.contains(&attr.name))
195        {
196            self.set_attribute(node_id, attr.name, &attr.value);
197        }
198    }
199
200    pub fn set_attribute(&mut self, node_id: usize, name: QualName, value: &str) {
201        self.doc.snapshot_node(node_id);
202
203        let node = &mut self.doc.nodes[node_id];
204        if let Some(data) = &mut *node.stylo_element_data.borrow_mut() {
205            data.hint |= RestyleHint::restyle_subtree();
206            data.damage.insert(ALL_DAMAGE);
207        }
208
209        // TODO: make this fine grained / conditional based on ElementSelectorFlags
210        let parent = node.parent;
211        if let Some(parent_id) = parent {
212            let parent = &mut self.doc.nodes[parent_id];
213            if let Some(data) = &mut *parent.stylo_element_data.borrow_mut() {
214                data.hint |= RestyleHint::restyle_subtree();
215            }
216        }
217
218        let node = &mut self.doc.nodes[node_id];
219
220        let NodeData::Element(ref mut element) = node.data else {
221            return;
222        };
223
224        element.attrs.set(name.clone(), value);
225
226        let tag = &element.name.local;
227        let attr = &name.local;
228
229        if *attr == local_name!("id") {
230            element.id = Some(Atom::from(value))
231        }
232
233        if *attr == local_name!("value") {
234            if let Some(input_data) = element.text_input_data_mut() {
235                // Update text input value
236                input_data.set_text(
237                    &mut self.doc.font_ctx.lock().unwrap(),
238                    &mut self.doc.layout_ctx,
239                    value,
240                );
241            }
242            return;
243        }
244
245        if *attr == local_name!("style") {
246            element.flush_style_attribute(&self.doc.guard, &self.doc.url.url_extra_data());
247            return;
248        }
249
250        // If node if not in the document, then don't apply any special behaviours
251        // and simply set the attribute value
252        if !node.flags.is_in_document() {
253            return;
254        }
255
256        if (tag, attr) == tag_and_attr!("input", "checked") {
257            set_input_checked_state(element, value.to_string());
258        } else if (tag, attr) == tag_and_attr!("img", "src") {
259            self.load_image(node_id);
260        } else if (tag, attr) == tag_and_attr!("canvas", "src") {
261            self.load_custom_paint_src(node_id);
262        }
263    }
264
265    pub fn clear_attribute(&mut self, node_id: usize, name: QualName) {
266        self.doc.snapshot_node(node_id);
267
268        let node = &mut self.doc.nodes[node_id];
269
270        let mut stylo_element_data = node.stylo_element_data.borrow_mut();
271        if let Some(data) = &mut *stylo_element_data {
272            data.hint |= RestyleHint::restyle_subtree();
273            data.damage.insert(ALL_DAMAGE);
274        }
275        drop(stylo_element_data);
276
277        let Some(element) = node.element_data_mut() else {
278            return;
279        };
280
281        let removed_attr = element.attrs.remove(&name);
282        let had_attr = removed_attr.is_some();
283        if !had_attr {
284            return;
285        }
286
287        if name.local == local_name!("id") {
288            element.id = None;
289        }
290
291        // Update text input value
292        if name.local == local_name!("value") {
293            if let Some(input_data) = element.text_input_data_mut() {
294                input_data.set_text(
295                    &mut self.doc.font_ctx.lock().unwrap(),
296                    &mut self.doc.layout_ctx,
297                    "",
298                );
299            }
300        }
301
302        let tag = &element.name.local;
303        let attr = &name.local;
304        if *attr == local_name!("style") {
305            element.flush_style_attribute(&self.doc.guard, &self.doc.url.url_extra_data());
306        } else if (tag, attr) == tag_and_attr!("canvas", "src") {
307            self.recompute_is_animating = true;
308        } else if (tag, attr) == tag_and_attr!("link", "href") {
309            self.unload_stylesheet(node_id);
310        }
311    }
312
313    pub fn set_style_property(&mut self, node_id: usize, name: &str, value: &str) {
314        self.doc.set_style_property(node_id, name, value)
315    }
316
317    pub fn remove_style_property(&mut self, node_id: usize, name: &str) {
318        self.doc.remove_style_property(node_id, name)
319    }
320
321    /// Remove the node from it's parent but don't drop it
322    pub fn remove_node(&mut self, node_id: usize) {
323        let node = &mut self.doc.nodes[node_id];
324
325        // Update child_idx values
326        if let Some(parent_id) = node.parent.take() {
327            let parent = &mut self.doc.nodes[parent_id];
328            parent.insert_damage(ALL_DAMAGE);
329            parent.children.retain(|id| *id != node_id);
330            self.maybe_record_node(parent_id);
331        }
332
333        self.process_removed_subtree(node_id);
334    }
335
336    fn remove_node_ignoring_parent(&mut self, node_id: usize) -> Option<Node> {
337        let mut node = self.doc.nodes.try_remove(node_id);
338        if let Some(node) = &mut node {
339            for &child in &node.children {
340                self.remove_node_ignoring_parent(child);
341            }
342        }
343        node
344    }
345
346    pub fn remove_and_drop_node(&mut self, node_id: usize) -> Option<Node> {
347        self.process_removed_subtree(node_id);
348
349        let node = self.remove_node_ignoring_parent(node_id);
350
351        // Update child_idx values
352        if let Some(parent_id) = node.as_ref().and_then(|node| node.parent) {
353            let parent = &mut self.doc.nodes[parent_id];
354            parent.insert_damage(ALL_DAMAGE);
355            let parent_is_in_doc = parent.flags.is_in_document();
356
357            // TODO: make this fine grained / conditional based on ElementSelectorFlags
358            if parent_is_in_doc {
359                if let Some(data) = &mut *parent.stylo_element_data.borrow_mut() {
360                    data.hint |= RestyleHint::restyle_subtree();
361                }
362            }
363
364            parent.children.retain(|id| *id != node_id);
365            self.maybe_record_node(parent_id);
366        }
367
368        node
369    }
370
371    pub fn remove_and_drop_all_children(&mut self, node_id: usize) {
372        let parent = &mut self.doc.nodes[node_id];
373        let parent_is_in_doc = parent.flags.is_in_document();
374
375        // TODO: make this fine grained / conditional based on ElementSelectorFlags
376        if parent_is_in_doc {
377            if let Some(data) = &mut *parent.stylo_element_data.borrow_mut() {
378                data.hint |= RestyleHint::restyle_subtree();
379            }
380        }
381
382        let children = mem::take(&mut parent.children);
383        for child_id in children {
384            self.process_removed_subtree(child_id);
385            let _ = self.remove_node_ignoring_parent(child_id);
386        }
387        self.maybe_record_node(node_id);
388    }
389
390    // Tree mutation methods
391    pub fn remove_node_if_unparented(&mut self, node_id: usize) {
392        if let Some(node) = self.doc.get_node(node_id) {
393            if node.parent.is_none() {
394                self.remove_and_drop_node(node_id);
395            }
396        }
397    }
398
399    /// Remove all of the children from old_parent_id and append them to new_parent_id
400    pub fn append_children(&mut self, parent_id: usize, child_ids: &[usize]) {
401        self.add_children_to_parent(parent_id, child_ids, &|parent, child_ids| {
402            parent.children.extend_from_slice(child_ids);
403        });
404    }
405
406    pub fn insert_nodes_before(&mut self, anchor_node_id: usize, new_node_ids: &[usize]) {
407        let parent_id = self.doc.nodes[anchor_node_id].parent.unwrap();
408        self.add_children_to_parent(parent_id, new_node_ids, &|parent, child_ids| {
409            let node_child_idx = parent.index_of_child(anchor_node_id).unwrap();
410            parent
411                .children
412                .splice(node_child_idx..node_child_idx, child_ids.iter().copied());
413        });
414    }
415
416    fn add_children_to_parent(
417        &mut self,
418        parent_id: usize,
419        child_ids: &[usize],
420        insert_children_fn: &dyn Fn(&mut Node, &[usize]),
421    ) {
422        let new_parent = &mut self.doc.nodes[parent_id];
423        new_parent.insert_damage(ALL_DAMAGE);
424        let new_parent_is_in_doc = new_parent.flags.is_in_document();
425
426        // TODO: make this fine grained / conditional based on ElementSelectorFlags
427        if new_parent_is_in_doc {
428            if let Some(data) = &mut *new_parent.stylo_element_data.borrow_mut() {
429                data.hint |= RestyleHint::restyle_subtree();
430            }
431        }
432
433        insert_children_fn(new_parent, child_ids);
434
435        for child_id in child_ids.iter().copied() {
436            let child = &mut self.doc.nodes[child_id];
437            let old_parent_id = child.parent.replace(parent_id);
438
439            let child_was_in_doc = child.flags.is_in_document();
440            if new_parent_is_in_doc != child_was_in_doc {
441                self.process_added_subtree(child_id);
442            }
443
444            if let Some(old_parent_id) = old_parent_id {
445                let old_parent = &mut self.doc.nodes[old_parent_id];
446                old_parent.insert_damage(ALL_DAMAGE);
447
448                // TODO: make this fine grained / conditional based on ElementSelectorFlags
449                if child_was_in_doc {
450                    if let Some(data) = &mut *old_parent.stylo_element_data.borrow_mut() {
451                        data.hint |= RestyleHint::restyle_subtree();
452                    }
453                }
454
455                old_parent.children.retain(|id| *id != child_id);
456                self.maybe_record_node(old_parent_id);
457            }
458        }
459
460        self.maybe_record_node(parent_id);
461    }
462
463    // Tree mutation methods (that defer to other methods)
464    pub fn insert_nodes_after(&mut self, anchor_node_id: usize, new_node_ids: &[usize]) {
465        match self.next_sibling_id(anchor_node_id) {
466            Some(id) => self.insert_nodes_before(id, new_node_ids),
467            None => {
468                let parent_id = self.parent_id(anchor_node_id).unwrap();
469                self.append_children(parent_id, new_node_ids)
470            }
471        }
472    }
473
474    pub fn reparent_children(&mut self, old_parent_id: usize, new_parent_id: usize) {
475        let child_ids = std::mem::take(&mut self.doc.nodes[old_parent_id].children);
476        self.maybe_record_node(old_parent_id);
477        self.append_children(new_parent_id, &child_ids);
478    }
479
480    pub fn replace_node_with(&mut self, anchor_node_id: usize, new_node_ids: &[usize]) {
481        self.insert_nodes_before(anchor_node_id, new_node_ids);
482        self.remove_node(anchor_node_id);
483    }
484}
485
486impl<'doc> DocumentMutator<'doc> {
487    pub fn flush(&mut self) {
488        if self.recompute_is_animating {
489            self.doc.has_canvas = self.doc.compute_has_canvas();
490        }
491
492        if let Some(id) = self.title_node {
493            let title = self.doc.nodes[id].text_content();
494            self.doc.shell_provider.set_window_title(title);
495        }
496
497        // Add/Update inline stylesheets (<style> elements)
498        for id in self.style_nodes.drain() {
499            self.doc.process_style_element(id);
500        }
501
502        for id in self.form_nodes.drain() {
503            self.doc.reset_form_owner(id);
504        }
505
506        #[cfg(feature = "autofocus")]
507        if let Some(node_id) = self.node_to_autofocus.take() {
508            if self.doc.get_node(node_id).is_some() {
509                self.doc.set_focus_to(node_id);
510            }
511        }
512    }
513
514    pub fn set_inner_html(&mut self, node_id: usize, html: &str) {
515        self.remove_and_drop_all_children(node_id);
516        self.doc
517            .html_parser_provider
518            .clone()
519            .parse_inner_html(self, node_id, html);
520    }
521
522    fn flush_eager_ops(&mut self) {
523        let mut ops = mem::take(&mut self.eager_op_queue);
524        for op in ops.drain(0..) {
525            match op {
526                SpecialOp::LoadImage(node_id) => self.load_image(node_id),
527                SpecialOp::LoadStylesheet(node_id) => self.load_linked_stylesheet(node_id),
528                SpecialOp::UnloadStylesheet(node_id) => self.unload_stylesheet(node_id),
529                SpecialOp::LoadCustomPaintSource(node_id) => self.load_custom_paint_src(node_id),
530                SpecialOp::ProcessButtonInput(node_id) => self.process_button_input(node_id),
531            }
532        }
533
534        // Queue is empty, but put Vec back anyway so allocation can be reused.
535        self.eager_op_queue = ops;
536    }
537
538    fn process_added_subtree(&mut self, node_id: usize) {
539        self.doc.iter_subtree_mut(node_id, |node_id, doc| {
540            let node = &mut doc.nodes[node_id];
541            node.flags.set(NodeFlags::IS_IN_DOCUMENT, true);
542            node.insert_damage(ALL_DAMAGE);
543
544            // If the node has an "id" attribute, store it in the ID map.
545            if let Some(id_attr) = node.attr(local_name!("id")) {
546                doc.nodes_to_id.insert(id_attr.to_string(), node_id);
547            }
548
549            let NodeData::Element(ref mut element) = node.data else {
550                return;
551            };
552
553            // Custom post-processing by element tag name
554            let tag = element.name.local.as_ref();
555            match tag {
556                "title" => self.title_node = Some(node_id),
557                "link" => self.eager_op_queue.push(SpecialOp::LoadStylesheet(node_id)),
558                "img" => self.eager_op_queue.push(SpecialOp::LoadImage(node_id)),
559                "canvas" => self
560                    .eager_op_queue
561                    .push(SpecialOp::LoadCustomPaintSource(node_id)),
562                "style" => {
563                    self.style_nodes.insert(node_id);
564                }
565                "button" | "fieldset" | "input" | "select" | "textarea" | "object" | "output" => {
566                    self.eager_op_queue
567                        .push(SpecialOp::ProcessButtonInput(node_id));
568                    self.form_nodes.insert(node_id);
569                }
570                _ => {}
571            }
572
573            #[cfg(feature = "autofocus")]
574            if node.is_focussable() {
575                if let NodeData::Element(ref element) = node.data {
576                    if let Some(value) = element.attr(local_name!("autofocus")) {
577                        if value == "true" {
578                            self.node_to_autofocus = Some(node_id);
579                        }
580                    }
581                }
582            }
583        });
584
585        self.flush_eager_ops();
586    }
587
588    fn process_removed_subtree(&mut self, node_id: usize) {
589        self.doc.iter_subtree_mut(node_id, |node_id, doc| {
590            let node = &mut doc.nodes[node_id];
591            node.flags.set(NodeFlags::IS_IN_DOCUMENT, false);
592
593            // If the node has an "id" attribute remove it from the ID map.
594            if let Some(id_attr) = node.attr(local_name!("id")) {
595                doc.nodes_to_id.remove(id_attr);
596            }
597
598            let NodeData::Element(ref mut element) = node.data else {
599                return;
600            };
601
602            match &element.special_data {
603                SpecialElementData::Stylesheet(_) => self
604                    .eager_op_queue
605                    .push(SpecialOp::UnloadStylesheet(node_id)),
606                SpecialElementData::Image(_) => {}
607                SpecialElementData::Canvas(_) => {
608                    self.recompute_is_animating = true;
609                }
610                SpecialElementData::TableRoot(_) => {}
611                SpecialElementData::TextInput(_) => {}
612                SpecialElementData::CheckboxInput(_) => {}
613                #[cfg(feature = "file_input")]
614                SpecialElementData::FileInput(_) => {}
615                SpecialElementData::None => {}
616            }
617        });
618
619        self.flush_eager_ops();
620    }
621
622    fn maybe_record_node(&mut self, node_id: impl Into<Option<usize>>) {
623        let Some(node_id) = node_id.into() else {
624            return;
625        };
626
627        let Some(tag_name) = self.doc.nodes[node_id]
628            .data
629            .downcast_element()
630            .map(|elem| &elem.name.local)
631        else {
632            return;
633        };
634
635        match tag_name.as_ref() {
636            "title" => self.title_node = Some(node_id),
637            "style" => {
638                self.style_nodes.insert(node_id);
639            }
640            _ => {}
641        }
642    }
643
644    fn load_linked_stylesheet(&mut self, target_id: usize) {
645        let node = &self.doc.nodes[target_id];
646
647        let rel_attr = node.attr(local_name!("rel"));
648        let href_attr = node.attr(local_name!("href"));
649
650        let (Some(rels), Some(href)) = (rel_attr, href_attr) else {
651            return;
652        };
653        if !rels.split_ascii_whitespace().any(|rel| rel == "stylesheet") {
654            return;
655        }
656
657        let url = self.doc.resolve_url(href);
658        self.doc.net_provider.fetch(
659            self.doc.id(),
660            Request::get(url.clone()),
661            Box::new(CssHandler {
662                node: target_id,
663                source_url: url,
664                guard: self.doc.guard.clone(),
665                provider: self.doc.net_provider.clone(),
666            }),
667        );
668    }
669
670    fn unload_stylesheet(&mut self, node_id: usize) {
671        let node = &mut self.doc.nodes[node_id];
672        let Some(element) = node.element_data_mut() else {
673            unreachable!();
674        };
675        let SpecialElementData::Stylesheet(stylesheet) = element.special_data.take() else {
676            unreachable!();
677        };
678
679        let guard = self.doc.guard.read();
680        self.doc.stylist.remove_stylesheet(stylesheet, &guard);
681        self.doc
682            .stylist
683            .force_stylesheet_origins_dirty(OriginSet::all());
684
685        self.doc.nodes_to_stylesheet.remove(&node_id);
686    }
687
688    fn load_image(&mut self, target_id: usize) {
689        let node = &self.doc.nodes[target_id];
690        if let Some(raw_src) = node.attr(local_name!("src")) {
691            if !raw_src.is_empty() {
692                let src = self.doc.resolve_url(raw_src);
693                self.doc.net_provider.fetch(
694                    self.doc.id(),
695                    Request::get(src),
696                    Box::new(ImageHandler::new(target_id, ImageType::Image)),
697                );
698            }
699        }
700    }
701
702    fn load_custom_paint_src(&mut self, target_id: usize) {
703        let node = &mut self.doc.nodes[target_id];
704        if let Some(raw_src) = node.attr(local_name!("src")) {
705            if let Ok(custom_paint_source_id) = raw_src.parse::<u64>() {
706                self.recompute_is_animating = true;
707                let canvas_data = SpecialElementData::Canvas(CanvasData {
708                    custom_paint_source_id,
709                });
710                node.element_data_mut().unwrap().special_data = canvas_data;
711            }
712        }
713    }
714
715    fn process_button_input(&mut self, target_id: usize) {
716        let node = &self.doc.nodes[target_id];
717        let Some(data) = node.element_data() else {
718            return;
719        };
720
721        let tagname = data.name.local.as_ref();
722        let type_attr = data.attr(local_name!("type"));
723        let value = data.attr(local_name!("value"));
724
725        // Add content of "value" attribute as a text node child if:
726        //   - Tag name is
727        if let ("input", Some("button" | "submit" | "reset"), Some(value)) =
728            (tagname, type_attr, value)
729        {
730            let value = value.to_string();
731            let id = self.create_text_node(&value);
732            self.append_children(target_id, &[id]);
733            return;
734        }
735        #[cfg(feature = "file_input")]
736        if let ("input", Some("file")) = (tagname, type_attr) {
737            let button_id = self.create_element(
738                qual_name!("button", html),
739                vec![
740                    Attribute {
741                        name: qual_name!("type", html),
742                        value: "button".to_string(),
743                    },
744                    Attribute {
745                        name: qual_name!("tabindex", html),
746                        value: "-1".to_string(),
747                    },
748                ],
749            );
750            let label_id = self.create_element(qual_name!("label", html), vec![]);
751            let text_id = self.create_text_node("No File Selected");
752            let button_text_id = self.create_text_node("Browse");
753            self.append_children(target_id, &[button_id, label_id]);
754            self.append_children(label_id, &[text_id]);
755            self.append_children(button_id, &[button_text_id]);
756        }
757    }
758}
759
760/// Set 'checked' state on an input based on given attributevalue
761fn set_input_checked_state(element: &mut ElementData, value: String) {
762    let Ok(checked) = value.parse() else {
763        return;
764    };
765    match element.special_data {
766        SpecialElementData::CheckboxInput(ref mut checked_mut) => *checked_mut = checked,
767        // If we have just constructed the element, set the node attribute,
768        // and NodeSpecificData will be created from that later
769        // this simulates the checked attribute being set in html,
770        // and the element's checked property being set from that
771        SpecialElementData::None => element.attrs.push(Attribute {
772            name: qual_name!("checked", html),
773            value: checked.to_string(),
774        }),
775        _ => {}
776    }
777}
778
779/// Type that allows mutable access to the viewport
780/// And syncs it back to stylist on drop.
781pub struct ViewportMut<'doc> {
782    doc: &'doc mut BaseDocument,
783    initial_scale: f64,
784}
785impl ViewportMut<'_> {
786    pub fn new(doc: &mut BaseDocument) -> ViewportMut<'_> {
787        let initial_scale = doc.viewport.scale_f64();
788        ViewportMut { doc, initial_scale }
789    }
790}
791impl Deref for ViewportMut<'_> {
792    type Target = Viewport;
793
794    fn deref(&self) -> &Self::Target {
795        &self.doc.viewport
796    }
797}
798impl DerefMut for ViewportMut<'_> {
799    fn deref_mut(&mut self) -> &mut Self::Target {
800        &mut self.doc.viewport
801    }
802}
803impl Drop for ViewportMut<'_> {
804    fn drop(&mut self) {
805        self.doc
806            .set_stylist_device(make_device(&self.doc.viewport, self.doc.font_ctx.clone()));
807        self.doc.scroll_viewport_by(0.0, 0.0); // Clamp scroll offset
808
809        let scale_has_changed = self.doc.viewport().scale_f64() != self.initial_scale;
810        if scale_has_changed {
811            self.doc.invalidate_inline_contexts();
812        }
813    }
814}