Skip to main content

parsec/
edit.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Changing a parsed document: new nodes, moves, removals and attributes.
5//! A removed node stays in the document's arena, detached, and can be
6//! inserted again.
7//!
8//! A shadow root is edited as a template's contents are: nodes go in and
9//! out of it like any parent, but it's never anyone's child
10//! ([`EditError::NotInsertable`]), and a host can't go into its own shadow
11//! tree ([`EditError::Cycle`]). A host keeps its shadow root when it's
12//! removed, moved or renamed, as an element keeps it in the DOM; a root
13//! is made with [`Document::attach_shadow`] and never taken away.
14
15use crate::dom::{Attr, AttrNs, Data, Document, Element, NONE, Name, NodeId, Ns, Span};
16use crate::tags::Tag;
17
18/// Why an edit was refused.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum EditError {
21    /// The node would end up inside itself.
22    Cycle,
23    /// The parent can't have children: text, a comment, a doctype or a
24    /// processing instruction.
25    NotAParent,
26    /// `before` isn't a child of the parent.
27    NotAChild,
28    /// The node is a document, a fragment or a shadow root, such as the
29    /// root or a template's contents, which is never anyone's child.
30    NotInsertable,
31    /// A node was taken out with [`Document::remove`], so it can't be used
32    /// again. [`Document::detach`] takes one out to move it.
33    Removed,
34    /// The element can't have a shadow root: it already has one, or it
35    /// isn't an HTML element that may (`div`, `span`, `section`, a
36    /// custom element...).
37    NotAShadowHost,
38}
39
40impl std::fmt::Display for EditError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.write_str(match self {
43            EditError::Cycle => "a node can't be inserted into itself or its descendants",
44            EditError::NotAParent => "only an element, a document or a fragment can have children",
45            EditError::NotAChild => "the node to insert before isn't a child of the parent",
46            EditError::NotInsertable => {
47                "a document, fragment or shadow root can't be inserted, only its children"
48            }
49            EditError::Removed => {
50                "the node was removed from its document, so it can't be used again"
51            }
52            EditError::NotAShadowHost => "the element can't have a shadow root, or has one",
53        })
54    }
55}
56
57impl std::error::Error for EditError {}
58
59impl Document {
60    /// A new element, not yet in the tree. HTML names are lowercased, as
61    /// `createElement` does.
62    pub fn create_element(&mut self, ns: Ns, name: &str) -> NodeId {
63        let (tag, name) = self.name_element(ns, name);
64        let at = self.attrs.len() as u32;
65        let contents = if ns == Ns::Html && tag == Tag::Template {
66            self.add(Data::Fragment)
67        } else {
68            NONE
69        };
70        let id = self.add(Data::Element(Element {
71            ns,
72            tag,
73            name,
74            attrs: Span { start: at, end: at },
75            contents,
76            html_integration: false,
77        }));
78        if contents != NONE
79            && let Some(hosts) = &mut self.hosts
80        {
81            hosts.insert(contents, id);
82        }
83        id
84    }
85
86    pub fn create_text(&mut self, text: &str) -> NodeId {
87        let span = self.push_stable(text);
88        self.add(Data::Text(span))
89    }
90
91    pub fn create_cdata(&mut self, text: &str) -> NodeId {
92        let span = self.push_stable(text);
93        self.add(Data::Cdata(span))
94    }
95
96    pub fn create_comment(&mut self, text: &str) -> NodeId {
97        let span = self.push_stable(text);
98        self.add(Data::Comment(span))
99    }
100
101    pub fn create_processing_instruction(&mut self, target: &str, data: &str) -> NodeId {
102        let target = self.push_stable(target);
103        let data = self.push_stable(data);
104        self.add(Data::ProcessingInstruction { target, data })
105    }
106
107    pub fn create_doctype(&mut self, name: &str, public_id: &str, system_id: &str) -> NodeId {
108        let name = self.push_stable(name);
109        let public_id = self.push_stable(public_id);
110        let system_id = self.push_stable(system_id);
111        self.add(Data::Doctype {
112            name,
113            public_id,
114            system_id,
115        })
116    }
117
118    /// Moves `child` to be the last child of `parent`.
119    pub fn append(&mut self, parent: NodeId, child: NodeId) -> Result<(), EditError> {
120        self.insert_before(parent, child, None)
121    }
122
123    /// Moves `child` into `parent`, before `before`, or last for `None`.
124    pub fn insert_before(
125        &mut self,
126        parent: NodeId,
127        child: NodeId,
128        before: Option<NodeId>,
129    ) -> Result<(), EditError> {
130        if self.is_removed(parent)
131            || self.is_removed(child)
132            || before.is_some_and(|b| self.is_removed(b))
133        {
134            return Err(EditError::Removed);
135        }
136        if !matches!(
137            self.nodes[parent as usize].data,
138            Data::Element(_) | Data::Document | Data::Fragment | Data::ShadowRoot { .. }
139        ) {
140            return Err(EditError::NotAParent);
141        }
142        // As the DOM's pre-insertion check: the root, or a template's
143        // contents, would otherwise end up under a detached element.
144        if matches!(
145            self.nodes[child as usize].data,
146            Data::Document | Data::Fragment | Data::ShadowRoot { .. }
147        ) {
148            return Err(EditError::NotInsertable);
149        }
150        if let Some(b) = before
151            && self.parent(b) != Some(parent)
152        {
153            return Err(EditError::NotAChild);
154        }
155        // Up through the parents, and out of a template's contents to the
156        // template and out of a shadow root to its host: serializing goes
157        // down into both, so a template put in its own contents, or a host
158        // in its own shadow tree, would never end.
159        let mut at = Some(parent);
160        while let Some(a) = at {
161            if a == child {
162                return Err(EditError::Cycle);
163            }
164            at = self.parent(a).or_else(|| self.host(a));
165        }
166        if before == Some(child) {
167            return Ok(());
168        }
169        self.detach(child);
170        self.insert(parent, child, before.unwrap_or(NONE));
171        Ok(())
172    }
173
174    /// The template whose contents `fragment` is, if it's any's. The map
175    /// is built once, then kept as edits add and rename templates, so a
176    /// run of inserts into contents stays linear.
177    fn host(&mut self, fragment: NodeId) -> Option<NodeId> {
178        if let Data::ShadowRoot { host, .. } = self.nodes[fragment as usize].data {
179            return Some(host);
180        }
181        if !matches!(self.nodes[fragment as usize].data, Data::Fragment) {
182            return None;
183        }
184        let nodes = &self.nodes;
185        self.hosts
186            .get_or_insert_with(|| {
187                (0..nodes.len() as NodeId)
188                    .filter_map(|id| match nodes[id as usize].data {
189                        Data::Element(e) if e.contents != NONE => Some((e.contents, id)),
190                        _ => None,
191                    })
192                    .collect()
193            })
194            .get(&fragment)
195            .copied()
196            .inspect(|&t| {
197                debug_assert!(
198                    self.element(t).is_some_and(|e| e.contents == fragment),
199                    "the hosts map says {t} holds {fragment}, which it doesn't"
200                )
201            })
202    }
203
204    /// Moves every template's contents in under the template element
205    /// itself, as lxml and Beautiful Soup show them and scrapers expect:
206    /// selectors and walks then see them. The contents are left empty.
207    pub fn adopt_template_contents(&mut self) {
208        for id in 0..self.nodes.len() as NodeId {
209            let Data::Element(e) = self.nodes[id as usize].data else {
210                continue;
211            };
212            if e.ns != Ns::Html || e.tag != Tag::Template || e.contents == NONE {
213                continue;
214            }
215            if self.is_removed(id) {
216                continue;
217            }
218            while let Some(child) = self.first_child(e.contents) {
219                self.detach(child);
220                self.insert(id, child, NONE);
221            }
222        }
223    }
224
225    /// Takes `id`, and everything in it, out of the document for good. From
226    /// then on each of their ids reads as nothing (see
227    /// [`Document::is_removed`]), editing one does nothing, and inserting
228    /// one, or anything into one, is [`EditError::Removed`]. A template's
229    /// contents go with it, and so does a shadow host's shadow tree. To move
230    /// a node, take it out with [`Document::detach`] and insert it again.
231    /// The root, a template's contents or a shadow root on its own can't be
232    /// removed: they're never anyone's child.
233    pub fn remove(&mut self, id: NodeId) {
234        if matches!(
235            self.nodes[id as usize].data,
236            Data::Document | Data::Fragment | Data::ShadowRoot { .. }
237        ) || self.is_removed(id)
238        {
239            return;
240        }
241        self.detach(id);
242        // By the links themselves: the readers say nothing of a node once
243        // it's marked.
244        let mut stack = vec![id];
245        while let Some(n) = stack.pop() {
246            self.mark_removed(n);
247            let node = &self.nodes[n as usize];
248            if let Data::Element(e) = &node.data
249                && e.contents != NONE
250            {
251                stack.push(e.contents);
252            }
253            // A shadow host's shadow tree goes with it, by the map: the
254            // reader says nothing once the host is marked.
255            if let Some(&shadow) = self.shadow_roots.get(&n) {
256                stack.push(shadow);
257            }
258            let mut c = node.first_child;
259            while c != NONE {
260                stack.push(c);
261                c = self.nodes[c as usize].next;
262            }
263        }
264    }
265
266    /// Sets an attribute, replacing the first one of the same qualified name
267    /// in any namespace (`xlink:href`), as `setAttribute` does. HTML
268    /// elements' attribute names are lowercased; SVG's and MathML's keep the
269    /// case they're given.
270    /// A node taken out with [`Document::remove`] is left alone.
271    pub fn set_attr(&mut self, id: NodeId, name: &str, value: &str) {
272        if self.is_removed(id) {
273            return;
274        }
275        let Some(e) = self.element(id) else { return };
276        let ns = e.ns;
277        let given = name;
278        let name = stored_attr_name(ns, given);
279        let value = self.push_stable(value);
280        let name_span = self.push_stable(&name);
281        self.rewrite_attrs(id, |doc, attrs| {
282            // By qualified name in any namespace, as setAttribute does, so
283            // xlink:href finds a parsed xlink:href and keeps its namespace;
284            // on a foreign element by the name as written too, so viewBox
285            // finds a parsed viewBox and no two are ever written alike.
286            match attrs.iter_mut().find(|a| doc.is_attr(ns, a, &name, given)) {
287                Some(a) => a.value = value,
288                None => attrs.push(Attr {
289                    ns: AttrNs::None,
290                    name: name_span,
291                    value,
292                }),
293            }
294            true
295        });
296    }
297
298    /// Adds an attribute as given, after the others, without replacing one
299    /// of the same name: for building XML, where the caller has already
300    /// checked names.
301    /// A node taken out with [`Document::remove`] is left alone.
302    pub fn add_attr(&mut self, id: NodeId, ns: AttrNs, name: &str, value: &str) {
303        if self.is_removed(id) {
304            return;
305        }
306        let name = self.push_stable(name);
307        let value = self.push_stable(value);
308        let attr = Attr { ns, name, value };
309        let len = self.attrs.len() as u32;
310        // An element whose attributes are the last in the list, as while
311        // it's being built, grows in place: a clone sharing the range keeps
312        // its own end, so it's unchanged. Anything else goes through a copy.
313        if let Data::Element(e) = &mut self.nodes[id as usize].data
314            && e.attrs.end == len
315        {
316            e.attrs.end += 1;
317            self.attrs.push(attr);
318            return;
319        }
320        self.rewrite_attrs(id, |_, attrs| {
321            attrs.push(attr);
322            true
323        });
324    }
325
326    /// Replaces all of the element's attributes at once.
327    /// A node taken out with [`Document::remove`] is left alone.
328    pub fn set_attrs(&mut self, id: NodeId, attrs: &[(AttrNs, &str, &str)]) {
329        if self.is_removed(id) {
330            return;
331        }
332        if self.element(id).is_none() {
333            return;
334        }
335        let start = self.attrs.len() as u32;
336        for &(ns, name, value) in attrs {
337            let name = self.push_stable(name);
338            let value = self.push_stable(value);
339            self.attrs.push(Attr { ns, name, value });
340        }
341        let end = self.attrs.len() as u32;
342        if let Data::Element(e) = &mut self.nodes[id as usize].data {
343            e.attrs = Span { start, end };
344        }
345    }
346
347    /// Renames the element: lowercased for HTML, as given for the rest.
348    /// An element renamed to `template` gets empty contents, as a new one
349    /// does. A template renamed to anything else gives its contents up as
350    /// ordinary children, ahead of any it has, so its markup stays the same
351    /// and nothing in them is lost.
352    /// A node taken out with [`Document::remove`] is left alone.
353    pub fn rename(&mut self, id: NodeId, name: &str) {
354        if self.is_removed(id) {
355            return;
356        }
357        let Some(e) = self.element(id).copied() else {
358            return;
359        };
360        let (tag, new) = self.name_element(e.ns, name);
361        let template = e.ns == Ns::Html && tag == Tag::Template;
362        let contents = if template && e.contents == NONE {
363            let contents = self.add(Data::Fragment);
364            if let Some(hosts) = &mut self.hosts {
365                hosts.insert(contents, id);
366            }
367            contents
368        } else if !template && e.contents != NONE {
369            let first = self.first_child(id).unwrap_or(NONE);
370            while let Some(child) = self.first_child(e.contents) {
371                self.detach(child);
372                self.insert(id, child, first);
373            }
374            if let Some(hosts) = &mut self.hosts {
375                hosts.remove(&e.contents);
376            }
377            NONE
378        } else {
379            e.contents
380        };
381        if let Data::Element(e) = &mut self.nodes[id as usize].data {
382            e.tag = tag;
383            e.name = new;
384            e.contents = contents;
385        }
386    }
387
388    /// The tag and stored name of an element called `name` in `ns`. HTML
389    /// names are lowercased; foreign ones keep their case.
390    fn name_element(&mut self, ns: Ns, name: &str) -> (Tag, Name) {
391        let lower = name.to_ascii_lowercase();
392        match ns {
393            Ns::Html => {
394                let tag = Tag::from_name(&lower);
395                let name = if tag == Tag::Other {
396                    Name::Span(self.push_stable(&lower))
397                } else {
398                    Name::Tag
399                };
400                (tag, name)
401            }
402            // An XML element is never an HTML one, whatever its name.
403            Ns::Xml => (Tag::Other, Name::Span(self.push_stable(name))),
404            _ => {
405                let tag = Tag::from_name(&lower);
406                // SVG's mixed-case names, written as the spec writes them, are
407                // stored as the parser stores them, so lower_name and the
408                // markup agree with a parsed element's.
409                if ns == Ns::Svg
410                    && let Some(i) = crate::tree::svg_tag_name(&lower)
411                    && crate::tree::SVG_TAG_NAMES[i as usize].1 == name
412                {
413                    return (tag, Name::Svg(i));
414                }
415                let name = if tag != Tag::Other && tag.name() == name {
416                    Name::Tag
417                } else {
418                    Name::Span(self.push_stable(name))
419                };
420                (tag, name)
421            }
422        }
423    }
424
425    /// Renames the element's `index`th attribute, and sets its namespace.
426    /// A node taken out with [`Document::remove`] is left alone.
427    pub fn rename_attr(&mut self, id: NodeId, index: usize, ns: AttrNs, name: &str) {
428        if self.is_removed(id) {
429            return;
430        }
431        let name = self.push_stable(name);
432        self.rewrite_attrs(id, |_, attrs| match attrs.get_mut(index) {
433            Some(a) => {
434                a.ns = ns;
435                a.name = name;
436                true
437            }
438            None => false,
439        });
440    }
441
442    /// Removes the element's `index`th attribute; false if there's none.
443    /// A node taken out with [`Document::remove`] is left alone, and gives
444    /// false.
445    pub fn remove_attr_at(&mut self, id: NodeId, index: usize) -> bool {
446        if self.is_removed(id) {
447            return false;
448        }
449        self.rewrite_attrs(id, |_, attrs| {
450            if index < attrs.len() {
451                attrs.remove(index);
452                true
453            } else {
454                false
455            }
456        })
457    }
458
459    /// Removes an attribute by name; false if there wasn't one.
460    /// A node taken out with [`Document::remove`] is left alone, and gives
461    /// false.
462    pub fn remove_attr(&mut self, id: NodeId, name: &str) -> bool {
463        if self.is_removed(id) {
464            return false;
465        }
466        let Some(e) = self.element(id) else {
467            return false;
468        };
469        let (ns, given) = (e.ns, name);
470        let name = stored_attr_name(ns, given);
471        self.rewrite_attrs(id, |doc, attrs| {
472            let before = attrs.len();
473            attrs.retain(|a| !doc.is_attr(ns, a, &name, given));
474            attrs.len() != before
475        })
476    }
477
478    /// Whether `a`, on an element in `ns`, is the attribute code calls
479    /// `given`, stored as `stored`: by the name as stored when it has no
480    /// namespace (a namespaced one stores its local name), or on a foreign
481    /// element by the name as written, so viewBox finds a parsed viewBox
482    /// and no two attributes are ever written alike.
483    fn is_attr(&self, ns: Ns, a: &Attr, stored: &str, given: &str) -> bool {
484        (a.ns == AttrNs::None && self.str(a.name) == stored)
485            || (ns != Ns::Html && self.written_name(ns, a) == given)
486    }
487
488    /// Changes an element's attributes through a copy at the end of the
489    /// list, never in place: the parser's clones of a formatting element
490    /// share their original's attributes.
491    fn rewrite_attrs(
492        &mut self,
493        id: NodeId,
494        change: impl FnOnce(&Document, &mut Vec<Attr>) -> bool,
495    ) -> bool {
496        let Some(e) = self.element(id) else {
497            return false;
498        };
499        let mut attrs = self.attrs[e.attrs.start as usize..e.attrs.end as usize].to_vec();
500        if !change(self, &mut attrs) {
501            return false;
502        }
503        let start = self.attrs.len() as u32;
504        self.attrs.extend(attrs);
505        let end = self.attrs.len() as u32;
506        if let Data::Element(e) = &mut self.nodes[id as usize].data {
507            e.attrs = Span { start, end };
508        }
509        true
510    }
511}
512
513/// An attribute name set from code, as the parser would store it: on an
514/// HTML element lowercased, as `setAttribute` does. On SVG and MathML a
515/// name whose case the writer puts back (viewBox, definitionURL) is
516/// lowercased too, and any other keeps the case it's given, as does an XML
517/// one.
518fn stored_attr_name(ns: Ns, given: &str) -> String {
519    let lower = given.to_ascii_lowercase();
520    let restored = match ns {
521        Ns::Html => true,
522        Ns::Svg => crate::tree::svg_attr_name(&lower) == Some(given),
523        Ns::MathMl => lower == "definitionurl" && given == "definitionURL",
524        Ns::Xml => false,
525    };
526    if restored { lower } else { given.to_string() }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::EditError;
532    use crate::{NodeId, Ns, parse, parse_fragment};
533
534    #[test]
535    fn nodes_can_be_made_moved_and_removed() {
536        let mut doc = parse_fragment("<p>a</p><p>b</p>", Ns::Html, "div", false);
537        let (first, second) = {
538            let mut c = doc.children(0);
539            (c.next().unwrap(), c.next().unwrap())
540        };
541        let em = doc.create_element(Ns::Html, "EM");
542        let t = doc.create_text("x & y");
543        doc.append(em, t).unwrap();
544        doc.insert_before(first, em, doc.first_child(first))
545            .unwrap();
546        assert_eq!(doc.inner_html(0), "<p><em>x &amp; y</em>a</p><p>b</p>");
547        doc.append(second, em).unwrap();
548        assert_eq!(doc.inner_html(0), "<p>a</p><p>b<em>x &amp; y</em></p>");
549        doc.detach(second);
550        assert_eq!(doc.inner_html(0), "<p>a</p>");
551        doc.append(0, second).unwrap();
552        assert_eq!(doc.inner_html(0), "<p>a</p><p>b<em>x &amp; y</em></p>");
553    }
554
555    /// Moves, removals, renames and new templates in a pseudo-random
556    /// order, the whole tree checked after each.
557    #[cfg(debug_assertions)]
558    #[test]
559    fn edits_keep_every_invariant() {
560        let mut doc = parse(
561            "<div><p>a<b>b</b></p><template><i>c</i></template><ul><li>d</ul></div>",
562            false,
563        );
564        let mut seed: u32 = 0x2545_f491;
565        let mut next = move |n: usize| {
566            seed ^= seed << 13;
567            seed ^= seed >> 17;
568            seed ^= seed << 5;
569            seed as usize % n
570        };
571        for i in 0..2000 {
572            let n = doc.len();
573            let (a, b) = (next(n) as NodeId, next(n) as NodeId);
574            match next(6) {
575                0 => {
576                    let _ = doc.append(a, b);
577                }
578                1 => {
579                    let before = doc.first_child(a);
580                    let _ = doc.insert_before(a, b, before);
581                }
582                2 if i % 2 == 0 => doc.remove(b),
583                2 => doc.detach(b),
584                3 => doc.rename(a, if i % 2 == 0 { "template" } else { "span" }),
585                4 => {
586                    let t = doc.create_element(Ns::Html, "template");
587                    let _ = doc.append(a, t);
588                }
589                _ => {
590                    let t = doc.create_text("t");
591                    let _ = doc.append(a, t);
592                }
593            }
594            doc.check_tree();
595        }
596    }
597
598    #[test]
599    fn a_created_svg_element_is_named_as_a_parsed_one() {
600        let parsed = parse_fragment("<svg><linearGradient/></svg>", Ns::Html, "div", false);
601        let svg = parsed.children(parsed.root()).next().unwrap();
602        let parsed_gradient = parsed.children(svg).next().unwrap();
603        let mut doc = parse_fragment("", Ns::Html, "div", false);
604        let made = doc.create_element(Ns::Svg, "linearGradient");
605        assert_eq!(doc.lower_name(made), Some("lineargradient"));
606        assert_eq!(doc.lower_name(made), parsed.lower_name(parsed_gradient));
607        assert_eq!(doc.outer_html(made), parsed.outer_html(parsed_gradient));
608        // Another case is another element, kept as written.
609        let shouting = doc.create_element(Ns::Svg, "LINEARGRADIENT");
610        assert_eq!(
611            doc.outer_html(shouting),
612            "<LINEARGRADIENT></LINEARGRADIENT>"
613        );
614    }
615
616    #[test]
617    fn a_document_or_fragment_is_never_inserted() {
618        let mut doc = parse("<template><b>x</b></template><p>y</p>", false);
619        let root = doc.root();
620        let contents = (0..doc.len() as NodeId)
621            .find_map(|n| doc.template_contents(n))
622            .unwrap();
623        let loose = doc.create_element(Ns::Html, "div");
624        let before = doc.inner_html(root);
625        assert_eq!(doc.append(loose, root), Err(EditError::NotInsertable));
626        assert_eq!(doc.append(loose, contents), Err(EditError::NotInsertable));
627        assert_eq!(
628            doc.insert_before(loose, root, None),
629            Err(EditError::NotInsertable)
630        );
631        assert_eq!(doc.inner_html(root), before);
632        assert_eq!(doc.inner_html(loose), "");
633        // Their children still go anywhere.
634        let b = doc.first_child(contents).unwrap();
635        assert_eq!(doc.append(loose, b), Ok(()));
636        assert_eq!(doc.inner_html(loose), "<b>x</b>");
637    }
638
639    #[test]
640    fn set_attr_replaces_a_namespaced_attribute_of_the_same_name() {
641        let mut doc = parse_fragment(
642            "<svg><use xlink:href=\"#a\"></use></svg>",
643            Ns::Html,
644            "div",
645            false,
646        );
647        let svg = doc.children(doc.root()).next().unwrap();
648        let used = doc.children(svg).next().unwrap();
649        doc.set_attr(used, "xlink:href", "#b");
650        assert_eq!(doc.outer_html(used), "<use xlink:href=\"#b\"></use>");
651        let attrs: Vec<_> = doc.attrs(used).collect();
652        assert_eq!(attrs, [(crate::AttrNs::XLink, "href", "#b")]);
653        // A plain href is another attribute: its qualified name isn't xlink:href.
654        assert!(!doc.remove_attr(used, "href"));
655        doc.set_attr(used, "href", "#c");
656        let attrs: Vec<_> = doc.attrs(used).collect();
657        assert_eq!(
658            attrs,
659            [
660                (crate::AttrNs::XLink, "href", "#b"),
661                (crate::AttrNs::None, "href", "#c")
662            ]
663        );
664        assert!(doc.remove_attr(used, "href"));
665        let attrs: Vec<_> = doc.attrs(used).collect();
666        assert_eq!(attrs, [(crate::AttrNs::XLink, "href", "#b")]);
667    }
668
669    #[test]
670    fn set_attr_keeps_the_case_of_foreign_names() {
671        let mut doc = parse_fragment(
672            "<svg viewBox=\"0 0 1 1\"></svg><math definitionURL=\"a\"></math><p></p>",
673            Ns::Html,
674            "div",
675            false,
676        );
677        let kids: Vec<_> = doc.children(doc.root()).collect();
678        let (svg, math, p) = (kids[0], kids[1], kids[2]);
679        doc.set_attr(svg, "dataFoo", "x");
680        doc.set_attr(svg, "viewBox", "0 0 2 2");
681        doc.set_attr(math, "mathVariant", "bold");
682        doc.set_attr(math, "definitionURL", "b");
683        doc.set_attr(p, "DATA-X", "y");
684        assert_eq!(
685            doc.outer_html(svg),
686            "<svg viewBox=\"0 0 2 2\" dataFoo=\"x\"></svg>"
687        );
688        assert_eq!(
689            doc.outer_html(math),
690            "<math definitionURL=\"b\" mathVariant=\"bold\"></math>"
691        );
692        assert_eq!(doc.outer_html(p), "<p data-x=\"y\"></p>");
693        // A lowercase viewbox finds the same attribute: never two written alike.
694        doc.set_attr(svg, "viewbox", "0 0 3 3");
695        assert_eq!(
696            doc.outer_html(svg),
697            "<svg viewBox=\"0 0 3 3\" dataFoo=\"x\"></svg>"
698        );
699        // And it's set again, not added, when the case matches what was given.
700        doc.set_attr(svg, "dataFoo", "z");
701        assert_eq!(
702            doc.outer_html(svg),
703            "<svg viewBox=\"0 0 3 3\" dataFoo=\"z\"></svg>"
704        );
705        // What set_attr sets, remove_attr finds by the same name.
706        assert!(doc.remove_attr(svg, "dataFoo"));
707        assert!(doc.remove_attr(svg, "viewBox"));
708        assert!(doc.remove_attr(math, "mathVariant"));
709        assert!(!doc.remove_attr(svg, "dataFoo"));
710        assert_eq!(doc.outer_html(svg), "<svg></svg>");
711        assert_eq!(doc.outer_html(math), "<math definitionURL=\"b\"></math>");
712    }
713
714    #[test]
715    fn renaming_to_or_from_template_adds_or_gives_up_its_contents() {
716        let mut doc = parse_fragment("<template><b>x</b>y</template>", Ns::Html, "div", false);
717        let t = doc.first_child(doc.root()).unwrap();
718        doc.rename(t, "div");
719        assert_eq!(doc.template_contents(t), None);
720        assert_eq!(doc.outer_html(t), "<div><b>x</b>y</div>");
721        doc.rename(t, "template");
722        let contents = doc.template_contents(t).expect("new contents");
723        assert_eq!(doc.first_child(contents), None);
724        assert_eq!(doc.outer_html(t), "<template><b>x</b>y</template>");
725        // Contents go ahead of children a template already has, as written.
726        let p = doc.create_element(Ns::Html, "p");
727        doc.append(contents, p).unwrap();
728        doc.rename(t, "section");
729        assert_eq!(doc.outer_html(t), "<section><p></p><b>x</b>y</section>");
730        // Renaming a template to template leaves its contents be.
731        let u = doc.create_element(Ns::Html, "template");
732        let kept = doc.template_contents(u);
733        doc.rename(u, "TEMPLATE");
734        assert_eq!(doc.template_contents(u), kept);
735    }
736
737    #[test]
738    fn a_renamed_foreign_element_takes_its_new_names_tag() {
739        let mut doc = parse_fragment("", Ns::Html, "div", false);
740        let svg_title = doc.create_element(Ns::Svg, "title");
741        let title_tag = doc.known_tag(svg_title);
742        assert!(title_tag.is_some());
743        let n = doc.create_element(Ns::Svg, "rect");
744        doc.rename(n, "title");
745        assert_eq!(doc.known_tag(n), title_tag);
746        doc.rename(n, "rect");
747        assert_eq!(doc.known_tag(n), None);
748    }
749
750    #[test]
751    fn template_contents_can_become_children() {
752        let mut doc = parse_fragment("<template><b>x</b></template>", Ns::Html, "div", false);
753        let t = doc.first_child(0).unwrap();
754        assert_eq!(doc.first_child(t), None);
755        doc.adopt_template_contents();
756        let b = doc.first_child(t).unwrap();
757        assert_eq!(doc.outer_html(b), "<b>x</b>");
758        // Written the same before and after.
759        assert_eq!(doc.inner_html(0), "<template><b>x</b></template>");
760    }
761
762    /// Netweir reads strings through a shared borrow while an edit may
763    /// run under its own lock, so a string an edit didn't touch must stay
764    /// exactly where it was.
765    #[test]
766    fn edits_never_move_strings_already_read() {
767        // Values with references: the parser copies those into its buffer,
768        // the one place that could move.
769        let mut doc = parse_fragment("<a href='x&amp;y'>t&amp;u</a>", Ns::Html, "div", false);
770        let a = doc.first_child(0).unwrap();
771        let text = doc.first_child(a).unwrap();
772        let href = doc.attrs(a).next().unwrap().2.as_ptr();
773        let data = match doc.kind(text) {
774            crate::Kind::Text(t) => t.as_ptr(),
775            _ => unreachable!(),
776        };
777        for i in 0..10_000 {
778            let n = doc.create_element(Ns::Html, &format!("custom-{i}"));
779            doc.set_attr(n, "data-long", &"y".repeat(100));
780            let t = doc.create_text(&"z".repeat(100));
781            doc.append(n, t).unwrap();
782            doc.append(0, n).unwrap();
783        }
784        doc.set_attr(a, "title", "new");
785        assert_eq!(doc.attrs(a).next().unwrap().2.as_ptr(), href);
786        assert!(matches!(doc.kind(text), crate::Kind::Text(t) if t.as_ptr() == data));
787    }
788
789    #[test]
790    fn xml_is_built_as_written_and_matched_as_netweir_did() {
791        use crate::css::SelectorList;
792        use crate::{AttrNs, Document};
793        let mut doc = Document::empty();
794        let feed = doc.create_element(Ns::Xml, "Feed");
795        doc.append(0, feed).unwrap();
796        let entry = doc.create_element(Ns::Xml, "dc:Creator");
797        doc.add_attr(entry, AttrNs::None, "ID", "up");
798        doc.add_attr(entry, AttrNs::None, "id", "lo");
799        doc.add_attr(entry, AttrNs::Host(3), "x:href", "/p");
800        doc.append(feed, entry).unwrap();
801        let cdata = doc.create_cdata("<raw>");
802        doc.append(entry, cdata).unwrap();
803        let found = |css: &str| SelectorList::parse(css).unwrap().select(&doc, 0).len();
804        assert_eq!(found("feed creator"), 1);
805        assert_eq!(found("[id=lo]"), 1);
806        assert_eq!(found("[id=up]"), 0);
807        assert_eq!(found("#lo"), 1);
808        assert_eq!(found("#up"), 0);
809        assert_eq!(found("[href^='/']"), 1);
810        assert_eq!(
811            doc.outer_html(entry),
812            "<dc:Creator ID=\"up\" id=\"lo\" x:href=\"/p\"><![CDATA[<raw>]]></dc:Creator>"
813        );
814        doc.rename(entry, "Creator");
815        doc.rename_attr(entry, 2, AttrNs::None, "href");
816        assert!(doc.remove_attr_at(entry, 0));
817        assert_eq!(
818            doc.outer_html(entry),
819            "<Creator id=\"lo\" href=\"/p\"><![CDATA[<raw>]]></Creator>"
820        );
821    }
822
823    #[test]
824    fn a_node_cant_go_inside_itself() {
825        let mut doc = parse_fragment("<div><span></span></div>", Ns::Html, "body", false);
826        let div = doc.first_child(0).unwrap();
827        let span = doc.first_child(div).unwrap();
828        assert_eq!(doc.append(span, div), Err(EditError::Cycle));
829        assert_eq!(doc.append(div, div), Err(EditError::Cycle));
830        let text = doc.create_text("t");
831        assert_eq!(doc.append(text, span), Err(EditError::NotAParent));
832        assert_eq!(
833            doc.insert_before(span, text, Some(div)),
834            Err(EditError::NotAChild)
835        );
836    }
837
838    #[test]
839    fn a_template_cant_go_inside_its_own_contents() {
840        let mut doc = parse_fragment(
841            "<div><template><p></p></template></div>",
842            Ns::Html,
843            "body",
844            false,
845        );
846        let div = doc.first_child(0).unwrap();
847        let template = doc.first_child(div).unwrap();
848        let contents = doc.template_contents(template).unwrap();
849        let p = doc.first_child(contents).unwrap();
850        assert_eq!(doc.append(contents, template), Err(EditError::Cycle));
851        assert_eq!(doc.append(contents, div), Err(EditError::Cycle));
852        assert_eq!(doc.insert_before(p, div, None), Err(EditError::Cycle));
853        // Through a template made after the first check, two deep.
854        let made = doc.create_element(Ns::Html, "template");
855        doc.append(p, made).unwrap();
856        let made_contents = doc.template_contents(made).unwrap();
857        assert_eq!(doc.append(made_contents, div), Err(EditError::Cycle));
858        // And one renamed into a template.
859        let span = doc.create_element(Ns::Html, "span");
860        doc.append(made_contents, span).unwrap();
861        doc.rename(span, "template");
862        let span_contents = doc.template_contents(span).unwrap();
863        assert_eq!(doc.append(span_contents, template), Err(EditError::Cycle));
864        // A template renamed away leaves contents nothing reaches.
865        doc.rename(span, "section");
866        doc.append(span_contents, template).unwrap();
867        assert_eq!(doc.inner_html(0), "<div></div>");
868        doc.append(div, template).unwrap();
869        assert_eq!(
870            doc.inner_html(0),
871            "<div><template><p><template><section></section></template></p></template></div>"
872        );
873    }
874
875    #[test]
876    fn attributes_can_be_set_replaced_and_removed() {
877        let mut doc = parse_fragment("<a href=x>a</a><a href=x>b</a>", Ns::Html, "div", false);
878        let a = doc.first_child(0).unwrap();
879        doc.set_attr(a, "HREF", "y");
880        doc.set_attr(a, "title", "t");
881        assert_eq!(doc.outer_html(a), "<a href=\"y\" title=\"t\">a</a>");
882        assert!(doc.remove_attr(a, "href"));
883        assert!(!doc.remove_attr(a, "href"));
884        assert_eq!(doc.outer_html(a), "<a title=\"t\">a</a>");
885        let b = doc.next_sibling(a).unwrap();
886        assert_eq!(doc.outer_html(b), "<a href=\"x\">b</a>");
887    }
888
889    /// The parser's clones of a formatting element share its attributes
890    /// until one of them is changed.
891    #[test]
892    fn changing_a_reconstructed_clone_leaves_the_original_alone() {
893        let mut doc = parse_fragment("<p><b class=x>a</p>t", Ns::Html, "body", false);
894        let p = doc.first_child(0).unwrap();
895        let original = doc.first_child(p).unwrap();
896        let clone = doc.next_sibling(p).unwrap();
897        assert_eq!(doc.outer_html(clone), "<b class=\"x\">t</b>");
898        doc.set_attr(clone, "class", "y");
899        assert_eq!(doc.outer_html(original), "<b class=\"x\">a</b>");
900        assert_eq!(doc.outer_html(clone), "<b class=\"y\">t</b>");
901    }
902
903    #[test]
904    fn foreign_names_keep_their_case() {
905        let mut doc = parse_fragment("<svg></svg>", Ns::Svg, "svg", false);
906        let g = doc.create_element(Ns::Svg, "linearGradient");
907        doc.set_attr(g, "gradientUnits", "u");
908        doc.append(0, g).unwrap();
909        assert!(
910            doc.inner_html(0)
911                .contains("<linearGradient gradientUnits=\"u\"></linearGradient>")
912        );
913    }
914
915    /// The `<p id=a>` in `<div><p id=a>one <b>two</b></p><p id=b>three</p></div>`,
916    /// its `<b>` and the `<b>`'s text.
917    fn removable() -> (crate::Document, NodeId, NodeId, NodeId) {
918        let doc = parse(
919            "<div><p id=a>one <b>two</b></p><p id=b>three</p></div>",
920            false,
921        );
922        let id = |name: &str| {
923            (0..doc.len() as NodeId)
924                .find(|&n| doc.lower_name(n) == Some(name))
925                .unwrap()
926        };
927        let (p, b) = (id("p"), id("b"));
928        let text = doc.first_child(b).unwrap();
929        (doc, p, b, text)
930    }
931
932    #[test]
933    fn a_removed_node_reads_as_nothing() {
934        let (mut doc, p, _, _) = removable();
935        let div = doc.parent(p).unwrap();
936        doc.remove(p);
937        assert!(doc.is_removed(p));
938        assert_eq!(doc.outer_html(div), "<div><p id=\"b\">three</p></div>");
939        assert_eq!(doc.parent(p), None);
940        assert_eq!(doc.first_child(p), None);
941        assert_eq!(doc.children(p).count(), 0);
942        assert_eq!(doc.attrs(p).count(), 0);
943        assert_eq!(doc.attrs_written(p).count(), 0);
944        assert_eq!(doc.lower_name(p), None);
945        assert_eq!(doc.known_tag(p), None);
946        assert_eq!(doc.outer_html(p), "");
947        assert_eq!(doc.inner_html(p), "");
948        assert_eq!(doc.html_alone(p), "");
949        assert_eq!(doc.text(p), "");
950        // Its kind stays, an element's name with it.
951        assert!(matches!(
952            doc.kind(p),
953            crate::Kind::Element { name: "p", .. }
954        ));
955        // Removing it again, or the root, does nothing.
956        doc.remove(p);
957        doc.remove(doc.root());
958        assert!(!doc.is_removed(doc.root()));
959    }
960
961    #[test]
962    fn a_removed_node_cant_be_edited_or_inserted() {
963        let (mut doc, p, _, _) = removable();
964        let div = doc.parent(p).unwrap();
965        let other = doc.next_sibling(p).unwrap();
966        doc.remove(p);
967        assert_eq!(doc.append(div, p), Err(EditError::Removed));
968        let fresh = doc.create_element(Ns::Html, "span");
969        assert_eq!(doc.append(p, fresh), Err(EditError::Removed));
970        assert_eq!(
971            doc.insert_before(div, fresh, Some(p)),
972            Err(EditError::Removed)
973        );
974        // The setters, which return nothing to fail with, do nothing.
975        doc.set_attr(p, "class", "x");
976        doc.rename(p, "section");
977        assert!(!doc.remove_attr(p, "id"));
978        assert_eq!(doc.attrs(p).count(), 0);
979        assert!(matches!(
980            doc.kind(p),
981            crate::Kind::Element { name: "p", .. }
982        ));
983        // Nothing else was touched.
984        doc.append(div, fresh).unwrap();
985        assert_eq!(
986            doc.outer_html(div),
987            "<div><p id=\"b\">three</p><span></span></div>"
988        );
989        assert_eq!(doc.text(other), "three");
990    }
991
992    #[test]
993    fn removing_a_parent_removes_what_it_holds() {
994        let (mut doc, p, b, text) = removable();
995        doc.remove(p);
996        for n in [b, text] {
997            assert!(doc.is_removed(n), "node {n}");
998            assert_eq!(doc.parent(n), None);
999            assert_eq!(doc.outer_html(n), "");
1000        }
1001        assert!(matches!(doc.kind(text), crate::Kind::Text("")));
1002        assert_eq!(doc.append(doc.root(), b), Err(EditError::Removed));
1003    }
1004
1005    #[test]
1006    fn a_detached_node_can_be_inserted_again() {
1007        let (mut doc, p, b, _) = removable();
1008        let div = doc.parent(p).unwrap();
1009        doc.detach(p);
1010        assert!(!doc.is_removed(p));
1011        assert_eq!(doc.outer_html(div), "<div><p id=\"b\">three</p></div>");
1012        assert_eq!(doc.outer_html(p), "<p id=\"a\">one <b>two</b></p>");
1013        assert_eq!(doc.parent(b), Some(p));
1014        doc.append(div, p).unwrap();
1015        assert_eq!(
1016            doc.outer_html(div),
1017            "<div><p id=\"b\">three</p><p id=\"a\">one <b>two</b></p></div>"
1018        );
1019    }
1020
1021    #[test]
1022    fn a_removed_templates_contents_go_with_it() {
1023        let mut doc = parse("<template><i>x</i></template>", false);
1024        let template = (0..doc.len() as NodeId)
1025            .find(|&n| doc.lower_name(n) == Some("template"))
1026            .unwrap();
1027        let contents = doc.template_contents(template).unwrap();
1028        let i = doc.first_child(contents).unwrap();
1029        doc.remove(template);
1030        assert!(doc.is_removed(contents) && doc.is_removed(i));
1031        assert_eq!(doc.template_contents(template), None);
1032        #[cfg(debug_assertions)]
1033        doc.check_tree();
1034    }
1035
1036    #[test]
1037    fn a_removed_node_matches_no_selector() {
1038        let (mut doc, p, b, _) = removable();
1039        let list = crate::css::SelectorList::parse("p, b, #a").unwrap();
1040        assert!(list.matches(&doc, p, None));
1041        doc.remove(p);
1042        assert!(!list.matches(&doc, p, None));
1043        assert!(!list.matches(&doc, b, None));
1044        assert_eq!(list.select(&doc, p), Vec::<NodeId>::new());
1045        // From the root, only the paragraph that wasn't removed is left.
1046        let left = list.select(&doc, doc.root());
1047        assert_eq!(left.len(), 1);
1048        assert_eq!(doc.outer_html(left[0]), "<p id=\"b\">three</p>");
1049    }
1050
1051    #[test]
1052    fn a_removed_hosts_shadow_tree_goes_with_it() {
1053        let mut doc = parse("<div id=host><span>light</span></div>", false);
1054        let host = (0..doc.len() as NodeId)
1055            .find(|&n| doc.lower_name(n) == Some("div"))
1056            .unwrap();
1057        let light = doc.first_child(host).unwrap();
1058        let shadow = doc.attach_shadow(host, crate::ShadowRoot::open()).unwrap();
1059        let slot = doc.create_element(Ns::Html, "slot");
1060        doc.append(shadow, slot).unwrap();
1061        assert_eq!(doc.assigned_nodes(slot), [light]);
1062        doc.remove(host);
1063        for n in [shadow, slot, light] {
1064            assert!(doc.is_removed(n), "node {n}");
1065        }
1066        assert_eq!(doc.shadow_root(host), None);
1067        assert_eq!(doc.shadow_host(shadow), None);
1068        assert_eq!(doc.assigned_nodes(slot), Vec::<NodeId>::new());
1069        assert_eq!(doc.flat_tree(host).count(), 0);
1070        assert_eq!(
1071            doc.attach_shadow(host, crate::ShadowRoot::open()),
1072            Err(EditError::Removed)
1073        );
1074        // A shadow root on its own isn't removed, like a template's contents.
1075        let mut doc = parse("<div></div>", false);
1076        let host = (0..doc.len() as NodeId)
1077            .find(|&n| doc.lower_name(n) == Some("div"))
1078            .unwrap();
1079        let shadow = doc.attach_shadow(host, crate::ShadowRoot::open()).unwrap();
1080        doc.remove(shadow);
1081        assert!(!doc.is_removed(shadow));
1082        assert_eq!(doc.shadow_root(host), Some(shadow));
1083        #[cfg(debug_assertions)]
1084        doc.check_tree();
1085    }
1086}