Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_button_element.lucb

#==============================================================================================
#
#   html_button_element - HTML::HTMLButtonElement: <button>
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLButtonElement.cpp (lines 1-352) and the inline functions of
#       HTMLButtonElement.h: construction (which moves the mixin tables to HTMLButtonElement's,
#       as C++'s vptrs move), button layout's display adjustment, the type attribute's states,
#       the value, the activation behavior (submitting or resetting the form owner, the command
#       and commandfor attributes, the popover target), the command IDL attribute and the
#       FormAssociatedElement overrides.
#
#       Copyright (c) 2020, the SerenityOS developers.
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Construction ============================================================================

## The button element of its FormAssociatedElement base (C++'s `this` adjustment).
func html_button_element_from_form_associated_element(base: HtmlFormAssociatedElement*) -> HtmlButtonElement*:
    return (HtmlButtonElement*)((u8*)base - memory.offset_of(HtmlElement, form_associated_element))

## Ported from HTMLButtonElement.cpp:21 Web::HTML::HTMLButtonElement::HTMLButtonElement.
pub func html_button_element_construct(this: HtmlButtonElement*, document: DomDocument*, qualified_name: DomQualifiedName):
    html_element_construct(this.html_element(), document, qualified_name)
    # The vptrs of the mixin bases move to HTMLButtonElement's tables.
    let element = this.html_element()
    element.element.slottable_mixin.vtable = &html_button_element_slottable_mixin_vtable
    element.element.aria_mixin.vtable = &html_button_element_aria_mixin_vtable
    element.element.animatable.vtable = &html_button_element_animatable_vtable
    element.global_event_handlers.vtable = &html_button_element_global_event_handlers_vtable
    element.form_associated_element.vtable = &html_button_element_form_associated_element_vtable

## Ported from HTMLButtonElement.cpp:28 Web::HTML::HTMLButtonElement::initialize (override).
pub func html_button_element_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.html_button_element)
    html_element_initialize_impl(base, realm)

## Ported from HTMLButtonElement.cpp:34 Web::HTML::HTMLButtonElement::adjust_computed_style (override).
pub func html_button_element_adjust_computed_style_impl(base: DomElement*, style: CssComputedProperties*):
    _ = base
    # https://html.spec.whatwg.org/multipage/rendering.html#button-layout
    # If the computed value of 'display' is 'inline-grid', 'grid', 'inline-flex', 'flex', 'none', or 'contents', then behave as the computed value.
    let display = css_computed_properties_display(style)
    if css_display_is_flex_inside(&display) or css_display_is_grid_inside(&display) or css_display_is_none(&display) or css_display_is_contents(&display):
        # No-op
        _ = display
    elif css_display_is_inline_outside(&display):
        # Otherwise, if the computed value of 'display' is a value such that the outer display type is 'inline', then behave as 'inline-block'.
        # AD-HOC: See https://github.com/whatwg/html/issues/11857
        css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.inline_block)).css_style_value())
    else:
        # Otherwise, behave as 'flow-root'.
        css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.flow_root)).css_style_value())

# mark: The type attribute ======================================================================

## The keywords of ENUMERATE_HTML_BUTTON_TYPE_ATTRIBUTES, in the order of TypeAttributeState.
let html_button_element_type_keywords: str[4] = ["submit", "reset", "button", "auto"]

## Ported from HTMLButtonElement.cpp:51 Web::HTML::HTMLButtonElement::type_state.
pub func html_button_element_type_state(this: HtmlButtonElement*) -> HtmlButtonElementTypeAttributeState:
    let value = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_type)

    for (index, keyword) in html_button_element_type_keywords.indexed():
        if ak.string_equals_ignoring_ascii_case_string_view(&value, ak.sv(keyword)):
            return (HtmlButtonElementTypeAttributeState)(i32)index

    # The attribute's missing value default and invalid value default are both the Auto state.
    # https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type-auto-state
    return HtmlButtonElementTypeAttributeState.auto

## Ported from HTMLButtonElement.cpp:67 Web::HTML::HTMLButtonElement::type_for_bindings.
# https://html.spec.whatwg.org/multipage/form-elements.html#dom-button-type
pub func html_button_element_type_for_bindings(this: HtmlButtonElement*) -> ak.String:
    # The type getter steps are:
    # 1. If this is a submit button, then return "submit".
    if html_button_element_is_submit_button_impl(&this.html_element_base.form_associated_element):
        return ak.string_from_str("submit")

    # 2. Let state be this's type attribute.
    let state = html_button_element_type_state(this)

    # 3. Assert: state is not in the Submit Button state.
    assert(state != HtmlButtonElementTypeAttributeState.submit)

    # 4. If state is in the Auto state, then return "button".
    if state == HtmlButtonElementTypeAttributeState.auto:
        return ak.string_from_str("button")

    # 5. Return the keyword value corresponding to state.
    let index = (usize)(i32)state
    if index < html_button_element_type_keywords.length:
        return ak.string_from_str(html_button_element_type_keywords[index])
    trap("VERIFY_NOT_REACHED")

## Ported from HTMLButtonElement.cpp:96 Web::HTML::HTMLButtonElement::set_type_for_bindings.
# https://html.spec.whatwg.org/multipage/form-elements.html#dom-button-type
pub func html_button_element_set_type_for_bindings(this: HtmlButtonElement*, type_: ak.String):
    # The type setter steps are to set the type content attribute to the given value.
    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_type, type_)

## Ported from HTMLButtonElement.cpp:102 Web::HTML::HTMLButtonElement::form_associated_element_attribute_changed (override).
pub func html_button_element_form_associated_element_attribute_changed_impl(base: HtmlFormAssociatedElement*, name: ak.FlyString, old_value: ak.String?, value: ak.String?, namespace_: ak.FlyString?):
    _ = old_value
    let this = html_button_element_from_form_associated_element(base)
    html_popover_target_attributes_associated_attribute_changed(&this.popover_target_attributes, name, value, namespace_)

## Ported from HTMLButtonElement.cpp:107 Web::HTML::HTMLButtonElement::visit_edges (override).
pub func html_button_element_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlButtonElement*)base
    html_element_visit_edges_impl(base, visitor)
    html_popover_target_attributes_visit_edges(&this.popover_target_attributes, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_command_for_element)

## Ported from HTMLButtonElement.cpp:115 Web::HTML::HTMLButtonElement::default_tab_index_value (override).
# https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
pub func html_button_element_default_tab_index_value_impl(base: DomElement*) -> i32:
    _ = base
    # See the base function for the spec comments.
    return 0

## Ported from HTMLButtonElement.cpp:123 Web::HTML::HTMLButtonElement::is_submit_button (override).
# https://html.spec.whatwg.org/multipage/forms.html#concept-submit-button
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:concept-submit-button
pub func html_button_element_is_submit_button_impl(base: HtmlFormAssociatedElement*) -> bool:
    let this = html_button_element_from_form_associated_element(base)
    # A button element is said to be a submit button if any of the following are true:
    match html_button_element_type_state(this):
        # - the type attribute is in the Auto state and both the command and commandfor content attributes are not present; or
        .auto:
            return not dom_element_has_attribute(this.dom_element(), html_attribute_names_command) and not dom_element_has_attribute(this.dom_element(), html_attribute_names_commandfor)
        # - the type attribute is in the Submit Button state.
        .submit:
            return true
        _:
            return false

# mark: The value ===============================================================================

## Ported from HTMLButtonElement.cpp:139 Web::HTML::HTMLButtonElement::value.
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:concept-fe-value
pub func html_button_element_value(this: HtmlButtonElement*) -> ak.Utf16String:
    # The element's value is the value of the element's value attribute, if there is one; otherwise the empty string.
    let value = dom_element_attribute(this.dom_element(), html_attribute_names_value) else ak.string_new()
    return ak.utf16_string_from_utf8_string(&value)

## Ported from HTMLButtonElement.cpp:146 Web::HTML::HTMLButtonElement::optional_value (override).
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:concept-fe-optional-value
pub func html_button_element_optional_value_impl(base: HtmlFormAssociatedElement*) -> ak.String?:
    let this = html_button_element_from_form_associated_element(base)
    # The element's optional value is the value of the element's value attribute, if there is one; otherwise null.
    return dom_element_attribute(this.dom_element(), html_attribute_names_value)

# mark: Activation ==============================================================================

## Ported from HTMLButtonElement.cpp:152 Web::HTML::HTMLButtonElement::has_activation_behavior (override).
pub func html_button_element_has_activation_behavior_impl(base: DomEventTarget*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.cpp:158 Web::HTML::determine_if_a_command_is_valid_for_a_target.
# https://html.spec.whatwg.org/multipage/form-elements.html#determine-if-command-is-valid
func html_determine_if_a_command_is_valid_for_a_target(command: ak.String, target: DomElement*?) -> bool:
    # 1. If command is in the Unknown state, then return false.
    if ak.string_is_empty(&command):
        return false

    # 2. If command is in the Custom state, then return true.
    if ak.string_starts_with_bytes(&command, ak.sv("--")):
        return true

    # 3. If target is not an HTML element, then return false.
    let target_node = target else return false
    let target_element = as_if_html_element(target_node) else return false

    # 4. If command is in any of the following states:
    #    - Toggle Popover
    #    - Show Popover
    #    - Hide Popover
    #    then return true.
    if ak.string_eq_string_view(&command, ak.sv("toggle-popover")) or ak.string_eq_string_view(&command, ak.sv("show-popover")) or ak.string_eq_string_view(&command, ak.sv("hide-popover")):
        return true

    # 5. If this standard does not define is valid command steps for target's local name, then return false.
    # 6. Otherwise, return the result of running target's corresponding is valid command steps given command.
    var command_value = command
    return html_element_is_valid_command(target_element, &command_value)

## Ported from HTMLButtonElement.cpp:187 Web::HTML::HTMLButtonElement::activation_behavior (override).
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:activation-behaviour
pub func html_button_element_activation_behavior_impl(base: DomEventTarget*, event: DomEvent*):
    let this = (HtmlButtonElement*)base
    let form_associated_element = &this.html_element_base.form_associated_element
    # 1. If element is disabled, then return.
    if not html_form_associated_element_enabled(form_associated_element):
        return

    # 2. If element's node document is not fully active, then return.
    if not dom_document_is_fully_active(dom_node_document(this.dom_node())):
        return

    # 3. If element has a form owner:
    if let form = html_form_associated_element_form(form_associated_element):
        # 1. If element is a submit button, then submit element's form owner from element with userInvolvement set to event's user navigation involvement, and return.
        if html_button_element_is_submit_button_impl(form_associated_element):
            html_form_element_submit_form(form, this.html_element(), HtmlFormElementSubmitFormOptions(user_involvement = html_user_navigation_involvement(event))) else trap("FIXME: should propagate errors")
            return
        # 2. If element's type attribute is in the Reset Button state, then reset element's form owner, and return.
        if html_button_element_type_state(this) == HtmlButtonElementTypeAttributeState.reset:
            html_form_element_reset_form(form)
            return
        # 3. If element's type attribute is in the Auto state, then return.
        if html_button_element_type_state(this) == HtmlButtonElementTypeAttributeState.auto:
            return

    # 4. Let target be the result of running element's get the commandfor-associated element.
    let target = dom_element_get_the_attribute_associated_element(this.dom_element(), html_attribute_names_commandfor, this.m_command_for_element)

    # 5. If target is not null:
    if let target_node = target:
        # 1. Let command be element's command attribute.
        var command = html_button_element_command(this)

        # 2. If the result of determining if a command is valid for a target given command and target is false, then return.
        if not html_determine_if_a_command_is_valid_for_a_target(command, target):
            return

        # 3. Let continue be the result of firing an event named command at target, using CommandEvent, with its
        #    command attribute initialized to command, its source attribute initialized to element, and its cancelable
        #    attribute initialized to true.
        # NOTE: DOM standard issue #1328 tracks how to better standardize associated event data in a way which makes
        #       sense on Events. Currently an event attribute initialized to a value cannot also have a getter, and so
        #       an internal slot (or map of additional fields) is required to properly specify this.
        var event_init = HtmlCommandEventInit(event_init = DomEventInit(), command = ak.string_new(), source = none)
        event_init.command = command
        event_init.source = this.dom_element()
        event_init.event_init.cancelable = true

        let command_event = html_command_event_create(html_element_realm(this.html_element()), html_event_names_command, event_init)
        dom_event_set_is_trusted(command_event, true)
        let continue_ = dom_event_target_dispatch_event(target_node.dom_event_target(), command_event)

        # 4. If continue is false, then return.
        if not continue_:
            return

        # 5. If target is not connected, then return.
        if not dom_node_is_connected(target_node.dom_node()):
            return

        # 6. If command is in the Custom state, then return.
        if ak.string_starts_with_bytes(&command, ak.sv("--")):
            return

        let target_element = as_html_element(target_node)

        # 7. If command is in the Hide Popover state:
        if ak.string_eq_string_view(&command, ak.sv("hide-popover")):
            # 1. If the result of running check popover validity given target, true, false, and null is true,
            #    then run the hide popover algorithm given target, true, true, false, and element.
            if html_element_check_popover_validity(target_element, HtmlExpectedToBeShowing.yes, HtmlThrowExceptions.no, none, HtmlIgnoreDomState.no) else trap("MUST: check_popover_validity"):
                html_element_hide_popover(target_element, HtmlFocusPreviousElement.yes, HtmlFireEvents.yes, HtmlThrowExceptions.no, HtmlIgnoreDomState.no, this.html_element()) else trap("MUST: hide_popover")

        # 8. Otherwise, if command is in the Toggle Popover state:
        elif ak.string_eq_string_view(&command, ak.sv("toggle-popover")):
            # 1. If the result of running check popover validity given target, false, false, and null is true,
            #    then run the show popover algorithm given target, false, and this.
            if html_element_check_popover_validity(target_element, HtmlExpectedToBeShowing.no, HtmlThrowExceptions.no, none, HtmlIgnoreDomState.no) else trap("MUST: check_popover_validity"):
                html_element_show_popover(target_element, HtmlThrowExceptions.no, this.html_element()) else trap("MUST: show_popover")

            # 2. Otherwise, if the result of running check popover validity given target, true, false, and null is true,
            #    then run the hide popover algorithm given target, true, true, false and element.
            elif html_element_check_popover_validity(target_element, HtmlExpectedToBeShowing.yes, HtmlThrowExceptions.no, none, HtmlIgnoreDomState.no) else trap("MUST: check_popover_validity"):
                html_element_hide_popover(target_element, HtmlFocusPreviousElement.yes, HtmlFireEvents.yes, HtmlThrowExceptions.no, HtmlIgnoreDomState.no, this.html_element()) else trap("MUST: hide_popover")

        # 9. Otherwise, if command is in the Show Popover state:
        elif ak.string_eq_string_view(&command, ak.sv("show-popover")):
            # 1. If the result of running check popover validity given target, false, false, and null is true,
            #    then run the show popover algorithm given target, false, and this.
            if html_element_check_popover_validity(target_element, HtmlExpectedToBeShowing.no, HtmlThrowExceptions.no, none, HtmlIgnoreDomState.no) else trap("MUST: check_popover_validity"):
                html_element_show_popover(target_element, HtmlThrowExceptions.no, this.html_element()) else trap("MUST: show_popover")

        # 10. Otherwise, if this standard defines command steps for target's local name,
        #     then run the corresponding command steps given target, element, and command.
        else:
            html_element_command_steps(target_element, this.dom_element(), &command)

    # 6. Otherwise, run the popover target attribute activation behavior given element and event's target.
    elif let event_target = dom_event_target(event):
        if is_dom_node(event_target):
            html_popover_target_attributes_popover_target_activation_behaviour(this.dom_node(), as_dom_node(event_target))

## Ported from HTMLButtonElement.cpp:300 Web::HTML::HTMLButtonElement::is_focusable (override).
pub func html_button_element_is_focusable_impl(base: DomEventTarget*) -> bool:
    let this = (HtmlButtonElement*)base
    return html_form_associated_element_enabled(&this.html_element_base.form_associated_element)

# mark: The command attribute ===================================================================

## The valid command keywords: `Array valid_values { "toggle-popover"_string, ... }`.
let html_button_element_command_valid_values: str[6] = ["toggle-popover", "show-popover", "hide-popover", "close", "request-close", "show-modal"]

## Ported from HTMLButtonElement.cpp:306 Web::HTML::HTMLButtonElement::command.
# https://html.spec.whatwg.org/multipage/form-elements.html#dom-button-command
pub func html_button_element_command(this: HtmlButtonElement*) -> ak.String:
    # 1. Let command be this's command attribute.
    let command = dom_element_get_attribute(this.dom_element(), html_attribute_names_command)

    # https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-command
    # The command attribute is an enumerated attribute with the following keywords and states:
    # Keyword                  State          Brief description
    # toggle-popover           Toggle Popover Shows or hides the targeted popover element.
    # show-popover             Show Popover   Shows the targeted popover element.
    # hide-popover             Hide Popover   Hides the targeted popover element.
    # close                    Close          Closes the targeted dialog element.
    # request-close            Request Close  Requests to close the targeted dialog element.
    # show-modal               Show Modal     Opens the targeted dialog element as modal.
    # A custom command keyword Custom         Only dispatches the command event on the targeted element.

    # 2. If command is in the Custom state, then return command's value.
    #    A custom command keyword is a string that starts with "--".
    if let command_value = command:
        if ak.string_starts_with_bytes(&command_value, ak.sv("--")):
            return command_value

    # NOTE: Steps are re-ordered a bit.

    # 4. Return the keyword corresponding to the value of command.return
    if let command_value = command:
        for value in html_button_element_command_valid_values:
            if ak.string_equals_ignoring_ascii_case_string_view(&command_value, ak.sv(value)):
                return ak.string_from_str(value)

    # 3. If command is in the Unknown state, then return the empty string.
    #    The attribute's missing value default and invalid value default are both the Unknown state.
    return ak.string_new()

## Ported from HTMLButtonElement.cpp:347 Web::HTML::HTMLButtonElement::set_command.
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:dom-button-command-2
pub func html_button_element_set_command(this: HtmlButtonElement*, value: ak.String):
    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_command, value)

# mark: Inline functions of HTMLButtonElement.h =================================================

## Ported from HTMLButtonElement.h:52 Web::HTML::HTMLButtonElement::is_form_associated_element (override).
pub func html_button_element_is_form_associated_element_impl(base: HtmlFormAssociatedElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:56 Web::HTML::HTMLButtonElement::is_listed (override).
# https://html.spec.whatwg.org/multipage/forms.html#category-listed
pub func html_button_element_is_listed_impl(base: HtmlFormAssociatedElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:59 Web::HTML::HTMLButtonElement::is_submittable (override).
# https://html.spec.whatwg.org/multipage/forms.html#category-submit
pub func html_button_element_is_submittable_impl(base: HtmlFormAssociatedElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:62 Web::HTML::HTMLButtonElement::is_autocapitalize_and_autocorrect_inheriting (override).
# https://html.spec.whatwg.org/multipage/forms.html#category-autocapitalize
pub func html_button_element_is_autocapitalize_and_autocorrect_inheriting_impl(base: HtmlFormAssociatedElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:66 Web::HTML::HTMLButtonElement::is_button (override).
# https://html.spec.whatwg.org/multipage/forms.html#concept-button
# https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element:concept-button
pub func html_button_element_is_button_impl(base: HtmlFormAssociatedElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:72 Web::HTML::HTMLButtonElement::is_labelable (override).
# https://html.spec.whatwg.org/multipage/forms.html#category-label
pub func html_button_element_is_labelable_impl(base: HtmlElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:75 Web::HTML::HTMLButtonElement::default_role (override).
# https://www.w3.org/TR/html-aria/#el-button
pub func html_button_element_default_role_impl(base: AriaMixin*) -> AriaRole?:
    _ = base
    return AriaRole.button

## Ported from HTMLButtonElement.h:78 Web::HTML::HTMLButtonElement::form_value (override).
pub func html_button_element_form_value_impl(base: HtmlFormAssociatedElement*) -> ak.Utf16String:
    return html_button_element_value(html_button_element_from_form_associated_element(base))

## Ported from HTMLButtonElement.h:87 Web::HTML::HTMLButtonElement::command_for_element.
pub func html_button_element_command_for_element(this: HtmlButtonElement*) -> DomElement*?:
    return this.m_command_for_element

## Ported from HTMLButtonElement.h:88 Web::HTML::HTMLButtonElement::set_command_for_element.
pub func html_button_element_set_command_for_element(this: HtmlButtonElement*, value: DomElement*?):
    this.m_command_for_element = value

## Ported from HTMLButtonElement.h:91 Web::HTML::HTMLButtonElement::uses_button_layout (override).
# https://html.spec.whatwg.org/multipage/rendering.html#the-button-element-2:button-layout-2
pub func html_button_element_uses_button_layout_impl(base: HtmlElement*) -> bool:
    _ = base
    return true

## Ported from HTMLButtonElement.h:96 Web::HTML::HTMLButtonElement::is_html_button_element (override).
pub func html_button_element_is_html_button_element_impl(base: DomNode*) -> bool:
    _ = base
    return true