script/dom/html/interactive/htmldialogelement.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/. */
4use std::cell::Cell;
5use std::rc::Rc;
6
7use app_units::Au;
8use dom_struct::dom_struct;
9use euclid::Point2D;
10use html5ever::{LocalName, Prefix, local_name, ns};
11use js::context::{JSContext, NoGC};
12use js::rust::HandleObject;
13use script_bindings::cell::DomRefCell;
14use script_bindings::codegen::GenericBindings::EventBinding::EventMethods;
15use script_bindings::codegen::GenericBindings::HTMLElementBinding::HTMLElementMethods;
16use script_bindings::domstring::TracedDOMString;
17use script_bindings::error::{Error, ErrorResult};
18use script_bindings::root::Dom;
19use stylo_dom::ElementState;
20
21use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods;
22use crate::dom::bindings::inheritance::Castable;
23use crate::dom::bindings::refcounted::Trusted;
24use crate::dom::bindings::root::{DomRoot, MutNullableDom};
25use crate::dom::bindings::str::DOMString;
26use crate::dom::closewatcher::internalclosewatcher::{
27 InternalCloseWatcher, InternalCloseWatcherOwner,
28};
29use crate::dom::document::Document;
30use crate::dom::element::storage::AttrRef;
31use crate::dom::element::{AttributeMutation, Element};
32use crate::dom::event::{Event, EventBubbles, EventCancelable};
33use crate::dom::eventtarget::EventTarget;
34use crate::dom::html::htmlelement::HTMLElement;
35use crate::dom::htmlbuttonelement::{CommandState, HTMLButtonElement};
36use crate::dom::iterators::ShadowIncluding;
37use crate::dom::mouseevent::MouseEvent;
38use crate::dom::node::focus::FocusTrigger;
39use crate::dom::node::virtualmethods::VirtualMethods;
40use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
41use crate::dom::pointerevent::PointerEvent;
42use crate::dom::toggleevent::ToggleEvent;
43
44#[dom_struct]
45pub(crate) struct HTMLDialogElement {
46 htmlelement: HTMLElement,
47 return_value: DomRefCell<TracedDOMString>,
48 /// <https://html.spec.whatwg.org/multipage/#dialog-close-watcher>
49 #[conditional_malloc_size_of]
50 close_watcher: DomRefCell<Option<Rc<InternalCloseWatcher>>>,
51 /// <https://html.spec.whatwg.org/multipage/#request-close-return-value>
52 request_close_return_value: DomRefCell<Option<TracedDOMString>>,
53 /// <https://html.spec.whatwg.org/multipage/#request-close-source-element>
54 request_close_source_element: MutNullableDom<Element>,
55 /// <https://html.spec.whatwg.org/multipage/#enable-close-watcher-for-requestclose()>
56 enable_close_watcher_for_request_close: Cell<bool>,
57}
58
59impl HTMLDialogElement {
60 fn new_inherited(
61 local_name: LocalName,
62 prefix: Option<Prefix>,
63 document: &Document,
64 ) -> HTMLDialogElement {
65 HTMLDialogElement {
66 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
67 return_value: DomRefCell::new(DOMString::new().traced()),
68 close_watcher: Default::default(),
69 request_close_return_value: Default::default(),
70 request_close_source_element: Default::default(),
71 enable_close_watcher_for_request_close: Default::default(),
72 }
73 }
74
75 pub(crate) fn new(
76 cx: &mut js::context::JSContext,
77 local_name: LocalName,
78 prefix: Option<Prefix>,
79 document: &Document,
80 proto: Option<HandleObject>,
81 ) -> DomRoot<HTMLDialogElement> {
82 Node::reflect_node_with_proto(
83 cx,
84 Box::new(HTMLDialogElement::new_inherited(
85 local_name, prefix, document,
86 )),
87 document,
88 proto,
89 )
90 }
91
92 /// <https://html.spec.whatwg.org/multipage/#show-a-modal-dialog>
93 pub(crate) fn show_a_modal(
94 &self,
95 cx: &mut js::context::JSContext,
96 source: Option<DomRoot<Element>>,
97 ) -> ErrorResult {
98 let subject = self.upcast::<Element>();
99 // Step 1. If subject has an open attribute and is modal of subject is true, then return.
100 if subject.has_attribute(&local_name!("open")) &&
101 subject.state().contains(ElementState::MODAL)
102 {
103 return Ok(());
104 }
105
106 // Step 2. If subject has an open attribute, then throw an "InvalidStateError" DOMException.
107 if subject.has_attribute(&local_name!("open")) {
108 return Err(Error::InvalidState(Some(
109 "Cannot call showModal() on an already open dialog.".into(),
110 )));
111 }
112
113 // Step 3. If subject's node document is not fully active, then throw an "InvalidStateError" DOMException.
114 if !subject.owner_document().is_fully_active() {
115 return Err(Error::InvalidState(Some(
116 "Cannot call showModal() on a dialog whose document is not fully active.".into(),
117 )));
118 }
119
120 // Step 4. If subject is not connected, then throw an "InvalidStateError" DOMException.
121 if !subject.is_connected() {
122 return Err(Error::InvalidState(Some(
123 "Cannot call showModal() on a dialog that is not connected.".into(),
124 )));
125 }
126
127 // TODO: Step 5. If subject is in the popover showing state, then throw an "InvalidStateError" DOMException.
128
129 // Step 6. If the result of firing an event named beforetoggle, using ToggleEvent, with the cancelable attribute initialized to true, the oldState attribute initialized to "closed", the newState attribute initialized to "open", and the source attribute initialized to source at subject is false, then return.
130 let event = ToggleEvent::new(
131 cx,
132 &self.owner_window(),
133 atom!("beforetoggle"),
134 EventBubbles::DoesNotBubble,
135 EventCancelable::Cancelable,
136 DOMString::from_static("closed"),
137 DOMString::from_static("open"),
138 source.as_deref(),
139 );
140 let event = event.upcast::<Event>();
141 if !event.fire(cx, self.upcast::<EventTarget>()) {
142 return Ok(());
143 }
144
145 // Step 7. If subject has an open attribute, then return.
146 if subject.has_attribute(&local_name!("open")) {
147 return Ok(());
148 }
149
150 // Step 8. If subject is not connected, then return.
151 if !subject.is_connected() {
152 return Ok(());
153 }
154
155 // TODO: Step 9. If subject is in the popover showing state, then return.
156
157 // Step 10. Queue a dialog toggle event task given subject, "closed", "open", and source.
158 self.queue_dialog_toggle_event_task("closed", "open", source);
159
160 // Step 11. Add an open attribute to subject, whose value is the empty string.
161 subject.set_bool_attribute(cx, &local_name!("open"), true);
162 subject.set_open_state(cx.no_gc(), true);
163
164 // Step 12. Assert: subject's close watcher is not null.
165 assert!(self.close_watcher.borrow().is_some());
166
167 // Step 13. Set is modal of subject to true.
168 self.upcast::<Element>().set_modal_state(cx.no_gc(), true);
169
170 // Step 14. Set subject's node document to be blocked by the modal dialog subject.
171 //
172 // This is computed based on the top layer.
173
174 // Step 15. If subject's node document's top layer does not already contain subject, then add an element to the top layer given subject.
175 // Note: Just checking the top layer would break when a modal is shown right after being closed, as the dialog would still be pending removal.
176 let document = subject.owner_document();
177 if !document.overlay_handler().is_in_the_top_layer(subject) {
178 document
179 .overlay_handler()
180 .add_an_element_to_the_top_layer(subject, cx.no_gc());
181 }
182
183 // Step 16. Set subject's previously focused element to the focused element.
184 self.upcast::<HTMLElement>().set_previously_focused_element(
185 self.owner_document()
186 .focus_handler()
187 .focused_area()
188 .element(),
189 cx.no_gc(),
190 );
191
192 // TODO: Step 17. Let document be subject's node document.
193
194 // TODO: Step 18. Let hideUntil be the result of running topmost popover ancestor given subject, document's showing hint popover list, null, and false.
195
196 // TODO: Step 19. If hideUntil is null, then set hideUntil to the result of running topmost popover ancestor given subject, document's showing auto popover list, null, and false.
197
198 // TODO: Step 20. If hideUntil is null, then set hideUntil to document.
199
200 // TODO: Step 21. Run hide all popovers until given hideUntil, false, and true.
201
202 // Step 22. Run the dialog focusing steps given subject.
203 self.run_dialog_focusing_steps(cx);
204 Ok(())
205 }
206
207 /// <https://html.spec.whatwg.org/multipage/#set-the-dialog-close-watcher>
208 pub(crate) fn set_the_close_watcher(&self, no_gc: &NoGC) {
209 // Step 1. Assert: dialog's close watcher is null.
210 assert!(self.close_watcher.borrow().is_none());
211
212 // Step 2. Assert: dialog has an open attribute and dialog's node document is fully active.
213 let dialog = self.upcast::<Element>();
214 assert!(
215 dialog.has_attribute(&local_name!("open")) && dialog.owner_document().is_fully_active()
216 );
217
218 // Step 3. Set dialog's close watcher to the result of establishing a close watcher given
219 // dialog's relevant global object, with:
220 // - cancelAction given canPreventClose being to return the result of firing an event named
221 // cancel at dialog, with the cancelable attribute initialized to canPreventClose.
222 // - closeAction being to close the dialog given dialog, dialog's request close return
223 // value, and dialog's request close source element.
224 // - getEnabledState being to return true if dialog's enable close watcher for request close
225 // is true or dialog's computed closed-by state is not None; otherwise false.
226 let close_watcher = InternalCloseWatcher::establish(
227 no_gc,
228 dialog.owner_document().window(),
229 &InternalCloseWatcherOwner::Dialog(Dom::from_ref(self)),
230 );
231 self.close_watcher
232 .safe_borrow_mut(no_gc)
233 .replace(close_watcher);
234 }
235
236 /// <https://html.spec.whatwg.org/multipage/#close-the-dialog>
237 pub(crate) fn close_the_dialog(
238 &self,
239 cx: &mut js::context::JSContext,
240 result: Option<DOMString>,
241 source: Option<DomRoot<Element>>,
242 ) {
243 let subject = self.upcast::<Element>();
244 // Step 1. If subject does not have an open attribute, then return.
245 if !subject.has_attribute(&local_name!("open")) {
246 return;
247 }
248
249 // Step 2. Fire an event named beforetoggle, using ToggleEvent, with the oldState attribute initialized to "open", the newState attribute initialized to "closed", and the source attribute initialized to source at subject.
250 let event = ToggleEvent::new(
251 cx,
252 &self.owner_window(),
253 atom!("beforetoggle"),
254 EventBubbles::DoesNotBubble,
255 EventCancelable::NotCancelable,
256 DOMString::from_static("open"),
257 DOMString::from_static("closed"),
258 source.as_deref(),
259 );
260 let event = event.upcast::<Event>();
261 event.fire(cx, self.upcast::<EventTarget>());
262
263 // Step 3. If subject does not have an open attribute, then return.
264 if !subject.has_attribute(&local_name!("open")) {
265 return;
266 }
267
268 // Step 4. Queue a dialog toggle event task given subject, "open", "closed", and source.
269 self.queue_dialog_toggle_event_task("open", "closed", source);
270
271 // Step 5. Remove subject's open attribute.
272 subject.remove_attribute(cx, &ns!(), &local_name!("open"));
273 subject.set_open_state(cx.no_gc(), false);
274
275 // Step 6. If is modal of subject is true, then request an element to be removed from the top layer given subject.
276 if subject.state().contains(ElementState::MODAL) {
277 subject
278 .owner_document()
279 .overlay_handler()
280 .request_an_element_to_be_removed_from_the_top_layer(subject, cx.no_gc());
281 }
282
283 // Step 7. Let wasModal be the value of subject's is modal flag.
284 let was_modal = subject.state().contains(ElementState::MODAL);
285
286 // Step 8. Set is modal of subject to false.
287 self.upcast::<Element>().set_modal_state(cx.no_gc(), false);
288
289 // Step 9. If result is not null, then set subject's returnValue attribute to result.
290 if let Some(new_value) = result {
291 *self.return_value.safe_borrow_mut(cx.no_gc()) = new_value.traced();
292 }
293
294 // Step 10. Set subject's request close return value to null.
295 *self.request_close_return_value.safe_borrow_mut(cx) = None;
296
297 // Step 11. Set subject's request close source element to null.
298 self.request_close_source_element.set(None);
299
300 // Step 12. If subject's previously focused element is not null, then:
301 if let Some(element) = self
302 .upcast::<HTMLElement>()
303 .previously_focused_element(cx.no_gc())
304 {
305 // Step 12.1. Let element be subject's previously focused element.
306 // Step 12.2. Set subject's previously focused element to null.
307 self.upcast::<HTMLElement>()
308 .set_previously_focused_element(None, cx.no_gc());
309
310 // Step 12.3. If subject's node document's focused area of the document's DOM anchor is
311 // a shadow-including inclusive descendant of subject, or wasModal is true, then run the
312 // focusing steps for element; the viewport should not be scrolled by doing this step.
313 let subject_node = subject.upcast::<Node>();
314 let document = subject.owner_document();
315 if document
316 .focus_handler()
317 .focused_area()
318 .dom_anchor(&document)
319 .traverse_preorder(ShadowIncluding::Yes)
320 .any(|node| &*node == subject_node) ||
321 was_modal
322 {
323 element
324 .upcast::<Node>()
325 .run_the_focusing_steps(cx, None, FocusTrigger::Script);
326 }
327 }
328
329 // Step 13. Queue an element task on the user interaction task source given the subject element to fire an event named close at subject.
330 let target = self.upcast::<EventTarget>();
331 self.owner_global()
332 .task_manager()
333 .user_interaction_task_source()
334 .queue_simple_event(target, atom!("close"));
335 }
336
337 /// <https://html.spec.whatwg.org/multipage/#dialog-request-close>
338 pub(crate) fn request_to_close(
339 &self,
340 cx: &mut JSContext,
341 return_value: Option<DOMString>,
342 source: Option<DomRoot<Element>>,
343 ) {
344 let subject = self.upcast::<Element>();
345
346 // Step 1. If subject does not have an open attribute, then return.
347 if !subject.has_attribute(&local_name!("open")) {
348 return;
349 }
350
351 // Step 2. If subject is not connected or subject's node document is not fully active, then
352 // return.
353 if !subject.is_connected() || !subject.owner_document().is_fully_active() {
354 return;
355 }
356
357 // Step 3. Assert: subject's close watcher is not null.
358 //
359 // Clone the handle so the cell isn't borrowed while script runs: a `close` listener can
360 // call `dialog.close()`, which runs `dialog_cleanup_steps` and nulls the close watcher.
361 let close_watcher = self
362 .close_watcher
363 .borrow()
364 .clone()
365 .expect("Close watcher must always exist");
366
367 // Step 4. Set subject's enable close watcher for request close to true.
368 self.enable_close_watcher_for_request_close.set(true);
369
370 // Step 5. Set subject's request close return value to returnValue.
371 *self.request_close_return_value.safe_borrow_mut(cx) = return_value.map(DOMString::traced);
372
373 // Step 6. Set subject's request close source element to source.
374 self.request_close_source_element.set(source.as_deref());
375
376 // Step 7. Request to close subject's close watcher with false.
377 close_watcher.request_to_close(cx, false);
378
379 // Step 8. Set subject's enable close watcher for request close to false.
380 self.enable_close_watcher_for_request_close.set(false);
381 }
382
383 /// <https://html.spec.whatwg.org/multipage/#queue-a-dialog-toggle-event-task>
384 pub(crate) fn queue_dialog_toggle_event_task(
385 &self,
386 old_state: &'static str,
387 new_state: &'static str,
388 source: Option<DomRoot<Element>>,
389 ) {
390 // TODO: Step 1. If element's dialog toggle task tracker is not null, then:
391 // TODO: Step 1.1. Set oldState to element's dialog toggle task tracker's old state.
392 // TODO: Step 1.2. Remove element's dialog toggle task tracker's task from its task queue.
393 // TODO: Step 1.3. Set element's dialog toggle task tracker to null.
394 // Step 2. Queue an element task given the DOM manipulation task source and element to run the following steps:
395 let this = Trusted::new(self);
396 let trusted_source = source.map(|el| Trusted::new(&*el));
397
398 self.owner_global()
399 .task_manager()
400 .dom_manipulation_task_source()
401 .queue(task!(fire_toggle_event: move |cx| {
402 let this = this.root();
403
404 let source = trusted_source.map(|s| s.root());
405
406 // Step 2.1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to oldState, the newState attribute initialized to newState, and the source attribute initialized to source.
407 let event = ToggleEvent::new(
408 cx,
409 &this.owner_window(),
410 atom!("toggle"),
411 EventBubbles::DoesNotBubble,
412 EventCancelable::NotCancelable,
413 DOMString::from_static(old_state),
414 DOMString::from_static(new_state),
415 source.as_deref(),
416 );
417 let event = event.upcast::<Event>();
418 event.fire(cx, this.upcast::<EventTarget>());
419
420 // TODO: Step 2.2. Set element's dialog toggle task tracker to null.
421 }));
422 // TODO: Step 3. Set element's dialog toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.
423 }
424
425 /// <https://html.spec.whatwg.org/multipage/#dialog-focusing-steps>
426 fn run_dialog_focusing_steps(&self, cx: &mut JSContext) {
427 // TODO: Step 1. If the allow focus steps given subject's node document return false, then return.
428
429 // Step 2. Let control be null.
430 rooted!(&in(cx) let mut control = None);
431
432 // Step 3. If subject has the autofocus attribute, then set control to subject.
433 if self.upcast::<HTMLElement>().Autofocus() {
434 control.set(
435 self.upcast::<Node>()
436 .get_the_focusable_area(cx, FocusTrigger::Script),
437 );
438 }
439
440 // Step 4. If control is null, then set control to the focus delegate of subject.
441 if control.is_none() {
442 control.set(self.upcast::<Node>().focus_delegate(cx, None));
443 }
444
445 // Step 5. If control is null, then set control to subject.
446 if control.is_none() {
447 control.set(
448 self.upcast::<Node>()
449 .get_the_focusable_area(cx, FocusTrigger::Script),
450 );
451 }
452
453 // Step 6. Run the focusing steps for control.
454 // FIXME: Use the focusing step once they support a focusable area as an argument
455 if control.is_some() {
456 let document = self.owner_document();
457 document
458 .focus_handler()
459 .focus(cx, &control.take().unwrap(), FocusTrigger::Script);
460 }
461
462 // TODO: Step 7. Let topDocument be control's node navigable's top-level traversable's active document.
463 // TODO: Step 8. If control's node document's origin is not the same as the origin of topDocument, then return.
464 // TODO: Step 9. Empty topDocument's autofocus candidates.
465 // TODO: Step 10. Set topDocument's autofocus processed flag to true.
466 }
467
468 /// <https://html.spec.whatwg.org/multipage/#dialog-setup-steps>
469 pub(crate) fn dialog_setup_steps(&self, no_gc: &NoGC) {
470 // Step 1. Assert: subject has an open attribute.
471 let subject = self.upcast::<Element>();
472 assert!(subject.has_attribute(&local_name!("open")));
473
474 // Step 2. Assert: subject is connected.
475 assert!(subject.is_connected());
476
477 // Step 3. Assert: subject's node document's open dialogs list does not contain subject.
478 let document = subject.owner_document();
479 assert!(!document.overlay_handler().open_dialogs_list_contains(self));
480
481 // Step 4. Add subject to subject's node document's open dialogs list.
482 document
483 .overlay_handler()
484 .add_to_open_dialogs_list(self, no_gc);
485
486 // Step 5. Set the dialog close watcher with subject.
487 self.set_the_close_watcher(no_gc);
488 }
489
490 /// <https://html.spec.whatwg.org/multipage/#dialog-setup-steps>
491 pub(crate) fn dialog_cleanup_steps(&self, no_gc: &NoGC) {
492 // Step 1. Remove subject from subject's node document's open dialogs list.
493 self.owner_document()
494 .overlay_handler()
495 .remove_from_open_dialogs_list(self, no_gc);
496
497 // Step 2. If subject's close watcher is not null, then:
498 // Step 2.1. Destroy subject's close watcher.
499 // Step 2.2. Set subject's close watcher to null.
500 let close_watcher = self.close_watcher.safe_borrow_mut(no_gc).take();
501 if let Some(close_watcher) = close_watcher {
502 close_watcher.destroy(no_gc);
503 }
504 }
505
506 pub(crate) fn close_watcher_close(&self, cx: &mut JSContext) {
507 let return_value = self
508 .request_close_return_value
509 .borrow()
510 .clone()
511 .map(TracedDOMString::root);
512 let source = self.request_close_source_element.get();
513 self.close_the_dialog(cx, return_value, source)
514 }
515
516 pub(crate) fn close_watcher_enabled_state(&self) -> bool {
517 self.enable_close_watcher_for_request_close.get() ||
518 self.computed_closed_by_state() != ComputedClosedByState::None
519 }
520
521 /// <https://html.spec.whatwg.org/multipage/#computed-closed-by-state>
522 fn computed_closed_by_state(&self) -> ComputedClosedByState {
523 let element = self.upcast::<Element>();
524
525 // Step 2. Return the state of dialog's closedby attribute.
526 if let Some(closed_by) = element.get_attribute_string_ref(&local_name!("closedby")) {
527 if closed_by.eq_ignore_ascii_case("any") {
528 return ComputedClosedByState::Any;
529 }
530 if closed_by.eq_ignore_ascii_case("closerequest") {
531 return ComputedClosedByState::CloseRequest;
532 }
533 if closed_by.eq_ignore_ascii_case("none") {
534 return ComputedClosedByState::None;
535 }
536 }
537
538 // Step 1. If the state of dialog's closedby attribute is Auto:
539 // https://html.spec.whatwg.org/multipage/#attr-dialog-closedby-auto-state
540 // > The closedby attribute's invalid value default and missing value default are both the
541 // > Auto state.
542
543 // Step 1.1. If dialog's is modal is true, then return Close Request.
544 if element.state().contains(ElementState::MODAL) {
545 return ComputedClosedByState::CloseRequest;
546 }
547
548 // Step 1.2. Return None.
549 ComputedClosedByState::None
550 }
551
552 /// <https://html.spec.whatwg.org/multipage/#light-dismiss-open-dialogs>
553 pub(crate) fn light_dismiss_open_dialogs(
554 cx: &mut JSContext,
555 pointer_event: &PointerEvent,
556 target: &EventTarget,
557 ) {
558 // Step 1. Assert: event's isTrusted attribute is true.
559 let event = pointer_event.upcast::<Event>();
560 assert!(event.IsTrusted());
561
562 // Step 2. Let document be event's target's node document.
563 let Some(target) = target.downcast::<Node>() else {
564 return;
565 };
566 let document = target.owner_doc();
567
568 // Step 3. If document's open dialogs list is empty, then return.
569 if document.overlay_handler().topmost_open_dialog().is_none() {
570 return;
571 }
572
573 // Step 4. Let ancestor be the result of running nearest clicked dialog given event.
574 let ancestor = Self::nearest_clicked_dialog(cx, pointer_event, target);
575
576 // Step 5. If event's type is "pointerdown", then set document's dialog pointerdown
577 // target to ancestor.
578 if event.type_() == *"pointerdown" {
579 document
580 .overlay_handler()
581 .set_dialog_pointerdown_target(ancestor.as_deref());
582 }
583
584 // Step 6. If event's type is "pointerup":
585 if event.type_() == *"pointerup" {
586 // Step 6.1. Let sameTarget be true if ancestor is document's dialog pointerdown target.
587 let same_target = ancestor == document.overlay_handler().dialog_pointerdown_target();
588
589 // Step 6.2. Set document's dialog pointerdown target to null.
590 document
591 .overlay_handler()
592 .set_dialog_pointerdown_target(None);
593
594 // Step 6.3. If sameTarget is false, then return.
595 if !same_target {
596 return;
597 }
598
599 // Step 6.4. Let topmostDialog be the last element of document's open dialogs list.
600 let Some(topmost_dialog) = document.overlay_handler().topmost_open_dialog() else {
601 return;
602 };
603
604 // Step 6.5. If ancestor is topmostDialog, then return.
605 if ancestor.as_ref() == Some(&topmost_dialog) {
606 return;
607 }
608
609 // Step 6.6. If topmostDialog's computed closed-by state is not Any, then return.
610 if topmost_dialog.computed_closed_by_state() != ComputedClosedByState::Any {
611 return;
612 }
613
614 // Step 6.7. Assert: topmostDialog's close watcher is not null.
615 let close_watcher = topmost_dialog
616 .close_watcher
617 .borrow()
618 .clone()
619 .expect("Open dialog must have a close watcher");
620
621 // Step 6.8. Request to close topmostDialog's close watcher with false.
622 close_watcher.request_to_close(cx, false);
623 }
624 }
625
626 /// <https://html.spec.whatwg.org/multipage/#nearest-clicked-dialog>
627 fn nearest_clicked_dialog(
628 cx: &mut JSContext,
629 pointer_event: &PointerEvent,
630 target: &Node,
631 ) -> Option<DomRoot<HTMLDialogElement>> {
632 // Step 1. Let target be event's target.
633 // Step 2. If target is a dialog element, target has an open attribute, target's is modal is
634 // true, and event's clientX and clientY are outside the bounds of target, then return null.
635 let point = pointer_event.upcast::<MouseEvent>().client_point();
636 let point = Point2D::new(Au::from_px(point.x), Au::from_px(point.y));
637 if target.is::<HTMLDialogElement>() &&
638 let Some(element) = target.downcast::<Element>() &&
639 element.has_attribute(&local_name!("open")) &&
640 element.state().contains(ElementState::MODAL) &&
641 target
642 .border_box(cx)
643 .is_some_and(|rect| !rect.contains(point))
644 {
645 return None;
646 }
647
648 // Step 3. Let currentNode be target.
649 let mut current_node = Some(DomRoot::from_ref(target));
650
651 // Step 4. While currentNode is not null:
652 while let Some(node) = current_node {
653 // Step 4.1. If currentNode is a dialog element and currentNode has an open attribute,
654 // then return currentNode.
655 if let Some(dialog) = node.downcast::<HTMLDialogElement>() &&
656 dialog
657 .upcast::<Element>()
658 .has_attribute(&local_name!("open"))
659 {
660 return Some(DomRoot::from_ref(dialog));
661 }
662
663 // Step 4.2. Set currentNode to currentNode's parent in the flat tree.
664 current_node = node
665 .parent_in_flat_tree(cx.no_gc())
666 .into_parent()
667 .map(|parent| parent.as_rooted());
668 }
669
670 // Step 5. Return null.
671 None
672 }
673}
674
675impl HTMLDialogElementMethods<crate::DomTypeHolder> for HTMLDialogElement {
676 // https://html.spec.whatwg.org/multipage/#dom-dialog-open
677 make_bool_getter!(Open, "open");
678
679 // https://html.spec.whatwg.org/multipage/#dom-dialog-open
680 make_bool_setter!(SetOpen, "open");
681
682 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue>
683 fn ReturnValue(&self) -> DOMString {
684 let return_value = self.return_value.borrow();
685 return_value.clone().root()
686 }
687
688 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue>
689 fn SetReturnValue(&self, cx: &mut JSContext, return_value: DOMString) {
690 *self.return_value.safe_borrow_mut(cx.no_gc()) = return_value.traced();
691 }
692
693 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-closedby>
694 fn ClosedBy(&self) -> DOMString {
695 // > The closedBy getter steps are to return the keyword
696 // > corresponding to the computed closed-by state given this.
697 match self.computed_closed_by_state() {
698 ComputedClosedByState::Any => DOMString::from_static("any"),
699 ComputedClosedByState::CloseRequest => DOMString::from_static("closerequest"),
700 ComputedClosedByState::None => DOMString::from_static("none"),
701 }
702 }
703
704 // https://html.spec.whatwg.org/multipage/#the-dialog-element:dom-dialog-closedby
705 make_setter!(SetClosedBy, "closedby");
706
707 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-show>
708 fn Show(&self, cx: &mut js::context::JSContext) -> ErrorResult {
709 let element = self.upcast::<Element>();
710 // Step 1. If this has an open attribute and is modal of this is false, then return.
711 if element.has_attribute(&local_name!("open")) &&
712 !element.state().contains(ElementState::MODAL)
713 {
714 return Ok(());
715 }
716
717 // Step 2. If this has an open attribute, then throw an "InvalidStateError" DOMException.
718 if element.has_attribute(&local_name!("open")) {
719 return Err(Error::InvalidState(Some(
720 "Cannot call show() on an already open dialog.".into(),
721 )));
722 }
723
724 // Step 3. If the result of firing an event named beforetoggle, using ToggleEvent, with the cancelable attribute initialized to true, the oldState attribute initialized to "closed", and the newState attribute initialized to "open" at this is false, then return.
725 let event = ToggleEvent::new(
726 cx,
727 &self.owner_window(),
728 atom!("beforetoggle"),
729 EventBubbles::DoesNotBubble,
730 EventCancelable::Cancelable,
731 DOMString::from_static("closed"),
732 DOMString::from_static("open"),
733 None,
734 );
735 let event = event.upcast::<Event>();
736 if !event.fire(cx, self.upcast::<EventTarget>()) {
737 return Ok(());
738 }
739
740 // Step 4. If this has an open attribute, then return.
741 if element.has_attribute(&local_name!("open")) {
742 return Ok(());
743 }
744
745 // Step 5. Queue a dialog toggle event task given this, "closed", "open", and null.
746 self.queue_dialog_toggle_event_task("closed", "open", None);
747
748 // Step 6. Add an open attribute to this, whose value is the empty string.
749 element.set_bool_attribute(cx, &local_name!("open"), true);
750 element.set_open_state(cx.no_gc(), true);
751
752 // Step 7. Set this's previously focused element to the focused element.
753 self.upcast::<HTMLElement>().set_previously_focused_element(
754 self.owner_document()
755 .focus_handler()
756 .focused_area()
757 .element(),
758 cx.no_gc(),
759 );
760
761 // TODO: Step 8. Let document be this's node document.
762
763 // TODO: Step 9. Let hideUntil be the result of running topmost popover ancestor given this, document's showing hint popover list, null, and false.
764
765 // TODO: Step 10. If hideUntil is null, then set hideUntil to the result of running topmost popover ancestor given this, document's showing auto popover list, null, and false.
766
767 // TODO: Step 11. If hideUntil is null, then set hideUntil to document.
768
769 // TODO: Step 12. Run hide all popovers until given hideUntil, false, and true.
770
771 // Step 13. Run the dialog focusing steps given this.
772 self.run_dialog_focusing_steps(cx);
773 Ok(())
774 }
775
776 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-showmodal>
777 fn ShowModal(&self, cx: &mut js::context::JSContext) -> ErrorResult {
778 // The showModal() method steps are to show a modal dialog given this and null.
779 self.show_a_modal(cx, None)
780 }
781
782 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-close>
783 fn Close(&self, cx: &mut js::context::JSContext, return_value: Option<DOMString>) {
784 // Step 1. If returnValue is not given, then set it to null.
785 // Step 2. Close the dialog this with returnValue and null.
786 self.close_the_dialog(cx, return_value, None);
787 }
788
789 /// <https://html.spec.whatwg.org/multipage/#dom-dialog-requestclose>
790 fn RequestClose(&self, cx: &mut js::context::JSContext, return_value: Option<DOMString>) {
791 // Step 1. If returnValue is not given, then set it to null.
792 // Step 2. Request to close the dialog this with returnValue and null.
793 self.request_to_close(cx, return_value, None);
794 }
795}
796
797impl VirtualMethods for HTMLDialogElement {
798 fn super_type(&self) -> Option<&dyn VirtualMethods> {
799 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
800 }
801
802 /// <https://html.spec.whatwg.org/multipage/#the-dialog-element:is-valid-command-steps>
803 fn is_valid_command_steps(&self, command: CommandState) -> bool {
804 // Step 1. If command is in the Close state, the Request Close state, or the
805 // ShowModal state, then return true.
806 if command == CommandState::Close ||
807 command == CommandState::RequestClose ||
808 command == CommandState::ShowModal
809 {
810 return true;
811 }
812
813 // Step 2. Return false.
814 false
815 }
816
817 /// <https://html.spec.whatwg.org/multipage/#the-dialog-element:command-steps>
818 fn command_steps(
819 &self,
820 cx: &mut js::context::JSContext,
821 source: DomRoot<HTMLButtonElement>,
822 command: CommandState,
823 ) -> bool {
824 if self
825 .super_type()
826 .unwrap()
827 .command_steps(cx, source.clone(), command)
828 {
829 return true;
830 }
831
832 // TODO Step 1. If element is in the popover showing state, then return.
833 let element = self.upcast::<Element>();
834
835 // Step 2. If command is in the Close state and element has an open attribute, then
836 // close the dialog element with source's optional value and source.
837 if command == CommandState::Close && element.has_attribute(&local_name!("open")) {
838 let button_element = DomRoot::from_ref(source.upcast::<Element>());
839 self.close_the_dialog(cx, source.optional_value(), Some(button_element));
840 return true;
841 }
842
843 // Step 3. If command is in the Request Close state and element has an open attribute,
844 // then request to close the dialog element with source's optional value and source.
845 if command == CommandState::RequestClose && element.has_attribute(&local_name!("open")) {
846 let button_element = DomRoot::from_ref(source.upcast::<Element>());
847 self.request_to_close(cx, source.optional_value(), Some(button_element));
848 return true;
849 }
850
851 // Step 4. If command is the Show Modal state and element does not have an open attribute,
852 // then show a modal dialog given element and source.
853 if command == CommandState::ShowModal && !element.has_attribute(&local_name!("open")) {
854 let button_element = DomRoot::from_ref(source.upcast::<Element>());
855 let _ = self.show_a_modal(cx, Some(button_element));
856 return true;
857 }
858
859 false
860 }
861
862 /// <https://html.spec.whatwg.org/multipage/#the-dialog-element:html-element-insertion-steps>
863 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
864 self.super_type().unwrap().bind_to_tree(cx, context);
865 let inserted_node = self.upcast::<Element>();
866
867 // Step 1. If insertedNode's node document is not fully active, then return.
868 if !inserted_node.owner_document().is_fully_active() {
869 return;
870 }
871
872 // Step 2. If insertedNode has an open attribute and is connected, then run the dialog setup
873 // steps given insertedNode.
874 if inserted_node.has_attribute(&local_name!("open")) && inserted_node.is_connected() {
875 self.dialog_setup_steps(cx.no_gc());
876 }
877 }
878
879 /// <https://html.spec.whatwg.org/multipage/#the-dialog-element:html-element-removing-steps>
880 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
881 self.super_type().unwrap().unbind_from_tree(cx, context);
882 let removed_node = self.upcast::<Element>();
883
884 // Step 1. If removedNode has an open attribute, then run the dialog cleanup steps given
885 // removedNode.
886 if removed_node.has_attribute(&local_name!("open")) {
887 self.dialog_cleanup_steps(cx.no_gc());
888 }
889
890 // Step 2. If removedNode's node document's top layer contains removedNode, then remove
891 // an element from the top layer immediately given removedNode.
892 let document = removed_node.owner_document();
893 if document.overlay_handler().top_layer_contains(removed_node) {
894 document
895 .overlay_handler()
896 .remove_an_element_from_the_top_layer_immediately(removed_node, cx.no_gc());
897 }
898
899 // Step 3. Set is modal of removedNode to false.
900 removed_node.set_modal_state(cx.no_gc(), false)
901 }
902
903 fn attribute_mutated(
904 &self,
905 cx: &mut js::context::JSContext,
906 attr: AttrRef<'_>,
907 mutation: AttributeMutation,
908 ) {
909 self.super_type()
910 .unwrap()
911 .attribute_mutated(cx, attr, mutation);
912
913 // Step 1. If namespace is not null, then return.
914 if *attr.namespace() != ns!() {
915 return;
916 }
917
918 // Step 2. If localName is not open, then return.
919 if attr.local_name() != &local_name!("open") {
920 return;
921 }
922
923 // Step 3. If value is null and oldValue is not null, then run the dialog cleanup steps
924 // given element.
925 if matches!(mutation, AttributeMutation::Removed) {
926 self.dialog_cleanup_steps(cx.no_gc());
927 return;
928 }
929
930 // Step 4. If element's node document is not fully active, then return.
931 let element = self.upcast::<Element>();
932 if !element.owner_document().is_fully_active() {
933 return;
934 }
935
936 // Step 5. If element is not connected, then return.
937 if !element.is_connected() {
938 return;
939 }
940
941 // Step 6. If value is not null and oldValue is null, then run the dialog setup steps given
942 // element.
943 if matches!(mutation, AttributeMutation::Set(None)) {
944 self.dialog_setup_steps(cx.no_gc());
945 }
946 }
947}
948
949#[derive(Copy, Clone, Eq, PartialEq, Debug)]
950pub(crate) enum ComputedClosedByState {
951 Any,
952 CloseRequest,
953 None,
954}