Skip to main content

parsec/
shadow.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Shadow roots, slots and the flat tree, as the DOM Standard has them.
5//!
6//! A shadow root is a node of its own kind, like a template's contents:
7//! nobody's child, reached from its host by [`Document::shadow_root`] and
8//! back by [`Document::shadow_host`]. The host's children stay its
9//! children; which of them each slot shows is worked out when asked, from
10//! the `slot` and `name` attributes as they are then, so edits never leave
11//! an assignment stale. The flat tree, where a host's shadow root takes
12//! the place of its children and each slot shows its assigned nodes, is
13//! walked by [`Document::flat_children`] and [`Document::flat_parent`].
14//!
15//! Walks that follow the node tree (children, `select` from the document,
16//! XPath, `text`) don't go into shadow roots, as a browser's don't.
17
18use crate::dom::{AttrNs, Data, Document, NodeId, Ns, ShadowRoot, SlotAssignment};
19use crate::edit::EditError;
20use crate::tags::Tag;
21
22/// Whether an element of this name may host a shadow root: one of the
23/// HTML Standard's list, or a valid custom element name.
24pub(crate) fn valid_host(ns: Ns, tag: Tag, name: &str) -> bool {
25    use Tag::*;
26    ns == Ns::Html
27        && (matches!(
28            tag,
29            Article
30                | Aside
31                | Blockquote
32                | Body
33                | Div
34                | Footer
35                | H1
36                | H2
37                | H3
38                | H4
39                | H5
40                | H6
41                | Header
42                | Main
43                | Nav
44                | P
45                | Section
46                | Span
47        ) || (tag == Other && crate::css::custom_element_name(name)))
48}
49
50impl Document {
51    /// The element's shadow root, open or closed.
52    pub fn shadow_root(&self, host: NodeId) -> Option<NodeId> {
53        if self.shadow_roots.is_empty() || self.is_removed(host) {
54            return None;
55        }
56        self.shadow_roots.get(&host).copied()
57    }
58
59    /// A shadow root's host.
60    pub fn shadow_host(&self, root: NodeId) -> Option<NodeId> {
61        if self.is_removed(root) {
62            return None;
63        }
64        match self.nodes[root as usize].data {
65            Data::ShadowRoot { host, .. } => Some(host),
66            _ => None,
67        }
68    }
69
70    /// The node at the top of `id`'s tree: the document, a template's
71    /// contents, a shadow root, or a detached node.
72    pub fn tree_root(&self, id: NodeId) -> NodeId {
73        let mut at = id;
74        while let Some(p) = self.parent(at) {
75            at = p;
76        }
77        at
78    }
79
80    /// Attaches a shadow root to `host`, as `attachShadow` does: only an
81    /// HTML element of a name the standard lists (`div`, `span`,
82    /// `section`...) or a custom element may have one, and only one.
83    /// [`EditError::NotAShadowHost`] otherwise. The root starts empty. As
84    /// in the DOM, a root the parser made from a `<template
85    /// shadowrootmode>` is handed back once to a call with its mode,
86    /// emptied, keeping the settings it was declared with.
87    pub fn attach_shadow(&mut self, host: NodeId, init: ShadowRoot) -> Result<NodeId, EditError> {
88        if self.is_removed(host) {
89            return Err(EditError::Removed);
90        }
91        let Some(e) = self.element(host) else {
92            return Err(EditError::NotAShadowHost);
93        };
94        let name = self.element_name(e);
95        if !valid_host(e.ns, e.tag, name) {
96            return Err(EditError::NotAShadowHost);
97        }
98        let Some(&root) = self.shadow_roots.get(&host) else {
99            return Ok(self.add_shadow_root(host, init));
100        };
101        // A root the parser made is handed back once, emptied, to the
102        // first call asking for its mode; it keeps its other settings.
103        let Data::ShadowRoot { init: mut kept, .. } = self.nodes[root as usize].data else {
104            unreachable!("a host's shadow root");
105        };
106        if !kept.declarative || kept.mode != init.mode {
107            return Err(EditError::NotAShadowHost);
108        }
109        while let Some(child) = self.first_child(root) {
110            self.detach(child);
111        }
112        kept.declarative = false;
113        self.nodes[root as usize].data = Data::ShadowRoot { host, init: kept };
114        Ok(root)
115    }
116
117    /// Makes and links a shadow root, the checks done.
118    pub(crate) fn add_shadow_root(&mut self, host: NodeId, init: ShadowRoot) -> NodeId {
119        debug_assert!(!self.shadow_roots.contains_key(&host), "{host} has a root");
120        let root = self.add(Data::ShadowRoot { host, init });
121        self.shadow_roots.insert(host, root);
122        root
123    }
124
125    /// Whether `id` is a `slot` element in a shadow tree, the only kind
126    /// that's assigned nodes.
127    pub fn is_slot(&self, id: NodeId) -> bool {
128        !self.shadow_roots.is_empty()
129            && self
130                .element(id)
131                .is_some_and(|e| e.ns == Ns::Html && self.element_name(e) == "slot")
132            && self.shadow_host(self.tree_root(id)).is_some()
133    }
134
135    /// An attribute with no namespace.
136    fn plain_attr(&self, id: NodeId, name: &str) -> Option<&str> {
137        self.attrs(id)
138            .find(|&(ns, n, _)| ns == AttrNs::None && n == name)
139            .map(|(_, _, v)| v)
140    }
141
142    /// Whether `id` can be assigned to a slot: an element or text.
143    fn slottable(&self, id: NodeId) -> bool {
144        matches!(
145            self.nodes[id as usize].data,
146            Data::Element(_) | Data::Text(_)
147        )
148    }
149
150    /// Sets the nodes a slot in a shadow root with
151    /// [`SlotAssignment::Manual`] is assigned, as `slot.assign()` does:
152    /// in that order, each taken from any slot it was assigned before.
153    /// Only those that are children of the host are assigned, when asked;
154    /// in a root with named assignment the list is kept and unused.
155    pub fn assign(&mut self, slot: NodeId, nodes: &[NodeId]) {
156        if self.element(slot).is_none() || self.is_removed(slot) {
157            return;
158        }
159        for list in self.manual_slots.values_mut() {
160            list.retain(|n| !nodes.contains(n));
161        }
162        let mut list: Vec<NodeId> = Vec::with_capacity(nodes.len());
163        for &n in nodes {
164            if self.slottable(n) && !self.is_removed(n) && !list.contains(&n) {
165                list.push(n);
166            }
167        }
168        self.manual_slots.insert(slot, list);
169    }
170
171    /// The slot that `node` is assigned to, as the DOM's "find a slot":
172    /// `None` unless it's an element or text whose parent hosts a shadow
173    /// root (open or closed).
174    pub fn assigned_slot(&self, node: NodeId) -> Option<NodeId> {
175        if self.shadow_roots.is_empty() || !self.slottable(node) {
176            return None;
177        }
178        let root = self.shadow_root(self.parent(node)?)?;
179        let Data::ShadowRoot { init, .. } = self.nodes[root as usize].data else {
180            return None;
181        };
182        if init.slot_assignment == SlotAssignment::Manual {
183            return self.slots(root).find(|s| {
184                self.manual_slots
185                    .get(s)
186                    .is_some_and(|list| list.contains(&node))
187            });
188        }
189        let name = self.slot_name(node);
190        self.slots(root)
191            .find(|&s| self.plain_attr(s, "name").unwrap_or("") == name)
192    }
193
194    /// The name a slottable asks for: its `slot` attribute, or "".
195    fn slot_name(&self, node: NodeId) -> &str {
196        match self.nodes[node as usize].data {
197            Data::Element(_) => self.plain_attr(node, "slot").unwrap_or(""),
198            _ => "",
199        }
200    }
201
202    /// The slots in a shadow tree, in tree order.
203    fn slots(&self, root: NodeId) -> impl Iterator<Item = NodeId> + '_ {
204        self.descendants(root).filter(move |&n| {
205            self.element(n)
206                .is_some_and(|e| e.ns == Ns::Html && self.element_name(e) == "slot")
207        })
208    }
209
210    /// Every node under `id`, in tree order, not into template contents
211    /// or shadow roots.
212    fn descendants(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
213        let mut at = self.first_child(id);
214        std::iter::from_fn(move || {
215            let n = at?;
216            at = self.first_child(n).or_else(|| {
217                let mut up = n;
218                while up != id {
219                    if let Some(s) = self.next_sibling(up) {
220                        return Some(s);
221                    }
222                    up = self.parent(up)?;
223                }
224                None
225            });
226            Some(n)
227        })
228    }
229
230    /// The nodes assigned to a slot, as `slot.assignedNodes()`: the
231    /// host's children that [`Document::assigned_slot`] puts there, in
232    /// tree order (or the order [`Document::assign`] gave, for manual
233    /// assignment). Empty for an element that isn't a slot in a shadow
234    /// tree.
235    pub fn assigned_nodes(&self, slot: NodeId) -> Vec<NodeId> {
236        let Some(host) = self.shadow_host(self.tree_root(slot)) else {
237            return Vec::new();
238        };
239        if !self.is_slot(slot) {
240            return Vec::new();
241        }
242        let root = self.shadow_roots[&host];
243        if let Data::ShadowRoot { init, .. } = self.nodes[root as usize].data
244            && init.slot_assignment == SlotAssignment::Manual
245        {
246            return self.manual_slots.get(&slot).map_or(Vec::new(), |list| {
247                list.iter()
248                    .copied()
249                    .filter(|&n| self.parent(n) == Some(host))
250                    .collect()
251            });
252        }
253        // Only the first slot of a name is assigned anything.
254        let name = self.plain_attr(slot, "name").unwrap_or("");
255        if self
256            .slots(root)
257            .find(|&s| self.plain_attr(s, "name").unwrap_or("") == name)
258            != Some(slot)
259        {
260            return Vec::new();
261        }
262        self.children(host)
263            .filter(|&c| self.slottable(c) && self.slot_name(c) == name)
264            .collect()
265    }
266
267    /// `slot.assignedNodes({flatten: true})`: a slot assigned another
268    /// slot shows what that one shows, and a slot assigned nothing shows
269    /// its own children, its fallback content.
270    pub fn flattened_assigned_nodes(&self, slot: NodeId) -> Vec<NodeId> {
271        let mut out = Vec::new();
272        self.flatten_into(slot, &mut out);
273        out
274    }
275
276    fn flatten_into(&self, slot: NodeId, out: &mut Vec<NodeId>) {
277        if !self.is_slot(slot) {
278            return;
279        }
280        let mut nodes = self.assigned_nodes(slot);
281        if nodes.is_empty() {
282            nodes = self.children(slot).filter(|&c| self.slottable(c)).collect();
283        }
284        for n in nodes {
285            if self.is_slot(n) {
286                self.flatten_into(n, out);
287            } else {
288                out.push(n);
289            }
290        }
291    }
292
293    /// A node's children in the flat tree, as rendering sees them: a
294    /// shadow host's are its shadow root's children, a slot's are its
295    /// assigned nodes (or its own children when it has none), and every
296    /// other node's are its children.
297    pub fn flat_children(&self, id: NodeId) -> Vec<NodeId> {
298        if let Some(root) = self.shadow_root(id) {
299            return self.children(root).collect();
300        }
301        if self.is_slot(id) {
302            let assigned = self.assigned_nodes(id);
303            if !assigned.is_empty() {
304                return assigned;
305            }
306        }
307        self.children(id).collect()
308    }
309
310    /// A node's parent in the flat tree: its slot when it's assigned one,
311    /// the host for a shadow root's child, else its parent. `None` for a
312    /// node the flat tree leaves out: a host's child no slot takes, or a
313    /// slot's fallback content when the slot was assigned nodes.
314    pub fn flat_parent(&self, id: NodeId) -> Option<NodeId> {
315        let parent = self.parent(id)?;
316        if self.shadow_roots.is_empty() {
317            return Some(parent);
318        }
319        if let Some(host) = self.shadow_host(parent) {
320            return Some(host);
321        }
322        if self.shadow_root(parent).is_some() {
323            return self.assigned_slot(id);
324        }
325        if self.is_slot(parent) && !self.assigned_nodes(parent).is_empty() {
326            return None;
327        }
328        Some(parent)
329    }
330
331    /// The flat tree under `id`, in tree order, `id` first: what a
332    /// renderer walks.
333    pub fn flat_tree(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
334        let mut stack = if self.is_removed(id) {
335            vec![]
336        } else {
337            vec![id]
338        };
339        std::iter::from_fn(move || {
340            let n = stack.pop()?;
341            let at = stack.len();
342            stack.extend(self.flat_children(n));
343            stack[at..].reverse();
344            Some(n)
345        })
346    }
347
348    /// The parent, or for a shadow root its host: the DOM's
349    /// shadow-including parent, which `:host-context()` climbs.
350    pub(crate) fn shadow_including_parent(&self, id: NodeId) -> Option<NodeId> {
351        self.parent(id).or_else(|| self.shadow_host(id))
352    }
353}
354
355/// A shadow root's settings from a `<template>` start tag's attributes,
356/// or `None` when its `shadowrootmode` is missing or neither `open` nor
357/// `closed` (in any case).
358pub(crate) fn declared<'a>(attrs: impl Iterator<Item = (&'a str, &'a str)>) -> Option<ShadowRoot> {
359    let mut init = ShadowRoot::open();
360    let mut mode = None;
361    for (name, value) in attrs {
362        match name {
363            "shadowrootmode" if mode.is_none() => {
364                mode = Some(if value.eq_ignore_ascii_case("open") {
365                    Some(crate::ShadowRootMode::Open)
366                } else if value.eq_ignore_ascii_case("closed") {
367                    Some(crate::ShadowRootMode::Closed)
368                } else {
369                    None
370                })
371            }
372            "shadowrootdelegatesfocus" => init.delegates_focus = true,
373            "shadowrootclonable" => init.clonable = true,
374            "shadowrootserializable" => init.serializable = true,
375            // Any other value is the default, named.
376            "shadowrootslotassignment" if value.eq_ignore_ascii_case("manual") => {
377                init.slot_assignment = SlotAssignment::Manual
378            }
379            _ => {}
380        }
381    }
382    init.mode = mode??;
383    init.declarative = true;
384    Some(init)
385}
386
387#[cfg(test)]
388mod tests {
389    use crate::css::SelectorList;
390    use crate::{
391        Document, EditError, Kind, NodeId, Ns, Options, Parser, SerializeOptions, ShadowRoot,
392        SlotAssignment, parse, parse_fragment, parse_fragment_with, parse_with,
393    };
394
395    fn by_id(doc: &Document, id: &str) -> NodeId {
396        (0..doc.len() as NodeId)
397            .find(|&n| doc.attrs(n).any(|a| a.1 == "id" && a.2 == id))
398            .unwrap_or_else(|| panic!("no #{id}"))
399    }
400
401    fn ids(doc: &Document, nodes: &[NodeId]) -> Vec<String> {
402        nodes
403            .iter()
404            .map(|&n| match doc.kind(n) {
405                Kind::Text(t) => format!("'{t}'"),
406                _ => doc
407                    .attrs(n)
408                    .find(|a| a.1 == "id")
409                    .map_or("?".into(), |a| a.2.to_string()),
410            })
411            .collect()
412    }
413
414    const SLOTS: &str = "<div id=host><template shadowrootmode=open>\
415        <slot id=s-a name=a></slot><slot id=s-a2 name=a></slot><slot id=s-default>fallback</slot>\
416        <slot id=s-none name=none><i id=fb>fb</i></slot>\
417        </template><span id=x slot=a></span>t<b id=y></b><!--c--><em id=z slot=nope></em></div>";
418
419    #[test]
420    fn named_slots_take_the_hosts_children_by_their_slot_attribute() {
421        let doc = parse(SLOTS, false);
422        #[cfg(debug_assertions)]
423        doc.check_tree();
424        let host = by_id(&doc, "host");
425        let root = doc.shadow_root(host).unwrap();
426        assert_eq!(doc.shadow_host(root), Some(host));
427        assert!(matches!(doc.kind(root), Kind::ShadowRoot(i) if i.declarative));
428        let (a, a2, default) = (
429            by_id(&doc, "s-a"),
430            by_id(&doc, "s-a2"),
431            by_id(&doc, "s-default"),
432        );
433        assert_eq!(ids(&doc, &doc.assigned_nodes(a)), ["x"]);
434        // Only the first slot of a name gets anything.
435        assert!(doc.assigned_nodes(a2).is_empty());
436        assert_eq!(ids(&doc, &doc.assigned_nodes(default)), ["'t'", "y"]);
437        assert_eq!(doc.assigned_slot(by_id(&doc, "x")), Some(a));
438        assert_eq!(doc.assigned_slot(by_id(&doc, "z")), None);
439        // A slot with nothing assigned shows its fallback content.
440        let none = by_id(&doc, "s-none");
441        assert_eq!(ids(&doc, &doc.flattened_assigned_nodes(none)), ["fb"]);
442        assert!(doc.is_slot(a) && !doc.is_slot(host));
443    }
444
445    #[test]
446    fn the_flat_tree_puts_slotted_nodes_under_their_slots() {
447        let doc = parse(SLOTS, false);
448        let host = by_id(&doc, "host");
449        let a = by_id(&doc, "s-a");
450        let flat: Vec<NodeId> = doc.flat_tree(host).collect();
451        assert_eq!(
452            ids(&doc, &flat),
453            [
454                "host",
455                "s-a",
456                "x",
457                "s-a2",
458                "s-default",
459                "'t'",
460                "y",
461                "s-none",
462                "fb",
463                "'fb'"
464            ]
465        );
466        assert_eq!(doc.flat_parent(by_id(&doc, "x")), Some(a));
467        assert_eq!(doc.flat_parent(a), Some(host));
468        // Unassigned: not in the flat tree.
469        assert_eq!(doc.flat_parent(by_id(&doc, "z")), None);
470        let fallback = doc.first_child(by_id(&doc, "s-default")).unwrap();
471        assert_eq!(doc.flat_parent(fallback), None);
472        assert_eq!(doc.flat_children(a), [by_id(&doc, "x")]);
473    }
474
475    #[test]
476    fn a_slot_slotted_into_another_shows_what_it_shows_flattened() {
477        let doc = parse(
478            "<div id=outer><template shadowrootmode=open>\
479               <div id=inner><template shadowrootmode=open><slot id=deep></slot></template>\
480                 <slot id=mid></slot></div>\
481             </template><p id=light></p></div>",
482            false,
483        );
484        #[cfg(debug_assertions)]
485        doc.check_tree();
486        let deep = by_id(&doc, "deep");
487        assert_eq!(ids(&doc, &doc.assigned_nodes(deep)), ["mid"]);
488        assert_eq!(ids(&doc, &doc.flattened_assigned_nodes(deep)), ["light"]);
489        // ::slotted() in either shadow tree sees the light <p>, in the
490        // inner one through #mid.
491        let inner_root = doc.shadow_root(by_id(&doc, "inner")).unwrap();
492        let slotted = SelectorList::parse("::slotted(p)").unwrap();
493        assert!(slotted.matches(&doc, by_id(&doc, "light"), Some(inner_root)));
494        let outer_root = doc.shadow_root(by_id(&doc, "outer")).unwrap();
495        assert!(slotted.matches(&doc, by_id(&doc, "light"), Some(outer_root)));
496        assert!(!slotted.matches(&doc, by_id(&doc, "light"), None));
497    }
498
499    #[test]
500    fn manual_assignment_takes_only_what_assign_gives() {
501        let mut doc = parse(
502            "<div id=host><span id=x slot=a></span><b id=y></b></div>",
503            false,
504        );
505        let host = by_id(&doc, "host");
506        let init = ShadowRoot {
507            slot_assignment: SlotAssignment::Manual,
508            ..ShadowRoot::open()
509        };
510        let root = doc.attach_shadow(host, init).unwrap();
511        let (s1, s2) = (
512            doc.create_element(Ns::Html, "slot"),
513            doc.create_element(Ns::Html, "slot"),
514        );
515        doc.set_attr(s1, "name", "a");
516        doc.append(root, s1).unwrap();
517        doc.append(root, s2).unwrap();
518        let (x, y) = (by_id(&doc, "x"), by_id(&doc, "y"));
519        assert!(doc.assigned_nodes(s1).is_empty());
520        doc.assign(s1, &[y, x]);
521        assert_eq!(doc.assigned_nodes(s1), [y, x]);
522        assert_eq!(doc.assigned_slot(x), Some(s1));
523        // Assigning to another slot takes them from the first.
524        doc.assign(s2, &[x]);
525        assert_eq!(doc.assigned_nodes(s1), [y]);
526        assert_eq!(doc.assigned_slot(x), Some(s2));
527        // Only the host's children count.
528        doc.remove(y);
529        assert!(doc.assigned_nodes(s1).is_empty());
530        #[cfg(debug_assertions)]
531        doc.check_tree();
532    }
533
534    #[test]
535    fn attach_shadow_as_the_dom_has_it() {
536        let mut doc = parse(
537            "<div id=d><template shadowrootmode=open>x</template></div><p id=p></p>\
538             <progress id=g></progress><my-el id=c></my-el>",
539            false,
540        );
541        let (d, p, g, c) = (
542            by_id(&doc, "d"),
543            by_id(&doc, "p"),
544            by_id(&doc, "g"),
545            by_id(&doc, "c"),
546        );
547        assert_eq!(
548            doc.attach_shadow(g, ShadowRoot::open()),
549            Err(EditError::NotAShadowHost)
550        );
551        assert!(doc.attach_shadow(c, ShadowRoot::closed()).is_ok());
552        let root = doc.attach_shadow(p, ShadowRoot::open()).unwrap();
553        assert_eq!(
554            doc.attach_shadow(p, ShadowRoot::open()),
555            Err(EditError::NotAShadowHost)
556        );
557        let text = doc.create_text("t");
558        assert_eq!(
559            doc.attach_shadow(text, ShadowRoot::open()),
560            Err(EditError::NotAShadowHost)
561        );
562        // A declared root: a mismatched mode is refused, a matching one
563        // gets it back emptied, once.
564        let declared = doc.shadow_root(d).unwrap();
565        assert_eq!(
566            doc.attach_shadow(d, ShadowRoot::closed()),
567            Err(EditError::NotAShadowHost)
568        );
569        assert_eq!(doc.attach_shadow(d, ShadowRoot::open()), Ok(declared));
570        assert_eq!(doc.first_child(declared), None);
571        assert_eq!(
572            doc.attach_shadow(d, ShadowRoot::open()),
573            Err(EditError::NotAShadowHost)
574        );
575        // Shadow roots are never children, and a host can't go into its
576        // own shadow tree.
577        let div = doc.create_element(Ns::Html, "div");
578        assert_eq!(doc.append(div, root), Err(EditError::NotInsertable));
579        doc.append(root, div).unwrap();
580        assert_eq!(doc.append(div, p), Err(EditError::Cycle));
581        assert_eq!(doc.append(root, p), Err(EditError::Cycle));
582        #[cfg(debug_assertions)]
583        doc.check_tree();
584    }
585
586    #[test]
587    fn only_documents_and_asked_for_fragments_get_declarative_roots() {
588        let html = "<div><template shadowrootmode=open><b></b></template></div>";
589        let hosts = |doc: &Document| {
590            (0..doc.len() as NodeId)
591                .filter(|&n| doc.shadow_root(n).is_some())
592                .count()
593        };
594        assert_eq!(hosts(&parse(html, false)), 1);
595        assert_eq!(hosts(&parse_fragment(html, Ns::Html, "div", false)), 0);
596        let on = Options {
597            declarative_shadow_roots: Some(true),
598            ..Options::default()
599        };
600        let off = Options {
601            declarative_shadow_roots: Some(false),
602            ..Options::default()
603        };
604        assert_eq!(
605            hosts(&parse_fragment_with(html, Ns::Html, "div", on).unwrap()),
606            1
607        );
608        assert_eq!(hosts(&parse_with(html, off).unwrap()), 0);
609        // The context element is never the host: it isn't in the result.
610        let doc = parse_fragment_with(
611            "<template shadowrootmode=open></template>",
612            Ns::Html,
613            "div",
614            on,
615        )
616        .unwrap();
617        assert_eq!(hosts(&doc), 0);
618        assert_eq!(
619            doc.inner_html(0),
620            "<template shadowrootmode=\"open\"></template>"
621        );
622        // Nor the html element.
623        let doc = parse("<template shadowrootmode=open></template>", false);
624        assert_eq!(hosts(&doc), 0);
625    }
626
627    #[test]
628    fn a_shadow_root_is_built_alike_in_pieces() {
629        let html = "<div id=h><template shadowrootmode=closed shadowrootserializable>\
630                    <p>a<b>b</template>c</div><span><template shadowrootmode=open>x</template></span>";
631        let options = Options {
632            spans: true,
633            ..Options::default()
634        };
635        let whole = parse_with(html, options).unwrap();
636        let dump = |doc: &Document| {
637            doc.serialize_with(
638                0,
639                &SerializeOptions {
640                    html5test: true,
641                    ..SerializeOptions::default()
642                },
643            )
644        };
645        assert!(dump(&whole).contains("#shadow-root (closed serializable)"));
646        for size in 1..8 {
647            let mut parser = Parser::new(options);
648            for piece in html.as_bytes().chunks(size) {
649                parser.feed(std::str::from_utf8(piece).unwrap());
650            }
651            let doc = parser.finish().unwrap();
652            #[cfg(debug_assertions)]
653            doc.check_tree();
654            assert_eq!(dump(&doc), dump(&whole));
655        }
656        let root = whole.shadow_root(by_id(&whole, "h")).unwrap();
657        let p = whole.first_child(root).unwrap();
658        let at = html.find("<p>").unwrap();
659        assert_eq!(whole.span(p), Some(at..at + 3));
660    }
661
662    #[test]
663    fn get_html_writes_the_roots_asked_for() {
664        let doc = parse(
665            "<div id=a><template shadowrootmode=open shadowrootserializable>\
666               <span id=b><template shadowrootmode=closed>in</template></span>\
667             </template>light</div>",
668            false,
669        );
670        let a = by_id(&doc, "a");
671        assert_eq!(doc.outer_html(a), "<div id=\"a\">light</div>");
672        let serializable = SerializeOptions {
673            serializable_shadow_roots: true,
674            ..SerializeOptions::default()
675        };
676        assert_eq!(
677            doc.serialize_with(a, &serializable),
678            "<div id=\"a\"><template shadowrootmode=\"open\" shadowrootserializable=\"\">\
679             <span id=\"b\"></span></template>light</div>"
680        );
681        let b = by_id(&doc, "b");
682        let inner = doc.shadow_root(b).unwrap();
683        let listed = SerializeOptions {
684            serializable_shadow_roots: true,
685            shadow_roots: vec![inner],
686            ..SerializeOptions::default()
687        };
688        assert_eq!(
689            doc.serialize_with(a, &listed),
690            "<div id=\"a\"><template shadowrootmode=\"open\" shadowrootserializable=\"\">\
691             <span id=\"b\"><template shadowrootmode=\"closed\">in</template></span></template>\
692             light</div>"
693        );
694        // A shadow root's own markup is its children's.
695        let outer = doc.shadow_root(a).unwrap();
696        assert_eq!(doc.inner_html(outer), "<span id=\"b\"></span>");
697        // What was written parses back to the same tree.
698        let again = parse(&doc.serialize_with(0, &listed), false);
699        let b_again = by_id(&again, "b");
700        let listed_again = SerializeOptions {
701            shadow_roots: vec![again.shadow_root(b_again).unwrap()],
702            ..listed.clone()
703        };
704        assert_eq!(
705            again.serialize_with(0, &listed_again),
706            doc.serialize_with(0, &listed)
707        );
708        // Pretty-printing keeps the template whole.
709        let pretty = SerializeOptions {
710            pretty: true,
711            ..listed
712        };
713        let printed = doc.serialize_with(a, &pretty);
714        assert!(printed.contains("<template shadowrootmode=\"closed\">in</template>"));
715    }
716
717    #[test]
718    fn host_selectors_match_inside_the_shadow_tree_only() {
719        let doc = parse(
720            "<section class=ctx><div id=host class=h>\
721               <template shadowrootmode=open><p id=top></p><div id=d><p id=deep></p></div>\
722               <slot id=s></slot></template>\
723               <span id=l class=l></span><i id=other></i></div></section>",
724            false,
725        );
726        let host = by_id(&doc, "host");
727        let root = doc.shadow_root(host).unwrap();
728        let select = |css: &str, scope: NodeId| {
729            ids(&doc, &SelectorList::parse(css).unwrap().select(&doc, scope))
730        };
731        let matches = |css: &str, el: &str, scope: Option<NodeId>| {
732            SelectorList::parse(css)
733                .unwrap()
734                .matches(&doc, by_id(&doc, el), scope)
735        };
736        // The host stands in for the root.
737        assert_eq!(select(":host > p", root), ["top"]);
738        assert_eq!(select(":host p", root), ["top", "deep"]);
739        assert_eq!(select(":host(.h) > *", root), ["top", "d", "s"]);
740        assert!(select(":host(.nope) p", root).is_empty());
741        assert_eq!(select(":host-context(.ctx) p", root), ["top", "deep"]);
742        assert!(select(":host-context(.nope) p", root).is_empty());
743        // Featureless: nothing but :host matches the host, and it has no
744        // parent or siblings here.
745        assert!(matches(":host", "host", Some(root)));
746        assert!(matches(":is(:host(div))", "host", Some(root)));
747        assert!(!matches("div", "host", Some(root)));
748        assert!(!matches("*", "host", Some(root)));
749        assert!(select("section p", root).is_empty());
750        assert!(select("section :host p", root).is_empty());
751        // From an element inside, the tree is its own.
752        assert!(matches(":host > p", "top", None));
753        // Outside the shadow tree :host is nothing, and select from the
754        // document doesn't go into shadow roots.
755        assert!(!matches(":host", "host", None));
756        assert!(select("p", 0).is_empty());
757        // ::slotted(): elements assigned to a slot in this tree.
758        assert!(matches("::slotted(.l)", "l", Some(root)));
759        assert!(matches("slot::slotted(span)", "l", Some(root)));
760        assert!(matches(":host > slot::slotted(*)", "l", Some(root)));
761        assert!(!matches("::slotted(i)", "l", Some(root)));
762        assert!(!matches("p::slotted(span)", "l", Some(root)));
763        assert!(!matches("::slotted(span)", "l", None));
764        // Pseudo-elements never come out of select.
765        assert!(select("::slotted(*)", root).is_empty());
766        // :host()'s argument sees the host as it is outside, light
767        // children and all.
768        assert!(matches(":host(:has(> span.l))", "host", Some(root)));
769        assert!(!matches(":host(:has(> p))", "host", Some(root)));
770    }
771
772    #[test]
773    fn host_and_slotted_selectors_parse_with_compound_arguments() {
774        for ok in [
775            ":host",
776            ":host(div.x)",
777            ":host(:is(.a, .b + .c))",
778            ":host-context(body)",
779            "::slotted(span)",
780            "slot::slotted(*)::before",
781            ":not(:host)",
782        ] {
783            assert!(SelectorList::parse(ok).is_ok(), "{ok}");
784        }
785        for bad in [
786            ":host(div p)",
787            ":host(:not(.a .b))",
788            ":host-context(a > b)",
789            "::slotted(a b)",
790            "::slotted(span).x",
791            "::slotted(span) p",
792            ":host-context",
793        ] {
794            assert!(SelectorList::parse(bad).is_err(), "{bad}");
795        }
796        let spec = |s: &str| SelectorList::parse(s).unwrap().specificity();
797        assert_eq!(spec(":host"), (0, 1, 0));
798        assert_eq!(spec(":host(div.x)"), (0, 2, 1));
799        assert_eq!(spec("::slotted(.x)"), (0, 1, 1));
800    }
801}