1use 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#[dom_struct]
38pub(crate) struct HTMLSlotElement {
39 htmlelement: HTMLElement,
40
41 assigned_nodes: RefCell<Vec<Slottable>>,
43
44 manually_assigned_nodes: RefCell<Vec<Slottable>>,
46
47 is_in_agents_signal_slots: Cell<bool>,
51}
52
53impl HTMLSlotElementMethods<crate::DomTypeHolder> for HTMLSlotElement {
54 make_getter!(Name, "name");
56
57 make_atomic_setter!(SetName, "name");
59
60 fn AssignedNodes(&self, options: &AssignedNodesOptions) -> Vec<DomRoot<Node>> {
62 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 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 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 fn Assign(&self, nodes: Vec<ElementOrText>) {
93 let cx = GlobalScope::get_cx();
94
95 for slottable in self.manually_assigned_nodes.borrow().iter() {
97 slottable.set_manual_slot_assignment(None);
98 }
99
100 rooted_vec!(let mut nodes_set);
102
103 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 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 node.set_manual_slot_assignment(Some(self));
124
125 if !nodes_set.contains(&*node) {
127 nodes_set.push(node.clone());
128 }
129 }
130
131 *self.manually_assigned_nodes.borrow_mut() = nodes_set.iter().cloned().collect();
133
134 self.upcast::<Node>()
136 .GetRootNode(&GetRootNodeOptions::empty())
137 .assign_slottables_for_a_tree();
138 }
139}
140
141#[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#[derive(Default, JSTraceable, MallocSizeOf)]
159#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
160pub struct SlottableData {
161 pub(crate) assigned_slot: Option<Dom<HTMLSlotElement>>,
163
164 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 fn find_flattened_slottables(&self, result: &mut RootedVec<Slottable>) {
204 debug_assert!(result.is_empty());
206
207 if self.upcast::<Node>().containing_shadow_root().is_none() {
209 return;
210 };
211
212 rooted_vec!(let mut slottables);
214 self.find_slottables(&mut slottables);
215
216 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 for slottable in slottables.iter() {
233 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 rooted_vec!(let mut temporary_result);
243 slot_element.find_flattened_slottables(&mut temporary_result);
244
245 result.extend_from_slice(&temporary_result);
247 },
248 _ => {
250 result.push(slottable.clone());
251 },
252 };
253 }
254
255 }
257
258 fn find_slottables(&self, result: &mut RootedVec<Slottable>) {
263 let cx = GlobalScope::get_cx();
264
265 debug_assert!(result.is_empty());
267
268 let Some(root) = self.upcast::<Node>().containing_shadow_root() else {
271 return;
272 };
273
274 let host = root.Host();
276
277 if root.SlotAssignment() == SlotAssignmentMode::Manual {
279 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 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 let found_slot = slottable.find_a_slot(false);
306
307 if found_slot.is_some_and(|found_slot| &*found_slot == self) {
309 result.push(slottable.clone());
310 }
311 }
312 }
313 }
314
315 }
317
318 pub(crate) fn assign_slottables(&self) {
320 rooted_vec!(let mut slottables);
322 self.find_slottables(&mut slottables);
323
324 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 for slottable in self.assigned_nodes().iter() {
335 slottable.set_assigned_slot(None);
336 }
337
338 *self.assigned_nodes.borrow_mut() = slottables.iter().cloned().collect();
340
341 for slottable in slottables.iter() {
343 slottable.set_assigned_slot(Some(self));
344 }
345 }
346
347 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 ScriptThread::add_signal_slot(self);
358
359 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 pub(crate) fn assigned_nodes(&self) -> Ref<'_, [Slottable]> {
371 Ref::map(self.assigned_nodes.borrow(), Vec::as_slice)
372 }
373}
374
375impl Slottable {
376 pub(crate) fn find_a_slot(&self, open_flag: bool) -> Option<DomRoot<HTMLSlotElement>> {
378 let parent = self.node().GetParentNode()?;
380
381 let shadow_root = parent
384 .downcast::<Element>()
385 .and_then(Element::shadow_root)?;
386
387 if open_flag && shadow_root.Mode() != ShadowRootMode::Open {
389 return None;
390 }
391
392 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 shadow_root.slot_for_name(&self.name())
411 }
412
413 pub(crate) fn assign_a_slot(&self) {
415 let slot = self.find_a_slot(false);
417
418 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 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 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 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 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}