Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_element_3.lucb

#==============================================================================================
#
#   html_element_3 - HTML::HTMLElement: the default ARIA role, attachInternals, the popover
#                    attribute, adjusting computed style, and showing a popover
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLElement.cpp (lines 947-1395): default_role, attach_internals,
#       the popover attribute's states and reflection, adjust_computed_style (wbr), check popover
#       validity, showPopover() and the show popover algorithm. The show popover algorithm's
#       cleanupShowingFlag lambda is a function; its close watcher's closeAction is a native
#       function over the element.
#
#==============================================================================================

# mark: Helpers =================================================================================

## `Optional<String> == "text"sv`: present and equal to the text.
func html_element_optional_is(value: ak.String?, text: str) -> bool:
    let present = value else return false
    return ak.string_eq_string_view(&present, ak.sv(text))

## `value.has_value() && value.value().is_one_of("auto", "hint")`.
func html_element_optional_is_auto_or_hint(value: ak.String?) -> bool:
    return html_element_optional_is(value, "auto") or html_element_optional_is(value, "hint")

## `list.contains_slow(GC::Ref(*element))`.
func html_element_list_contains(list: const ak.Vector[HtmlElement*]*, element: HtmlElement*) -> bool:
    for entry in ak.vector_span_const(list):
        if entry == element:
            return true
    return false

## `!list.is_empty() && list.last() == element`.
func html_element_list_ends_with(list: const ak.Vector[HtmlElement*]*, element: HtmlElement*) -> bool:
    return not ak.vector_is_empty(list) and *ak.vector_last_const(list) == element

# mark: The default ARIA role ===================================================================

## `ancestor->local_name().is_one_of(names...)`.
func html_element_local_name_is_one_of(element: DomElement*, names: const ak.FlyString[]) -> bool:
    let local_name = dom_element_local_name(element)
    for name in names:
        if ak.fly_string_eq_fly_string(&local_name, &name):
            return true
    return false

## `first_is_one_of(ancestor->role_or_default(), roles...)`.
func html_element_role_is_one_of(element: DomElement*, roles: const AriaRole[]) -> bool:
    let role = aria_mixin_role_or_default(&element.aria_mixin) else return false
    for candidate in roles:
        if role == candidate:
            return true
    return false

## Ported from HTMLElement.cpp:949 Web::HTML::HTMLElement::default_role (override).
pub func html_element_default_role_impl(base: AriaMixin*) -> AriaRole?:
    let this = (HtmlElement*)dom_element_from_aria_mixin(base)
    let document = html_element_document(this)
    # https://www.w3.org/TR/html-aria/#el-address
    if html_element_local_name_is(this, html_tag_names_address):
        return AriaRole.group
    # https://www.w3.org/TR/html-aria/#el-article
    if html_element_local_name_is(this, html_tag_names_article):
        return AriaRole.article
    # https://www.w3.org/TR/html-aria/#el-aside
    if html_element_local_name_is(this, html_tag_names_aside):
        # https://w3c.github.io/html-aam/#el-aside
        let sectioning_names: ak.FlyString[4] = [html_tag_names_article, html_tag_names_aside, html_tag_names_nav, html_tag_names_section]
        var ancestor = dom_node_parent_element(this.dom_node())
        while let element = ancestor:
            if html_element_local_name_is_one_of(element, sectioning_names):
                let accessible_name = dom_node_accessible_name(this.dom_node(), document) else trap("ErrorOr::value() of accessible_name")
                if ak.string_is_empty(&accessible_name):
                    return AriaRole.generic
            ancestor = dom_node_parent_element(element.dom_node())
        # https://w3c.github.io/html-aam/#el-aside-ancestorbodymain
        return AriaRole.complementary
    # https://www.w3.org/TR/html-aria/#el-b
    if html_element_local_name_is(this, html_tag_names_b):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-bdi
    if html_element_local_name_is(this, html_tag_names_bdi):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-bdo
    if html_element_local_name_is(this, html_tag_names_bdo):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-code
    if html_element_local_name_is(this, html_tag_names_code):
        return AriaRole.code
    # https://w3c.github.io/html-aam/#el-dd
    if html_element_local_name_is(this, html_tag_names_dd):
        return AriaRole.definition
    # https://wpt.fyi/results/html-aam/dir-role.tentative.html
    if html_element_local_name_is(this, html_tag_names_dir):
        return AriaRole.list
    # https://w3c.github.io/html-aam/#el-dt
    if html_element_local_name_is(this, html_tag_names_dt):
        return AriaRole.term
    # https://www.w3.org/TR/html-aria/#el-dfn
    if html_element_local_name_is(this, html_tag_names_dfn):
        return AriaRole.term
    # https://www.w3.org/TR/html-aria/#el-em
    if html_element_local_name_is(this, html_tag_names_em):
        return AriaRole.emphasis
    # https://www.w3.org/TR/html-aria/#el-figure
    if html_element_local_name_is(this, html_tag_names_figure):
        return AriaRole.figure
    # https://www.w3.org/TR/html-aria/#el-footer
    # https://www.w3.org/TR/html-aria/#el-header
    if html_element_local_name_is(this, html_tag_names_footer) or html_element_local_name_is(this, html_tag_names_header):
        # If not a descendant of an article, aside, main, nav or section element, or an element with role=article,
        # complementary, main, navigation or region then (footer) role=contentinfo (header) role=banner. Otherwise,
        # role=generic.
        let sectioning_names: ak.FlyString[5] = [html_tag_names_article, html_tag_names_aside, html_tag_names_main, html_tag_names_nav, html_tag_names_section]
        let sectioning_roles: AriaRole[5] = [AriaRole.article, AriaRole.complementary, AriaRole.main, AriaRole.navigation, AriaRole.region]
        var ancestor = dom_node_parent_element(this.dom_node())
        while let element = ancestor:
            if html_element_local_name_is_one_of(element, sectioning_names):
                if html_element_local_name_is(this, html_tag_names_footer):
                    return AriaRole.sectionfooter
                return AriaRole.sectionheader
            if html_element_role_is_one_of(element, sectioning_roles):
                if html_element_local_name_is(this, html_tag_names_footer):
                    return AriaRole.sectionfooter
                return AriaRole.sectionheader
            ancestor = dom_node_parent_element(element.dom_node())
        # then (footer) role=contentinfo.
        if html_element_local_name_is(this, html_tag_names_footer):
            return AriaRole.contentinfo
        # (header) role=banner
        return AriaRole.banner
    # https://www.w3.org/TR/html-aria/#el-hgroup
    if html_element_local_name_is(this, html_tag_names_hgroup):
        return AriaRole.group
    # https://www.w3.org/TR/html-aria/#el-i
    if html_element_local_name_is(this, html_tag_names_i):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-main
    if html_element_local_name_is(this, html_tag_names_main):
        return AriaRole.main
    # https://www.w3.org/TR/html-aria/#el-mark
    if html_element_local_name_is(this, html_tag_names_mark):
        return AriaRole.mark
    # https://www.w3.org/TR/html-aria/#el-nav
    if html_element_local_name_is(this, html_tag_names_nav):
        return AriaRole.navigation
    # https://www.w3.org/TR/html-aria/#el-s
    if html_element_local_name_is(this, html_tag_names_s):
        return AriaRole.deletion
    # https://www.w3.org/TR/html-aria/#el-samp
    if html_element_local_name_is(this, html_tag_names_samp):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-search
    if html_element_local_name_is(this, html_tag_names_search):
        return AriaRole.search
    # https://www.w3.org/TR/html-aria/#el-section
    if html_element_local_name_is(this, html_tag_names_section):
        # role=region if the section element has an accessible name
        let accessible_name = dom_node_accessible_name(this.dom_node(), document) else trap("ErrorOr::value() of accessible_name")
        if not ak.string_is_empty(&accessible_name):
            return AriaRole.region
        # Otherwise, role=generic
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-small
    if html_element_local_name_is(this, html_tag_names_small):
        return AriaRole.generic
    # https://www.w3.org/TR/html-aria/#el-strong
    if html_element_local_name_is(this, html_tag_names_strong):
        return AriaRole.strong
    # https://www.w3.org/TR/html-aria/#el-sub
    if html_element_local_name_is(this, html_tag_names_sub):
        return AriaRole.subscript
    # https://www.w3.org/TR/html-aria/#el-summary
    if html_element_local_name_is(this, html_tag_names_summary):
        return AriaRole.button
    # https://www.w3.org/TR/html-aria/#el-sup
    if html_element_local_name_is(this, html_tag_names_sup):
        return AriaRole.superscript
    # https://www.w3.org/TR/html-aria/#el-u
    if html_element_local_name_is(this, html_tag_names_u):
        return AriaRole.generic

    return none

# mark: attachInternals =========================================================================

## Ported from HTMLElement.cpp:1077 Web::HTML::HTMLElement::attach_internals.
# https://html.spec.whatwg.org/multipage/custom-elements.html#dom-attachinternals
pub func html_element_attach_internals(this: HtmlElement*) -> HtmlElementInternals*!:
    let realm = html_element_realm(this)
    let element = this.dom_element()

    # 1. If this's is value is not null, then throw a "NotSupportedError" DOMException.
    if dom_element_is_value(element) != none:
        try idl_throw(.idl_dom_exception(idl_not_supported_error_create(realm, ak.utf16_string_from_str("ElementInternals cannot be attached to a customized built-in element"))))

    # 2. Let definition be the result of looking up a custom element definition given this's custom element registry,
    #    this's namespace, this's local name, and null.
    let definition = html_look_up_a_custom_element_definition(dom_element_custom_element_registry(element), dom_element_namespace_uri(element), dom_element_local_name(element), none)

    # 3. If definition is null, then throw an "NotSupportedError" DOMException.
    if definition == none:
        try idl_throw(.idl_dom_exception(idl_not_supported_error_create(realm, ak.utf16_string_from_str("ElementInternals cannot be attached to an element that is not a custom element"))))
    let found = definition else trap("unreachable")

    # 4. If definition's disable internals is true, then throw a "NotSupportedError" DOMException.
    if html_custom_element_definition_disable_internals(found):
        try idl_throw(.idl_dom_exception(idl_not_supported_error_create(realm, ak.utf16_string_from_str("ElementInternals are disabled for this custom element"))))

    # 5. If this's attached internals is non-null, then throw an "NotSupportedError" DOMException.
    if this.m_attached_internals != none:
        try idl_throw(.idl_dom_exception(idl_not_supported_error_create(realm, ak.utf16_string_from_str("ElementInternals already attached"))))

    # 6. If this's custom element state is not "precustomized" or "custom", then throw a "NotSupportedError" DOMException.
    let state = dom_element_custom_element_state(element)
    if state != DomCustomElementState.precustomized and state != DomCustomElementState.custom:
        try idl_throw(.idl_dom_exception(idl_not_supported_error_create(realm, ak.utf16_string_from_str("Custom element is in an invalid state to attach ElementInternals"))))

    # 7. Set this's attached internals to a new ElementInternals instance whose target element is this.
    let internals = html_element_internals_create(realm, this)

    this.m_attached_internals = internals

    # 8. Return this's attached internals.
    return internals

# mark: The popover attribute ===================================================================

## Ported from HTMLElement.cpp:1112 Web::HTML::HTMLElement::popover_value_to_state.
func html_element_popover_value_to_state(value: ak.String?) -> ak.String?:
    let present = value else return none

    if ak.string_is_empty(&present) or ak.string_equals_ignoring_ascii_case_string_view(&present, ak.sv("auto")):
        return ak.string_from_str("auto")

    if ak.string_equals_ignoring_ascii_case_string_view(&present, ak.sv("hint")):
        return ak.string_from_str("hint")

    return ak.string_from_str("manual")

## Ported from HTMLElement.cpp:1126 Web::HTML::HTMLElement::popover.
# https://html.spec.whatwg.org/multipage/popover.html#dom-popover
pub func html_element_popover(this: HtmlElement*) -> ak.String?:
    # FIXME: This should probably be `Reflect` in the IDL.
    # The popover IDL attribute must reflect the popover attribute, limited to only known values.
    let value = dom_element_get_attribute(this.dom_element(), html_attribute_names_popover)
    return html_element_popover_value_to_state(value)

## Ported from HTMLElement.cpp:1135 Web::HTML::HTMLElement::set_popover.
# https://html.spec.whatwg.org/multipage/popover.html#dom-popover
pub func html_element_set_popover(this: HtmlElement*, value: ak.String?):
    # FIXME: This should probably be `Reflect` in the IDL.
    # The popover IDL attribute must reflect the popover attribute, limited to only known values.
    if let present = value:
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_popover, present)
    else:
        dom_element_remove_attribute(this.dom_element(), html_attribute_names_popover)

## Ported from HTMLElement.cpp:1146 Web::HTML::HTMLElement::adjust_computed_style (override).
pub func html_element_adjust_computed_style_impl(base: DomElement*, style: CssComputedProperties*):
    let this = (HtmlElement*)base
    # https://drafts.csswg.org/css-display-3/#unbox
    if html_element_local_name_is(this, html_tag_names_wbr):
        let display = css_computed_properties_display(style)
        if css_display_is_contents(&display):
            css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.none_)).css_style_value())

# mark: Showing a popover =======================================================================

## Ported from HTMLElement.cpp:1157 Web::HTML::HTMLElement::check_popover_validity.
# https://html.spec.whatwg.org/multipage/popover.html#check-popover-validity
# https://whatpr.org/html/9457/popover.html#check-popover-validity
pub func html_element_check_popover_validity(this: HtmlElement*, expected_to_be_showing: HtmlExpectedToBeShowing, throw_exceptions: HtmlThrowExceptions, expected_document: DomDocument*?, ignore_dom_state: HtmlIgnoreDomState) -> bool!:
    # 1. If ignoreDomState is false and element's popover attribute is in the No Popover state, then:
    if ignore_dom_state == HtmlIgnoreDomState.no and html_element_popover(this) == none:
        # 1.1. If throwExceptions is true, then throw a "NotSupportedError" DOMException.
        if throw_exceptions == HtmlThrowExceptions.yes:
            try idl_throw(.idl_dom_exception(idl_not_supported_error_create(html_element_realm(this), ak.utf16_string_from_str("Element is not a popover"))))
        # 1.2. Return false.
        return false

    # 2. If any of the following are true:
    # - expectedToBeShowing is true and element's popover visibility state is not showing; or
    # - expectedToBeShowing is false and element's popover visibility state is not hidden,
    if (expected_to_be_showing == HtmlExpectedToBeShowing.yes and this.m_popover_visibility_state != HtmlElementPopoverVisibilityState.showing) or (expected_to_be_showing == HtmlExpectedToBeShowing.no and this.m_popover_visibility_state != HtmlElementPopoverVisibilityState.hidden):
        # then return false.
        return false

    # 3. If any of the following are true:
    # - ignoreDomState is false and element is not connected;
    # - element's node document is not fully active;
    # - ignoreDomState is false and expectedDocument is not null and element's node document is not expectedDocument;
    # - element is a dialog element and its is modal flag is set to true; or
    # - FIXME: element's fullscreen flag is set,
    # then:
    # 3.1 If throwExceptions is true, then throw an "InvalidStateError" DOMException.
    # 3.2 Return false.

    if (ignore_dom_state == HtmlIgnoreDomState.no and not dom_node_is_connected(this.dom_node())) or not dom_document_is_fully_active(html_element_document(this)) or (ignore_dom_state == HtmlIgnoreDomState.no and expected_document != none and html_element_document(this) != expected_document) or (is_html_dialog_element(this) and html_dialog_element_is_modal(as_html_dialog_element(this))):
        if throw_exceptions == HtmlThrowExceptions.yes:
            try idl_throw(.idl_dom_exception(idl_invalid_state_error_create(html_element_realm(this), ak.utf16_string_from_str("Element is not in a valid state to show a popover"))))
        return false

    # 4. Return true.
    return true

## Ported from HTMLElement.cpp:1197 Web::HTML::HTMLElement::show_popover_for_bindings.
# https://html.spec.whatwg.org/multipage/popover.html#dom-showpopover
pub func html_element_show_popover_for_bindings(this: HtmlElement*, options: HtmlShowPopoverOptions) -> !:
    # 1. Let source be options["source"] if it exists; otherwise, null.
    let source = options.source
    # 2. Run show popover given this, true, and source.
    try html_element_show_popover(this, HtmlThrowExceptions.yes, source)

## show_popover's `enum class StackToAppendTo : u8`.
enum HtmlElementShowPopoverStackToAppendTo as u8:
    null = 0
    auto_ = 1
    hint = 2

## show_popover's cleanupShowingFlag: `[&nested_show, this] { if (!nested_show) m_popover_showing_or_hiding = false; }`.
func html_element_show_popover_cleanup_showing_flag(this: HtmlElement*, nested_show: bool):
    # 8.1. If nestedShow is false, then set element's popover showing or hiding to false.
    if not nested_show:
        this.m_popover_showing_or_hiding = false

## show_popover's close watcher closeAction: `[this](JS::VM&) { MUST(hide_popover(...)); return js_undefined(); }`.
func html_element_show_popover_close_action(context: void*?, vm: Vm*) -> JsValue!:
    let this = (HtmlElement*)(context else trap("closeAction: no element"))
    html_element_hide_popover(this, HtmlFocusPreviousElement.yes, HtmlFireEvents.yes, HtmlThrowExceptions.no, HtmlIgnoreDomState.no, none) else trap("MUST: hide_popover")

    return js_undefined()

## show_popover's getEnabledState: `[] { return true; }`.
func html_element_show_popover_get_enabled_state(context: void*?) -> bool:
    return true

## Ported from HTMLElement.cpp:1207 Web::HTML::HTMLElement::show_popover.
# https://html.spec.whatwg.org/multipage/popover.html#show-popover
# https://whatpr.org/html/9457/popover.html#show-popover
pub func html_element_show_popover(this: HtmlElement*, throw_exceptions: HtmlThrowExceptions, source: HtmlElement*?) -> !:
    let realm = html_element_realm(this)

    # 1. If the result of running check popover validity given element, false, throwExceptions, null and false is false, then return.
    if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.no, throw_exceptions, none, HtmlIgnoreDomState.no):
        return

    # 2. Let document be element's node document.
    let document = html_element_document(this)

    # 3. Assert: element's popover trigger is null.
    assert(this.m_popover_trigger == none)

    # 4. Assert: element is not in document's top layer.
    assert(not dom_element_in_top_layer(this.dom_element()))

    # 5. Let nestedShow be element's popover showing or hiding.
    let nested_show = this.m_popover_showing_or_hiding

    # 6. Let fireEvents be the boolean negation of nestedShow.
    let fire_events = HtmlFireEvents.no if nested_show else HtmlFireEvents.yes

    # 7. Set element's popover showing or hiding to true.
    this.m_popover_showing_or_hiding = true

    # 8. Let cleanupShowingFlag be the following steps: (html_element_show_popover_cleanup_showing_flag)

    # 9. 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" at element, and the source attribute initialized to source at element is false,
    #    then run cleanupShowingFlag and return.
    var event_init = HtmlToggleEventInit()
    event_init.old_state = ak.string_from_str("closed")
    event_init.new_state = ak.string_from_str("open")
    event_init.event_init.cancelable = true
    if let source_element = source:
        event_init.source = source_element.dom_element()
    if not dom_event_target_dispatch_event(this.dom_event_target(), html_toggle_event_create(realm, html_event_names_beforetoggle, event_init).dom_event()):
        html_element_show_popover_cleanup_showing_flag(this, nested_show)
        return

    # 10. If the result of running check popover validity given element, false, throwExceptions, document, and false is false, then run cleanupShowingFlag and return.
    if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.no, throw_exceptions, document, HtmlIgnoreDomState.no):
        html_element_show_popover_cleanup_showing_flag(this, nested_show)
        return

    # 11. Let shouldRestoreFocus be false.
    let should_restore_focus = HtmlFocusPreviousElement.no

    # 12. Let originalType be the current state of element's popover attribute.
    let original_type = html_element_popover(this)

    # 13. Let stackToAppendTo be null.
    var stack_to_append_to = HtmlElementShowPopoverStackToAppendTo.null

    # NB: Steps 14 and 15 are implemented inside step 17 instead, see note below.

    # 16. If originalType is the Auto state, then:
    if html_element_optional_is(original_type, "auto"):
        # 1. Run close entire popover list given document's showing hint popover list, shouldRestoreFocus, and fireEvents.
        html_element_close_entire_popover_list(dom_document_showing_hint_popover_list(document), should_restore_focus, fire_events)

        # 2. Let ancestor be the result of running the topmost popover ancestor algorithm given element, document's showing auto popover list, source, and true.
        let topmost_ancestor = html_element_topmost_popover_ancestor(this.dom_node(), dom_document_showing_auto_popover_list(document), source, HtmlIsPopover.yes)
        var ancestor = HtmlElementOrDomDocument.html_element(topmost_ancestor)

        # 3. If ancestor is null, then set ancestor to document.
        if topmost_ancestor == none:
            ancestor = .dom_document(document)

        # 4. Run hide all popovers until given ancestor, shouldRestoreFocus, and fireEvents.
        html_element_hide_all_popovers_until(ancestor, should_restore_focus, fire_events)

        # 5. Set stackToAppendTo to "auto".
        stack_to_append_to = HtmlElementShowPopoverStackToAppendTo.auto_

    # 17. If originalType is the hint state, then:
    if html_element_optional_is(original_type, "hint"):
        # AD-HOC: Steps 14 and 15 have been moved here to avoid hitting the `popover != manual` assertion in the topmost popover ancestor algorithm.
        # Spec issue: https://github.com/whatwg/html/issues/10988.
        # 14. Let autoAncestor be the result of running the topmost popover ancestor algorithm given element, document's showing auto popover list, invoker, and true.
        let auto_ancestor = html_element_topmost_popover_ancestor(this.dom_node(), dom_document_showing_auto_popover_list(document), source, HtmlIsPopover.yes)

        # 15. Let hintAncestor be the result of running the topmost popover ancestor algorithm given element, document's showing hint popover list, invoker, and true.
        let hint_ancestor = html_element_topmost_popover_ancestor(this.dom_node(), dom_document_showing_hint_popover_list(document), source, HtmlIsPopover.yes)

        # 1. If hintAncestor is not null, then:
        if hint_ancestor != none:
            # 1. Run hide all popovers until given hintAncestor, shouldRestoreFocus, and fireEvents.
            html_element_hide_all_popovers_until(.html_element(hint_ancestor), should_restore_focus, fire_events)

            # 2. Set stackToAppendTo to "hint".
            stack_to_append_to = HtmlElementShowPopoverStackToAppendTo.hint
        # 2. Otherwise:
        else:
            # 1. Run close entire popover list given document's showing hint popover list, shouldRestoreFocus, and fireEvents.
            html_element_close_entire_popover_list(dom_document_showing_hint_popover_list(document), should_restore_focus, fire_events)

            # 2. If autoAncestor is not null, then:
            if auto_ancestor != none:
                # 1. Run hide all popovers until given autoAncestor, shouldRestoreFocus, and fireEvents.
                html_element_hide_all_popovers_until(.html_element(auto_ancestor), should_restore_focus, fire_events)

                # 2. Set stackToAppendTo to "auto".
                stack_to_append_to = HtmlElementShowPopoverStackToAppendTo.auto_
            # 3. Otherwise, set stackToAppendTo to "hint".
            else:
                stack_to_append_to = HtmlElementShowPopoverStackToAppendTo.hint

    # 18. If originalType is auto or hint, then:
    if html_element_optional_is_auto_or_hint(original_type):
        # 1. Assert: stackToAppendTo is not null.
        assert(stack_to_append_to != HtmlElementShowPopoverStackToAppendTo.null)

        # 2. If originalType is not equal to the value of element's popover attribute, then:
        if not dom_node_optional_strings_equal(original_type, html_element_popover(this)):
            # 1. If throwExceptions is true, then throw an "InvalidStateError" DOMException.
            if throw_exceptions == HtmlThrowExceptions.yes:
                try idl_throw(.idl_dom_exception(idl_invalid_state_error_create(realm, ak.utf16_string_from_str("Element is not in a valid state to show a popover"))))

            # 2. Return.
            return

        # 3. If the result of running check popover validity given element, false, throwExceptions, document, and false is false, then run cleanupShowingFlag and return.
        if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.no, throw_exceptions, document, HtmlIgnoreDomState.no):
            html_element_show_popover_cleanup_showing_flag(this, nested_show)
            return

        # FIXME: 4. If the result of running topmost auto or hint popover on document is null, then set shouldRestoreFocus to true.

        # 5. If stackToAppendTo is "auto":
        if stack_to_append_to == HtmlElementShowPopoverStackToAppendTo.auto_:
            # 1. Assert: document's showing auto popover list does not contain element.
            assert(not html_element_list_contains(dom_document_showing_auto_popover_list(document), this))

            # AD-HOC: Append element to the document's showing auto popover list.
            # Spec issue: https://github.com/whatwg/html/issues/11007
            ak.vector_append_t(dom_document_showing_auto_popover_list(document), this)

            # 2. Set element's opened in popover mode to "auto".
            this.m_opened_in_popover_mode = ak.string_from_str("auto")
        # Otherwise:
        else:
            # 1. Assert: stackToAppendTo is "hint".
            assert(stack_to_append_to == HtmlElementShowPopoverStackToAppendTo.hint)

            # 2. Assert: document's showing hint popover list does not contain element.
            assert(not html_element_list_contains(dom_document_showing_hint_popover_list(document), this))

            # AD-HOC: Append element to the document's showing hint popover list.
            # Spec issue: https://github.com/whatwg/html/issues/11007
            ak.vector_append_t(dom_document_showing_hint_popover_list(document), this)

            # 3. Set element's opened in popover mode to "hint".
            this.m_opened_in_popover_mode = ak.string_from_str("hint")

        # 6. Set element's popover close watcher to the result of establishing a close watcher given element's relevant global object, with:
        # - cancelAction being to return true.
        # NB: We simply don't add an event listener for the cancel action.
        # - closeAction being to hide a popover given element, true, true, false, and null.
        let close_callback_function = js_native_function_create(realm, JsNativeFunctionBehaviour(call = html_element_show_popover_close_action, context = this), 0, ak.utf16_fly_string_new(), realm)
        let close_callback = realm_create_idl_callback_type_realm(realm, (JsObject*)close_callback_function, realm, IdlOperationReturnsPromise.no)
        # - getEnabledState being to return true.
        let get_enabled_state = gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[bool](call = html_element_show_popover_get_enabled_state, context = none))

        let window = dom_document_window(document) else trap("VERIFY: GC::Ptr<Window>::operator* on null")
        let close_watcher = html_close_watcher_establish(window, get_enabled_state)
        this.m_popover_close_watcher = close_watcher
        dom_event_target_add_event_listener_without_options(close_watcher.dom_event_target(), html_event_names_close, dom_idl_event_listener_create(realm, close_callback))
    # FIXME: 19. Set element's previously focused element to null.
    # FIXME: 20. Let originallyFocusedElement be document's focused area of the document's DOM anchor.
    # 21. Add an element to the top layer given element.
    dom_document_add_an_element_to_the_top_layer(document, this.dom_element())
    # 22. Set element's popover visibility state to showing.
    this.m_popover_visibility_state = HtmlElementPopoverVisibilityState.showing
    # 23. Set element's popover trigger to source.
    this.m_popover_trigger = source
    # FIXME: 24. Set element's implicit anchor element to source.
    # FIXME: 25. Run the popover focusing steps given element.
    # FIXME: 26. If shouldRestoreFocus is true and element's popover attribute is not in the No Popover state, then set element's previously focused element to originallyFocusedElement.
    # 27. Queue a popover toggle event task given element, "closed", "open", and source.
    html_element_queue_a_popover_toggle_event_task(this, ak.string_from_str("closed"), ak.string_from_str("open"), source)
    # 28. Run cleanupShowingFlag.
    html_element_show_popover_cleanup_showing_flag(this, nested_show)