Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / element_12.lucb

#==============================================================================================
#
#   element_12 - DOM::Element: attribute change steps, lang, attributes(), animations, focus
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Element.cpp (lines 4247-4532 and 4565-4828): the attribute change
#       steps Element runs for slot, id, name, class, style, dir, lang, part and exportparts
#       and the ARIA element-reference attributes; the custom element reaction queue and
#       state set; the style sheets and ID map of the element's root; getHTML and
#       setHTMLUnsafe; counters; lang; rendering, view transitions and pointer capture;
#       attributes() and the HTML-uppercased qualified name; playing or cancelling CSS
#       animations; focus indication and focusability; computedStyleMap; random base values;
#       pointer lock; the element style is inherited from; and render blocking.
#
#==============================================================================================

# mark: Attribute change steps ==================================================================

## `value.bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace)` as FlyStrings, into
## `tokens` (cleared first, as the class and part steps do).
func dom_element_set_tokens_from_value(tokens: ak.Vector[ak.FlyString]*, value: const ak.String*):
    let view = ak.string_bytes_as_string_view(value)
    let predicate = DomElementIsAsciiWhitespace(unused = 0)
    var new_tokens = ak.string_view_split_view_if(&view, &predicate)
    ak.vector_clear(tokens)
    ak.vector_ensure_capacity(tokens, ak.vector_size(&new_tokens))
    for new_token in ak.vector_span(&new_tokens):
        ak.vector_append_t(tokens, ak.fly_string_from_utf8(new_token) else trap("FIXME: should propagate errors"))

## Ported from Element.cpp:4248 Web::DOM::Element::attribute_changed (virtual).
# https://dom.spec.whatwg.org/#concept-element-attributes-change-ext
pub func dom_element_attribute_changed_impl(this: DomElement*, local_name: ak.FlyString, old_value: ak.String?, value: ak.String?, namespace_: ak.FlyString?):
    # AD-HOC: Everything below requires that there is no namespace, so return early if there is one.
    if namespace_ != none:
        return

    # https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-change-ext①
    # 1. If localName is slot and namespace is null, then:
    if ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_slot):
        # 1. If value is oldValue, then return.
        if dom_node_optional_strings_equal(value, old_value):
            return

        # 2. If value is null and oldValue is the empty string, then return.
        if value == none and dom_node_optional_string_equals(old_value, ak.string_new()):
            return

        # 3. If value is the empty string and oldValue is null, then return.
        if dom_node_optional_string_equals(value, ak.string_new()) and old_value == none:
            return

        # 4. If value is null or the empty string, then set element’s name to the empty string.
        let new_name = value else ak.string_new()
        if ak.string_is_empty(&new_name):
            dom_slottable_mixin_set_slottable_name(&this.slottable_mixin, ak.fly_string_new())
        # 5. Otherwise, set element’s name to value.
        else:
            dom_slottable_mixin_set_slottable_name(&this.slottable_mixin, ak.fly_string_from_string(new_name))

        # 6. If element is assigned, then run assign slottables for element’s assigned slot.
        if let assigned_slot = dom_slottable_mixin_assigned_slot_internal(&this.slottable_mixin):
            dom_assign_slottables(assigned_slot)

        # 7. Run assign a slot for element.
        dom_assign_a_slot(DomSlottable.dom_element(this))
        return

    let value_or_empty = value else ak.string_new()

    if ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_id):
        if ak.string_is_empty(&value_or_empty):
            this.m_id = none
        else:
            this.m_id = ak.fly_string_from_string(value_or_empty)

        if dom_node_is_connected(this.dom_node()):
            var old_value_fly_string: ak.FlyString? = none
            if let old = old_value:
                old_value_fly_string = ak.fly_string_from_string(old)
            dom_document_element_id_changed(dom_element_document(this), this, old_value_fly_string)
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_name):
        if ak.string_is_empty(&value_or_empty):
            this.m_name = none
        else:
            this.m_name = ak.fly_string_from_string(value_or_empty)

        if dom_node_is_connected(this.dom_node()):
            dom_document_element_name_changed(dom_element_document(this), this)
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_class):
        if ak.string_is_empty(&value_or_empty):
            ak.vector_clear(&this.m_classes)
        else:
            dom_element_set_tokens_from_value(&this.m_classes, &value_or_empty)
        if let class_list = this.m_class_list:
            dom_token_list_associated_attribute_changed(class_list, ak.string_bytes_as_string_view(&value_or_empty))
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_style):
        # https://drafts.csswg.org/cssom/#ref-for-cssstyledeclaration-updating-flag
        if let inline_style = this.m_inline_style:
            if css_style_declaration_is_updating(inline_style.css_style_declaration()):
                return
        if this.m_inline_style == none:
            var properties: ak.Vector[CssStyleProperty]
            var custom_properties: ak.OrderedHashMap[ak.FlyString, CssStyleProperty, ak.FlyStringTraits]
            this.m_inline_style = css_style_properties_create_element_inline_style(dom_element_abstract_element(this), properties, custom_properties)
        let inline_style = this.m_inline_style else trap("unreachable")
        let text = value else ak.string_new()
        css_style_properties_set_declarations_from_text(inline_style, ak.string_bytes_as_string_view(&text))
        dom_prefetch_inline_style_image_resources(inline_style, dom_element_document(this))
        dom_node_set_needs_style_update(this.dom_node(), true)
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_dir) or ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_lang):
        let is_dir = ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_dir)
        if is_dir:
            # https://html.spec.whatwg.org/multipage/dom.html#attr-dir
            if dom_element_string_equals_ignoring_ascii_case(&value_or_empty, "ltr"):
                this.m_dir = DomElementDir.ltr
            elif dom_element_string_equals_ignoring_ascii_case(&value_or_empty, "rtl"):
                this.m_dir = DomElementDir.rtl
            elif dom_element_string_equals_ignoring_ascii_case(&value_or_empty, "auto"):
                this.m_dir = DomElementDir.auto
            else:
                this.m_dir = none
        if is_dir:
            css_invalidation_invalidate_style_after_directionality_change(this)
        else:
            css_invalidation_invalidate_style_after_language_change(this)
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_part):
        ak.vector_clear(&this.m_parts)
        if not ak.string_is_empty(&value_or_empty):
            dom_element_set_tokens_from_value(&this.m_parts, &value_or_empty)
        if let part_list = this.m_part_list:
            dom_token_list_associated_attribute_changed(part_list, ak.string_bytes_as_string_view(&value_or_empty))
        css_invalidation_invalidate_style_after_part_attribute_change(this)
    elif ak.fly_string_eq_fly_string(&local_name, &html_attribute_names_exportparts):
        css_invalidation_invalidate_style_after_exportparts_attribute_change(this)

    # https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:concept-element-attributes-change-ext
    # 1. If localName is not attr or namespace is not null, then return.
    # 2. Set element's explicitly set attr-element to null.
    # (ENUMERATE_ARIA_ELEMENT_REFERENCING_ATTRIBUTES)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_active_descendant):
        aria_mixin_set_aria_active_descendant_element(&this.aria_mixin, none)

    # https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes:concept-element-attributes-change-ext-2
    # 1. If localName is not attr or namespace is not null, then return.
    # 2. Set element's explicitly set attr-elements to null.
    # (ENUMERATE_ARIA_ELEMENT_LIST_REFERENCING_ATTRIBUTES)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_controls):
        aria_mixin_set_aria_controls_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_described_by):
        aria_mixin_set_aria_described_by_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_details):
        aria_mixin_set_aria_details_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_error_message):
        aria_mixin_set_aria_error_message_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_flow_to):
        aria_mixin_set_aria_flow_to_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_labelled_by):
        aria_mixin_set_aria_labelled_by_elements(&this.aria_mixin, none)
    elif ak.fly_string_eq_fly_string(&local_name, &aria_attribute_names_aria_owns):
        aria_mixin_set_aria_owns_elements(&this.aria_mixin, none)

# mark: Reaction queue, state set, style sheets and ID maps =====================================

## Ported from Element.cpp:4385 Web::DOM::Element::ensure_custom_element_reaction_queue.
pub func dom_element_ensure_custom_element_reaction_queue(this: DomElement*) -> ak.Vector[DomCustomElementUpgradeReactionOrDomCustomElementCallbackReaction]*:
    if this.m_custom_element_reaction_queue == none:
        this.m_custom_element_reaction_queue = new ak.Vector[DomCustomElementUpgradeReactionOrDomCustomElementCallbackReaction] else trap("out of memory")
    return this.m_custom_element_reaction_queue else trap("unreachable")

## Ported from Element.cpp:4392 Web::DOM::Element::ensure_custom_state_set.
pub func dom_element_ensure_custom_state_set(this: DomElement*) -> HtmlCustomStateSet*:
    if this.m_custom_state_set == none:
        this.m_custom_state_set = html_custom_state_set_create(dom_element_realm(this), this)
    return this.m_custom_state_set else trap("unreachable")

## Ported from Element.cpp:4399 Web::DOM::Element::document_or_shadow_root_style_sheets.
pub func dom_element_document_or_shadow_root_style_sheets(this: DomElement*) -> CssStyleSheetList*:
    let root_node = tree_node_root(this.dom_node())
    if let shadow_root = as_if_dom_shadow_root(root_node):
        return dom_shadow_root_style_sheets(shadow_root)

    return dom_document_style_sheets(dom_element_document(this))

## Ported from Element.cpp:4408 Web::DOM::Element::document_or_shadow_root_element_by_id_map.
pub func dom_element_document_or_shadow_root_element_by_id_map(this: DomElement*) -> DomElementByIdMap*:
    let root_node = tree_node_root(this.dom_node())
    if let shadow_root = as_if_dom_shadow_root(root_node):
        return dom_shadow_root_element_by_id(shadow_root)
    return dom_document_element_by_id(dom_element_document(this))

# mark: getHTML and setHTMLUnsafe ===============================================================

## Ported from Element.cpp:4417 Web::DOM::Element::get_html.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-gethtml
pub func dom_element_get_html(this: DomElement*, options: DomGetHtmlOptions) -> ak.String!:
    # Element's getHTML(options) method steps are to return the result
    # of HTML fragment serialization algorithm with this,
    # options["serializableShadowRoots"], and options["shadowRoots"].
    let serializable_shadow_roots = HtmlParserSerializableShadowRoots.yes if options.serializable_shadow_roots else HtmlParserSerializableShadowRoots.no
    return html_parser_serialize_html_fragment(this.dom_node(), serializable_shadow_roots, options.shadow_roots)

## Ported from Element.cpp:4429 Web::DOM::Element::set_html_unsafe.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-sethtmlunsafe
pub func dom_element_set_html_unsafe(this: DomElement*, html: TrustedTypesTrustedHtmlOrString) -> !:
    # 1. Let compliantHTML be the result of invoking the Get Trusted Type compliant string algorithm with
    #    TrustedHTML, this's relevant global object, html, "Element setHTMLUnsafe", and "script".
    # (TrustedTypes::Script.to_string() is "'script'".)
    let compliant_html = try trusted_types_get_trusted_type_compliant_string(TrustedTypesTrustedTypeName.trusted_html, html_relevant_global_object((JsObject*)this), dom_element_trusted_html_or_string_as_trusted_type(html), TrustedTypesInjectionSink.element_set_html_unsafe, ak.string_from_str("'script'"))

    # 2. Let target be this's template contents if this is a template element; otherwise this.
    var target = this.dom_node()
    if let template = as_if_html_template_element(this):
        target = html_template_element_content(template).dom_node()

    # 3. Unsafe set HTML given target, this, and compliantHTML.
    let compliant_utf8 = ak.utf16_string_base_to_utf8_but_should_be_ported_to_utf16(&compliant_html.utf16_string_base)
    try dom_node_unsafely_set_html(target, this, ak.string_bytes_as_string_view(&compliant_utf8))

# mark: Counters ================================================================================

## Ported from Element.cpp:4451 Web::DOM::Element::counters_set.
pub func dom_element_counters_set(this: DomElement*) -> const CssCountersSet*?:
    return this.m_counters_set

## Ported from Element.cpp:4458 Web::DOM::Element::ensure_counters_set.
pub func dom_element_ensure_counters_set(this: DomElement*) -> CssCountersSet*:
    if this.m_counters_set == none:
        this.m_counters_set = new CssCountersSet else trap("out of memory")
    return this.m_counters_set else trap("unreachable")

## Ported from Element.cpp:4465 Web::DOM::Element::set_counters_set.
pub func dom_element_set_counters_set(this: DomElement*, counters_set: CssCountersSet*?):
    this.m_counters_set = counters_set

# mark: lang ====================================================================================

## Element::lang's `determine_lang_attribute` lambda.
func dom_element_determine_lang_attribute(this: DomElement*) -> ak.String:
    # 1. If the node is an element that has a lang attribute in the XML namespace set
    #      Use the value of that attribute.
    let maybe_xml_lang = dom_element_get_attribute_ns(this, namespace_xml, html_attribute_names_lang)
    if let xml_lang = maybe_xml_lang:
        return xml_lang

    # 2. If the node is an HTML element or an element in the SVG namespace, and it has a lang in no namespace attribute set
    #      Use the value of that attribute.
    if dom_node_is_html_element(this.dom_node()) or dom_node_optional_fly_string_is(dom_element_namespace_uri(this), namespace_svg):
        let maybe_lang = dom_element_get_attribute(this, html_attribute_names_lang)
        if let lang = maybe_lang:
            return lang

    # 3. If the node's parent is a shadow root
    #      Use the language of that shadow root's host.
    if let parent = tree_node_parent(this.dom_node()):
        if dom_node_is_shadow_root(parent):
            let host = dom_document_fragment_host(as_dom_shadow_root(parent).dom_document_fragment()) else trap("a shadow root has a host")
            return dom_element_lang(host) else ak.string_new()

    # 4. If the node's parent element is not null
    #      Use the language of that parent element.
    if let parent = dom_node_parent_element(this.dom_node()):
        return dom_element_lang(parent) else ak.string_new()

    # 5. Otherwise
    #      - If there is a pragma-set default language set, then that is the language of the node.
    if let pragma_set_default_language = dom_document_pragma_set_default_language(dom_element_document(this)):
        return pragma_set_default_language

    #      - If there is no pragma-set default language set, then language information from a higher-level protocol (such as HTTP),
    if let http_content_language = dom_document_http_content_language(dom_element_document(this)):
        return http_content_language

    #        if any, must be used as the final fallback language instead.
    #      - In the absence of any such language information, and in cases where the higher-level protocol reports multiple languages,
    #        the language of the node is unknown, and the corresponding language tag is the empty string.
    # Default locale sounds like a reasonable fallback here.
    return ak.string_new()

## Ported from Element.cpp:4471 Web::DOM::Element::lang.
# https://html.spec.whatwg.org/multipage/dom.html#the-lang-and-xml:lang-attributes
pub func dom_element_lang(this: DomElement*) -> ak.String?:
    if this.m_lang_value == none:
        this.m_lang_value = dom_element_determine_lang_attribute(this)

    # If the resulting value is the empty string, then it must be interpreted as meaning that the language of the node is explicitly unknown.
    let lang_value = this.m_lang_value else trap("unreachable")
    if ak.string_is_empty(&lang_value):
        return none

    return lang_value

## Ported from Element.cpp:4526 Web::DOM::Element::invalidate_lang_value.
pub func dom_element_invalidate_lang_value(this: DomElement*):
    if this.m_lang_value != none:
        this.m_lang_value = none
        dom_node_set_needs_style_update(this.dom_node(), true)

# mark: Rendering, view transitions and pointer capture =========================================

## Ported from Element.cpp:4566 Web::DOM::Element::not_rendered.
# https://drafts.csswg.org/css-images-4/#element-not-rendered
pub func dom_element_not_rendered(this: DomElement*) -> bool:
    # An element is not rendered if it does not have an associated box.
    if dom_element_layout_node(this) == none or dom_node_paintable_box(this.dom_node()) == none:
        return true

    return false

## Ported from Element.cpp:4576 Web::DOM::Element::document_scoped_view_transition_name.
# https://drafts.csswg.org/css-view-transitions-1/#document-scoped-view-transition-name
pub func dom_element_document_scoped_view_transition_name(this: DomElement*) -> ak.FlyString?:
    # To get the document-scoped view transition name for an Element element:

    # 1. Let scopedViewTransitionName be the computed value of view-transition-name for element.
    let computed_properties = dom_element_computed_properties(this) else trap("document_scoped_view_transition_name: no computed properties")
    let scoped_view_transition_name = css_computed_properties_view_transition_name(computed_properties)

    # 2. If scopedViewTransitionName is associated with element’s node document, then return
    #    scopedViewTransitionName.
    # FIXME: Properly handle tree-scoping of the name here.
    #        (see https://drafts.csswg.org/css-view-transitions-1/#propdef-view-transition-name , "Each view transition name is a tree-scoped name.")
    return scoped_view_transition_name

    # 3. Otherwise, return none.

## Ported from Element.cpp:4597 Web::DOM::Element::capture_the_image.
# https://drafts.csswg.org/css-view-transitions-1/#capture-the-image
# To capture the image given an element element, perform the following steps. They return an image.
pub func dom_element_capture_the_image(this: DomElement*) -> gfx.ImmutableBitmap*?:
    # FIXME: Actually implement this.
    var size: gfx.IntSize = ---
    gfx.int_size_construct(&size, 1, 1)
    let bitmap = gfx.bitmap_create_alpha_type(gfx.BitmapFormat.bgra8888, gfx.AlphaType.premultiplied, size) else trap("MUST: Gfx::Bitmap::create")
    var color_space: gfx.ColorSpace = ---
    gfx.color_space_construct(&color_space)
    return gfx.immutable_bitmap_create_color_space(bitmap, color_space)

## Ported from Element.cpp:4603 Web::DOM::Element::set_pointer_capture.
pub func dom_element_set_pointer_capture(this: DomElement*, pointer_id: i32):
    _ = pointer_id
    ak.dbgln("FIXME: Implement Element::setPointerCapture()")

## Ported from Element.cpp:4609 Web::DOM::Element::release_pointer_capture.
pub func dom_element_release_pointer_capture(this: DomElement*, pointer_id: i32):
    _ = pointer_id
    ak.dbgln("FIXME: Implement Element::releasePointerCapture()")

## Ported from Element.cpp:4615 Web::DOM::Element::has_pointer_capture.
pub func dom_element_has_pointer_capture(this: DomElement*, pointer_id: i32) -> bool:
    _ = pointer_id
    ak.dbgln("FIXME: Implement Element::hasPointerCapture()")
    return false

# mark: Attributes and the qualified name =======================================================

## Ported from Element.cpp:4622 Web::DOM::Element::attributes.
pub func dom_element_attributes(this: DomElement*) -> DomNamedNodeMap*?:
    if this.m_attributes == none:
        this.m_attributes = dom_named_node_map_create(this)
    return this.m_attributes

## Ported from Element.cpp:4629 Web::DOM::Element::attributes.
pub func dom_element_attributes_const(this: DomElement*) -> DomNamedNodeMap*?:
    return dom_element_attributes(this)

## Ported from Element.cpp:4634 Web::DOM::Element::html_uppercased_qualified_name.
pub func dom_element_html_uppercased_qualified_name(this: DomElement*) -> ak.FlyString:
    # m_html_uppercased_qualified_name.ensure(make_html_uppercased_qualified_name)
    if this.m_html_uppercased_qualified_name == none:
        this.m_html_uppercased_qualified_name = dom_element_make_html_uppercased_qualified_name(this)
    return this.m_html_uppercased_qualified_name else trap("unreachable")

# mark: CSS animations ==========================================================================

## Element::play_or_cancel_animations_after_display_property_change's `play_or_cancel_depending_on_display`
## lambda.
func dom_element_play_or_cancel_depending_on_display(this: DomElement*, has_inclusive_ancestor_with_display_none_ignoring_animations: bool, animations: ak.HashMap[ak.FlyString, CssAnimation*, ak.FlyStringTraits]*):
    for entry in ak.hash_map_begin(animations):
        let animation = entry.value.animations_animation()
        if has_inclusive_ancestor_with_display_none_ignoring_animations:
            animations_animation_cancel(animation)
        else:
            # NOTE: It is safe to assume this has a value as it is set when creating a CSS defined animation
            let play_state = animations_animation_last_css_animation_play_state(animation) else trap("a CSS defined animation has a play state")

            if play_state == css_data.AnimationPlayState.running:
                var context: HtmlTemporaryExecutionContext = ---
                html_temporary_execution_context_construct_realm(&context, dom_element_realm(this))
                defer html_temporary_execution_context_destruct(&context)
                animations_animation_play(animation) else trap("FIXME: should propagate errors")
            elif play_state == css_data.AnimationPlayState.paused:
                var context: HtmlTemporaryExecutionContext = ---
                html_temporary_execution_context_construct_realm(&context, dom_element_realm(this))
                defer html_temporary_execution_context_destruct(&context)
                animations_animation_pause(animation) else trap("FIXME: should propagate errors")

## Ported from Element.cpp:4639 Web::DOM::Element::play_or_cancel_animations_after_display_property_change.
func dom_element_play_or_cancel_animations_after_display_property_change(this: DomElement*):
    # OPTIMIZATION: We don't care about elements with no CSS defined animations
    if not animations_animatable_has_css_defined_animations(&this.animatable):
        return

    # OPTIMIZATION: We don't care about animations in disconnected subtrees.
    if not dom_node_is_connected(this.dom_node()):
        return

    # https://drafts.csswg.org/css-animations-2/#owning-element-section
    # If the display property of an element is set to none and its display value would compute to none when ignoring
    # the Transitions and Animations cascade origins, then terminate running animations with this owning element. If
    # an element has a display of none and its display value had computed to none when ignoring the Transitions and
    # Animations cascade origins, updating display to a value other than none will start all animations applied to
    # the element by the animation-name property.

    # FIXME: What does it mean that "is set to none" is separate from "would compute to none...", do we need to check
    #        the cascaded value as well?

    # AD-HOC: Other browsers also check for ancestors which meet the above criteria, so we do that as well.
    # FIXME: Do we need to open a spec issue for this?

    let has_inclusive_ancestor_with_display_none_ignoring_animations = dom_node_has_inclusive_ancestor_with_display_none_ignoring_animations(this.dom_node())

    dom_element_play_or_cancel_depending_on_display(this, has_inclusive_ancestor_with_display_none_ignoring_animations, animations_animatable_css_defined_animations(&this.animatable, none) else trap("css_defined_animations({}) is non-null"))

    for i in 0..<(u8)css_data.PseudoElement.known_pseudo_element_count:
        let pseudo_element = (css_data.PseudoElement)i
        dom_element_play_or_cancel_depending_on_display(this, has_inclusive_ancestor_with_display_none_ignoring_animations, animations_animatable_css_defined_animations(&this.animatable, pseudo_element) else trap("css_defined_animations(known pseudo-element) is non-null"))

# mark: Focus ===================================================================================

## Ported from Element.cpp:4692 Web::DOM::Element::should_indicate_focus.
# https://drafts.csswg.org/selectors/#indicate-focus
pub func dom_element_should_indicate_focus(this: DomElement*) -> bool:
    # User agents can choose their own heuristics for when to indicate focus; however, the following (non-normative)
    # suggestions can be used as a starting point for when to indicate focus on the currently focused element:

    # FIXME: * If the user has expressed a preference (such as via a system preference or a browser setting) to always see a
    #   visible focus indicator, indicate focus regardless of any other factors. (Another option may be for the user
    #   agent to show its own focus indicator regardless of author styles.)

    # * If the element which supports keyboard input (such as an input element, or any other element that would
    #   triggers a virtual keyboard to be shown on focus if a physical keyboard were not present), indicate focus.
    if as_if_form_associated_text_control_element(this) != none or dom_node_is_editable_or_editing_host(this.dom_node()):
        return true

    # * If the user interacts with the page via keyboard or some other non-pointing device, indicate focus. (This means
    #   keyboard usage may change whether this pseudo-class matches even if it doesn’t affect :focus).
    if dom_document_last_focus_trigger(dom_element_document(this)) == HtmlFocusTrigger.key:
        return true

    # FIXME: * If the user interacts with the page via a pointing device (mouse, touchscreen, etc.) and the focused element
    #   does not support keyboard input, don’t indicate focus.

    # * If the previously-focused element indicated focus, and a script causes focus to move elsewhere, indicate focus
    #   on the newly focused element.
    #   Conversely, if the previously-focused element did not indicate focus, and a script causes focus to move
    #   elsewhere, don’t indicate focus on the newly focused element.
    # AD-HOC: Other browsers seem to always indicate focus on programmatically focused elements.
    if dom_document_last_focus_trigger(dom_element_document(this)) == HtmlFocusTrigger.script:
        return true

    # FIXME: * If a newly-displayed element automatically gains focus (such as an action button in a freshly opened dialog),
    #   that element should indicate focus.

    return false

## Ported from Element.cpp:4729 Web::DOM::Element::is_focusable (override).
# https://html.spec.whatwg.org/multipage/interaction.html#tabindex-value
pub func dom_element_is_focusable_impl(base: DomEventTarget*) -> bool:
    let this = (DomElement*)base
    let tabindex = dom_element_get_attribute_value(this, html_attribute_names_tabindex)
    return html_parse_integer(ak.string_bytes_as_string_view(&tabindex)) != none

## Ported from Element.cpp:4734 Web::DOM::Element::set_had_duplicate_attribute_during_tokenization.
pub func dom_element_set_had_duplicate_attribute_during_tokenization(this: DomElement*):
    this.m_had_duplicate_attribute_during_tokenization = true

# mark: computedStyleMap, random values and pointer lock ========================================

## Ported from Element.cpp:4740 Web::DOM::Element::computed_style_map.
# https://drafts.css-houdini.org/css-typed-om-1/#dom-element-computedstylemap
pub func dom_element_computed_style_map(this: DomElement*) -> CssStylePropertyMapReadOnly*:
    # The computedStyleMap() method must, when called on an Element this, perform the following steps:

    # 1. If this’s [[computedStyleMapCache]] internal slot is set to null, set its value to a new
    #    StylePropertyMapReadOnly object, whose [[declarations]] internal slot are the name and computed value of
    #    every longhand CSS property supported by the User Agent, every registered custom property, and every
    #    non-registered custom property which is not set to its initial value on this, in the standard order.
    #
    #    The computed values in the [[declarations]] of this object must remain up-to-date, changing as style
    #    resolution changes the properties on this and how they’re computed.
    #
    # NOTE: In practice, since the values are "hidden" behind a .get() method call, UAs can delay computing anything
    #    until a given property is actually requested.
    if this.m_computed_style_map_cache == none:
        this.m_computed_style_map_cache = css_style_property_map_read_only_create_computed_style(dom_element_realm(this), dom_element_abstract_element(this))

    # 2. Return this’s [[computedStyleMapCache]] internal slot.
    return this.m_computed_style_map_cache else trap("unreachable")

## The function-scope `static XorShift128PlusRNG random_number_generator` of
## Element::ensure_css_random_base_value (constructed on first use).
var dom_element_ensure_css_random_base_value_random_number_generator: ak.XorShift128PlusRng
var dom_element_ensure_css_random_base_value_random_number_generator_initialized: bool

## Element::ensure_css_random_base_value's lambda: the next value of the shared generator.
func dom_element_ensure_css_random_base_value_next(context: void*?) -> f64:
    if not dom_element_ensure_css_random_base_value_random_number_generator_initialized:
        ak.xor_shift128_plus_rng_construct(&dom_element_ensure_css_random_base_value_random_number_generator)
        dom_element_ensure_css_random_base_value_random_number_generator_initialized = true
    return ak.xor_shift128_plus_rng_get(&dom_element_ensure_css_random_base_value_random_number_generator)

## Ported from Element.cpp:4762 Web::DOM::Element::ensure_css_random_base_value.
pub func dom_element_ensure_css_random_base_value(this: DomElement*, random_caching_key: CssRandomCachingKey) -> f64:
    # NB: We cache element-shared random base values on the Document and non-element-shared ones on the Element itself
    #     so that when an element is removed it takes its non-shared cache with it.
    if random_caching_key.element_id == none:
        return dom_document_ensure_element_shared_css_random_base_value(dom_element_document(this), random_caching_key)

    return *ak.hash_map_ensure_t_callback(&this.m_element_specific_css_random_base_value_cache, random_caching_key, ak.Function0[f64](call = dom_element_ensure_css_random_base_value_next, context = none))

## Ported from Element.cpp:4775 Web::DOM::Element::request_pointer_lock.
pub func dom_element_request_pointer_lock(this: DomElement*, arg0: DomPointerLockOptions?) -> JsPromiseCapability*:
    ak.dbgln("FIXME: request_pointer_lock()")
    let promise = idl_create_promise(dom_element_realm(this))
    let error_ = idl_not_supported_error_create(dom_element_realm(this), ak.utf16_string_from_str("request_pointer_lock() is not implemented"))
    idl_reject_promise(dom_element_realm(this), promise, bind_platform_object_wrapper(error_.bind_platform_object()))
    return promise

# mark: Style inheritance and render blocking ===================================================

## Ported from Element.cpp:4788 Web::DOM::Element::element_to_inherit_style_from.
# The element to inherit style from.
# If a pseudo-element is specified, this will return the element itself.
# Otherwise, if this element is slotted somewhere, it will return the slot.
# Otherwise, it will return the parent or shadow host element of this element.
pub func dom_element_element_to_inherit_style_from(this: DomElement*, pseudo_element: css_data.PseudoElement?) -> DomElement*?:
    if pseudo_element != none:
        return this
    if let slot = dom_slottable_mixin_assigned_slot_internal(&this.slottable_mixin):
        return slot.dom_element()
    return dom_node_parent_or_shadow_host_element(this.dom_node())

## Ported from Element.cpp:4798 Web::DOM::Element::block_rendering.
# https://html.spec.whatwg.org/multipage/dom.html#block-rendering
pub func dom_element_block_rendering(this: DomElement*):
    # 1. Let document be el's node document.
    let document = dom_element_document(this)

    # 2. If document allows adding render-blocking elements, then append el to document's render-blocking element set.
    if dom_document_allows_adding_render_blocking_elements(document):
        dom_document_add_render_blocking_element(document, this)

## Ported from Element.cpp:4810 Web::DOM::Element::unblock_rendering.
# https://html.spec.whatwg.org/multipage/dom.html#unblock-rendering
pub func dom_element_unblock_rendering(this: DomElement*):
    # 1. Let document be el's node document.
    let document = dom_element_document(this)

    # 2. Remove el from document's render-blocking element set.
    dom_document_remove_render_blocking_element(document, this)

## Ported from Element.cpp:4820 Web::DOM::Element::is_potentially_render_blocking.
# https://html.spec.whatwg.org/multipage/urls-and-fetching.html#potentially-render-blocking
pub func dom_element_is_potentially_render_blocking(this: DomElement*) -> bool:
    # An element is potentially render-blocking if
    # FIXME: its blocking tokens set contains "render",
    # or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
    return dom_element_is_implicitly_potentially_render_blocking(this)