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        if !self.is_slot(slot) {
273            return out;
274        }
275        // The nodes still to read, last first: a loop, not a call for each
276        // slot, so a long chain of slots assigned slots can't run out of
277        // stack.
278        let mut todo = vec![slot];
279        while let Some(n) = todo.pop() {
280            if !self.is_slot(n) {
281                out.push(n);
282                continue;
283            }
284            let mut nodes = self.assigned_nodes(n);
285            if nodes.is_empty() {
286                nodes = self.children(n).filter(|&c| self.slottable(c)).collect();
287            }
288            todo.extend(nodes.into_iter().rev());
289        }
290        out
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    /// Flattening called itself for each slot in a chain of slots
500    /// assigned slots, one for each level of nested shadow hosts.
501    #[test]
502    fn a_long_chain_of_slots_flattens_on_a_small_stack() {
503        let n = 20_000;
504        let html = "<div><template shadowrootmode=open>".repeat(n)
505            + "<slot id=deep></slot>"
506            + &"</template><slot></slot></div>".repeat(n - 1)
507            + "</template><p id=light></p></div>";
508        let found = std::thread::Builder::new()
509            .stack_size(256 * 1024)
510            .spawn(move || {
511                let doc = parse(&html, false);
512                ids(&doc, &doc.flattened_assigned_nodes(by_id(&doc, "deep")))
513            })
514            .unwrap()
515            .join()
516            .unwrap();
517        assert_eq!(found, ["light"]);
518    }
519
520    #[test]
521    fn manual_assignment_takes_only_what_assign_gives() {
522        let mut doc = parse(
523            "<div id=host><span id=x slot=a></span><b id=y></b></div>",
524            false,
525        );
526        let host = by_id(&doc, "host");
527        let init = ShadowRoot {
528            slot_assignment: SlotAssignment::Manual,
529            ..ShadowRoot::open()
530        };
531        let root = doc.attach_shadow(host, init).unwrap();
532        let (s1, s2) = (
533            doc.create_element(Ns::Html, "slot").unwrap(),
534            doc.create_element(Ns::Html, "slot").unwrap(),
535        );
536        doc.set_attr(s1, "name", "a").unwrap();
537        doc.append(root, s1).unwrap();
538        doc.append(root, s2).unwrap();
539        let (x, y) = (by_id(&doc, "x"), by_id(&doc, "y"));
540        assert!(doc.assigned_nodes(s1).is_empty());
541        doc.assign(s1, &[y, x]);
542        assert_eq!(doc.assigned_nodes(s1), [y, x]);
543        assert_eq!(doc.assigned_slot(x), Some(s1));
544        // Assigning to another slot takes them from the first.
545        doc.assign(s2, &[x]);
546        assert_eq!(doc.assigned_nodes(s1), [y]);
547        assert_eq!(doc.assigned_slot(x), Some(s2));
548        // Only the host's children count.
549        doc.remove(y);
550        assert!(doc.assigned_nodes(s1).is_empty());
551        #[cfg(debug_assertions)]
552        doc.check_tree();
553    }
554
555    #[test]
556    fn attach_shadow_as_the_dom_has_it() {
557        let mut doc = parse(
558            "<div id=d><template shadowrootmode=open>x</template></div><p id=p></p>\
559             <progress id=g></progress><my-el id=c></my-el>",
560            false,
561        );
562        let (d, p, g, c) = (
563            by_id(&doc, "d"),
564            by_id(&doc, "p"),
565            by_id(&doc, "g"),
566            by_id(&doc, "c"),
567        );
568        assert_eq!(
569            doc.attach_shadow(g, ShadowRoot::open()),
570            Err(EditError::NotAShadowHost)
571        );
572        assert!(doc.attach_shadow(c, ShadowRoot::closed()).is_ok());
573        let root = doc.attach_shadow(p, ShadowRoot::open()).unwrap();
574        assert_eq!(
575            doc.attach_shadow(p, ShadowRoot::open()),
576            Err(EditError::NotAShadowHost)
577        );
578        let text = doc.create_text("t");
579        assert_eq!(
580            doc.attach_shadow(text, ShadowRoot::open()),
581            Err(EditError::NotAShadowHost)
582        );
583        // A declared root: a mismatched mode is refused, a matching one
584        // gets it back emptied, once.
585        let declared = doc.shadow_root(d).unwrap();
586        assert_eq!(
587            doc.attach_shadow(d, ShadowRoot::closed()),
588            Err(EditError::NotAShadowHost)
589        );
590        assert_eq!(doc.attach_shadow(d, ShadowRoot::open()), Ok(declared));
591        assert_eq!(doc.first_child(declared), None);
592        assert_eq!(
593            doc.attach_shadow(d, ShadowRoot::open()),
594            Err(EditError::NotAShadowHost)
595        );
596        // Shadow roots are never children, and a host can't go into its
597        // own shadow tree.
598        let div = doc.create_element(Ns::Html, "div").unwrap();
599        assert_eq!(doc.append(div, root), Err(EditError::NotInsertable));
600        doc.append(root, div).unwrap();
601        assert_eq!(doc.append(div, p), Err(EditError::Cycle));
602        assert_eq!(doc.append(root, p), Err(EditError::Cycle));
603        #[cfg(debug_assertions)]
604        doc.check_tree();
605    }
606
607    #[test]
608    fn only_documents_and_asked_for_fragments_get_declarative_roots() {
609        let html = "<div><template shadowrootmode=open><b></b></template></div>";
610        let hosts = |doc: &Document| {
611            (0..doc.len() as NodeId)
612                .filter(|&n| doc.shadow_root(n).is_some())
613                .count()
614        };
615        assert_eq!(hosts(&parse(html, false)), 1);
616        assert_eq!(hosts(&parse_fragment(html, Ns::Html, "div", false)), 0);
617        let on = Options {
618            declarative_shadow_roots: Some(true),
619            ..Options::default()
620        };
621        let off = Options {
622            declarative_shadow_roots: Some(false),
623            ..Options::default()
624        };
625        assert_eq!(
626            hosts(&parse_fragment_with(html, Ns::Html, "div", on).unwrap()),
627            1
628        );
629        assert_eq!(hosts(&parse_with(html, off).unwrap()), 0);
630        // The context element is never the host: it isn't in the result.
631        let doc = parse_fragment_with(
632            "<template shadowrootmode=open></template>",
633            Ns::Html,
634            "div",
635            on,
636        )
637        .unwrap();
638        assert_eq!(hosts(&doc), 0);
639        assert_eq!(
640            doc.inner_html(0),
641            "<template shadowrootmode=\"open\"></template>"
642        );
643        // Nor the html element.
644        let doc = parse("<template shadowrootmode=open></template>", false);
645        assert_eq!(hosts(&doc), 0);
646    }
647
648    #[test]
649    fn a_shadow_root_is_built_alike_in_pieces() {
650        let html = "<div id=h><template shadowrootmode=closed shadowrootserializable>\
651                    <p>a<b>b</template>c</div><span><template shadowrootmode=open>x</template></span>";
652        let options = Options {
653            spans: true,
654            ..Options::default()
655        };
656        let whole = parse_with(html, options).unwrap();
657        let dump = |doc: &Document| {
658            doc.serialize_with(
659                0,
660                &SerializeOptions {
661                    html5test: true,
662                    ..SerializeOptions::default()
663                },
664            )
665        };
666        assert!(dump(&whole).contains("#shadow-root (closed serializable)"));
667        for size in 1..8 {
668            let mut parser = Parser::new(options);
669            for piece in html.as_bytes().chunks(size) {
670                parser.feed(std::str::from_utf8(piece).unwrap());
671            }
672            let doc = parser.finish().unwrap();
673            #[cfg(debug_assertions)]
674            doc.check_tree();
675            assert_eq!(dump(&doc), dump(&whole));
676        }
677        let root = whole.shadow_root(by_id(&whole, "h")).unwrap();
678        let p = whole.first_child(root).unwrap();
679        let at = html.find("<p>").unwrap();
680        assert_eq!(whole.span(p), Some(at..at + 3));
681    }
682
683    #[test]
684    fn get_html_writes_the_roots_asked_for() {
685        let doc = parse(
686            "<div id=a><template shadowrootmode=open shadowrootserializable>\
687               <span id=b><template shadowrootmode=closed>in</template></span>\
688             </template>light</div>",
689            false,
690        );
691        let a = by_id(&doc, "a");
692        assert_eq!(doc.outer_html(a), "<div id=\"a\">light</div>");
693        let serializable = SerializeOptions {
694            serializable_shadow_roots: true,
695            ..SerializeOptions::default()
696        };
697        assert_eq!(
698            doc.serialize_with(a, &serializable),
699            "<div id=\"a\"><template shadowrootmode=\"open\" shadowrootserializable=\"\">\
700             <span id=\"b\"></span></template>light</div>"
701        );
702        let b = by_id(&doc, "b");
703        let inner = doc.shadow_root(b).unwrap();
704        let listed = SerializeOptions {
705            serializable_shadow_roots: true,
706            shadow_roots: vec![inner],
707            ..SerializeOptions::default()
708        };
709        assert_eq!(
710            doc.serialize_with(a, &listed),
711            "<div id=\"a\"><template shadowrootmode=\"open\" shadowrootserializable=\"\">\
712             <span id=\"b\"><template shadowrootmode=\"closed\">in</template></span></template>\
713             light</div>"
714        );
715        // A shadow root's own markup is its children's.
716        let outer = doc.shadow_root(a).unwrap();
717        assert_eq!(doc.inner_html(outer), "<span id=\"b\"></span>");
718        // What was written parses back to the same tree.
719        let again = parse(&doc.serialize_with(0, &listed), false);
720        let b_again = by_id(&again, "b");
721        let listed_again = SerializeOptions {
722            shadow_roots: vec![again.shadow_root(b_again).unwrap()],
723            ..listed.clone()
724        };
725        assert_eq!(
726            again.serialize_with(0, &listed_again),
727            doc.serialize_with(0, &listed)
728        );
729        // Pretty-printing keeps the template whole.
730        let pretty = SerializeOptions {
731            pretty: true,
732            ..listed
733        };
734        let printed = doc.serialize_with(a, &pretty);
735        assert!(printed.contains("<template shadowrootmode=\"closed\">in</template>"));
736    }
737
738    #[test]
739    fn host_selectors_match_inside_the_shadow_tree_only() {
740        let doc = parse(
741            "<section class=ctx><div id=host class=h>\
742               <template shadowrootmode=open><p id=top></p><div id=d><p id=deep></p></div>\
743               <slot id=s></slot></template>\
744               <span id=l class=l></span><i id=other></i></div></section>",
745            false,
746        );
747        let host = by_id(&doc, "host");
748        let root = doc.shadow_root(host).unwrap();
749        let select = |css: &str, scope: NodeId| {
750            ids(&doc, &SelectorList::parse(css).unwrap().select(&doc, scope))
751        };
752        let matches = |css: &str, el: &str, scope: Option<NodeId>| {
753            SelectorList::parse(css)
754                .unwrap()
755                .matches(&doc, by_id(&doc, el), scope)
756        };
757        // The host stands in for the root.
758        assert_eq!(select(":host > p", root), ["top"]);
759        assert_eq!(select(":host p", root), ["top", "deep"]);
760        assert_eq!(select(":host(.h) > *", root), ["top", "d", "s"]);
761        assert!(select(":host(.nope) p", root).is_empty());
762        assert_eq!(select(":host-context(.ctx) p", root), ["top", "deep"]);
763        assert!(select(":host-context(.nope) p", root).is_empty());
764        // Featureless: nothing but :host matches the host, and it has no
765        // parent or siblings here.
766        assert!(matches(":host", "host", Some(root)));
767        assert!(matches(":is(:host(div))", "host", Some(root)));
768        assert!(!matches("div", "host", Some(root)));
769        assert!(!matches("*", "host", Some(root)));
770        assert!(select("section p", root).is_empty());
771        assert!(select("section :host p", root).is_empty());
772        // From an element inside, the tree is its own.
773        assert!(matches(":host > p", "top", None));
774        // Outside the shadow tree :host is nothing, and select from the
775        // document doesn't go into shadow roots.
776        assert!(!matches(":host", "host", None));
777        assert!(select("p", 0).is_empty());
778        // ::slotted(): elements assigned to a slot in this tree.
779        assert!(matches("::slotted(.l)", "l", Some(root)));
780        assert!(matches("slot::slotted(span)", "l", Some(root)));
781        assert!(matches(":host > slot::slotted(*)", "l", Some(root)));
782        assert!(!matches("::slotted(i)", "l", Some(root)));
783        assert!(!matches("p::slotted(span)", "l", Some(root)));
784        assert!(!matches("::slotted(span)", "l", None));
785        // Pseudo-elements never come out of select.
786        assert!(select("::slotted(*)", root).is_empty());
787        // :host()'s argument sees the host as it is outside, light
788        // children and all.
789        assert!(matches(":host(:has(> span.l))", "host", Some(root)));
790        assert!(!matches(":host(:has(> p))", "host", Some(root)));
791    }
792
793    #[test]
794    fn host_and_slotted_selectors_parse_with_compound_arguments() {
795        for ok in [
796            ":host",
797            ":host(div.x)",
798            ":host(:is(.a, .b + .c))",
799            ":host-context(body)",
800            "::slotted(span)",
801            "slot::slotted(*)::before",
802            ":not(:host)",
803        ] {
804            assert!(SelectorList::parse(ok).is_ok(), "{ok}");
805        }
806        for bad in [
807            ":host(div p)",
808            ":host(:not(.a .b))",
809            ":host-context(a > b)",
810            "::slotted(a b)",
811            "::slotted(span).x",
812            "::slotted(span) p",
813            ":host-context",
814        ] {
815            assert!(SelectorList::parse(bad).is_err(), "{bad}");
816        }
817        let spec = |s: &str| SelectorList::parse(s).unwrap().specificity();
818        assert_eq!(spec(":host"), (0, 1, 0));
819        assert_eq!(spec(":host(div.x)"), (0, 2, 1));
820        assert_eq!(spec("::slotted(.x)"), (0, 1, 1));
821    }
822}