Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_details_element.lucb

#==============================================================================================
#
#   html_details_element - HTML::HTMLDetailsElement: <details>, its name group and shadow tree
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLDetailsElement.cpp (lines 1-321) and HTMLDetailsElement.h: the
#       constructor (which moves the mixin tables to HTMLDetailsElement's, as C++'s vptrs move),
#       initialize, the insertion and attribute change steps, details toggle events, details
#       exclusivity in a name group, and the user-agent shadow tree with its summary and
#       descendants slots.
#
#==============================================================================================

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

## Ported from HTMLDetailsElement.cpp:27 Web::HTML::HTMLDetailsElement::HTMLDetailsElement.
pub func html_details_element_construct(this: HtmlDetailsElement*, document: DomDocument*, qualified_name: DomQualifiedName):
    html_element_construct(this.html_element(), document, qualified_name)
    # The vptrs of the mixin bases move to HTMLDetailsElement's tables.
    let element = this.html_element()
    element.element.slottable_mixin.vtable = &html_details_element_slottable_mixin_vtable
    element.element.aria_mixin.vtable = &html_details_element_aria_mixin_vtable
    element.element.animatable.vtable = &html_details_element_animatable_vtable
    element.global_event_handlers.vtable = &html_details_element_global_event_handlers_vtable
    element.form_associated_element.vtable = &html_details_element_form_associated_element_vtable

## Ported from HTMLDetailsElement.cpp:41 Web::HTML::HTMLDetailsElement::initialize (override).
pub func html_details_element_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.html_details_element)
    html_element_initialize_impl(base, realm)

## Ported from HTMLDetailsElement.cpp:34 Web::HTML::HTMLDetailsElement::visit_edges (override).
pub func html_details_element_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlDetailsElement*)base
    html_element_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_summary_slot)
    gc.cell_visitor_visit_t(visitor, this.m_descendants_slot)

# mark: Insertion and attribute changes =========================================================

## Ported from HTMLDetailsElement.cpp:48 Web::HTML::HTMLDetailsElement::inserted (override).
# https://html.spec.whatwg.org/multipage/interactive-elements.html#the-details-element:html-element-insertion-steps
pub func html_details_element_inserted_impl(base: DomNode*):
    let this = (HtmlDetailsElement*)base
    html_element_inserted_impl(base)

    # 1. Ensure details exclusivity by closing the given element if needed given insertedNode.
    html_details_element_ensure_details_exclusivity_by_closing_the_given_element_if_needed(this)

    html_details_element_create_shadow_tree_if_needed(this) else trap("FIXME: should propagate errors")
    html_details_element_update_shadow_tree_slots(this)

## Ported from HTMLDetailsElement.cpp:60 Web::HTML::HTMLDetailsElement::attribute_changed (override).
# https://html.spec.whatwg.org/multipage/interactive-elements.html#the-details-element:concept-element-attributes-change-ext
pub func html_details_element_attribute_changed_impl(base: DomElement*, local_name: ak.FlyString, old_value: ak.String?, value: ak.String?, namespace_: ak.FlyString?):
    let this = (HtmlDetailsElement*)base
    html_element_attribute_changed_impl(base, local_name, old_value, value, namespace_)

    # 1. If namespace is not null, then return.
    if namespace_ != none:
        return

    # 2. If localName is name, then ensure details exclusivity by closing the given element if needed given element.
    if ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_name):
        html_details_element_ensure_details_exclusivity_by_closing_the_given_element_if_needed(this)
        html_details_element_update_shadow_tree_style(this)

    # 3. If localName is open, then:
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_open):
        css_invalidation_invalidate_style_after_open_state_change(base)

        # 1. If one of oldValue or value is null and the other is not null, run the following steps, which are known as
        #    the details notification task steps, for this details element:
        if (old_value != none) != (value != none):
            # 1. If oldValue is null, queue a details toggle event task given the details element, "closed", and "open".
            if old_value == none:
                html_details_element_queue_a_details_toggle_event_task(this, ak.string_from_str("closed"), ak.string_from_str("open"))
            # 2. Otherwise, queue a details toggle event task given the details element, "open", and "closed".
            else:
                html_details_element_queue_a_details_toggle_event_task(this, ak.string_from_str("open"), ak.string_from_str("closed"))

        # 2. If oldValue is null and value is not null, then ensure details exclusivity by closing other elements if
        #    needed given element.
        if old_value == none and value != none:
            html_details_element_ensure_details_exclusivity_by_closing_other_elements_if_needed(this)

        html_details_element_update_shadow_tree_style(this)

## Ported from HTMLDetailsElement.cpp:101 Web::HTML::HTMLDetailsElement::children_changed (override).
pub func html_details_element_children_changed_impl(base: DomNode*, metadata: DomNodeChildrenChangedMetadata):
    dom_element_children_changed_impl(base, metadata)
    html_details_element_update_shadow_tree_slots((HtmlDetailsElement*)base)

# mark: Details toggle events ===================================================================

## The captures of queue_a_details_toggle_event_task's task: `[this, old_state, new_state = move(new_state)]`.
struct HtmlDetailsElementToggleEventTask:
    var this: HtmlDetailsElement*
    var old_state: ak.String
    var new_state: ak.String

    ## The task's steps.
    static func run(context: void*?):
        let captures = (HtmlDetailsElementToggleEventTask*)(context else trap("details toggle task: no captures"))
        let this = captures.this

        # 1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to
        #    oldState and the newState attribute initialized to newState.
        var event_init = HtmlToggleEventInit()
        event_init.old_state = captures.old_state
        event_init.new_state = captures.new_state

        _ = dom_event_target_dispatch_event(this.dom_event_target(), html_toggle_event_create(html_element_realm(this.html_element()), html_event_names_toggle, event_init).dom_event())

        # 2. Set element's details toggle task tracker to null.
        this.m_details_toggle_task_tracker = none

## Ported from HTMLDetailsElement.cpp:108 Web::HTML::HTMLDetailsElement::queue_a_details_toggle_event_task.
# https://html.spec.whatwg.org/multipage/interactive-elements.html#queue-a-details-toggle-event-task
pub func html_details_element_queue_a_details_toggle_event_task(this: HtmlDetailsElement*, old_state_argument: ak.String, new_state: ak.String):
    var old_state = old_state_argument

    # 1. If element's details toggle task tracker is not null, then:
    if let tracker = this.m_details_toggle_task_tracker:
        # 1. Set oldState to element's details toggle task tracker's old state.
        old_state = tracker.old_state

        # 2. Remove element's details toggle task tracker's task from its task queue.
        var task_id = tracker.task_id
        html_task_queue_remove_tasks_matching(html_event_loop_task_queue(html_main_thread_event_loop()), ak.Function1[HtmlTask*, bool](call = html_element_task_has_id, context = &task_id))

        # 3. Set element's details toggle task tracker to null.
        # (C++ clears the tracker's task id; the tracker itself stays set until it is replaced below.)
        var cleared = tracker
        cleared.task_id = none
        this.m_details_toggle_task_tracker = cleared

    # 2. Queue an element task given the DOM manipulation task source and element to run the following steps:
    let captures = new HtmlDetailsElementToggleEventTask(this = this, old_state = old_state, new_state = new_state) else trap("out of memory")
    let task_id = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.dom_manipulation, ak.Function0[unit](call = HtmlDetailsElementToggleEventTask.run, context = captures))

    # 3. Set element's details toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.
    this.m_details_toggle_task_tracker = HtmlToggleTaskTracker(task_id = task_id, old_state = old_state)

# mark: Details name groups =====================================================================

## Ported from HTMLDetailsElement.cpp:147 Web::HTML::for_each_element_in_details_name_group.
## (The C++ template's callback is an ak.Function1 returning the TraversalDecision.)
# https://html.spec.whatwg.org/multipage/interactive-elements.html#details-name-group
func html_for_each_element_in_details_name_group(details: HtmlDetailsElement*, name: ak.String, callback: ak.Function1[HtmlDetailsElement*, TraversalDecision]):
    # The details name group that contains a details element a also contains all the other details elements b that
    # fulfill all of the following conditions:
    # (name_group_contains_element:)
    # 1. Both a and b are in the same tree.
    # NOTE: This is true due to the way we iterate the tree below.

    # 2. They both have a name attribute, their name attributes are not the empty string, and the value of a's name
    #    attribute equals the value of b's name attribute.
    for node in dom_node_inclusive_subtree(tree_node_root(details.dom_node())):
        let candidate = as_if_html_details_element(node) else continue
        if candidate == details:
            continue
        let candidate_name = dom_element_attribute(candidate.dom_element(), html_attribute_names_name) else continue
        if not ak.string_equals(&candidate_name, &name):
            continue
        if ak.function1_call(&callback, candidate) == TraversalDecision.break_:
            break

## ensure_details_exclusivity_by_closing_other_elements_if_needed's callback: close an open
## other element and stop.
func html_details_element_close_other_element(context: void*?, other_element: HtmlDetailsElement*) -> TraversalDecision:
    # 1. If the open attribute is set on otherElement, then:
    if dom_element_has_attribute(other_element.dom_element(), html_attribute_names_open):
        # 1. Assert: otherElement is the only element in groupMembers that has the open attribute set.

        # 2. Remove the open attribute on otherElement.
        dom_element_remove_attribute(other_element.dom_element(), html_attribute_names_open)

        # 3. Break.
        return TraversalDecision.break_

    return TraversalDecision.continue_

## Ported from HTMLDetailsElement.cpp:168 Web::HTML::HTMLDetailsElement::ensure_details_exclusivity_by_closing_other_elements_if_needed.
# https://html.spec.whatwg.org/multipage/interactive-elements.html#ensure-details-exclusivity-by-closing-other-elements-if-needed
pub func html_details_element_ensure_details_exclusivity_by_closing_other_elements_if_needed(this: HtmlDetailsElement*):
    # 1. Assert: element has an open attribute.
    assert(dom_element_has_attribute(this.dom_element(), html_attribute_names_open))

    # 2. If element does not have a name attribute, or its name attribute is the empty string, then return.
    let name = dom_element_attribute(this.dom_element(), html_attribute_names_name) else return
    if ak.string_is_empty(&name):
        return

    # 3. Let groupMembers be a list of elements, containing all elements in element's details name group except for
    #    element, in tree order.
    # 4. For each element otherElement of groupMembers:
    html_for_each_element_in_details_name_group(this, name, ak.Function1[HtmlDetailsElement*, TraversalDecision](call = html_details_element_close_other_element, context = none))

## ensure_details_exclusivity_by_closing_the_given_element_if_needed's callback (its context is the
## element): close the element if another one is open.
func html_details_element_close_given_element(context: void*?, other_element: HtmlDetailsElement*) -> TraversalDecision:
    let this = (HtmlDetailsElement*)(context else trap("no details element"))
    # 1. If the open attribute is set on otherElement, then:
    if dom_element_has_attribute(other_element.dom_element(), html_attribute_names_open):
        # 1. Remove the open attribute on element.
        dom_element_remove_attribute(this.dom_element(), html_attribute_names_open)

        # 2. Break.
        return TraversalDecision.break_

    return TraversalDecision.continue_

## Ported from HTMLDetailsElement.cpp:198 Web::HTML::HTMLDetailsElement::ensure_details_exclusivity_by_closing_the_given_element_if_needed.
# https://html.spec.whatwg.org/multipage/interactive-elements.html#ensure-details-exclusivity-by-closing-the-given-element-if-needed
pub func html_details_element_ensure_details_exclusivity_by_closing_the_given_element_if_needed(this: HtmlDetailsElement*):
    # 1. If element does not have an open attribute, then return.
    if not dom_element_has_attribute(this.dom_element(), html_attribute_names_open):
        return

    # 2. If element does not have a name attribute, or its name attribute is the empty string, then return.
    let name = dom_element_attribute(this.dom_element(), html_attribute_names_name) else return
    if ak.string_is_empty(&name):
        return

    # 3. Let groupMembers be a list of elements, containing all elements in element's details name group except for
    #    element, in tree order.
    # 4. For each element otherElement of groupMembers:
    html_for_each_element_in_details_name_group(this, name, ak.Function1[HtmlDetailsElement*, TraversalDecision](call = html_details_element_close_given_element, context = this))

# mark: The shadow tree =========================================================================

## Ported from HTMLDetailsElement.cpp:227 Web::HTML::HTMLDetailsElement::create_shadow_tree_if_needed.
# https://html.spec.whatwg.org/multipage/rendering.html#the-details-and-summary-elements
pub func html_details_element_create_shadow_tree_if_needed(this: HtmlDetailsElement*) -> !:
    if dom_element_shadow_root(this.dom_element()) != none:
        return

    let realm = html_element_realm(this.html_element())
    let document = dom_node_document(this.dom_node())

    # The details element is expected to have an internal shadow tree with three child elements:
    let shadow_root = realm_create_dom_shadow_root(realm, document, this.dom_element(), BindShadowRootMode.closed)
    dom_shadow_root_set_user_agent_internal(shadow_root, true)
    dom_shadow_root_set_slot_assignment(shadow_root, BindSlotAssignmentMode.manual)

    # The first child element is a slot that is expected to take the details element's first summary element child, if any.
    let summary_slot = try dom_create_element(document, html_tag_names_slot, namespace_html)
    _ = dom_node_append_child(shadow_root.dom_node(), summary_slot.dom_node()) else trap("MUST: append_child")

    # The second child element is a slot that is expected to take the details element's remaining descendants, if any.
    let descendants_slot = try dom_create_element(document, html_tag_names_slot, namespace_html)
    dom_element_set_use_pseudo_element(descendants_slot, css_data.PseudoElement.details_content)
    _ = dom_node_append_child(shadow_root.dom_node(), descendants_slot.dom_node()) else trap("MUST: append_child")

    # The third child element is either a link or style element with the following styles for the default summary
    # (the C++ raw string literal, whitespace included):
    let style = try dom_create_element(document, html_tag_names_style, namespace_html)
    let style_text = realm_create_dom_text_utf16_string(realm, document, ak.utf16_string_from_str("\n        :host summary {\n            display: list-item;\n            counter-increment: list-item 0;\n            list-style: disclosure-closed inside;\n        }\n        :host([open]) summary {\n            list-style-type: disclosure-open;\n        }\n    "))
    _ = dom_node_append_child(style.dom_node(), style_text.dom_node()) else trap("MUST: append_child")
    _ = dom_node_append_child(shadow_root.dom_node(), style.dom_node()) else trap("MUST: append_child")

    this.m_summary_slot = (HtmlSlotElement*)summary_slot
    this.m_descendants_slot = (HtmlSlotElement*)descendants_slot
    dom_element_set_shadow_root(this.dom_element(), shadow_root)

## Ported from HTMLDetailsElement.cpp:270 Web::HTML::HTMLDetailsElement::update_shadow_tree_slots.
pub func html_details_element_update_shadow_tree_slots(this: HtmlDetailsElement*):
    if dom_element_shadow_root(this.dom_element()) == none:
        return

    var summary_assignment: ak.Vector[HtmlSlotElementSlottableHandle]
    var descendants_assignment: ak.Vector[HtmlSlotElementSlottableHandle]

    let summary = tree_node_first_child_of_type(this.dom_node(), &html_summary_element_class)
    if let summary_node = summary:
        ak.vector_append_t(&summary_assignment, HtmlSlotElementSlottableHandle.dom_element((DomElement*)summary_node))

    for child in dom_node_subtree(this.dom_node()):
        if summary == child:
            continue
        if not dom_node_is_slottable(child):
            continue

        match dom_node_as_slottable(child):
            .dom_element(element): ak.vector_append_t(&descendants_assignment, HtmlSlotElementSlottableHandle.dom_element(element))
            .dom_text(text): ak.vector_append_t(&descendants_assignment, HtmlSlotElementSlottableHandle.dom_text(text))

    html_slot_element_assign(this.m_summary_slot else trap("the summary slot"), summary_assignment)
    html_slot_element_assign(this.m_descendants_slot else trap("the descendants slot"), descendants_assignment)

    html_details_element_update_shadow_tree_style(this)

## Ported from HTMLDetailsElement.cpp:302 Web::HTML::HTMLDetailsElement::update_shadow_tree_style.
# https://html.spec.whatwg.org/multipage/rendering.html#the-details-and-summary-elements%3Athe-details-element-6
pub func html_details_element_update_shadow_tree_style(this: HtmlDetailsElement*):
    let shadow_root = dom_element_shadow_root(this.dom_element()) else return

    let descendants_slot = this.m_descendants_slot else trap("the descendants slot")
    if dom_element_has_attribute(this.dom_element(), html_attribute_names_open):
        dom_element_set_attribute_value(descendants_slot.dom_element(), html_attribute_names_style, ak.string_from_str("\n            display: block;\n        "))
    else:
        dom_element_set_attribute_value(descendants_slot.dom_element(), html_attribute_names_style, ak.string_from_str("\n            display: block;\n            content-visibility: hidden;\n        "))

    dom_node_set_needs_layout_tree_update(shadow_root.dom_node(), true, DomSetNeedsLayoutTreeUpdateReason.details_element_opened_or_closed)

## Ported from HTMLDetailsElement.h:26 Web::HTML::HTMLDetailsElement::default_role (override).
# https://www.w3.org/TR/html-aria/#el-details
pub func html_details_element_default_role_impl(base: AriaMixin*) -> AriaRole?:
    return AriaRole.group