1use std::cell::{Cell, Ref};
6use std::collections::HashMap;
7use std::collections::hash_map::Entry;
8
9use dom_struct::dom_struct;
10use html5ever::{LocalName, Prefix, QualName, local_name, ns};
11use js::context::JSContext;
12use js::rust::HandleObject;
13use script_bindings::cell::DomRefCell;
14use script_bindings::domstring::DOMString;
15use style::selector_parser::PseudoElement;
16
17use crate::dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods;
18use crate::dom::bindings::codegen::Bindings::HTMLSlotElementBinding::HTMLSlotElement_Binding::HTMLSlotElementMethods;
19use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
20use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
21use crate::dom::bindings::codegen::UnionTypes::ElementOrText;
22use crate::dom::bindings::inheritance::Castable;
23use crate::dom::bindings::refcounted::Trusted;
24use crate::dom::bindings::reflector::DomGlobal;
25use crate::dom::bindings::root::{Dom, DomRoot};
26use crate::dom::document::Document;
27use crate::dom::element::attributes::storage::AttrRef;
28use crate::dom::element::{AttributeMutation, CustomElementCreationMode, Element, ElementCreator};
29use crate::dom::event::{Event, EventBubbles, EventCancelable};
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::html::htmlelement::HTMLElement;
32use crate::dom::html::htmlslotelement::HTMLSlotElement;
33use crate::dom::iterators::ShadowIncluding;
34use crate::dom::node::virtualmethods::VirtualMethods;
35use crate::dom::node::{
36 BindContext, ChildrenMutation, IsShadowTree, Node, NodeDamage, NodeTraits, UnbindContext,
37};
38use crate::dom::text::Text;
39use crate::dom::toggleevent::ToggleEvent;
40
41const DEFAULT_SUMMARY: &str = "Details";
43
44#[derive(Clone, JSTraceable, MallocSizeOf)]
49#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
50struct ShadowTree {
51 summary: Dom<HTMLSlotElement>,
52 details_content: Dom<HTMLSlotElement>,
53 implicit_summary: Dom<HTMLElement>,
55}
56
57#[dom_struct]
58pub(crate) struct HTMLDetailsElement {
59 htmlelement: HTMLElement,
60 toggle_counter: Cell<u32>,
61
62 shadow_tree: DomRefCell<Option<ShadowTree>>,
64}
65
66#[derive(Clone, Default, JSTraceable, MallocSizeOf)]
69#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
70pub(crate) struct DetailsNameGroups {
71 pub(crate) groups: HashMap<DOMString, Vec<Dom<HTMLDetailsElement>>>,
73}
74
75#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79enum ExclusivityConflictResolution {
80 CloseThisElement,
81 CloseExistingOpenElement,
82}
83
84impl DetailsNameGroups {
85 fn register_details_element(&mut self, details_element: &HTMLDetailsElement) {
86 let name = details_element.Name();
87 if name.is_empty() {
88 return;
89 }
90
91 debug!("Registering details element with name={name:?}");
92 let details_elements_with_the_same_name = self.groups.entry(name).or_default();
93
94 details_elements_with_the_same_name.push(Dom::from_ref(details_element));
96 }
97
98 fn unregister_details_element(
99 &mut self,
100 name: DOMString,
101 details_element: &HTMLDetailsElement,
102 ) {
103 if name.is_empty() {
104 return;
105 }
106
107 debug!("Unregistering details element with name={name:?}");
108 let Entry::Occupied(mut entry) = self.groups.entry(name) else {
109 panic!("details element is not registered");
110 };
111 entry
112 .get_mut()
113 .retain(|group_member| details_element != &**group_member);
114 }
115
116 fn group_members_for(
118 &self,
119 name: &DOMString,
120 details: &HTMLDetailsElement,
121 ) -> impl Iterator<Item = DomRoot<HTMLDetailsElement>> {
122 self.groups
123 .get(name)
124 .map(|members| members.iter())
125 .expect("No details element with the given name was registered for the tree")
126 .filter(move |member| **member != details)
127 .map(|member| member.as_rooted())
128 }
129}
130
131impl HTMLDetailsElement {
132 fn new_inherited(
133 local_name: LocalName,
134 prefix: Option<Prefix>,
135 document: &Document,
136 ) -> HTMLDetailsElement {
137 HTMLDetailsElement {
138 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
139 toggle_counter: Cell::new(0),
140 shadow_tree: Default::default(),
141 }
142 }
143
144 pub(crate) fn new(
145 cx: &mut js::context::JSContext,
146 local_name: LocalName,
147 prefix: Option<Prefix>,
148 document: &Document,
149 proto: Option<HandleObject>,
150 ) -> DomRoot<HTMLDetailsElement> {
151 Node::reflect_node_with_proto(
152 cx,
153 Box::new(HTMLDetailsElement::new_inherited(
154 local_name, prefix, document,
155 )),
156 document,
157 proto,
158 )
159 }
160
161 pub(crate) fn toggle(&self, cx: &mut JSContext) {
162 self.SetOpen(cx, !self.Open());
163 }
164
165 fn shadow_tree(&self, cx: &mut JSContext) -> Ref<'_, ShadowTree> {
166 if !self.upcast::<Element>().is_shadow_host() {
167 self.create_shadow_tree(cx);
168 }
169
170 Ref::filter_map(self.shadow_tree.borrow(), Option::as_ref)
171 .ok()
172 .expect("UA shadow tree was not created")
173 }
174
175 fn create_shadow_tree(&self, cx: &mut JSContext) {
176 let document = self.owner_document();
177 let root = self.upcast::<Element>().attach_ua_shadow_root(cx, true);
180
181 let summary = Element::create(
182 cx,
183 QualName::new(None, ns!(html), local_name!("slot")),
184 None,
185 &document,
186 ElementCreator::ScriptCreated,
187 CustomElementCreationMode::Asynchronous,
188 None,
189 );
190 let summary = DomRoot::downcast::<HTMLSlotElement>(summary).unwrap();
191 root.upcast::<Node>()
192 .AppendChild(cx, summary.upcast::<Node>())
193 .unwrap();
194
195 let fallback_summary = Element::create(
196 cx,
197 QualName::new(None, ns!(html), local_name!("summary")),
198 None,
199 &document,
200 ElementCreator::ScriptCreated,
201 CustomElementCreationMode::Asynchronous,
202 None,
203 );
204 let fallback_summary = DomRoot::downcast::<HTMLElement>(fallback_summary).unwrap();
205 fallback_summary
206 .upcast::<Node>()
207 .set_text_content_for_element(cx, Some(DEFAULT_SUMMARY.into()));
208 summary
209 .upcast::<Node>()
210 .AppendChild(cx, fallback_summary.upcast::<Node>())
211 .unwrap();
212
213 let details_content = Element::create(
214 cx,
215 QualName::new(None, ns!(html), local_name!("slot")),
216 None,
217 &document,
218 ElementCreator::ScriptCreated,
219 CustomElementCreationMode::Asynchronous,
220 None,
221 );
222 let details_content = DomRoot::downcast::<HTMLSlotElement>(details_content).unwrap();
223
224 root.upcast::<Node>()
225 .AppendChild(cx, details_content.upcast::<Node>())
226 .unwrap();
227 details_content
228 .upcast::<Node>()
229 .set_implemented_pseudo_element(PseudoElement::DetailsContent);
230
231 let _ = self.shadow_tree.borrow_mut().insert(ShadowTree {
232 summary: summary.as_traced(),
233 details_content: details_content.as_traced(),
234 implicit_summary: fallback_summary.as_traced(),
235 });
236 self.upcast::<Node>()
237 .dirty(crate::dom::node::NodeDamage::Other);
238 }
239
240 pub(crate) fn find_corresponding_summary_element(&self) -> Option<DomRoot<HTMLElement>> {
241 self.upcast::<Node>()
242 .children()
243 .filter_map(DomRoot::downcast::<HTMLElement>)
244 .find(|html_element| {
245 html_element.upcast::<Element>().local_name() == &local_name!("summary")
246 })
247 }
248
249 fn update_shadow_tree_contents(&self, cx: &mut JSContext) {
250 let shadow_tree = self.shadow_tree(cx);
251
252 if let Some(summary) = self.find_corresponding_summary_element() {
253 shadow_tree
254 .summary
255 .Assign(cx, vec![ElementOrText::Element(DomRoot::upcast(summary))]);
256 }
257
258 let mut slottable_children = vec![];
259 for child in self.upcast::<Node>().children() {
260 if let Some(element) = child.downcast::<Element>() {
261 if element.local_name() == &local_name!("summary") {
262 continue;
263 }
264
265 slottable_children.push(ElementOrText::Element(DomRoot::from_ref(element)));
266 }
267
268 if let Some(text) = child.downcast::<Text>() {
269 slottable_children.push(ElementOrText::Text(DomRoot::from_ref(text)));
270 }
271 }
272 shadow_tree.details_content.Assign(cx, slottable_children);
273 }
274
275 fn update_shadow_tree_styles(&self, cx: &mut JSContext) {
276 let shadow_tree = self.shadow_tree(cx);
277
278 let implicit_summary_list_item_style = if self.Open() {
282 "disclosure-open"
283 } else {
284 "disclosure-closed"
285 };
286 let implicit_summary_style = format!(
287 "display: list-item;
288 counter-increment: list-item 0;
289 list-style: {implicit_summary_list_item_style} inside;"
290 );
291 shadow_tree
292 .implicit_summary
293 .upcast::<Element>()
294 .set_string_attribute(cx, &local_name!("style"), implicit_summary_style.into());
295 }
296
297 fn ensure_details_exclusivity(
300 &self,
301 cx: &mut js::context::JSContext,
302 conflict_resolution_behaviour: ExclusivityConflictResolution,
303 ) {
304 if !self.Open() {
311 if conflict_resolution_behaviour ==
312 ExclusivityConflictResolution::CloseExistingOpenElement
313 {
314 unreachable!()
315 } else {
316 return;
317 }
318 }
319
320 let name = self.Name();
323 if name.is_empty() {
324 return;
325 }
326
327 let other_open_member = if let Some(shadow_root) = self.containing_shadow_root() {
335 shadow_root
336 .details_name_groups()
337 .group_members_for(&name, self)
338 .find(|group_member| group_member.Open())
339 } else if self.upcast::<Node>().is_in_a_document_tree() {
340 self.owner_document()
341 .details_name_groups()
342 .group_members_for(&name, self)
343 .find(|group_member| group_member.Open())
344 } else {
345 self.upcast::<Node>()
347 .GetRootNode(&GetRootNodeOptions::empty())
348 .traverse_preorder(ShadowIncluding::No)
349 .flat_map(DomRoot::downcast::<HTMLDetailsElement>)
350 .filter(|details_element| {
351 details_element
352 .upcast::<Element>()
353 .get_string_attribute(&local_name!("name")) ==
354 name
355 })
356 .filter(|group_member| &**group_member != self)
357 .find(|group_member| group_member.Open())
358 };
359
360 if let Some(other_open_member) = other_open_member {
361 match conflict_resolution_behaviour {
369 ExclusivityConflictResolution::CloseThisElement => self.SetOpen(cx, false),
370 ExclusivityConflictResolution::CloseExistingOpenElement => {
371 other_open_member.SetOpen(cx, false)
372 },
373 }
374 }
375 }
376}
377
378impl HTMLDetailsElementMethods<crate::DomTypeHolder> for HTMLDetailsElement {
379 make_getter!(Name, "name");
381
382 make_atomic_setter!(SetName, "name");
384
385 make_bool_getter!(Open, "open");
387
388 make_bool_setter!(SetOpen, "open");
390}
391
392impl VirtualMethods for HTMLDetailsElement {
393 fn super_type(&self) -> Option<&dyn VirtualMethods> {
394 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
395 }
396
397 fn attribute_mutated(
399 &self,
400 cx: &mut js::context::JSContext,
401 attr: AttrRef<'_>,
402 mutation: AttributeMutation,
403 ) {
404 self.super_type()
405 .unwrap()
406 .attribute_mutated(cx, attr, mutation);
407
408 if *attr.namespace() != ns!() {
410 return;
411 }
412
413 if attr.local_name() == &local_name!("name") {
416 let old_name: Option<DOMString> = match mutation {
417 AttributeMutation::Set(old, _) => old.map(|value| value.to_string().into()),
418 AttributeMutation::Removed => Some(attr.value().to_string().into()),
419 };
420
421 if let Some(shadow_root) = self.containing_shadow_root() {
422 if let Some(old_name) = old_name {
423 shadow_root
424 .details_name_groups()
425 .unregister_details_element(old_name, self);
426 }
427 if matches!(mutation, AttributeMutation::Set(..)) {
428 shadow_root
429 .details_name_groups()
430 .register_details_element(self);
431 }
432 } else if self.upcast::<Node>().is_in_a_document_tree() {
433 let document = self.owner_document();
434 if let Some(old_name) = old_name {
435 document
436 .details_name_groups()
437 .unregister_details_element(old_name, self);
438 }
439 if matches!(mutation, AttributeMutation::Set(..)) {
440 document
441 .details_name_groups()
442 .register_details_element(self);
443 }
444 }
445
446 self.ensure_details_exclusivity(cx, ExclusivityConflictResolution::CloseThisElement);
447 }
448 else if attr.local_name() == &local_name!("open") {
450 self.update_shadow_tree_styles(cx);
451
452 let counter = self.toggle_counter.get().wrapping_add(1);
453 self.toggle_counter.set(counter);
454 let (old_state, new_state) = if self.Open() {
455 ("closed", "open")
456 } else {
457 ("open", "closed")
458 };
459
460 let this = Trusted::new(self);
461 self.owner_global()
462 .task_manager()
463 .dom_manipulation_task_source()
464 .queue(task!(details_notification_task_steps: move |cx| {
465 let this = this.root();
466 if counter == this.toggle_counter.get() {
467 let event = ToggleEvent::new(
468 cx,
469 this.global().as_window(),
470 atom!("toggle"),
471 EventBubbles::DoesNotBubble,
472 EventCancelable::NotCancelable,
473 DOMString::from(old_state),
474 DOMString::from(new_state),
475 None,
476 );
477 let event = event.upcast::<Event>();
478 event.fire(cx, this.upcast::<EventTarget>());
479 }
480 }));
481 self.upcast::<Node>().dirty(NodeDamage::Other);
482
483 let was_previously_closed = match mutation {
486 AttributeMutation::Set(old, _) => old.is_none(),
487 AttributeMutation::Removed => false,
488 };
489 if was_previously_closed && self.Open() {
490 self.ensure_details_exclusivity(
491 cx,
492 ExclusivityConflictResolution::CloseExistingOpenElement,
493 );
494 }
495
496 self.upcast::<Element>().set_open_state(self.Open());
497 }
498 }
499
500 fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
501 self.super_type().unwrap().children_changed(cx, mutation);
502
503 self.update_shadow_tree_contents(cx);
504 }
505
506 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
508 self.super_type().unwrap().bind_to_tree(cx, context);
509
510 self.update_shadow_tree_contents(cx);
511 self.update_shadow_tree_styles(cx);
512
513 if context.tree_is_in_a_document_tree {
514 self.owner_document()
517 .details_name_groups()
518 .register_details_element(self);
519 }
520
521 let was_already_in_shadow_tree = context.is_shadow_tree == IsShadowTree::Yes;
522 if !was_already_in_shadow_tree && let Some(shadow_root) = self.containing_shadow_root() {
523 shadow_root
524 .details_name_groups()
525 .register_details_element(self);
526 }
527
528 self.ensure_details_exclusivity(cx, ExclusivityConflictResolution::CloseThisElement);
530 }
531
532 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
533 self.super_type().unwrap().unbind_from_tree(cx, context);
534
535 if context.tree_is_in_a_document_tree && !self.upcast::<Node>().is_in_a_document_tree() {
536 self.owner_document()
537 .details_name_groups()
538 .unregister_details_element(self.Name(), self);
539 }
540
541 if !self.upcast::<Node>().is_in_a_shadow_tree() &&
542 let Some(old_shadow_root) = self.containing_shadow_root()
543 {
544 old_shadow_root
547 .details_name_groups()
548 .unregister_details_element(self.Name(), self);
549 }
550 }
551}