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