1use std::default::Default;
5use std::rc::Rc;
6
7use dom_struct::dom_struct;
8use html5ever::{LocalName, Prefix, QualName, local_name, ns};
9use js::context::{JSContext, NoGC};
10use js::rust::HandleObject;
11use layout_api::{QueryMsg, ScrollContainerQueryFlags, ScrollContainerResponse};
12use rustc_hash::FxHashSet;
13use script_bindings::callback::RootedCallback;
14use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
15use script_bindings::codegen::GenericBindings::DocumentFragmentBinding::DocumentFragmentMethods;
16use script_bindings::codegen::GenericBindings::ElementBinding::ScrollLogicalPosition;
17use script_bindings::codegen::GenericBindings::WindowBinding::ScrollBehavior;
18use script_bindings::dom::UnrootedDom;
19use style::attr::AttrValue;
20use stylo_dom::ElementState;
21
22use crate::dom::NodeFlags;
23use crate::dom::activation::Activatable;
24use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterData_Binding::CharacterDataMethods;
25use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::{
26 EventHandlerNonNull, OnErrorEventHandlerNonNull,
27};
28use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::{
29 HTMLElementMethods, ShowPopoverOptions,
30};
31use crate::dom::bindings::codegen::Bindings::HTMLLabelElementBinding::HTMLLabelElementMethods;
32use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
33use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
34use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
35use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
36use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
37use crate::dom::bindings::codegen::UnionTypes::TogglePopoverOptionsOrBoolean;
38use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
39use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
40use crate::dom::bindings::refcounted::Trusted;
41use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
42use crate::dom::bindings::str::DOMString;
43use crate::dom::characterdata::CharacterData;
44use crate::dom::closewatcher::internalclosewatcher::{
45 InternalCloseWatcher, InternalCloseWatcherOwner,
46};
47use crate::dom::css::cssstyledeclaration::{
48 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
49};
50use crate::dom::customelementregistry::{CustomElementRegistry, CustomElementState};
51use crate::dom::document::Document;
52use crate::dom::document::focus::FocusableArea;
53use crate::dom::document_event_handler::character_to_code;
54use crate::dom::documentfragment::DocumentFragment;
55use crate::dom::domstringmap::DOMStringMap;
56use crate::dom::element::attributes::storage::AttrRef;
57use crate::dom::element::{
58 AttributeMutation, CustomElementCreationMode, Element, ElementCreator,
59 is_element_affected_by_legacy_background_presentational_hint,
60};
61use crate::dom::event::{Event, EventBubbles, EventCancelable};
62use crate::dom::eventtarget::EventTarget;
63use crate::dom::html::form_controls::htmlbuttonelement::HTMLButtonElement;
64use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
65use crate::dom::html::form_controls::input_type::InputType;
66use crate::dom::html::htmlbodyelement::HTMLBodyElement;
67use crate::dom::html::htmldetailselement::HTMLDetailsElement;
68use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
69use crate::dom::html::htmlframesetelement::HTMLFrameSetElement;
70use crate::dom::html::htmlhtmlelement::HTMLHtmlElement;
71use crate::dom::html::htmllabelelement::HTMLLabelElement;
72use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
73use crate::dom::html::interactive::htmldialogelement::HTMLDialogElement;
74use crate::dom::html::internals::elementinternals::ElementInternals;
75use crate::dom::htmlelement::PopoverState::NoPopover;
76use crate::dom::htmlformelement::FormControlElementHelpers;
77use crate::dom::iterators::ShadowIncluding;
78use crate::dom::medialist::MediaList;
79use crate::dom::node::focus::FocusTrigger;
80use crate::dom::node::virtualmethods::VirtualMethods;
81use crate::dom::node::{
82 BindContext, MoveContext, Node, NodeDamage, NodeTraits, UnbindContext,
83 from_untrusted_node_address,
84};
85use crate::dom::shadowroot::shadowroot::ShadowRoot;
86use crate::dom::text::Text;
87use crate::dom::toggleevent::ToggleEvent;
88use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollRequirement};
89
90#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
92pub(crate) enum PopoverState {
93 Auto,
94 Manual,
95 Hint,
96 NoPopover,
97}
98
99impl PopoverState {
100 fn from_attribute_value(value: Option<String>) -> Self {
102 let Some(value) = value else {
109 return PopoverState::NoPopover;
110 };
111
112 if value.is_empty() || value.eq_ignore_ascii_case("auto") {
113 PopoverState::Auto
114 } else if value.eq_ignore_ascii_case("hint") {
115 PopoverState::Hint
116 } else {
117 PopoverState::Manual
118 }
119 }
120
121 fn reflect_attribute(&self) -> Option<DOMString> {
123 match self {
125 PopoverState::Auto => Some(DOMString::from_static("auto")),
126 PopoverState::Manual => Some(DOMString::from_static("manual")),
127 PopoverState::Hint => Some(DOMString::from_static("hint")),
128 PopoverState::NoPopover => None,
129 }
130 }
131}
132
133#[dom_struct]
134pub(crate) struct HTMLElement {
135 element: Element,
136 style_decl: MutNullableDom<CSSStyleDeclaration>,
137 dataset: MutNullableDom<DOMStringMap>,
138}
139
140impl HTMLElement {
141 pub(crate) fn new_inherited(
142 tag_name: LocalName,
143 prefix: Option<Prefix>,
144 document: &Document,
145 ) -> HTMLElement {
146 HTMLElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
147 }
148
149 pub(crate) fn new_inherited_with_state(
150 state: ElementState,
151 tag_name: LocalName,
152 prefix: Option<Prefix>,
153 document: &Document,
154 ) -> HTMLElement {
155 HTMLElement {
156 element: Element::new_inherited_with_state(
157 state,
158 tag_name,
159 ns!(html),
160 prefix,
161 document,
162 ),
163 style_decl: Default::default(),
164 dataset: Default::default(),
165 }
166 }
167
168 pub(crate) fn new(
169 cx: &mut js::context::JSContext,
170 local_name: LocalName,
171 prefix: Option<Prefix>,
172 document: &Document,
173 proto: Option<HandleObject>,
174 ) -> DomRoot<HTMLElement> {
175 Node::reflect_node_with_proto(
176 cx,
177 Box::new(HTMLElement::new_inherited(local_name, prefix, document)),
178 document,
179 proto,
180 )
181 }
182
183 fn is_body_or_frameset(&self) -> bool {
184 let eventtarget = self.upcast::<EventTarget>();
185 eventtarget.is::<HTMLBodyElement>() || eventtarget.is::<HTMLFrameSetElement>()
186 }
187
188 pub(crate) fn get_inner_outer_text(&self, cx: &mut JSContext) -> DOMString {
194 let node = self.upcast::<Node>();
195 let window = node.owner_window();
196 let element = self.as_element();
197
198 let element_not_rendered =
200 !node.is_connected() || !element.has_css_layout_box_deprecated(cx);
201 if element_not_rendered {
202 return node.GetTextContent().unwrap();
203 }
204
205 window.layout_reflow(cx, QueryMsg::ElementInnerOuterTextQuery);
206 let text = window
207 .layout()
208 .query_element_inner_outer_text(node.to_trusted_node_address());
209
210 DOMString::from(text)
211 }
212
213 pub(crate) fn set_inner_text(&self, cx: &mut JSContext, input: DOMString) {
215 let fragment = self.rendered_text_fragment(cx, input);
218
219 Node::replace_all(cx, Some(fragment.upcast()), self.upcast::<Node>());
221 }
222
223 pub(crate) fn media_attribute_matches_media_environment(&self) -> bool {
225 self.element
229 .get_attribute_string_ref(&local_name!("media"))
230 .is_none_or(|media| {
231 let media = media.as_attr_ref();
232 MediaList::matches_environment(&self.owner_document(), &media.value())
233 })
234 }
235
236 pub(crate) fn is_editing_host(&self) -> bool {
238 matches!(&*self.ContentEditable().str(), "true" | "plaintext-only")
240 }
243
244 pub(crate) fn previously_focused_element(&self, no_gc: &NoGC) -> Option<DomRoot<Element>> {
245 self.upcast::<Element>()
246 .ensure_rare_data(no_gc)
247 .previously_focused_element
248 .get()
249 }
250
251 pub(crate) fn set_previously_focused_element(&self, element: Option<&Element>, no_gc: &NoGC) {
252 self.upcast::<Element>()
253 .ensure_rare_data(no_gc)
254 .previously_focused_element
255 .set(element);
256 }
257
258 pub(crate) fn ensure_element_internals(&self, cx: &mut JSContext) -> DomRoot<ElementInternals> {
259 let element = self.upcast::<Element>();
260 let Some(element_internals) = element.get_element_internals() else {
261 let internals = ElementInternals::new(cx, self);
262 element.ensure_rare_data(cx.no_gc()).element_internals =
263 Some(Dom::from_ref(&*internals));
264 return internals;
265 };
266 element_internals
267 }
268
269 pub(crate) fn is_disableable_form_control(&self) -> bool {
270 match self.upcast::<Node>().type_id() {
271 NodeTypeId::Element(ElementTypeId::HTMLElement(
272 HTMLElementTypeId::HTMLButtonElement |
273 HTMLElementTypeId::HTMLInputElement |
274 HTMLElementTypeId::HTMLSelectElement |
275 HTMLElementTypeId::HTMLTextAreaElement,
276 )) => true,
277 NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLElement)) => {
278 self.is_form_associated_custom_element()
279 },
280 _ => false,
281 }
282 }
283
284 pub(crate) fn is_form_element_disabled(&self, no_gc: &NoGC) -> bool {
286 let element = self.as_element();
294 self.is_disableable_form_control() &&
295 (element.has_attribute(&local_name!("disabled")) ||
296 element.is_disabled_by_ancestor_fieldset(no_gc))
297 }
298
299 pub(crate) fn popover_state(&self) -> PopoverState {
301 let attribute_value = self
302 .upcast::<Element>()
303 .get_attribute_string_value(&local_name!("popover"));
304 PopoverState::from_attribute_value(attribute_value)
305 }
306
307 pub(crate) fn show_popover(
309 &self,
310 cx: &mut JSContext,
311 throw_exceptions: bool,
312 source: Option<&HTMLElement>,
313 ) -> Fallible<()> {
314 let element = self.upcast::<Element>();
315
316 let document = self.owner_document();
318 let overlay_handler = document.overlay_handler();
319
320 if overlay_handler.showing_popover() || overlay_handler.hiding_popover_nesting_count() != 0
323 {
324 if throw_exceptions {
326 return Err(Error::InvalidState(Some(
327 "Cannot show a popover while another popover is being shown or hidden.".into(),
328 )));
329 }
330
331 return Ok(());
333 }
334
335 let validity_result = self.check_popover_validity(false, None);
339
340 if !matches!(validity_result, Ok(true)) {
342 if throw_exceptions && let Err(error) = validity_result {
345 return Err(error);
346 }
347
348 return Ok(());
350 }
351
352 assert!(self.popover_trigger().is_none());
354
355 assert!(!overlay_handler.is_in_the_top_layer(element));
357
358 overlay_handler.set_showing_popover(true);
360
361 let cleanup_showing_steps = || {
363 overlay_handler.set_showing_popover(false);
365 };
366
367 let event = ToggleEvent::new(
372 cx,
373 &self.owner_window(),
374 atom!("beforetoggle"),
375 EventBubbles::DoesNotBubble,
376 EventCancelable::Cancelable,
377 DOMString::from_static("closed"),
378 DOMString::from_static("open"),
379 source.map(|source| source.upcast::<Element>()),
380 );
381 if !event
382 .upcast::<Event>()
383 .fire(cx, self.upcast::<EventTarget>())
384 {
385 cleanup_showing_steps();
386 return Ok(());
387 }
388
389 let validity_result = self.check_popover_validity(false, Some(&document));
393
394 if !matches!(validity_result, Ok(true)) {
396 cleanup_showing_steps();
398
399 if throw_exceptions && let Err(error) = validity_result {
402 return Err(error);
403 }
404
405 return Ok(());
407 }
408
409 let mut should_restore_focus = false;
411
412 let original_type = self.popover_state();
414
415 let mut effective_type = original_type;
417
418 let mut ancestor = None;
419
420 if matches!(original_type, PopoverState::Auto | PopoverState::Hint) {
422 ancestor = element.topmost_popover_ancestor(cx.no_gc(), source, true);
425
426 if ancestor.as_ref().is_some_and(|ancestor| {
432 ancestor.opened_in_popover_mode() == Some(PopoverState::Hint)
433 }) && effective_type == PopoverState::Auto
434 {
435 effective_type = PopoverState::Hint;
436 }
437
438 overlay_handler.hide_popover_stack_until(
441 cx,
442 ancestor.as_deref(),
443 PopoverState::Hint,
444 should_restore_focus,
445 true,
446 );
447
448 if effective_type == PopoverState::Auto {
451 overlay_handler.hide_popover_stack_until(
452 cx,
453 ancestor.as_deref(),
454 PopoverState::Auto,
455 should_restore_focus,
456 true,
457 );
458 }
459
460 if original_type != self.popover_state() {
462 cleanup_showing_steps();
464
465 if throw_exceptions {
467 return Err(Error::InvalidState(Some(
468 "The popover attribute changed while showing the popover.".into(),
469 )));
470 }
471
472 return Ok(());
474 }
475
476 let validity_result = self.check_popover_validity(false, Some(&document));
480
481 if !matches!(validity_result, Ok(true)) {
483 cleanup_showing_steps();
485
486 if throw_exceptions && let Err(error) = validity_result {
489 return Err(error);
490 }
491
492 return Ok(());
494 }
495
496 if overlay_handler
499 .find_the_topmost_auto_or_hint_popover(cx.no_gc())
500 .is_none()
501 {
502 should_restore_focus = true;
503 }
504
505 if effective_type == PopoverState::Auto {
507 debug_assert!(!overlay_handler.showing_popover_list_contains(
509 cx.no_gc(),
510 PopoverState::Auto,
511 self
512 ));
513
514 self.set_opened_in_popover_mode(cx.no_gc(), Some(PopoverState::Auto));
516 }
517 else {
519 debug_assert!(effective_type == PopoverState::Hint);
521
522 debug_assert!(!overlay_handler.showing_popover_list_contains(
524 cx.no_gc(),
525 PopoverState::Hint,
526 self
527 ));
528
529 self.set_opened_in_popover_mode(cx.no_gc(), Some(PopoverState::Hint));
531 }
532
533 let close_watcher = InternalCloseWatcher::establish(
539 cx.no_gc(),
540 document.window(),
541 &InternalCloseWatcherOwner::Popover(Dom::from_ref(self)),
542 );
543 self.set_popover_close_watcher(cx.no_gc(), close_watcher);
544 }
545
546 self.set_previously_focused_element(None, cx.no_gc());
548
549 let originally_focused_element = document
552 .focus_handler()
553 .focused_area()
554 .element()
555 .map(DomRoot::from_ref);
556
557 overlay_handler.add_an_element_to_the_top_layer(element, cx.no_gc());
559
560 if effective_type == PopoverState::Hint &&
563 let Some(ancestor) = &ancestor &&
564 ancestor.opened_in_popover_mode() == Some(PopoverState::Auto)
565 {
566 overlay_handler.set_hint_stack_parent(Some(ancestor));
567 }
568
569 element.set_popover_visibility_state_showing(cx.no_gc(), true);
571
572 self.set_popover_trigger(cx.no_gc(), source);
574
575 self.run_popover_focusing_steps(cx);
579
580 if should_restore_focus && self.popover_state() != PopoverState::NoPopover {
584 self.set_previously_focused_element(originally_focused_element.as_deref(), cx.no_gc());
585 }
586
587 cleanup_showing_steps();
589
590 self.queue_a_popover_toggle_event_task("closed", "open", source);
592 Ok(())
593 }
594
595 fn queue_a_popover_toggle_event_task(
597 &self,
598 old_state: &'static str,
599 new_state: &'static str,
600 source: Option<&HTMLElement>,
601 ) {
602 let this = Trusted::new(self);
610 let trusted_source = source.map(|source| Trusted::new(source.upcast::<Element>()));
611 self.owner_global()
612 .task_manager()
613 .dom_manipulation_task_source()
614 .queue(task!(fire_popover_toggle_event: move |cx| {
615 let this = this.root();
616 let source = trusted_source.map(|source| source.root());
617
618 let event = ToggleEvent::new(
622 cx,
623 &this.owner_window(),
624 atom!("toggle"),
625 EventBubbles::DoesNotBubble,
626 EventCancelable::NotCancelable,
627 DOMString::from_static(old_state),
628 DOMString::from_static(new_state),
629 source.as_deref(),
630 );
631 event.upcast::<Event>().fire(cx, this.upcast::<EventTarget>());
632
633 }));
635
636 }
639
640 pub(crate) fn hide_popover(
642 &self,
643 cx: &mut JSContext,
644 focus_previous_element: bool,
645 mut fire_events: bool,
646 throw_exceptions: bool,
647 source: Option<&HTMLElement>,
648 ) -> Fallible<()> {
649 let element = self.upcast::<Element>();
650
651 let validity_result = self.check_popover_validity(true, None);
655
656 if !matches!(validity_result, Ok(true)) {
658 if throw_exceptions && let Err(error) = validity_result {
661 return Err(error);
662 }
663
664 return Ok(());
666 }
667
668 let document = self.owner_document();
670 let overlay_handler = document.overlay_handler();
671
672 let nested_hide = self.popover_hiding();
674
675 self.set_popover_hiding(cx.no_gc(), true);
677
678 if nested_hide {
680 fire_events = false;
681 }
682
683 overlay_handler.increment_hiding_popover_nesting_count();
685
686 let cleanup_steps = |no_gc: &NoGC| {
688 if !nested_hide {
690 self.set_popover_hiding(no_gc, false);
691 }
692
693 overlay_handler.decrement_hiding_popover_nesting_count();
695 };
696
697 let auto_popover_list_contains_element =
700 overlay_handler.showing_popover_list_contains(cx.no_gc(), PopoverState::Auto, self);
701
702 let hint_popover_list_contains_element =
705 overlay_handler.showing_popover_list_contains(cx.no_gc(), PopoverState::Hint, self);
706
707 if matches!(
709 self.opened_in_popover_mode(),
710 Some(PopoverState::Auto) | Some(PopoverState::Hint)
711 ) {
712 if hint_popover_list_contains_element {
715 overlay_handler.hide_popover_stack_until(
716 cx,
717 Some(self),
718 PopoverState::Hint,
719 focus_previous_element,
720 fire_events,
721 );
722 }
723
724 if overlay_handler.is_hint_stack_parent(self) {
727 overlay_handler.hide_popover_stack_until(
728 cx,
729 None,
730 PopoverState::Hint,
731 focus_previous_element,
732 fire_events,
733 );
734 }
735
736 if auto_popover_list_contains_element {
739 overlay_handler.hide_popover_stack_until(
740 cx,
741 Some(self),
742 PopoverState::Auto,
743 focus_previous_element,
744 fire_events,
745 );
746 }
747
748 let validity_result = self.check_popover_validity(true, Some(&document));
752
753 if !matches!(validity_result, Ok(true)) {
755 cleanup_steps(cx);
757
758 if throw_exceptions && let Err(error) = validity_result {
761 return Err(error);
762 }
763
764 return Ok(());
766 }
767 }
768
769 if fire_events {
771 let event = ToggleEvent::new(
775 cx,
776 &self.owner_window(),
777 atom!("beforetoggle"),
778 EventBubbles::DoesNotBubble,
779 EventCancelable::NotCancelable,
780 DOMString::from_static("open"),
781 DOMString::from_static("closed"),
782 source.map(|source| source.upcast::<Element>()),
783 );
784 event
785 .upcast::<Event>()
786 .fire(cx, self.upcast::<EventTarget>());
787
788 let validity_result = self.check_popover_validity(true, Some(&document));
791
792 if !matches!(validity_result, Ok(true)) {
794 cleanup_steps(cx);
796
797 if throw_exceptions && let Err(error) = validity_result {
800 return Err(error);
801 }
802
803 return Ok(());
805 }
806
807 overlay_handler
809 .request_an_element_to_be_removed_from_the_top_layer(element, cx.no_gc());
810
811 }
813 else {
815 overlay_handler.remove_an_element_from_the_top_layer_immediately(element, cx.no_gc());
816 }
817
818 self.set_popover_trigger(cx.no_gc(), None);
820
821 self.set_opened_in_popover_mode(cx.no_gc(), None);
823
824 element.set_popover_visibility_state_showing(cx.no_gc(), false);
826
827 if overlay_handler.is_hint_stack_parent(self) ||
830 overlay_handler
831 .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Hint)
832 .is_empty()
833 {
834 overlay_handler.set_hint_stack_parent(None);
835 }
836
837 if fire_events {
840 self.queue_a_popover_toggle_event_task("open", "closed", source);
841 }
842
843 if let Some(previously_focused_element) = self.previously_focused_element(cx.no_gc()) {
846 self.set_previously_focused_element(None, cx.no_gc());
848
849 if focus_previous_element &&
854 document
855 .focus_handler()
856 .focused_area()
857 .dom_anchor(&document)
858 .inclusive_ancestors(ShadowIncluding::Yes)
859 .any(|node| &*node == self.upcast::<Node>())
860 {
861 previously_focused_element
862 .upcast::<Node>()
863 .run_the_focusing_steps(cx, None, FocusTrigger::Script);
864 }
865 }
866
867 if let Some(close_watcher) = self.take_popover_close_watcher(cx.no_gc()) {
871 close_watcher.destroy(cx.no_gc());
872 }
873
874 cleanup_steps(cx.no_gc());
876 Ok(())
877 }
878
879 fn run_popover_focusing_steps(&self, cx: &mut JSContext) {
881 if let Some(dialog) = self.downcast::<HTMLDialogElement>() {
887 dialog.run_dialog_focusing_steps(cx);
888 return;
889 }
890
891 let node = self.upcast::<Node>();
893 rooted!(&in(cx) let control = if self.Autofocus() {
894 node.get_the_focusable_area(cx, FocusTrigger::Script)
895 }
896 else {
898 node.autofocus_delegate(cx, FocusTrigger::Script)
899 });
900
901 let Some(control) = &*control else {
903 return;
904 };
905
906 self.owner_document()
909 .focus_handler()
910 .focus(cx, control, FocusTrigger::Script);
911
912 }
919
920 pub(crate) fn check_popover_validity(
922 &self,
923 expected_to_be_showing: bool,
924 expected_document: Option<&Document>,
925 ) -> Fallible<bool> {
926 if self.popover_state() == NoPopover {
929 return Err(Error::NotSupported(Some(
930 "Element does not have a popover attribute.".into(),
931 )));
932 }
933
934 let element = self.upcast::<Element>();
939 if expected_to_be_showing != element.popover_visibility_state_showing() {
940 return Ok(false);
941 }
942
943 let document = self.owner_document();
951 if (!expected_to_be_showing &&
952 (!self.upcast::<Node>().is_connected() || !document.is_fully_active())) ||
953 expected_document.is_some_and(|expected| *expected != *document) ||
954 (self.is::<HTMLDialogElement>() && element.state().contains(ElementState::MODAL)) ||
955 element.state().contains(ElementState::FULLSCREEN)
956 {
957 return Err(Error::InvalidState(Some(
958 "Element is not in a valid state to show or hide a popover.".into(),
959 )));
960 }
961
962 Ok(true)
964 }
965
966 pub(crate) fn popover_target_attribute_activation_behavior(
968 &self,
969 cx: &mut JSContext,
970 event_target: &Node,
971 ) {
972 let popover = self.popover_target_element(cx);
974
975 let Some(popover) = popover else {
977 return;
978 };
979
980 let popover_node = popover.upcast::<Node>();
983 if popover_node.is_shadow_including_inclusive_ancestor_of(event_target) &&
984 self.upcast::<Node>()
985 .is_shadow_including_inclusive_ancestor_of(popover_node)
986 {
987 return;
988 }
989
990 let popover_showing = popover
991 .upcast::<Element>()
992 .popover_visibility_state_showing();
993 let popover_target_action = self
994 .upcast::<Element>()
995 .get_string_attribute(&local_name!("popovertargetaction"))
996 .to_ascii_lowercase();
997
998 if popover_target_action == "show" && popover_showing {
1001 return;
1002 }
1003
1004 if popover_target_action == "hide" && !popover_showing {
1007 return;
1008 }
1009
1010 if popover_showing {
1013 popover
1014 .hide_popover(cx, true, true, false, Some(self))
1015 .expect("This shouldn't fail in this codepath");
1016 }
1017 else {
1019 let validity = popover.check_popover_validity(false, None);
1022
1023 if matches!(validity, Ok(true)) {
1025 popover
1026 .show_popover(cx, false, Some(self))
1027 .expect("This shouldn't fail in this codepath");
1028 }
1029 }
1030 }
1031
1032 pub(crate) fn popover_target_element(
1034 &self,
1035 cx: &mut JSContext,
1036 ) -> Option<DomRoot<HTMLElement>> {
1037 if !self.is_a_button() {
1039 return None;
1040 }
1041
1042 if self.is_form_element_disabled(cx.no_gc()) {
1044 return None;
1045 }
1046
1047 if self
1049 .downcast::<HTMLButtonElement>()
1050 .is_some_and(|button| button.form_owner().is_some() && button.is_submit_button()) ||
1051 self.downcast::<HTMLInputElement>()
1052 .is_some_and(|input| input.form_owner().is_some() && input.is_submit_button())
1053 {
1054 return None;
1055 }
1056
1057 let popover_target_value = self
1059 .upcast::<Element>()
1060 .get_attribute_string_value(&local_name!("popovertarget"))?
1061 .into();
1062
1063 let root_node = self
1064 .upcast::<Node>()
1065 .GetRootNode(&GetRootNodeOptions::empty());
1066
1067 let popover_element = if let Some(document) = root_node.downcast::<Document>() {
1068 document.GetElementById(cx, popover_target_value)
1069 } else if let Some(document_fragment) = root_node.downcast::<DocumentFragment>() {
1070 document_fragment.GetElementById(cx, popover_target_value)
1071 } else {
1072 unreachable!("Element must be in a document or document fragment")
1073 };
1074
1075 let popover_element = DomRoot::downcast::<HTMLElement>(popover_element?)?;
1077
1078 if popover_element.popover_state() == PopoverState::NoPopover {
1080 return None;
1081 }
1082
1083 Some(popover_element)
1085 }
1086
1087 pub(crate) fn popover_stack_position(&self, cx: &mut JSContext) -> usize {
1089 let document = self.upcast::<Element>().owner_document();
1090
1091 let hint_list = document
1093 .overlay_handler()
1094 .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Hint);
1095
1096 let auto_list = document
1098 .overlay_handler()
1099 .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Auto);
1100
1101 if let Some(hint_list_index) = hint_list.iter().position(|popover| popover == self) {
1104 return hint_list_index + auto_list.len() + 1;
1105 }
1106
1107 if let Some(auto_list_index) = auto_list.iter().position(|popover| popover == self) {
1109 return auto_list_index + 1;
1110 }
1111
1112 0
1114 }
1115
1116 fn is_a_button(&self) -> bool {
1118 self.is::<HTMLButtonElement>() ||
1119 self.downcast::<HTMLInputElement>().is_some_and(|input| {
1120 matches!(
1121 *input.input_type(),
1122 InputType::Submit(_) |
1123 InputType::Reset(_) |
1124 InputType::Image(_) |
1125 InputType::Button(_)
1126 )
1127 })
1128 }
1129
1130 pub(crate) fn opened_in_popover_mode(&self) -> Option<PopoverState> {
1131 self.upcast::<Element>()
1132 .rare_data()
1133 .as_ref()?
1134 .opened_in_popover_mode
1135 }
1136
1137 fn set_opened_in_popover_mode(&self, no_gc: &NoGC, mode: Option<PopoverState>) {
1138 self.upcast::<Element>()
1139 .ensure_rare_data(no_gc)
1140 .opened_in_popover_mode = mode;
1141 }
1142
1143 fn popover_trigger(&self) -> Option<DomRoot<HTMLElement>> {
1144 self.upcast::<Element>()
1145 .rare_data()
1146 .as_ref()?
1147 .popover_trigger
1148 .get()
1149 }
1150
1151 fn set_popover_trigger(&self, no_gc: &NoGC, trigger: Option<&HTMLElement>) {
1152 self.upcast::<Element>()
1153 .ensure_rare_data(no_gc)
1154 .popover_trigger
1155 .set(trigger);
1156 }
1157
1158 fn popover_hiding(&self) -> bool {
1159 self.upcast::<Element>()
1160 .rare_data()
1161 .as_ref()
1162 .is_some_and(|rare_data| rare_data.popover_hiding)
1163 }
1164
1165 fn set_popover_hiding(&self, no_gc: &NoGC, value: bool) {
1166 self.upcast::<Element>()
1167 .ensure_rare_data(no_gc)
1168 .popover_hiding = value;
1169 }
1170
1171 fn set_popover_close_watcher(&self, no_gc: &NoGC, close_watcher: Rc<InternalCloseWatcher>) {
1172 self.upcast::<Element>()
1173 .ensure_rare_data(no_gc)
1174 .popover_close_watcher
1175 .safe_borrow_mut(no_gc)
1176 .replace(close_watcher);
1177 }
1178
1179 fn take_popover_close_watcher(&self, no_gc: &NoGC) -> Option<Rc<InternalCloseWatcher>> {
1180 self.upcast::<Element>()
1181 .rare_data()
1182 .as_ref()?
1183 .popover_close_watcher
1184 .safe_borrow_mut(no_gc)
1185 .take()
1186 }
1187}
1188
1189impl HTMLElementMethods<crate::DomTypeHolder> for HTMLElement {
1190 fn Style(&self, cx: &mut JSContext) -> DomRoot<CSSStyleDeclaration> {
1192 self.style_decl.or_init(|| {
1193 let global = self.owner_window();
1194 CSSStyleDeclaration::new(
1195 cx,
1196 &global,
1197 CSSStyleOwner::Element(Dom::from_ref(self.upcast())),
1198 None,
1199 CSSModificationAccess::ReadWrite,
1200 )
1201 })
1202 }
1203
1204 make_getter!(Title, "title");
1206 make_setter!(SetTitle, "title");
1208
1209 make_getter!(Lang, "lang");
1211 make_setter!(SetLang, "lang");
1213
1214 make_enumerated_getter!(
1216 Dir,
1217 "dir",
1218 "ltr" | "rtl" | "auto",
1219 missing => "",
1220 invalid => ""
1221 );
1222
1223 make_setter!(SetDir, "dir");
1225
1226 make_bool_getter!(Hidden, "hidden");
1228 make_bool_setter!(SetHidden, "hidden");
1230
1231 make_bool_getter!(Inert, "inert");
1233 make_bool_setter!(SetInert, "inert");
1234
1235 global_event_handlers!(NoOnload);
1237
1238 fn Dataset(&self, cx: &mut JSContext) -> DomRoot<DOMStringMap> {
1240 self.dataset
1241 .or_init(|| DOMStringMap::new(cx, self.upcast()))
1242 }
1243
1244 fn GetOnerror(&self, cx: &mut JSContext) -> Option<RootedCallback<OnErrorEventHandlerNonNull>> {
1246 if self.is_body_or_frameset() {
1247 let document = self.owner_document();
1248 if document.has_browsing_context() {
1249 document.window().GetOnerror(cx)
1250 } else {
1251 None
1252 }
1253 } else {
1254 self.upcast::<EventTarget>()
1255 .get_event_handler_common(cx, "error")
1256 }
1257 }
1258
1259 fn SetOnerror(
1261 &self,
1262 cx: &mut JSContext,
1263 listener: Option<RootedCallback<OnErrorEventHandlerNonNull>>,
1264 ) {
1265 if self.is_body_or_frameset() {
1266 let document = self.owner_document();
1267 if document.has_browsing_context() {
1268 document.window().SetOnerror(cx, listener)
1269 }
1270 } else {
1271 self.upcast::<EventTarget>()
1273 .set_error_event_handler(cx, "error", listener)
1274 }
1275 }
1276
1277 fn GetOnload(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1279 if self.is_body_or_frameset() {
1280 let document = self.owner_document();
1281 if document.has_browsing_context() {
1282 document.window().GetOnload(cx)
1283 } else {
1284 None
1285 }
1286 } else {
1287 self.upcast::<EventTarget>()
1288 .get_event_handler_common(cx, "load")
1289 }
1290 }
1291
1292 fn SetOnload(&self, cx: &mut JSContext, listener: Option<RootedCallback<EventHandlerNonNull>>) {
1294 if self.is_body_or_frameset() {
1295 let document = self.owner_document();
1296 if document.has_browsing_context() {
1297 document.window().SetOnload(cx, listener)
1298 }
1299 } else {
1300 self.upcast::<EventTarget>()
1301 .set_event_handler_common(cx, "load", listener)
1302 }
1303 }
1304
1305 fn GetOnblur(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1307 if self.is_body_or_frameset() {
1308 let document = self.owner_document();
1309 if document.has_browsing_context() {
1310 document.window().GetOnblur(cx)
1311 } else {
1312 None
1313 }
1314 } else {
1315 self.upcast::<EventTarget>()
1316 .get_event_handler_common(cx, "blur")
1317 }
1318 }
1319
1320 fn SetOnblur(&self, cx: &mut JSContext, listener: Option<RootedCallback<EventHandlerNonNull>>) {
1322 if self.is_body_or_frameset() {
1323 let document = self.owner_document();
1324 if document.has_browsing_context() {
1325 document.window().SetOnblur(cx, listener)
1326 }
1327 } else {
1328 self.upcast::<EventTarget>()
1329 .set_event_handler_common(cx, "blur", listener)
1330 }
1331 }
1332
1333 fn GetOnfocus(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1335 if self.is_body_or_frameset() {
1336 let document = self.owner_document();
1337 if document.has_browsing_context() {
1338 document.window().GetOnfocus(cx)
1339 } else {
1340 None
1341 }
1342 } else {
1343 self.upcast::<EventTarget>()
1344 .get_event_handler_common(cx, "focus")
1345 }
1346 }
1347
1348 fn SetOnfocus(
1350 &self,
1351 cx: &mut JSContext,
1352 listener: Option<RootedCallback<EventHandlerNonNull>>,
1353 ) {
1354 if self.is_body_or_frameset() {
1355 let document = self.owner_document();
1356 if document.has_browsing_context() {
1357 document.window().SetOnfocus(cx, listener)
1358 }
1359 } else {
1360 self.upcast::<EventTarget>()
1361 .set_event_handler_common(cx, "focus", listener)
1362 }
1363 }
1364
1365 fn GetOnresize(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1367 if self.is_body_or_frameset() {
1368 let document = self.owner_document();
1369 if document.has_browsing_context() {
1370 document.window().GetOnresize(cx)
1371 } else {
1372 None
1373 }
1374 } else {
1375 self.upcast::<EventTarget>()
1376 .get_event_handler_common(cx, "resize")
1377 }
1378 }
1379
1380 fn SetOnresize(
1382 &self,
1383 cx: &mut JSContext,
1384 listener: Option<RootedCallback<EventHandlerNonNull>>,
1385 ) {
1386 if self.is_body_or_frameset() {
1387 let document = self.owner_document();
1388 if document.has_browsing_context() {
1389 document.window().SetOnresize(cx, listener)
1390 }
1391 } else {
1392 self.upcast::<EventTarget>()
1393 .set_event_handler_common(cx, "resize", listener)
1394 }
1395 }
1396
1397 fn GetOnscroll(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1399 if self.is_body_or_frameset() {
1400 let document = self.owner_document();
1401 if document.has_browsing_context() {
1402 document.window().GetOnscroll(cx)
1403 } else {
1404 None
1405 }
1406 } else {
1407 self.upcast::<EventTarget>()
1408 .get_event_handler_common(cx, "scroll")
1409 }
1410 }
1411
1412 fn SetOnscroll(
1414 &self,
1415 cx: &mut JSContext,
1416 listener: Option<RootedCallback<EventHandlerNonNull>>,
1417 ) {
1418 if self.is_body_or_frameset() {
1419 let document = self.owner_document();
1420 if document.has_browsing_context() {
1421 document.window().SetOnscroll(cx, listener)
1422 }
1423 } else {
1424 self.upcast::<EventTarget>()
1425 .set_event_handler_common(cx, "scroll", listener)
1426 }
1427 }
1428
1429 fn Itemtypes(&self) -> Option<Vec<DOMString>> {
1431 let atoms = self
1432 .element
1433 .get_tokenlist_attribute(&local_name!("itemtype"));
1434
1435 if atoms.is_empty() {
1436 return None;
1437 }
1438
1439 Some(
1440 FxHashSet::from_iter(
1441 atoms
1442 .iter()
1443 .map(|attr_value| DOMString::from(String::from(attr_value.trim()))),
1444 )
1445 .into_iter()
1446 .collect(),
1447 )
1448 }
1449
1450 fn PropertyNames(&self) -> Option<Vec<DOMString>> {
1452 let atoms = self
1453 .element
1454 .get_tokenlist_attribute(&local_name!("itemprop"));
1455
1456 if atoms.is_empty() {
1457 return None;
1458 }
1459
1460 Some(
1461 FxHashSet::from_iter(
1462 atoms
1463 .iter()
1464 .map(|attr_value| DOMString::from(String::from(attr_value.trim()))),
1465 )
1466 .into_iter()
1467 .collect(),
1468 )
1469 }
1470
1471 fn Click(&self, cx: &mut JSContext) {
1473 if self.is_form_element_disabled(cx.no_gc()) {
1475 return;
1476 }
1477
1478 let element = self.as_element();
1480 if element.click_in_progress() {
1481 return;
1482 }
1483
1484 element.set_click_in_progress(true);
1486
1487 self.upcast::<Node>()
1489 .fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
1490
1491 element.set_click_in_progress(false);
1493 }
1494
1495 fn Focus(&self, cx: &mut JSContext, options: &FocusOptions) {
1497 if !self
1502 .upcast::<Node>()
1503 .run_the_focusing_steps(cx, None, FocusTrigger::Script)
1504 {
1505 return;
1509 }
1510
1511 if !options.preventScroll {
1518 let scroll_axis = ScrollAxisState {
1519 position: ScrollLogicalPosition::Center,
1520 requirement: ScrollRequirement::IfNotVisible,
1521 };
1522 self.upcast::<Element>().scroll_into_view_with_options(
1523 cx,
1524 ScrollBehavior::Smooth,
1525 scroll_axis,
1526 scroll_axis,
1527 None,
1528 None,
1529 );
1530 }
1531 }
1532
1533 fn Blur(&self, cx: &mut JSContext) {
1535 if !self.as_element().focus_state() {
1538 return;
1539 }
1540 self.owner_document().focus_handler().focus(
1542 cx,
1543 &FocusableArea::Viewport,
1544 FocusTrigger::Script,
1545 );
1546 }
1547
1548 #[expect(unsafe_code)]
1550 fn ScrollParent(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1551 self.owner_window()
1552 .scroll_container_query(
1553 Some(self.upcast()),
1554 ScrollContainerQueryFlags::ForScrollParent,
1555 )
1556 .and_then(|response| match response {
1557 ScrollContainerResponse::Viewport(..) => {
1558 self.owner_document().GetScrollingElement(cx)
1559 },
1560 ScrollContainerResponse::Element(parent_node_address, ..) => {
1561 let node = unsafe { from_untrusted_node_address(parent_node_address) };
1562 DomRoot::downcast(node)
1563 },
1564 })
1565 }
1566
1567 fn GetOffsetParent(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1569 if self.is::<HTMLBodyElement>() || self.element.is_root() {
1570 return None;
1571 }
1572
1573 let node = self.upcast::<Node>();
1574 let window = self.owner_window();
1575 let (element, _) = window.offset_parent_query(cx, node);
1576
1577 element
1578 }
1579
1580 fn OffsetTop(&self, cx: &mut JSContext) -> i32 {
1582 if self.is_body_element() {
1583 return 0;
1584 }
1585
1586 let node = self.upcast::<Node>();
1587 let window = self.owner_window();
1588 let (_, rect) = window.offset_parent_query(cx, node);
1589
1590 rect.origin.y.to_nearest_px()
1591 }
1592
1593 fn OffsetLeft(&self, cx: &mut JSContext) -> i32 {
1595 if self.is_body_element() {
1596 return 0;
1597 }
1598
1599 let node = self.upcast::<Node>();
1600 let window = self.owner_window();
1601 let (_, rect) = window.offset_parent_query(cx, node);
1602
1603 rect.origin.x.to_nearest_px()
1604 }
1605
1606 fn OffsetWidth(&self, cx: &mut JSContext) -> i32 {
1608 let node = self.upcast::<Node>();
1609 let window = self.owner_window();
1610 let (_, rect) = window.offset_parent_query(cx, node);
1611
1612 rect.size.width.to_nearest_px()
1613 }
1614
1615 fn OffsetHeight(&self, cx: &mut JSContext) -> i32 {
1617 let node = self.upcast::<Node>();
1618 let window = self.owner_window();
1619 let (_, rect) = window.offset_parent_query(cx, node);
1620
1621 rect.size.height.to_nearest_px()
1622 }
1623
1624 fn InnerText(&self, cx: &mut JSContext) -> DOMString {
1626 self.get_inner_outer_text(cx)
1627 }
1628
1629 fn SetInnerText(&self, cx: &mut JSContext, input: DOMString) {
1631 self.set_inner_text(cx, input)
1632 }
1633
1634 fn GetOuterText(&self, cx: &mut JSContext) -> Fallible<DOMString> {
1636 Ok(self.get_inner_outer_text(cx))
1637 }
1638
1639 fn SetOuterText(&self, cx: &mut JSContext, input: DOMString) -> Fallible<()> {
1641 let Some(parent) = self.upcast::<Node>().GetParentNode() else {
1643 return Err(Error::NoModificationAllowed(Some(
1644 "Cannot modify HTML element as its parent element is null".into(),
1645 )));
1646 };
1647
1648 let node = self.upcast::<Node>();
1649 let document = self.owner_document();
1650
1651 let next = node.GetNextSibling();
1653
1654 let previous = node.GetPreviousSibling();
1656
1657 let fragment = self.rendered_text_fragment(cx, input);
1660
1661 if fragment.upcast::<Node>().children_count() == 0 {
1664 let text_node = Text::new(cx, DOMString::new(), &document);
1665
1666 fragment
1667 .upcast::<Node>()
1668 .AppendChild(cx, text_node.upcast())?;
1669 }
1670
1671 parent.ReplaceChild(cx, fragment.upcast(), node)?;
1673
1674 if let Some(next_sibling) = next &&
1677 let Some(node) = next_sibling.GetPreviousSibling()
1678 {
1679 Self::merge_with_the_next_text_node(cx, &node);
1680 }
1681
1682 if let Some(previous) = previous {
1684 Self::merge_with_the_next_text_node(cx, &previous)
1685 }
1686
1687 Ok(())
1688 }
1689
1690 fn Translate(&self) -> bool {
1692 self.as_element().is_translate_enabled()
1693 }
1694
1695 fn SetTranslate(&self, cx: &mut JSContext, yesno: bool) {
1697 self.as_element().set_string_attribute(
1698 cx,
1699 &html5ever::local_name!("translate"),
1700 match yesno {
1701 true => DOMString::from_static("yes"),
1702 false => DOMString::from_static("no"),
1703 },
1704 );
1705 }
1706
1707 make_enumerated_getter!(
1709 ContentEditable,
1710 "contenteditable",
1711 "true" | "false" | "plaintext-only",
1712 missing => "inherit",
1713 invalid => "inherit",
1714 empty => "true"
1715 );
1716
1717 fn SetContentEditable(&self, cx: &mut JSContext, value: DOMString) -> ErrorResult {
1719 let attr_name = &local_name!("contenteditable");
1720 if value.eq_ignore_ascii_case("inherit") {
1721 self.element.remove_attribute_by_name(cx, attr_name);
1723 } else if value.eq_ignore_ascii_case("true") ||
1724 value.eq_ignore_ascii_case("false") ||
1725 value.eq_ignore_ascii_case("plaintext-only")
1726 {
1727 let lower_value = value.to_ascii_lowercase();
1731 self.element
1732 .set_attribute(cx, attr_name, AttrValue::String(lower_value));
1733 } else {
1734 return Err(Error::Syntax(Some(
1736 "Invalid attribute for HTML element".into(),
1737 )));
1738 };
1739 Ok(())
1740 }
1741
1742 fn IsContentEditable(&self) -> bool {
1744 self.upcast::<Node>().is_editable_or_editing_host()
1746 }
1747
1748 fn AttachInternals(&self, cx: &mut JSContext) -> Fallible<DomRoot<ElementInternals>> {
1750 if self.element.get_is().is_some() {
1752 return Err(Error::NotSupported(Some(
1753 "Local name of HTML element must not be set".into(),
1754 )));
1755 }
1756
1757 let lookup_registry = {
1759 let registry = self.as_element().custom_element_registry();
1762 if registry
1763 .as_ref()
1764 .is_some_and(|registry| registry.is_scoped())
1765 {
1766 registry
1767 } else {
1768 self.upcast::<Node>().owner_doc().custom_element_registry()
1769 }
1770 };
1771 let definition = CustomElementRegistry::lookup_custom_element_definition(
1772 lookup_registry.as_deref(),
1773 self.upcast::<Element>().namespace(),
1774 self.as_element().local_name(),
1775 None,
1776 );
1777
1778 let definition = match definition {
1780 Some(definition) => definition,
1781 None => {
1782 return Err(Error::NotSupported(Some(
1783 "Custom element definition is missing".into(),
1784 )));
1785 },
1786 };
1787
1788 if definition.disable_internals {
1790 return Err(Error::NotSupported(Some(
1791 "Custom element definition's `disabledFeatures` must not include \"internals\""
1792 .into(),
1793 )));
1794 }
1795
1796 let internals = self.ensure_element_internals(cx);
1798 if internals.attached() {
1799 return Err(Error::NotSupported(Some(
1800 "HTML element's internals are already attached".into(),
1801 )));
1802 }
1803
1804 if !matches!(
1807 self.element.get_custom_element_state(),
1808 CustomElementState::Precustomized | CustomElementState::Custom
1809 ) {
1810 return Err(Error::NotSupported(Some(
1811 "HTML element is not yet upgraded".into(),
1812 )));
1813 }
1814
1815 if self.is_form_associated_custom_element() {
1816 self.element.init_state_for_internals(cx.no_gc());
1817 }
1818
1819 internals.set_attached();
1821 Ok(internals)
1822 }
1823
1824 fn ShowPopover(&self, cx: &mut JSContext, options: &ShowPopoverOptions) -> Fallible<()> {
1826 self.show_popover(cx, true, options.source.as_deref())
1829 }
1830
1831 fn HidePopover(&self, cx: &mut JSContext) -> Fallible<()> {
1833 self.hide_popover(cx, true, true, true, None)
1835 }
1836
1837 fn TogglePopover(
1839 &self,
1840 cx: &mut JSContext,
1841 options: TogglePopoverOptionsOrBoolean,
1842 ) -> Fallible<bool> {
1843 let (force, source) = match &options {
1845 TogglePopoverOptionsOrBoolean::Boolean(options) => (Some(*options), None),
1847 TogglePopoverOptionsOrBoolean::TogglePopoverOptions(options) => {
1850 (options.force, options.parent.source.as_deref())
1851 },
1852 };
1853
1854 if self.upcast::<Element>().popover_visibility_state_showing() &&
1857 force.is_none_or(|force| !force)
1858 {
1859 self.hide_popover(cx, true, true, true, None)?
1860 }
1861 else if force.is_none_or(|force| force) {
1863 self.show_popover(cx, true, source)?;
1864 }
1865 else {
1867 let expected_to_be_showing =
1870 self.upcast::<Element>().popover_visibility_state_showing();
1871
1872 self.check_popover_validity(expected_to_be_showing, None)?;
1874 }
1875
1876 Ok(self.upcast::<Element>().popover_visibility_state_showing())
1878 }
1879
1880 fn GetPopover(&self) -> Option<DOMString> {
1882 self.popover_state().reflect_attribute()
1883 }
1884
1885 fn SetPopover(&self, cx: &mut JSContext, value: Option<DOMString>) {
1887 let element = self.upcast::<Element>();
1888 if let Some(value) = value {
1889 element.set_string_attribute(cx, &local_name!("popover"), value);
1890 } else {
1891 element.remove_attribute_by_name(cx, &local_name!("popover"));
1892 }
1893 }
1894
1895 fn Nonce(&self) -> DOMString {
1897 self.as_element().nonce_value().into()
1898 }
1899
1900 fn SetNonce(&self, cx: &mut JSContext, value: DOMString) {
1902 self.as_element()
1903 .update_nonce_internal_slot(String::from(value), cx.no_gc())
1904 }
1905
1906 fn Autofocus(&self) -> bool {
1908 self.element.has_attribute(&local_name!("autofocus"))
1909 }
1910
1911 fn SetAutofocus(&self, cx: &mut JSContext, autofocus: bool) {
1913 self.element
1914 .set_bool_attribute(cx, &local_name!("autofocus"), autofocus);
1915 }
1916
1917 fn TabIndex(&self) -> i32 {
1919 self.element.tab_index()
1920 }
1921
1922 fn SetTabIndex(&self, cx: &mut JSContext, tab_index: i32) {
1924 self.element
1925 .set_attribute(cx, &local_name!("tabindex"), tab_index.into());
1926 }
1927
1928 make_getter!(AccessKey, "accesskey");
1930
1931 make_setter!(SetAccessKey, "accesskey");
1933
1934 fn AccessKeyLabel(&self) -> DOMString {
1936 if !self.element.has_attribute(&local_name!("accesskey")) {
1940 return Default::default();
1941 }
1942
1943 let access_key_string =
1944 String::from(self.element.get_string_attribute(&local_name!("accesskey")));
1945
1946 #[cfg(target_os = "macos")]
1947 let access_key_label = format!("⌃⌥{access_key_string}");
1948 #[cfg(not(target_os = "macos"))]
1949 let access_key_label = format!("Alt+Shift+{access_key_string}");
1950
1951 access_key_label.into()
1952 }
1953}
1954
1955fn append_text_node_to_fragment(
1956 cx: &mut JSContext,
1957 document: &Document,
1958 fragment: &DocumentFragment,
1959 text: String,
1960) {
1961 let text = Text::new(cx, DOMString::from(text), document);
1962 fragment
1963 .upcast::<Node>()
1964 .AppendChild(cx, text.upcast())
1965 .unwrap();
1966}
1967
1968impl HTMLElement {
1969 pub(crate) fn is_labelable_element(&self) -> bool {
1971 match self.upcast::<Node>().type_id() {
1972 NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
1973 HTMLElementTypeId::HTMLInputElement => !matches!(
1974 *self.downcast::<HTMLInputElement>().unwrap().input_type(),
1975 InputType::Hidden(_)
1976 ),
1977 HTMLElementTypeId::HTMLButtonElement |
1978 HTMLElementTypeId::HTMLMeterElement |
1979 HTMLElementTypeId::HTMLOutputElement |
1980 HTMLElementTypeId::HTMLProgressElement |
1981 HTMLElementTypeId::HTMLSelectElement |
1982 HTMLElementTypeId::HTMLTextAreaElement => true,
1983 _ => self.is_form_associated_custom_element(),
1984 },
1985 _ => false,
1986 }
1987 }
1988
1989 pub(crate) fn is_form_associated_custom_element(&self) -> bool {
1991 if let Some(definition) = self.as_element().get_custom_element_definition() {
1992 definition.is_autonomous() && definition.form_associated
1993 } else {
1994 false
1995 }
1996 }
1997
1998 pub(crate) fn is_listed_element(&self) -> bool {
2000 match self.upcast::<Node>().type_id() {
2001 NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
2002 HTMLElementTypeId::HTMLButtonElement |
2003 HTMLElementTypeId::HTMLFieldSetElement |
2004 HTMLElementTypeId::HTMLInputElement |
2005 HTMLElementTypeId::HTMLObjectElement |
2006 HTMLElementTypeId::HTMLOutputElement |
2007 HTMLElementTypeId::HTMLSelectElement |
2008 HTMLElementTypeId::HTMLTextAreaElement => true,
2009 _ => self.is_form_associated_custom_element(),
2010 },
2011 _ => false,
2012 }
2013 }
2014
2015 pub(crate) fn is_body_element(&self) -> bool {
2017 let self_node = self.upcast::<Node>();
2018 self_node.GetParentNode().is_some_and(|parent| {
2019 let parent_node = parent.upcast::<Node>();
2020 (self_node.is::<HTMLBodyElement>() || self_node.is::<HTMLFrameSetElement>()) &&
2021 parent_node.is::<HTMLHtmlElement>() &&
2022 self_node
2023 .preceding_siblings()
2024 .all(|n| !n.is::<HTMLBodyElement>() && !n.is::<HTMLFrameSetElement>())
2025 })
2026 }
2027
2028 pub(crate) fn is_submittable_element(&self) -> bool {
2030 match self.upcast::<Node>().type_id() {
2031 NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
2032 HTMLElementTypeId::HTMLButtonElement |
2033 HTMLElementTypeId::HTMLInputElement |
2034 HTMLElementTypeId::HTMLSelectElement |
2035 HTMLElementTypeId::HTMLTextAreaElement => true,
2036 _ => self.is_form_associated_custom_element(),
2037 },
2038 _ => false,
2039 }
2040 }
2041
2042 pub(crate) fn label_at<'a>(
2045 &self,
2046 no_gc: &'a NoGC,
2047 index: u32,
2048 ) -> Option<UnrootedDom<'a, Node>> {
2049 let element = self.as_element();
2050
2051 let root_element = element.root_element();
2062 let root_node = root_element.upcast::<Node>();
2063 root_node
2064 .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
2065 .filter_map(UnrootedDom::downcast::<HTMLLabelElement>)
2066 .filter(|elem| match elem.GetControl(no_gc) {
2067 Some(control) => &*control == self,
2068 _ => false,
2069 })
2070 .nth(index as usize)
2071 .map(UnrootedDom::upcast)
2072 }
2073
2074 pub(crate) fn labels_count(&self, no_gc: &NoGC) -> u32 {
2077 let element = self.as_element();
2079 let root_element = element.root_element();
2080 let root_node = root_element.upcast::<Node>();
2081 root_node
2082 .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
2083 .filter_map(UnrootedDom::downcast::<HTMLLabelElement>)
2084 .filter(|elem| match elem.GetControl(no_gc) {
2085 Some(control) => &*control == self,
2086 _ => false,
2087 })
2088 .count() as u32
2089 }
2090
2091 pub(crate) fn directionality(&self) -> Option<String> {
2095 let element_direction = &self.Dir();
2096
2097 if element_direction == "ltr" {
2098 return Some("ltr".to_owned());
2099 }
2100
2101 if element_direction == "rtl" {
2102 return Some("rtl".to_owned());
2103 }
2104
2105 if let Some(input) = self.downcast::<HTMLInputElement>() &&
2106 matches!(*input.input_type(), InputType::Tel(_))
2107 {
2108 return Some("ltr".to_owned());
2109 }
2110
2111 if element_direction == "auto" {
2112 if let Some(directionality) = self
2113 .downcast::<HTMLInputElement>()
2114 .and_then(|input| input.auto_directionality())
2115 {
2116 return Some(directionality);
2117 }
2118
2119 if let Some(area) = self.downcast::<HTMLTextAreaElement>() {
2120 return Some(area.auto_directionality());
2121 }
2122 }
2123
2124 None
2131 }
2132
2133 pub(crate) fn summary_activation_behavior(&self, cx: &mut js::context::JSContext) {
2135 debug_assert!(self.as_element().local_name() == &local_name!("summary"));
2136
2137 let is_implicit_summary_element = self.is_implicit_summary_element();
2139 if !is_implicit_summary_element && !self.is_a_summary_for_its_parent_details() {
2140 return;
2141 }
2142
2143 let parent = if is_implicit_summary_element {
2145 DomRoot::downcast::<HTMLDetailsElement>(self.containing_shadow_root().unwrap().Host())
2146 .unwrap()
2147 } else {
2148 self.upcast::<Node>()
2149 .GetParentNode()
2150 .and_then(DomRoot::downcast::<HTMLDetailsElement>)
2151 .unwrap()
2152 };
2153
2154 parent.toggle(cx);
2157 }
2158
2159 pub(crate) fn is_a_summary_for_its_parent_details(&self) -> bool {
2161 let Some(parent) = self.upcast::<Node>().GetParentNode() else {
2164 return false;
2165 };
2166
2167 let Some(details) = parent.downcast::<HTMLDetailsElement>() else {
2169 return false;
2170 };
2171
2172 details
2176 .find_corresponding_summary_element()
2177 .is_some_and(|summary| &*summary == self.upcast())
2178 }
2179
2180 fn is_implicit_summary_element(&self) -> bool {
2183 self.containing_shadow_root()
2187 .as_deref()
2188 .map(ShadowRoot::Host)
2189 .is_some_and(|host| host.is::<HTMLDetailsElement>())
2190 }
2191
2192 fn rendered_text_fragment(
2194 &self,
2195 cx: &mut JSContext,
2196 input: DOMString,
2197 ) -> DomRoot<DocumentFragment> {
2198 let document = self.owner_document();
2200 let fragment = DocumentFragment::new(cx, &document);
2201
2202 let input = input.str();
2205 let mut position = input.chars().peekable();
2206
2207 let mut text = String::new();
2209
2210 while let Some(ch) = position.next() {
2212 match ch {
2213 '\u{000A}' | '\u{000D}' => {
2216 if ch == '\u{000D}' && position.peek() == Some(&'\u{000A}') {
2217 position.next();
2220 }
2221
2222 if !text.is_empty() {
2223 append_text_node_to_fragment(cx, &document, &fragment, text);
2224 text = String::new();
2225 }
2226
2227 let br = Element::create(
2228 cx,
2229 QualName::new(None, ns!(html), local_name!("br")),
2230 None,
2231 &document,
2232 ElementCreator::ScriptCreated,
2233 CustomElementCreationMode::Asynchronous,
2234 None,
2235 );
2236 fragment
2237 .upcast::<Node>()
2238 .AppendChild(cx, br.upcast())
2239 .unwrap();
2240 },
2241 _ => {
2242 text.push(ch);
2245 },
2246 }
2247 }
2248
2249 if !text.is_empty() {
2252 append_text_node_to_fragment(cx, &document, &fragment, text);
2253 }
2254
2255 fragment
2256 }
2257
2258 fn merge_with_the_next_text_node(cx: &mut JSContext, node: &Node) {
2264 if !node.is::<Text>() {
2266 return;
2267 }
2268
2269 let next = match node.GetNextSibling() {
2271 Some(next) => next,
2272 None => return,
2273 };
2274
2275 if !next.is::<Text>() {
2277 return;
2278 }
2279 let node_chars = node.downcast::<CharacterData>().expect("Node is Text");
2281 let next_chars = next.downcast::<CharacterData>().expect("Next node is Text");
2282 node_chars
2283 .ReplaceData(cx, node_chars.Length(), 0, next_chars.Data())
2284 .expect("Got chars from Text");
2285
2286 next.remove_self(cx);
2288 }
2289
2290 fn update_assigned_access_key(&self) {
2294 if !self.element.has_attribute(&local_name!("accesskey")) {
2296 self.owner_document()
2298 .event_handler()
2299 .unassign_access_key(self);
2300 }
2301
2302 let attribute_value = self.element.get_string_attribute(&local_name!("accesskey"));
2304 let string_view = attribute_value.str();
2305 let values = string_view.split_html_space_characters();
2306
2307 for value in values {
2310 let mut characters = value.chars();
2313 let Some(character) = characters.next() else {
2314 continue;
2315 };
2316 if characters.count() > 0 {
2317 continue;
2318 }
2319
2320 let Some(code) = character_to_code(character) else {
2323 continue;
2324 };
2325
2326 self.owner_document()
2331 .event_handler()
2332 .assign_access_key(self, code);
2333 return;
2334 }
2335
2336 self.owner_document()
2342 .event_handler()
2343 .unassign_access_key(self);
2344 }
2345}
2346
2347impl VirtualMethods for HTMLElement {
2348 fn super_type(&self) -> Option<&dyn VirtualMethods> {
2349 Some(self.as_element() as &dyn VirtualMethods)
2350 }
2351
2352 fn attribute_mutated(
2353 &self,
2354 cx: &mut JSContext,
2355 attr: AttrRef<'_>,
2356 mutation: AttributeMutation,
2357 ) {
2358 self.super_type()
2359 .unwrap()
2360 .attribute_mutated(cx, attr, mutation);
2361 let element = self.as_element();
2362 match (attr.local_name(), mutation) {
2363 (&local_name!("accesskey"), ..) => {
2364 self.update_assigned_access_key();
2365 },
2366 (&local_name!("popover"), mutation) => {
2368 let old_state = PopoverState::from_attribute_value(mutation.old_value(attr));
2372 if element.popover_visibility_state_showing() && old_state != self.popover_state() {
2373 let _ = self.hide_popover(cx, true, true, false, None);
2374 }
2375 },
2376 (&local_name!("inert"), mutation) => {
2378 let is_blocked_document = element.is_document_element() &&
2382 element
2383 .owner_document()
2384 .overlay_handler()
2385 .is_blocked_by_a_modal_dialog();
2386
2387 element.set_state(
2388 cx.no_gc(),
2389 ElementState::INERT,
2390 is_blocked_document || !matches!(mutation, AttributeMutation::Removed),
2391 );
2392 },
2393 (&local_name!("form"), mutation) if self.is_form_associated_custom_element() => {
2394 self.form_attribute_mutated(cx, mutation);
2395 },
2396 (&local_name!("contenteditable"), ..) => {
2399 if let Some(selection) = self.owner_document().selection() &&
2400 self.upcast::<Node>()
2401 .get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION)
2402 {
2403 selection.set_visible_selection_dirty();
2404 }
2405 },
2406 (&local_name!("disabled"), _) => {
2407 element.invalidate_disabled_state(cx);
2408 },
2409 (&local_name!("readonly"), mutation) if self.is_form_associated_custom_element() => {
2410 match mutation {
2411 AttributeMutation::Set(_) => {
2412 element.set_read_write_state(cx.no_gc(), true);
2413 },
2414 AttributeMutation::Removed => {
2415 element.set_read_write_state(cx.no_gc(), false);
2416 },
2417 }
2418 },
2419 (&local_name!("nonce"), mutation) => match mutation {
2420 AttributeMutation::Set(_) => {
2421 let nonce = &**attr.value();
2422 element.update_nonce_internal_slot(nonce.to_owned(), cx.no_gc());
2423 },
2424 AttributeMutation::Removed => {
2425 element.update_nonce_internal_slot(String::new(), cx.no_gc());
2426 },
2427 },
2428 (name, _) if &**name == "containertiming" || &**name == "containertimingignore" => {
2432 self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
2433 },
2434 _ => {},
2435 }
2436 }
2437
2438 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
2439 if let Some(super_type) = self.super_type() {
2440 super_type.bind_to_tree(cx, context);
2441 }
2442 self.element.invalidate_disabled_state(cx);
2443 if self.element.has_attribute(&local_name!("accesskey")) {
2444 self.update_assigned_access_key();
2445 }
2446 }
2447
2448 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
2449 if let Some(super_type) = self.super_type() {
2450 super_type.unbind_from_tree(cx, context);
2451 }
2452 self.element.invalidate_disabled_state(cx);
2453 if self.as_element().has_attribute(&local_name!("accesskey")) {
2454 self.owner_document()
2455 .event_handler()
2456 .unassign_access_key(self);
2457 }
2458
2459 if self.popover_state() != PopoverState::NoPopover {
2463 let _ = self.hide_popover(cx, false, false, false, None);
2464 }
2465 }
2466
2467 fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
2468 if is_element_affected_by_legacy_background_presentational_hint(
2469 self.element.namespace(),
2470 self.element.local_name(),
2471 ) && attr.local_name() == &local_name!("background")
2472 {
2473 return true;
2474 }
2475
2476 self.super_type()
2477 .unwrap()
2478 .attribute_affects_presentational_hints(attr)
2479 }
2480
2481 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
2482 match *name {
2483 local_name!("itemprop") => AttrValue::from_serialized_tokenlist(value.into()),
2484 local_name!("itemtype") => AttrValue::from_serialized_tokenlist(value.into()),
2485 local_name!("background")
2486 if is_element_affected_by_legacy_background_presentational_hint(
2487 self.element.namespace(),
2488 self.element.local_name(),
2489 ) =>
2490 {
2491 AttrValue::from_resolved_url(
2492 &self.owner_document().base_url().get_arc(),
2493 value.into(),
2494 )
2495 },
2496 _ => self
2497 .super_type()
2498 .unwrap()
2499 .parse_plain_attribute(name, value),
2500 }
2501 }
2502
2503 fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
2505 if let Some(super_type) = self.super_type() {
2509 super_type.moving_steps(cx, context);
2510 }
2511
2512 if let Some(form_control) = self.element.as_maybe_form_control() {
2516 form_control.moving_steps(cx);
2517 }
2518
2519 self.element.invalidate_disabled_state(cx);
2520 }
2521}
2522
2523impl Activatable for HTMLElement {
2524 fn as_element(&self) -> &Element {
2525 &self.element
2526 }
2527
2528 fn is_instance_activatable(&self) -> bool {
2529 self.element.local_name() == &local_name!("summary")
2530 }
2531
2532 fn activation_behavior(
2534 &self,
2535 cx: &mut js::context::JSContext,
2536 _event: &Event,
2537 _target: &EventTarget,
2538 ) {
2539 self.summary_activation_behavior(cx);
2540 }
2541}
2542
2543impl FormControl for HTMLElement {
2549 fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
2550 debug_assert!(self.is_form_associated_custom_element());
2551 self.element
2552 .get_element_internals()
2553 .and_then(|e| e.form_owner())
2554 }
2555
2556 fn set_form_owner(&self, cx: &mut JSContext, form: Option<&HTMLFormElement>) {
2557 debug_assert!(self.is_form_associated_custom_element());
2558 self.ensure_element_internals(cx).set_form_owner(form);
2559 }
2560
2561 fn to_html_element(&self) -> &HTMLElement {
2562 self
2563 }
2564}