Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_element_1.lucb

#==============================================================================================
#
#   html_element_1 - HTML::HTMLElement: construction, edges, translate, dir, contenteditable,
#                    innerText and outerText
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLElement.cpp (lines 1-455): the constructor (which constructs
#       the GlobalEventHandlers, HTMLOrSVGElement and FormAssociatedElement bases and moves
#       Element's mixin tables to HTMLElement's), initialize, visit_edges, the translate and dir
#       reflections, focusability, contentEditable, the innerText / outerText setters with the
#       rendered text fragment, the rendered text collection steps and the get the text steps.
#
#==============================================================================================

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

## `document()` of an HTML element: its node document.
func html_element_document(this: HtmlElement*) -> DomDocument*:
    return dom_node_document(this.dom_node())

## `realm()` of an HTML element: its platform object's realm.
func html_element_realm(this: HtmlElement*) -> Realm*:
    return bind_platform_object_realm(this.bind_platform_object())

## `local_name() == name`.
func html_element_local_name_is(this: HtmlElement*, name: ak.FlyString) -> bool:
    let local_name = dom_element_local_name(this.dom_element())
    return ak.fly_string_eq_fly_string(&local_name, &name)

## `Optional<String>::value().equals_ignoring_ascii_case(text)` of a present value.
func html_element_string_is(value: ak.String?, text: str) -> bool:
    let present = value else return false
    return ak.string_equals_ignoring_ascii_case_string_view(&present, ak.sv(text))

## `Optional<String>::value().is_empty()` of a present value.
func html_element_string_is_empty(value: ak.String?) -> bool:
    let present = value else return false
    return ak.string_is_empty(&present)

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

## Ported from HTMLElement.cpp:59 Web::HTML::HTMLElement::HTMLElement.
pub func html_element_construct(this: HtmlElement*, document: DomDocument*, qualified_name: DomQualifiedName):
    dom_element_construct(this.dom_element(), document, qualified_name)
    # The bases after Element: GlobalEventHandlers (no state), HTMLOrSVGElement<HTMLElement> (its
    # two fields start null and empty) and FormAssociatedElement, whose defaulted constructor runs
    # its members' initializers (html_form_associated_element_construct). The vptrs of every
    # mixin base are HTMLElement's (a subclass moves them on, DESIGN.md ยง2.5).
    html_form_associated_element_construct(&this.form_associated_element)
    this.element.slottable_mixin.vtable = &html_element_slottable_mixin_vtable
    this.element.aria_mixin.vtable = &html_element_aria_mixin_vtable
    this.element.animatable.vtable = &html_element_animatable_vtable
    this.global_event_handlers.vtable = &html_element_global_event_handlers_vtable
    this.global_event_handlers.class_id = this.cell().class_id
    this.form_associated_element.vtable = &html_element_form_associated_element_vtable
    this.form_associated_element.class_id = this.cell().class_id
    html_element_init_fields(this)

## Ported from HTMLElement.cpp:66 Web::HTML::HTMLElement::initialize (override).
pub func html_element_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.html_element)
    dom_element_initialize_impl(base, realm)

## Ported from HTMLElement.cpp:72 Web::HTML::HTMLElement::visit_edges (override).
pub func html_element_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlElement*)base
    dom_element_visit_edges_impl(base, visitor)
    html_or_svg_element_visit_edges(&this.html_or_svg_element, visitor)
    html_form_associated_element_visit_edges(&this.form_associated_element, visitor)
    gc.cell_visitor_visit_t[DomNodeList](visitor, this.m_labels)
    gc.cell_visitor_visit_t[HtmlElementInternals](visitor, this.m_attached_internals)
    gc.cell_visitor_visit_t[HtmlElement](visitor, this.m_popover_trigger)
    gc.cell_visitor_visit_t(visitor, this.m_popover_close_watcher)

# mark: translate and dir =======================================================================

## Ported from HTMLElement.cpp:84 Web::HTML::HTMLElement::translate.
# https://html.spec.whatwg.org/multipage/dom.html#dom-translate
pub func html_element_translate(this: HtmlElement*) -> bool:
    # The translate IDL attribute must, on getting, return true if the element's translation mode is
    # translate-enabled, and false otherwise
    return dom_element_translation_mode(this.dom_element()) == DomElementTranslationMode.translate_enabled

## Ported from HTMLElement.cpp:92 Web::HTML::HTMLElement::set_translate.
# https://html.spec.whatwg.org/multipage/dom.html#dom-translate
pub func html_element_set_translate(this: HtmlElement*, new_value: bool):
    # On setting, it must set the content attribute's value to "yes" if the new value is true, and set the content
    # attribute's value to "no" otherwise.
    if new_value:
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_translate, ak.string_from_str("yes"))
    else:
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_translate, ak.string_from_str("no"))

## ENUMERATE_HTML_ELEMENT_DIR_ATTRIBUTES (HTMLElement.h:22).
let html_element_dir_attributes: str[3] = ["ltr", "rtl", "auto"]

## Ported from HTMLElement.cpp:103 Web::HTML::HTMLElement::dir.
# https://html.spec.whatwg.org/multipage/dom.html#dom-dir
pub func html_element_dir(this: HtmlElement*) -> ak.StringView:
    # FIXME: This should probably be `Reflect` in the IDL.
    # The dir IDL attribute on an element must reflect the dir content attribute of that element, limited to only known values.
    let dir = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_dir)
    for keyword in html_element_dir_attributes:
        if ak.string_equals_ignoring_ascii_case_string_view(&dir, ak.sv(keyword)):
            return ak.sv(keyword)

    return ak.StringView()

## Ported from HTMLElement.cpp:116 Web::HTML::HTMLElement::set_dir.
pub func html_element_set_dir(this: HtmlElement*, dir: ak.String):
    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_dir, dir)

## Ported from HTMLElement.cpp:121 Web::HTML::HTMLElement::is_focusable (override).
pub func html_element_is_focusable_impl(base: DomEventTarget*) -> bool:
    return dom_element_is_focusable_impl(base) or dom_node_is_editing_host((DomNode*)base)

# mark: contentEditable =========================================================================

## Ported from HTMLElement.cpp:127 Web::HTML::HTMLElement::is_content_editable.
# https://html.spec.whatwg.org/multipage/interaction.html#dom-iscontenteditable
pub func html_element_is_content_editable(this: HtmlElement*) -> bool:
    # The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or
    # editable, and false otherwise.
    return dom_node_is_editable_or_editing_host(this.dom_node())

## Ported from HTMLElement.cpp:134 Web::HTML::HTMLElement::content_editable.
pub func html_element_content_editable(this: HtmlElement*) -> ak.StringView:
    match this.m_content_editable_state:
        .true_: return ak.sv("true")
        .false_: return ak.sv("false")
        .plaintext_only: return ak.sv("plaintext-only")
        .inherit: return ak.sv("inherit")
        _: trap("VERIFY_NOT_REACHED")

## Ported from HTMLElement.cpp:150 Web::HTML::HTMLElement::set_content_editable.
# https://html.spec.whatwg.org/multipage/interaction.html#contenteditable
pub func html_element_set_content_editable(this: HtmlElement*, content_editable: ak.StringView) -> !:
    if ak.string_view_equals_ignoring_ascii_case(&content_editable, ak.sv("inherit")):
        dom_element_remove_attribute(this.dom_element(), html_attribute_names_contenteditable)
        return
    if ak.string_view_equals_ignoring_ascii_case(&content_editable, ak.sv("true")):
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_contenteditable, ak.string_from_str("true"))
        return
    if ak.string_view_equals_ignoring_ascii_case(&content_editable, ak.sv("plaintext-only")):
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_contenteditable, ak.string_from_str("plaintext-only"))
        return
    if ak.string_view_equals_ignoring_ascii_case(&content_editable, ak.sv("false")):
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_contenteditable, ak.string_from_str("false"))
        return
    try idl_throw(.idl_dom_exception(idl_syntax_error_create(html_element_realm(this), ak.utf16_string_from_str("Invalid contentEditable value, must be 'true', 'false', 'plaintext-only' or 'inherit'"))))

# mark: innerText and outerText =================================================================

## Ported from HTMLElement.cpp:171 Web::HTML::HTMLElement::set_inner_text.
# https://html.spec.whatwg.org/multipage/dom.html#set-the-inner-text-steps
pub func html_element_set_inner_text(this: HtmlElement*, text: ak.Utf16View):
    # 1. Let fragment be the rendered text fragment for value given element's node document.
    let fragment = html_element_rendered_text_fragment(this, text)

    # 2. Replace all with fragment within element.
    dom_node_replace_all(this.dom_node(), fragment.dom_node())

    dom_node_set_needs_style_update(this.dom_node(), true)

## Ported from HTMLElement.cpp:183 Web::HTML::merge_with_the_next_text_node.
# https://html.spec.whatwg.org/multipage/dom.html#merge-with-the-next-text-node
func html_merge_with_the_next_text_node(node: DomText*):
    # 1. Let next be node's next sibling.
    let next = tree_node_next_sibling(node.dom_node())

    # 2. If next is not a Text node, then return.
    let present_next = next else return
    let text = as_if_dom_text(present_next) else return

    # 3. Replace data with node, node's data's length, 0, and next's data.
    let data = dom_character_data_data(text.dom_character_data())
    let length = dom_character_data_length_in_utf16_code_units(node.dom_character_data())
    dom_character_data_replace_data(node.dom_character_data(), (usize)length, 0, ak.utf16_string_base_utf16_view(&data.utf16_string_base)) else trap("MUST: CharacterData::replace_data")

    # 4. Remove next.
    dom_node_remove(present_next)

## Ported from HTMLElement.cpp:201 Web::HTML::HTMLElement::set_outer_text.
# https://html.spec.whatwg.org/multipage/dom.html#the-innertext-idl-attribute:dom-outertext-2
pub func html_element_set_outer_text(this: HtmlElement*, value: ak.Utf16View) -> !:
    # 1. If this's parent is null, then throw a "NoModificationAllowedError" DOMException.
    let parent = tree_node_parent(this.dom_node())
    if parent == none:
        try idl_throw(.idl_dom_exception(idl_no_modification_allowed_error_create(html_element_realm(this), ak.utf16_string_from_str("setOuterText: parent is null"))))

    # 2. Let next be this's next sibling.
    let next = tree_node_next_sibling(this.dom_node())

    # 3. Let previous be this's previous sibling.
    let previous = tree_node_previous_sibling(this.dom_node())

    # 4. Let fragment be the rendered text fragment for the given value given this's node document.
    let fragment = html_element_rendered_text_fragment(this, value)

    # 5. If fragment has no children, then append a new Text node whose data is the empty string and node document is this's node document to fragment.
    if not tree_node_has_children(fragment.dom_node()):
        let empty_text = dom_document_create_text_node(html_element_document(this), ak.utf16_string_new())
        _ = dom_node_append_child(fragment.dom_node(), empty_text.dom_node()) else trap("MUST: append_child")

    # 6. Replace this with fragment within this's parent.
    let parent_node = parent else trap("unreachable")
    _ = dom_node_replace_child(parent_node, fragment.dom_node(), this.dom_node()) else trap("MUST: replace_child")

    # 7. If next is non-null and next's previous sibling is a Text node, then merge with the next text node given next's previous sibling.
    if let next_node = next:
        if let next_previous = tree_node_previous_sibling(next_node):
            if let previous_text = as_if_dom_text(next_previous):
                html_merge_with_the_next_text_node(previous_text)

    # 8. If previous is a Text node, then merge with the next text node given previous.
    if let previous_node = previous:
        if let previous_text = as_if_dom_text(previous_node):
            html_merge_with_the_next_text_node(previous_text)

    dom_node_set_needs_style_update(this.dom_node(), true)

## `first_is_one_of(code_unit, u'\n', u'\r')`.
func html_element_is_newline(code_unit: u16) -> bool:
    return code_unit == (u16)'\n' or code_unit == (u16)'\r'

## Ported from HTMLElement.cpp:239 Web::HTML::HTMLElement::rendered_text_fragment.
# https://html.spec.whatwg.org/multipage/dom.html#rendered-text-fragment
func html_element_rendered_text_fragment(this: HtmlElement*, input: ak.Utf16View) -> DomDocumentFragment*:
    let document = html_element_document(this)

    # 1. Let fragment be a new DocumentFragment whose node document is document.
    let fragment = realm_create_dom_document_fragment(html_element_realm(this), document)

    # 2. Let position be a position variable for input, initially pointing at the start of input.
    var position: usize = 0
    let length = ak.utf16_view_length_in_code_units(&input)

    # 3. Let text be the empty string.
    # 4. While position is not past the end of input:
    while position < length:
        let start = position

        # 1. Collect a sequence of code points that are not U+000A LF or U+000D CR from input given position, and set
        #    text to the result.
        while position < length and not html_element_is_newline(ak.utf16_view_code_unit_at(&input, position)):
            position += 1

        let text = ak.utf16_view_substring_view_usize(&input, start, position - start)

        # 2. If text is not the empty string, then append a new Text node whose data is text and node document is
        #    document to fragment.
        if not ak.utf16_view_is_empty(&text):
            let text_node = dom_document_create_text_node(document, ak.utf16_string_from_utf16(text))
            _ = dom_node_append_child(fragment.dom_node(), text_node.dom_node()) else trap("MUST: append_child")

        # 3. While position is not past the end of input, and the code point at position is either U+000A LF or U+000D CR:
        while position < length and html_element_is_newline(ak.utf16_view_code_unit_at(&input, position)):
            # 1. If the code point at position is U+000D CR and the next code point is U+000A LF, then advance position
            #    to the next code point in input.
            if ak.utf16_view_code_unit_at(&input, position) == (u16)'\r':
                if position + 1 < length and ak.utf16_view_code_unit_at(&input, position + 1) == (u16)'\n':
                    position += 1

            # 2. Advance position to the next code point in input.
            position += 1

            # 3. Append the result of creating an element given document, "br", and the HTML namespace to fragment.
            let br_element = dom_create_element(document, html_tag_names_br, namespace_html) else trap("MUST: create_element")
            _ = dom_node_append_child(fragment.dom_node(), br_element.dom_node()) else trap("MUST: append_child")

    # 5. Return fragment.
    return fragment

# mark: The get the text steps ==================================================================

## Ported from HTMLElement.cpp:292 Web::HTML::rendered_text_collection_steps.
# https://html.spec.whatwg.org/multipage/dom.html#rendered-text-collection-steps
func html_rendered_text_collection_steps(node: DomNode*) -> ak.Vector[Utf16StringOrHtmlRequiredLineBreakCount]:
    # 1. Let items be the result of running the rendered text collection steps with each child node of node in tree
    #    order, and then concatenating the results to a single list.
    var items: ak.Vector[Utf16StringOrHtmlRequiredLineBreakCount]
    for child in dom_node_children(node):
        var child_items = html_rendered_text_collection_steps(child)
        ak.vector_extend(&items, &child_items)

    # NOTE: Steps are re-ordered here a bit.

    # 3. If node is not being rendered, then return items.
    #    For the purpose of this step, the following elements must act as described
    #    if the computed value of the 'display' property is not 'none':
    #    FIXME: - select elements have an associated non-replaced inline CSS box whose child boxes include only those of optgroup and option element child nodes;
    #    FIXME: - optgroup elements have an associated non-replaced block-level CSS box whose child boxes include only those of option element child nodes; and
    #    FIXME: - option elements have an associated non-replaced block-level CSS box whose child boxes are as normal for non-replaced block-level CSS boxes.
    let layout_node = dom_node_layout_node(node) else return items

    let computed_values = layout_node_computed_values(layout_node)

    # 2. If node's computed value of 'visibility' is not 'visible', then return items.
    if css_computed_values_visibility(&computed_values.computed_values) != css_data.Visibility.visible:
        return items

    # AD-HOC: If node's computed value of 'content-visibility' is 'hidden', then return items.
    if css_computed_values_content_visibility(&computed_values.computed_values) == css_data.ContentVisibility.hidden:
        return items

    # 4. If node is a Text node, then for each CSS text box produced by node, in content order, compute the text of the
    #    box after application of the CSS 'white-space' processing rules and 'text-transform' rules, set items to the
    #    list of the resulting strings, and return items.

    #    FIXME: The CSS 'white-space' processing rules are slightly modified: collapsible spaces at the end of lines are
    #    always collapsed, but they are only removed if the line is the last line of the block, or it ends with a br
    #    element. Soft hyphens should be preserved. [CSSTEXT]

    if let layout_text_node = as_if_layout_text_node(layout_node):
        var iterator: LayoutTextNodeChunkIterator = ---
        layout_text_node_chunk_iterator_construct(&iterator, layout_text_node, false, false)
        while true:
            let chunk = layout_text_node_chunk_iterator_next(&iterator) else break
            ak.vector_append_t(&items, .utf16_string(ak.utf16_string_from_utf16(chunk.view)))
        return items

    # 5. If node is a br element, then append a string containing a single U+000A LF code point to items.
    if is_html_htmlbr_element(node):
        ak.vector_append_t(&items, .utf16_string(ak.utf16_string_from_str("\n")))
        return items

    let display = css_computed_values_display(&computed_values.computed_values)

    # 6. If node's computed value of 'display' is 'table-cell', and node's CSS box is not the last 'table-cell' box of its enclosing 'table-row' box, then append a string containing a single U+0009 TAB code point to items.
    if css_display_is_table_cell(&display) and tree_node_next_sibling(node) != none:
        ak.vector_append_t(&items, .utf16_string(ak.utf16_string_from_str("\t")))

    # 7. If node's computed value of 'display' is 'table-row', and node's CSS box is not the last 'table-row' box of the nearest ancestor 'table' box, then append a string containing a single U+000A LF code point to items.
    if css_display_is_table_row(&display) and tree_node_next_sibling(node) != none:
        ak.vector_append_t(&items, .utf16_string(ak.utf16_string_from_str("\n")))

    # 8. If node is a p element, then append 2 (a required line break count) at the beginning and end of items.
    if is_html_paragraph_element(node):
        ak.vector_prepend_u(&items, .html_required_line_break_count(HtmlRequiredLineBreakCount(count = 2)))
        ak.vector_append_t(&items, .html_required_line_break_count(HtmlRequiredLineBreakCount(count = 2)))

    # 9. If node's used value of 'display' is block-level or 'table-caption', then append 1 (a required line break count) at the beginning and end of items. [CSSDISPLAY]
    if css_display_is_block_outside(&display) or css_display_is_table_caption(&display):
        ak.vector_prepend_u(&items, .html_required_line_break_count(HtmlRequiredLineBreakCount(count = 1)))
        ak.vector_append_t(&items, .html_required_line_break_count(HtmlRequiredLineBreakCount(count = 1)))

    # 10. Return items.
    return items

## `item.has<RequiredLineBreakCount>()`: the count, if the item is one.
func html_required_line_break_count_of(item: const Utf16StringOrHtmlRequiredLineBreakCount*) -> i32?:
    match *item:
        .html_required_line_break_count(count): return count.count
        .utf16_string(_): return none

## get_the_text_steps' remove_all_matching predicate: the item is the empty string.
func html_element_is_empty_string_item(context: void*?, item: const Utf16StringOrHtmlRequiredLineBreakCount*) -> bool:
    match *item:
        .utf16_string(string): return ak.utf16_string_base_is_empty(&string.utf16_string_base)
        .html_required_line_break_count(_): return false

## Ported from HTMLElement.cpp:377 Web::HTML::HTMLElement::get_the_text_steps.
# https://html.spec.whatwg.org/multipage/dom.html#get-the-text-steps
pub func html_element_get_the_text_steps(this: HtmlElement*) -> ak.Utf16String:
    # 1. If element is not being rendered or if the user agent is a non-CSS user agent, then return element's descendant text content.
    dom_document_update_layout(html_element_document(this), DomUpdateLayoutReason.html_element_get_the_text_steps)
    if dom_node_layout_node(this.dom_node()) == none:
        return dom_node_descendant_text_content(this.dom_node())

    # 2. Let results be a new empty list.
    var results: ak.Vector[Utf16StringOrHtmlRequiredLineBreakCount]

    # 3. For each child node node of element:
    for node in dom_node_children(this.dom_node()):
        # 1. Let current be the list resulting in running the rendered text collection steps with node.
        #    Each item in results will either be a string or a positive integer (a required line break count).
        var current = html_rendered_text_collection_steps(node)

        # 2. For each item item in current, append item to results.
        ak.vector_extend(&results, &current)

    # 4. Remove any items from results that are the empty string.
    _ = ak.vector_remove_all_matching(&results, ak.Function1[const Utf16StringOrHtmlRequiredLineBreakCount*, bool](call = html_element_is_empty_string_item, context = none))

    # 5. Remove any runs of consecutive required line break count items at the start or end of results.
    while not ak.vector_is_empty(&results) and html_required_line_break_count_of(ak.vector_first(&results)) != none:
        _ = ak.vector_take_first(&results)
    while not ak.vector_is_empty(&results) and html_required_line_break_count_of(ak.vector_last(&results)) != none:
        _ = ak.vector_take_last(&results)

    # 6. Replace each remaining run of consecutive required line break count items with a string consisting of as many
    #    U+000A LF code points as the maximum of the values in the required line break count items.
    var builder = ak.string_builder_new_mode(ak.StringBuilderMode.utf16)
    var i: usize = 0
    while i < ak.vector_size(&results):
        match *ak.vector_at(&results, i):
            .utf16_string(string):
                ak.string_builder_append_utf16_view(&builder, ak.utf16_string_base_utf16_view(&string.utf16_string_base))
            .html_required_line_break_count(line_break_count):
                var max_line_breaks = line_break_count.count
                var j = i + 1
                while j < ak.vector_size(&results):
                    let count = html_required_line_break_count_of(ak.vector_at(&results, j)) else break
                    if count > max_line_breaks:
                        max_line_breaks = count
                    j += 1

                # Skip over the run of required line break counts.
                i = j - 1

                ak.string_builder_append_repeated_u8(&builder, '\n', (usize)max_line_breaks)
        i += 1

    # 7. Return the concatenation of the string items in results.
    return ak.string_builder_to_utf16_string(&builder)

## Ported from HTMLElement.cpp:435 Web::HTML::HTMLElement::inner_text.
# https://html.spec.whatwg.org/multipage/dom.html#dom-innertext
pub func html_element_inner_text(this: HtmlElement*) -> ak.Utf16String:
    # The innerText and outerText getter steps are to return the result of running get the text steps with this.
    return html_element_get_the_text_steps(this)

## Ported from HTMLElement.cpp:442 Web::HTML::HTMLElement::outer_text.
# https://html.spec.whatwg.org/multipage/dom.html#dom-outertext
pub func html_element_outer_text(this: HtmlElement*) -> ak.Utf16String:
    # The innerText and outerText getter steps are to return the result of running get the text steps with this.
    return html_element_get_the_text_steps(this)

## Ported from HTMLElement.cpp:452 Web::HTML::any_ancestor_establishes_a_fixed_position_containing_block.
func html_any_ancestor_establishes_a_fixed_position_containing_block(node: LayoutNodeWithStyle*) -> bool:
    # https://www.w3.org/TR/css-position-3/#fixed-positioning-containing-block
    # The containing block is established by the nearest ancestor box that establishes an fixed positioning containing
    # block, with the bounds of the containing block determined identically to the absolute positioning containing block.
    var ancestor = layout_node_containing_block(node.layout_node())
    while let box = ancestor:
        if layout_node_establishes_a_fixed_positioning_containing_block(box.layout_node()):
            return true
        ancestor = layout_node_containing_block(box.layout_node())
    return false