script/dom/html/
htmlslotelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, Ref, RefCell};
6
7use dom_struct::dom_struct;
8use html5ever::{LocalName, Prefix, local_name, ns};
9use js::gc::RootedVec;
10use js::rust::HandleObject;
11use script_bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId};
12
13use crate::ScriptThread;
14use crate::dom::attr::Attr;
15use crate::dom::bindings::codegen::Bindings::HTMLSlotElementBinding::{
16    AssignedNodesOptions, HTMLSlotElementMethods,
17};
18use crate::dom::bindings::codegen::Bindings::NodeBinding::{GetRootNodeOptions, NodeMethods};
19use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
20use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
21    ShadowRootMode, SlotAssignmentMode,
22};
23use crate::dom::bindings::codegen::UnionTypes::ElementOrText;
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::root::{Dom, DomRoot};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::document::Document;
28use crate::dom::element::{AttributeMutation, Element};
29use crate::dom::globalscope::GlobalScope;
30use crate::dom::html::htmlelement::HTMLElement;
31use crate::dom::mutationobserver::MutationObserver;
32use crate::dom::node::{BindContext, Node, NodeDamage, NodeTraits, ShadowIncluding, UnbindContext};
33use crate::dom::virtualmethods::VirtualMethods;
34use crate::script_runtime::CanGc;
35
36/// <https://html.spec.whatwg.org/multipage/#the-slot-element>
37#[dom_struct]
38pub(crate) struct HTMLSlotElement {
39    htmlelement: HTMLElement,
40
41    /// <https://dom.spec.whatwg.org/#slot-assigned-nodes>
42    assigned_nodes: RefCell<Vec<Slottable>>,
43
44    /// <https://html.spec.whatwg.org/multipage/#manually-assigned-nodes>
45    manually_assigned_nodes: RefCell<Vec<Slottable>>,
46
47    /// Whether there is a queued signal change for this element
48    ///
49    /// Necessary to avoid triggering too many slotchange events
50    is_in_agents_signal_slots: Cell<bool>,
51}
52
53impl HTMLSlotElementMethods<crate::DomTypeHolder> for HTMLSlotElement {
54    // https://html.spec.whatwg.org/multipage/#dom-slot-name
55    make_getter!(Name, "name");
56
57    // https://html.spec.whatwg.org/multipage/#dom-slot-name
58    make_atomic_setter!(SetName, "name");
59
60    /// <https://html.spec.whatwg.org/multipage/#dom-slot-assignednodes>
61    fn AssignedNodes(&self, options: &AssignedNodesOptions) -> Vec<DomRoot<Node>> {
62        // Step 1. If options["flatten"] is false, then return this's assigned nodes.
63        if !options.flatten {
64            return self
65                .assigned_nodes
66                .borrow()
67                .iter()
68                .map(|slottable| slottable.node())
69                .map(DomRoot::from_ref)
70                .collect();
71        }
72
73        // Step 2. Return the result of finding flattened slottables with this.
74        rooted_vec!(let mut flattened_slottables);
75        self.find_flattened_slottables(&mut flattened_slottables);
76
77        flattened_slottables
78            .iter()
79            .map(|slottable| DomRoot::from_ref(slottable.node()))
80            .collect()
81    }
82
83    /// <https://html.spec.whatwg.org/multipage/#dom-slot-assignedelements>
84    fn AssignedElements(&self, options: &AssignedNodesOptions) -> Vec<DomRoot<Element>> {
85        self.AssignedNodes(options)
86            .into_iter()
87            .flat_map(|node| node.downcast::<Element>().map(DomRoot::from_ref))
88            .collect()
89    }
90
91    /// <https://html.spec.whatwg.org/multipage/#dom-slot-assign>
92    fn Assign(&self, nodes: Vec<ElementOrText>) {
93        let cx = GlobalScope::get_cx();
94
95        // Step 1. For each node of this's manually assigned nodes, set node's manual slot assignment to null.
96        for slottable in self.manually_assigned_nodes.borrow().iter() {
97            slottable.set_manual_slot_assignment(None);
98        }
99
100        // Step 2. Let nodesSet be a new ordered set.
101        rooted_vec!(let mut nodes_set);
102
103        // Step 3. For each node of nodes:
104        for element_or_text in nodes.into_iter() {
105            rooted!(in(*cx) let node = match element_or_text {
106                ElementOrText::Element(element) => Slottable(Dom::from_ref(element.upcast())),
107                ElementOrText::Text(text) => Slottable(Dom::from_ref(text.upcast())),
108            });
109
110            // Step 3.1 If node's manual slot assignment refers to a slot,
111            // then remove node from that slot's manually assigned nodes.
112            if let Some(slot) = node.manual_slot_assignment() {
113                let mut manually_assigned_nodes = slot.manually_assigned_nodes.borrow_mut();
114                if let Some(position) = manually_assigned_nodes
115                    .iter()
116                    .position(|value| *value == *node)
117                {
118                    manually_assigned_nodes.remove(position);
119                }
120            }
121
122            // Step 3.2 Set node's manual slot assignment to this.
123            node.set_manual_slot_assignment(Some(self));
124
125            // Step 3.3 Append node to nodesSet.
126            if !nodes_set.contains(&*node) {
127                nodes_set.push(node.clone());
128            }
129        }
130
131        // Step 4. Set this's manually assigned nodes to nodesSet.
132        *self.manually_assigned_nodes.borrow_mut() = nodes_set.iter().cloned().collect();
133
134        // Step 5. Run assign slottables for a tree for this's root.
135        self.upcast::<Node>()
136            .GetRootNode(&GetRootNodeOptions::empty())
137            .assign_slottables_for_a_tree();
138    }
139}
140
141/// <https://dom.spec.whatwg.org/#concept-slotable>
142///
143/// The contained node is assumed to be either `Element` or `Text`
144///
145/// This field is public to make it easy to construct slottables.
146/// As such, it is possible to put Nodes that are not slottables
147/// in there. Using a [Slottable] like this will quickly lead to
148/// a panic.
149#[derive(Clone, JSTraceable, MallocSizeOf, PartialEq)]
150#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
151#[repr(transparent)]
152pub(crate) struct Slottable(pub Dom<Node>);
153/// Data shared between all [slottables](https://dom.spec.whatwg.org/#concept-slotable)
154///
155/// Note that the [slottable name](https://dom.spec.whatwg.org/#slotable-name) is not
156/// part of this. While the spec says that all slottables have a name, only Element's
157/// can ever have a non-empty name, so they store it seperately
158#[derive(Default, JSTraceable, MallocSizeOf)]
159#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
160pub struct SlottableData {
161    /// <https://dom.spec.whatwg.org/#slotable-assigned-slot>
162    pub(crate) assigned_slot: Option<Dom<HTMLSlotElement>>,
163
164    /// <https://dom.spec.whatwg.org/#slottable-manual-slot-assignment>
165    pub(crate) manual_slot_assignment: Option<Dom<HTMLSlotElement>>,
166}
167
168impl HTMLSlotElement {
169    fn new_inherited(
170        local_name: LocalName,
171        prefix: Option<Prefix>,
172        document: &Document,
173    ) -> HTMLSlotElement {
174        HTMLSlotElement {
175            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
176            assigned_nodes: Default::default(),
177            manually_assigned_nodes: Default::default(),
178            is_in_agents_signal_slots: Default::default(),
179        }
180    }
181
182    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
183    pub(crate) fn new(
184        local_name: LocalName,
185        prefix: Option<Prefix>,
186        document: &Document,
187        proto: Option<HandleObject>,
188        can_gc: CanGc,
189    ) -> DomRoot<HTMLSlotElement> {
190        Node::reflect_node_with_proto(
191            Box::new(HTMLSlotElement::new_inherited(local_name, prefix, document)),
192            document,
193            proto,
194            can_gc,
195        )
196    }
197
198    pub(crate) fn has_assigned_nodes(&self) -> bool {
199        !self.assigned_nodes.borrow().is_empty()
200    }
201
202    /// <https://dom.spec.whatwg.org/#find-flattened-slotables>
203    fn find_flattened_slottables(&self, result: &mut RootedVec<Slottable>) {
204        // Step 1. Let result be an empty list.
205        debug_assert!(result.is_empty());
206
207        // Step 2. If slot’s root is not a shadow root, then return result.
208        if self.upcast::<Node>().containing_shadow_root().is_none() {
209            return;
210        };
211
212        // Step 3. Let slottables be the result of finding slottables given slot.
213        rooted_vec!(let mut slottables);
214        self.find_slottables(&mut slottables);
215
216        // Step 4. If slottables is the empty list, then append each slottable
217        // child of slot, in tree order, to slottables.
218        if slottables.is_empty() {
219            for child in self.upcast::<Node>().children() {
220                let is_slottable = matches!(
221                    child.type_id(),
222                    NodeTypeId::Element(_) |
223                        NodeTypeId::CharacterData(CharacterDataTypeId::Text(_))
224                );
225                if is_slottable {
226                    slottables.push(Slottable(child.as_traced()));
227                }
228            }
229        }
230
231        // Step 5. For each node in slottables:
232        for slottable in slottables.iter() {
233            // Step 5.1 If node is a slot whose root is a shadow root:
234            match slottable.0.downcast::<HTMLSlotElement>() {
235                Some(slot_element)
236                    if slot_element
237                        .upcast::<Node>()
238                        .containing_shadow_root()
239                        .is_some() =>
240                {
241                    // Step 5.1.1 Let temporaryResult be the result of finding flattened slottables given node.
242                    rooted_vec!(let mut temporary_result);
243                    slot_element.find_flattened_slottables(&mut temporary_result);
244
245                    // Step 5.1.2 Append each slottable in temporaryResult, in order, to result.
246                    result.extend_from_slice(&temporary_result);
247                },
248                // Step 5.2 Otherwise, append node to result.
249                _ => {
250                    result.push(slottable.clone());
251                },
252            };
253        }
254
255        // Step 6. Return result.
256    }
257
258    /// <https://dom.spec.whatwg.org/#find-slotables>
259    ///
260    /// To avoid rooting shenanigans, this writes the returned slottables
261    /// into the `result` argument
262    fn find_slottables(&self, result: &mut RootedVec<Slottable>) {
263        let cx = GlobalScope::get_cx();
264
265        // Step 1. Let result be an empty list.
266        debug_assert!(result.is_empty());
267
268        // Step 2. Let root be slot’s root.
269        // Step 3. If root is not a shadow root, then return result.
270        let Some(root) = self.upcast::<Node>().containing_shadow_root() else {
271            return;
272        };
273
274        // Step 4. Let host be root’s host.
275        let host = root.Host();
276
277        // Step 5. If root’s slot assignment is "manual":
278        if root.SlotAssignment() == SlotAssignmentMode::Manual {
279            // Step 5.1 Let result be « ».
280            // NOTE: redundant.
281
282            // Step 5.2 For each slottable slottable of slot’s manually assigned nodes,
283            // if slottable’s parent is host, append slottable to result.
284            for slottable in self.manually_assigned_nodes.borrow().iter() {
285                if slottable
286                    .node()
287                    .GetParentNode()
288                    .is_some_and(|node| &*node == host.upcast::<Node>())
289                {
290                    result.push(slottable.clone());
291                }
292            }
293        }
294        // Step 6. Otherwise, for each slottable child slottable of host, in tree order:
295        else {
296            for child in host.upcast::<Node>().children() {
297                let is_slottable = matches!(
298                    child.type_id(),
299                    NodeTypeId::Element(_) |
300                        NodeTypeId::CharacterData(CharacterDataTypeId::Text(_))
301                );
302                if is_slottable {
303                    rooted!(in(*cx) let slottable = Slottable(child.as_traced()));
304                    // Step 6.1 Let foundSlot be the result of finding a slot given slottable.
305                    let found_slot = slottable.find_a_slot(false);
306
307                    // Step 6.2 If foundSlot is slot, then append slottable to result.
308                    if found_slot.is_some_and(|found_slot| &*found_slot == self) {
309                        result.push(slottable.clone());
310                    }
311                }
312            }
313        }
314
315        // Step 7. Return result.
316    }
317
318    /// <https://dom.spec.whatwg.org/#assign-slotables>
319    pub(crate) fn assign_slottables(&self) {
320        // Step 1. Let slottables be the result of finding slottables for slot.
321        rooted_vec!(let mut slottables);
322        self.find_slottables(&mut slottables);
323
324        // Step 2. If slottables and slot’s assigned nodes are not identical,
325        // then run signal a slot change for slot.
326        let slots_are_identical = self.assigned_nodes.borrow().iter().eq(slottables.iter());
327        if !slots_are_identical {
328            self.signal_a_slot_change();
329        }
330
331        // NOTE: This is not written in the spec, which is likely a bug (https://github.com/whatwg/dom/issues/1352)
332        // If we don't disconnect the old slottables from this slot then they'll stay implictly
333        // connected, which causes problems later on
334        for slottable in self.assigned_nodes().iter() {
335            slottable.set_assigned_slot(None);
336        }
337
338        // Step 3. Set slot’s assigned nodes to slottables.
339        *self.assigned_nodes.borrow_mut() = slottables.iter().cloned().collect();
340
341        // Step 4. For each slottable in slottables, set slottable’s assigned slot to slot.
342        for slottable in slottables.iter() {
343            slottable.set_assigned_slot(Some(self));
344        }
345    }
346
347    /// <https://dom.spec.whatwg.org/#signal-a-slot-change>
348    pub(crate) fn signal_a_slot_change(&self) {
349        self.upcast::<Node>().dirty(NodeDamage::ContentOrHeritage);
350
351        if self.is_in_agents_signal_slots.get() {
352            return;
353        }
354        self.is_in_agents_signal_slots.set(true);
355
356        // Step 1. Append slot to slot’s relevant agent’s signal slots.
357        ScriptThread::add_signal_slot(self);
358
359        // Step 2. Queue a mutation observer microtask.
360        MutationObserver::queue_mutation_observer_microtask();
361    }
362
363    pub(crate) fn remove_from_signal_slots(&self) {
364        debug_assert!(self.is_in_agents_signal_slots.get());
365        self.is_in_agents_signal_slots.set(false);
366    }
367
368    /// Returns the slot's assigned nodes if the root's slot assignment mode
369    /// is "named", or the manually assigned nodes otherwise
370    pub(crate) fn assigned_nodes(&self) -> Ref<'_, [Slottable]> {
371        Ref::map(self.assigned_nodes.borrow(), Vec::as_slice)
372    }
373}
374
375impl Slottable {
376    /// <https://dom.spec.whatwg.org/#find-a-slot>
377    pub(crate) fn find_a_slot(&self, open_flag: bool) -> Option<DomRoot<HTMLSlotElement>> {
378        // Step 1. If slottable’s parent is null, then return null.
379        let parent = self.node().GetParentNode()?;
380
381        // Step 2. Let shadow be slottable’s parent’s shadow root.
382        // Step 3. If shadow is null, then return null.
383        let shadow_root = parent
384            .downcast::<Element>()
385            .and_then(Element::shadow_root)?;
386
387        // Step 4. If the open flag is set and shadow’s mode is not "open", then return null.
388        if open_flag && shadow_root.Mode() != ShadowRootMode::Open {
389            return None;
390        }
391
392        // Step 5. If shadow’s slot assignment is "manual", then return the slot in shadow’s descendants whose
393        // manually assigned nodes contains slottable, if any; otherwise null.
394        if shadow_root.SlotAssignment() == SlotAssignmentMode::Manual {
395            for node in shadow_root
396                .upcast::<Node>()
397                .traverse_preorder(ShadowIncluding::No)
398            {
399                if let Some(slot) = node.downcast::<HTMLSlotElement>() {
400                    if slot.manually_assigned_nodes.borrow().contains(self) {
401                        return Some(DomRoot::from_ref(slot));
402                    }
403                }
404            }
405            return None;
406        }
407
408        // Step 6. Return the first slot in tree order in shadow’s descendants whose
409        // name is slottable’s name, if any; otherwise null.
410        shadow_root.slot_for_name(&self.name())
411    }
412
413    /// <https://dom.spec.whatwg.org/#assign-a-slot>
414    pub(crate) fn assign_a_slot(&self) {
415        // Step 1. Let slot be the result of finding a slot with slottable.
416        let slot = self.find_a_slot(false);
417
418        // Step 2. If slot is non-null, then run assign slottables for slot.
419        if let Some(slot) = slot {
420            slot.assign_slottables();
421        }
422    }
423
424    fn node(&self) -> &Node {
425        &self.0
426    }
427
428    pub(crate) fn assigned_slot(&self) -> Option<DomRoot<HTMLSlotElement>> {
429        self.node().assigned_slot()
430    }
431
432    pub(crate) fn set_assigned_slot(&self, assigned_slot: Option<&HTMLSlotElement>) {
433        self.node().set_assigned_slot(assigned_slot);
434    }
435
436    pub(crate) fn set_manual_slot_assignment(
437        &self,
438        manually_assigned_slot: Option<&HTMLSlotElement>,
439    ) {
440        self.node()
441            .set_manual_slot_assignment(manually_assigned_slot);
442    }
443
444    pub(crate) fn manual_slot_assignment(&self) -> Option<DomRoot<HTMLSlotElement>> {
445        self.node().manual_slot_assignment()
446    }
447
448    fn name(&self) -> DOMString {
449        // NOTE: Only elements have non-empty names
450        let Some(element) = self.0.downcast::<Element>() else {
451            return DOMString::new();
452        };
453
454        element.get_string_attribute(&local_name!("slot"))
455    }
456}
457
458impl VirtualMethods for HTMLSlotElement {
459    fn super_type(&self) -> Option<&dyn VirtualMethods> {
460        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
461    }
462
463    /// <https://dom.spec.whatwg.org/#shadow-tree-slots>
464    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
465        self.super_type()
466            .unwrap()
467            .attribute_mutated(attr, mutation, can_gc);
468
469        if attr.local_name() == &local_name!("name") && attr.namespace() == &ns!() {
470            if let Some(shadow_root) = self.containing_shadow_root() {
471                // Shadow roots keep a list of slot descendants, so we need to tell it
472                // about our name change
473                let old_value = match mutation {
474                    AttributeMutation::Set(old) => old
475                        .map(|value| value.to_string().into())
476                        .unwrap_or_default(),
477                    AttributeMutation::Removed => attr.value().to_string().into(),
478                };
479
480                shadow_root.unregister_slot(old_value, self);
481                shadow_root.register_slot(self);
482            }
483
484            // Changing the name might cause slot assignments to change
485            self.upcast::<Node>()
486                .GetRootNode(&GetRootNodeOptions::empty())
487                .assign_slottables_for_a_tree()
488        }
489    }
490
491    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
492        if let Some(s) = self.super_type() {
493            s.bind_to_tree(context, can_gc);
494        }
495
496        if !context.tree_is_in_a_shadow_tree {
497            return;
498        }
499
500        self.containing_shadow_root()
501            .expect("not in a shadow tree")
502            .register_slot(self);
503    }
504
505    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
506        if let Some(s) = self.super_type() {
507            s.unbind_from_tree(context, can_gc);
508        }
509
510        if let Some(shadow_root) = self.containing_shadow_root() {
511            shadow_root.unregister_slot(self.Name(), self);
512        }
513    }
514}
515
516impl js::gc::Rootable for Slottable {}
517
518impl js::gc::Initialize for Slottable {
519    #[allow(unsafe_code)]
520    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
521    unsafe fn initial() -> Option<Self> {
522        None
523    }
524}