Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / dom / document_7.lucb

#==============================================================================================
#
#   document_7 - DOM::Document: cookies, legacy colors, activity, visibility, the load event
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 3610-4254): document.cookie and cookie-
#       averseness, the legacy body color attributes, the DOM JSON dump, script-blocking style
#       sheets, the referrer, full activity, location, visibility, the resize and scroll
#       steps, media query lists and @media rules, the DOMImplementation, the has-focus and
#       allow-focus steps, the parser link, XML names, node iterators, tree walkers and
#       document observers, the things delaying the load event, the HTML parser end check and
#       post-load readiness.
#
#==============================================================================================

# mark: Cookies =================================================================================

## Ported from Document.cpp:3611 Web::DOM::Document::cookie.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-cookie
pub func dom_document_cookie(this: DomDocument*) -> ak.String!:
    # On getting, if the document is a cookie-averse Document object, then the user agent must return the empty string.
    if dom_document_is_cookie_averse(this):
        return ak.String()

    # Otherwise, if the Document's origin is an opaque origin, the user agent must throw a "SecurityError" DOMException.
    let origin = dom_document_origin(this)
    if web_url.origin_is_opaque(&origin):
        return try dom_document_throw(idl_security_error_create(dom_document_realm(this), ak.utf16_string_from_str("Document origin is opaque")))

    # Otherwise, the user agent must return the cookie-string for the document's URL for a "non-HTTP" API, decoded using
    # UTF-8 decode without BOM.
    let client = page_client(dom_document_page(this))
    if let cookie_version_index = this.m_cookie_version_index:
        if let current_version = page_client_page_did_request_document_cookie_version(client, cookie_version_index):
            if this.m_cookie_version == current_version:
                return this.m_cookie

    let versioned_cookie = page_client_page_did_request_cookie(client, this.m_url, HttpSource.non_http)

    if let cookie_version = versioned_cookie.cookie_version:
        this.m_cookie_version = cookie_version
        this.m_cookie = versioned_cookie.cookie

    return versioned_cookie.cookie

## Ported from Document.cpp:3639 Web::DOM::Document::set_cookie.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-cookie
pub func dom_document_set_cookie(this: DomDocument*, cookie_string: ak.StringView) -> !:
    # On setting, if the document is a cookie-averse Document object, then the user agent must do nothing.
    if dom_document_is_cookie_averse(this):
        return

    # Otherwise, if the Document's origin is an opaque origin, the user agent must throw a "SecurityError" DOMException.
    let origin = dom_document_origin(this)
    if web_url.origin_is_opaque(&origin):
        return try dom_document_throw(idl_security_error_create(dom_document_realm(this), ak.utf16_string_from_str("Document origin is opaque")))

    # Otherwise, the user agent must act as it would when receiving a set-cookie-string for the document's URL via a
    # "non-HTTP" API, consisting of the new value encoded as UTF-8.
    if let cookie = http_parse_cookie(dom_document_url(this), cookie_string):
        page_client_page_did_set_cookie(page_client(dom_document_page(this)), this.m_url, cookie, HttpSource.non_http)

## Ported from Document.cpp:3658 Web::DOM::Document::is_cookie_averse.
# https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
pub func dom_document_is_cookie_averse(this: DomDocument*) -> bool:
    # A Document object that falls into one of the following conditions is a cookie-averse Document object:

    # * A Document object whose browsing context is null.
    if dom_document_browsing_context(this) == none:
        return true

    # * A Document whose URL's scheme is not an HTTP(S) scheme.
    let url = dom_document_url(this)
    let scheme = web_url.url_scheme(&url)
    if not (ak.string_eq_string_view(&scheme, ak.sv("http")) or ak.string_eq_string_view(&scheme, ak.sv("https"))):
        return true

    return false

# mark: Legacy colors ===========================================================================

## The body element when it is not a frameset (the legacy color attributes live on it).
func dom_document_body_for_legacy_colors(this: DomDocument*) -> DomElement*?:
    let body_element = dom_document_body(this) else return none
    if is_html_frame_set_element(body_element):
        return none
    return body_element.dom_element()

## Ported from Document.cpp:3673 Web::DOM::Document::fg_color.
pub func dom_document_fg_color(this: DomDocument*) -> ak.String:
    if let body_element = dom_document_body_for_legacy_colors(this):
        return dom_element_get_attribute_value(body_element, html_attribute_names_text)
    return ak.string_from_str("")

## Ported from Document.cpp:3680 Web::DOM::Document::set_fg_color.
pub func dom_document_set_fg_color(this: DomDocument*, value: ak.String):
    if let body_element = dom_document_body_for_legacy_colors(this):
        dom_element_set_attribute_value(body_element, html_attribute_names_text, value)

## Ported from Document.cpp:3686 Web::DOM::Document::link_color.
pub func dom_document_link_color(this: DomDocument*) -> ak.String:
    if let body_element = dom_document_body_for_legacy_colors(this):
        return dom_element_get_attribute_value(body_element, html_attribute_names_link)
    return ak.string_from_str("")

## Ported from Document.cpp:3693 Web::DOM::Document::set_link_color.
pub func dom_document_set_link_color(this: DomDocument*, value: ak.String):
    if let body_element = dom_document_body_for_legacy_colors(this):
        dom_element_set_attribute_value(body_element, html_attribute_names_link, value)

## Ported from Document.cpp:3699 Web::DOM::Document::vlink_color.
pub func dom_document_vlink_color(this: DomDocument*) -> ak.String:
    if let body_element = dom_document_body_for_legacy_colors(this):
        return dom_element_get_attribute_value(body_element, html_attribute_names_vlink)
    return ak.string_from_str("")

## Ported from Document.cpp:3706 Web::DOM::Document::set_vlink_color.
pub func dom_document_set_vlink_color(this: DomDocument*, value: ak.String):
    if let body_element = dom_document_body_for_legacy_colors(this):
        dom_element_set_attribute_value(body_element, html_attribute_names_vlink, value)

## Ported from Document.cpp:3712 Web::DOM::Document::alink_color.
pub func dom_document_alink_color(this: DomDocument*) -> ak.String:
    if let body_element = dom_document_body_for_legacy_colors(this):
        return dom_element_get_attribute_value(body_element, html_attribute_names_alink)
    return ak.string_from_str("")

## Ported from Document.cpp:3719 Web::DOM::Document::set_alink_color.
pub func dom_document_set_alink_color(this: DomDocument*, value: ak.String):
    if let body_element = dom_document_body_for_legacy_colors(this):
        dom_element_set_attribute_value(body_element, html_attribute_names_alink, value)

## Ported from Document.cpp:3725 Web::DOM::Document::bg_color.
pub func dom_document_bg_color(this: DomDocument*) -> ak.String:
    if let body_element = dom_document_body_for_legacy_colors(this):
        return dom_element_get_attribute_value(body_element, html_attribute_names_bgcolor)
    return ak.string_from_str("")

## Ported from Document.cpp:3732 Web::DOM::Document::set_bg_color.
pub func dom_document_set_bg_color(this: DomDocument*, value: ak.String):
    if let body_element = dom_document_body_for_legacy_colors(this):
        dom_element_set_attribute_value(body_element, html_attribute_names_bgcolor, value)

## Ported from Document.cpp:3738 Web::DOM::Document::dump_dom_tree_as_json.
pub func dom_document_dump_dom_tree_as_json(this: DomDocument*) -> ak.String:
    dom_document_update_layout(this, DomUpdateLayoutReason.inspect_dom_tree)

    var builder = ak.string_builder_new()
    var json = ak.json_object_serializer_try_create(&builder) else trap("MUST: JsonObjectSerializer::try_create")
    dom_node_serialize_tree_as_json(this.dom_node(), &json)

    ak.json_object_serializer_finish(&json) else trap("MUST: JsonObjectSerializer::finish")
    return ak.string_builder_to_string(&builder) else trap("MUST: StringBuilder::to_string")

# mark: Script-blocking style sheets and the referrer ===========================================

## Ported from Document.cpp:3751 Web::DOM::Document::has_no_style_sheet_that_is_blocking_scripts.
# https://html.spec.whatwg.org/multipage/semantics.html#has-no-style-sheet-that-is-blocking-scripts
pub func dom_document_has_no_style_sheet_that_is_blocking_scripts(this: DomDocument*) -> bool:
    # A Document has no style sheet that is blocking scripts if it does not have a style sheet that is blocking scripts.
    return not dom_document_has_a_style_sheet_that_is_blocking_scripts(this)

## Ported from Document.cpp:3758 Web::DOM::Document::has_a_style_sheet_that_is_blocking_scripts.
# https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
pub func dom_document_has_a_style_sheet_that_is_blocking_scripts(this: DomDocument*) -> bool:
    # 1. If document's script-blocking style sheet set is not empty, then return true.
    if not ak.hash_table_is_empty(&this.m_script_blocking_style_sheet_set):
        return true

    # 2. If document's node navigable is null, then return false.
    let navigable = dom_document_navigable(this) else return false

    # 3. Let containerDocument be document's node navigable's container document.
    let container_document = html_navigable_container_document(navigable)

    # 4. If containerDocument is non-null and containerDocument's script-blocking style sheet set is not empty, then return true.
    if let container = container_document:
        if not ak.hash_table_is_empty(&container.m_script_blocking_style_sheet_set):
            return true

    # 5. Return false
    return false

## Ported from Document.cpp:3780 Web::DOM::Document::referrer.
pub func dom_document_referrer(this: DomDocument*) -> ak.String:
    return this.m_referrer

## Ported from Document.cpp:3785 Web::DOM::Document::set_referrer.
pub func dom_document_set_referrer(this: DomDocument*, referrer: ak.String):
    this.m_referrer = referrer

# mark: Activity ================================================================================

## Ported from Document.cpp:3791 Web::DOM::Document::is_fully_active.
# https://html.spec.whatwg.org/multipage/document-sequences.html#fully-active
pub func dom_document_is_fully_active(this: DomDocument*) -> bool:
    # A Document d is said to be fully active when d is the active document of a navigable navigable, and either
    # navigable is a top-level traversable or navigable's container document is fully active.
    let navigable = dom_document_navigable(this) else return false

    let traversable = html_navigable_traversable_navigable(navigable)
    if let traversable_navigable = traversable:
        if navigable == traversable_navigable.html_navigable() and html_navigable_is_top_level_traversable(traversable_navigable.html_navigable()):
            return true

    let container_document = html_navigable_container_document(navigable)
    if let container = container_document:
        if container != this and dom_document_is_fully_active(container):
            return true

    return false

## Ported from Document.cpp:3810 Web::DOM::Document::is_active.
pub func dom_document_is_active(this: DomDocument*) -> bool:
    let navigable = dom_document_navigable(this) else return false
    return html_navigable_active_document(navigable) == this

## Ported from Document.cpp:3817 Web::DOM::Document::location.
# https://html.spec.whatwg.org/multipage/history.html#dom-document-location
pub func dom_document_location(this: DomDocument*) -> HtmlHtmlLocation*?:
    # The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
    # if this Document object is fully active, and null otherwise.

    if not dom_document_is_fully_active(this):
        return none

    let window = dom_document_window(this) else trap("a fully active document without a window")
    return html_window_location(window)

# mark: Visibility ==============================================================================

## Ported from Document.cpp:3829 Web::DOM::Document::hidden.
# https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hidden
pub func dom_document_hidden(this: DomDocument*) -> bool:
    return this.m_visibility_state == HtmlVisibilityState.hidden

## Ported from Document.cpp:3835 Web::DOM::Document::visibility_state.
# https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate
pub func dom_document_visibility_state(this: DomDocument*) -> ak.StringView:
    match this.m_visibility_state:
        .hidden: return ak.sv("hidden")
        .visible: return ak.sv("visible")
        _: trap("VERIFY_NOT_REACHED")

## Ported from Document.cpp:3847 Web::DOM::Document::update_the_visibility_state.
# https://html.spec.whatwg.org/multipage/interaction.html#update-the-visibility-state
pub func dom_document_update_the_visibility_state(this: DomDocument*, visibility_state: HtmlVisibilityState):
    # 1. If document's visibility state equals visibilityState, then return.
    if this.m_visibility_state == visibility_state:
        return

    # 2. Set document's visibility state to visibilityState.
    this.m_visibility_state = visibility_state

    # FIXME: 3. Queue a new VisibilityStateEntry whose visibility state is visibilityState and whose timestamp is the current
    #    high resolution time given document's relevant global object.

    # FIXME: 4. Run the screen orientation change steps with document.

    # 5. Run the view transition page visibility change steps with document.
    dom_document_view_transition_page_visibility_change_steps(this)

    # 6. Run any page visibility change steps which may be defined in other specifications, with visibility state and
    #    document.
    dom_document_notify_document_observers_of_visibility_state(this, this.m_visibility_state)

    # 7. Fire an event named visibilitychange at document, with its bubbles attribute initialized to true.
    let event = dom_event_create(dom_document_realm(this), html_event_names_visibilitychange)
    dom_event_set_bubbles(event, true)
    _ = dom_event_target_dispatch_event(this.dom_event_target(), event)

## Ported from Document.cpp:3878 Web::DOM::Document::run_the_resize_steps.
# https://drafts.csswg.org/cssom-view/#document-run-the-resize-steps
pub func dom_document_run_the_resize_steps(this: DomDocument*):
    # 1. If doc’s viewport has had its width or height changed
    #    (e.g. as a result of the user resizing the browser window, or changing the page zoom scale factor,
    #    or an iframe element’s dimensions are changed) since the last time these steps were run,
    #    fire an event named resize at the Window object associated with doc.
    # 2. If the VisualViewport associated with doc has had its scale, width, or height properties changed
    #    since the last time these steps were run, fire an event named resize at the VisualViewport.

    let viewport_rect = dom_document_viewport_rect(this)
    let viewport_css_size = gfx.css_pixel_rect_size(&viewport_rect)
    let viewport_size = gfx.css_pixel_size_to_type_i32(&viewport_css_size)
    let visual_viewport = dom_document_visual_viewport(this)
    var visual_viewport_state = DomDocumentVisualViewportState(scale = css_visual_viewport_scale(visual_viewport), size = gfx.CssPixelSize(m_width = gfx.css_pixels_from_f64(css_visual_viewport_width(visual_viewport)), m_height = gfx.css_pixels_from_f64(css_visual_viewport_height(visual_viewport))))
    let is_initial_size = this.m_last_viewport_size == none

    let viewport_size_changed = this.m_last_viewport_size != viewport_size
    let visual_viewport_state_changed = this.m_last_visual_viewport_state != visual_viewport_state

    if not viewport_size_changed and not visual_viewport_state_changed:
        return

    this.m_last_viewport_size = viewport_size
    this.m_last_visual_viewport_state = visual_viewport_state

    if not is_initial_size:
        if viewport_size_changed:
            let window_resize_event = dom_event_create(dom_document_realm(this), ui_events_event_names_resize)
            dom_event_set_is_trusted(window_resize_event, true)
            let window = dom_document_window(this) else trap("the document has no window")
            _ = dom_event_target_dispatch_event(window.dom_event_target(), window_resize_event)

        if visual_viewport_state_changed:
            let visual_viewport_resize_event = dom_event_create(dom_document_realm(this), ui_events_event_names_resize)
            dom_event_set_is_trusted(visual_viewport_resize_event, true)
            _ = dom_event_target_dispatch_event(visual_viewport.dom_event_target(), visual_viewport_resize_event)

## Ported from Document.cpp:3917 Web::DOM::Document::run_the_scroll_steps.
# https://drafts.csswg.org/cssom-view-1/#document-run-the-scroll-steps
pub func dom_document_run_the_scroll_steps(this: DomDocument*):
    # AD-HOC: Process auto-scroll ticks before dispatching scroll events. This is tied to the rendering update to
    #         ensure exactly one auto-scroll tick per frame.
    if let navigable = dom_document_navigable(this):
        event_handler_process_auto_scroll(html_navigable_event_handler(navigable))

    # FIXME: 1. For each scrolling box box that was scrolled:
    #        ...

    # 2. For each item (target, type) in doc’s pending scroll events, in the order they were added to the list, run
    #    these substeps:
    var pending_scroll_events = this.m_pending_scroll_events
    this.m_pending_scroll_events = ak.Vector[DomDocumentPendingScrollEvent]()
    for pending_scroll_event in ak.vector_span(&pending_scroll_events):
        let target = pending_scroll_event.event_target
        let type_ = pending_scroll_event.event_type
        # 1. If target is a Document, and type is "scroll" or "scrollend", fire an event named type that bubbles at target.
        if is_dom_document(target) and (ak.fly_string_eq_fly_string(&type_, &html_event_names_scroll) or ak.fly_string_eq_fly_string(&type_, &html_event_names_scrollend)):
            let event = dom_event_create(dom_document_realm(this), type_)
            dom_event_set_bubbles(event, true)
            _ = dom_event_target_dispatch_event(target, event)
        # FIXME: 2. Otherwise, if type is "scrollsnapchange", then:
        # FIXME: 3. Otherwise, if type is "scrollsnapchanging", then:
        # 4. Otherwise, fire an event named type at target.
        else:
            let event = dom_event_create(dom_document_realm(this), type_)
            _ = dom_event_target_dispatch_event(target, event)

    # 3. Empty doc’s pending scroll events.
    # AD-HOC: We already emptied the scroll events by moving in step 2. This prevents us from removing new scroll
    #         events that were added while dispatching the old scroll events.

# mark: Media queries ===========================================================================

## Ported from Document.cpp:3951 Web::DOM::Document::add_media_query_list.
pub func dom_document_add_media_query_list(this: DomDocument*, media_query_list: CssMediaQueryList*):
    this.m_needs_media_query_evaluation = true
    var weak: gc.Weak[CssMediaQueryList] = gc.Weak[CssMediaQueryList]()
    gc.weak_construct(&weak, media_query_list)
    ak.vector_append_t(&this.m_media_query_lists, weak)

## evaluate_media_queries_and_report_changes' pruning predicate: a null weak pointer.
func dom_document_media_query_list_is_gone(context: void*?, list: const gc.Weak[CssMediaQueryList]*) -> bool:
    return gc.weak_ptr(list) == none

## Ported from Document.cpp:3958 Web::DOM::Document::evaluate_media_queries_and_report_changes.
# https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes
pub func dom_document_evaluate_media_queries_and_report_changes(this: DomDocument*):
    if not this.m_needs_media_query_evaluation:
        return
    this.m_needs_media_query_evaluation = false

    # NOTE: Not in the spec, but we take this opportunity to prune null WeakPtrs.
    _ = ak.vector_remove_all_matching(&this.m_media_query_lists, ak.Function1[const gc.Weak[CssMediaQueryList]*, bool](call = dom_document_media_query_list_is_gone, context = none))

    # 1. For each MediaQueryList object target that has doc as its document,
    #    in the order they were created, oldest first, run these substeps:
    for media_query_list_ptr in ak.vector_span(&this.m_media_query_lists):
        # 1. If target’s matches state has changed since the last time these steps
        #    were run, fire an event at target using the MediaQueryListEvent constructor,
        #    with its type attribute initialized to change, its isTrusted attribute
        #    initialized to true, its media attribute initialized to target’s media,
        #    and its matches attribute initialized to target’s matches state.
        let media_query_list = gc.weak_ptr(&media_query_list_ptr) else continue
        let did_match = css_media_query_list_matches(media_query_list)
        let now_matches = css_media_query_list_evaluate(media_query_list)

        let did_change_internally = css_media_query_list_has_changed_state(media_query_list)
        css_media_query_list_set_has_changed_state(media_query_list, false)

        if did_change_internally == true or did_match != now_matches:
            var init = CssMediaQueryListEventInit()
            init.media = css_media_query_list_media(media_query_list)
            init.matches = now_matches
            let event = css_media_query_list_event_create(dom_document_realm(this), html_event_names_change, init)
            dom_event_set_is_trusted(event, true)
            _ = dom_event_target_dispatch_event(media_query_list.dom_event_target(), event)

    # Also not in the spec, but this is as good a place as any to evaluate @media rules!
    dom_document_evaluate_media_rules(this)

## Ported from Document.cpp:4000 Web::DOM::Document::evaluate_media_rules.
func dom_document_evaluate_media_rules(this: DomDocument*):
    css_invalidation_evaluate_media_rules_and_invalidate_style(this)

## Ported from Document.cpp:4005 Web::DOM::Document::implementation.
pub func dom_document_implementation(this: DomDocument*) -> DomImplementation*?:
    if this.m_implementation == none:
        this.m_implementation = dom_implementation_create(this)
    return this.m_implementation

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

## Ported from Document.cpp:4013 Web::DOM::Document::has_focus_for_bindings.
# https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hasfocus
pub func dom_document_has_focus_for_bindings(this: DomDocument*) -> bool:
    # The Document hasFocus() method steps are to return the result of running the has focus steps given this.
    return dom_document_has_focus(this)

## Ported from Document.cpp:4020 Web::DOM::Document::has_focus.
# https://html.spec.whatwg.org/multipage/interaction.html#has-focus-steps
pub func dom_document_has_focus(this: DomDocument*) -> bool:
    # 1. If target's node navigable's top-level traversable does not have system focus, then return false.
    let navigable = dom_document_navigable(this) else return false

    let traversable = html_navigable_traversable_navigable(navigable) else return false
    if not html_navigable_is_focused(traversable.html_navigable()):
        return false

    # 2. Let candidate be target's node navigable's top-level traversable's active document.
    var candidate = html_navigable_active_document(traversable.html_navigable())

    # 3. While true:
    while let current = candidate:
        # 3.1. If candidate is target, then return true.
        if current == this:
            return true

        # 3.2. If the focused area of candidate is a navigable container with a non-null content navigable,
        #      then set candidate to the active document of that navigable container's content navigable.
        if let focused_area = dom_document_focused_area(current):
            if let navigable_container = as_if_html_navigable_container(focused_area):
                if let content_navigable = html_navigable_container_content_navigable(navigable_container):
                    candidate = html_navigable_active_document(content_navigable)
                    continue

        # 3.3. Otherwise, return false.
        return false

    return false

## Ported from Document.cpp:4058 Web::DOM::Document::allow_focus.
# https://html.spec.whatwg.org/multipage/interaction.html#allow-focus-steps
pub func dom_document_allow_focus(this: DomDocument*) -> bool:
    # The allow focus steps, given a Document object target, are as follows:

    # 1. If target is allowed to use the "focus-without-user-activation" feature, then return true.
    if dom_document_is_allowed_to_use_feature(this, DomPolicyControlledFeature.focus_without_user_activation):
        return true

    # 2. If target's relevant global object has transient activation, then return true.
    if html_window_has_transient_activation(as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this))):
        return true

    # 3. Return false.
    return false

# mark: Parser, names, iterators and observers ==================================================

## Ported from Document.cpp:4074 Web::DOM::Document::set_parser.
pub func dom_document_set_parser(this: DomDocument*, parser: HtmlParser*):
    this.m_parser = parser

## Ported from Document.cpp:4079 Web::DOM::Document::detach_parser.
pub func dom_document_detach_parser(this: DomDocument*):
    this.m_parser = none

## Ported from Document.cpp:4085 Web::DOM::is_valid_name_start_character.
# https://www.w3.org/TR/xml/#NT-NameStartChar
func dom_is_valid_name_start_character(code_point: u32) -> bool:
    return code_point == (u32)':' or (code_point >= (u32)'A' and code_point <= (u32)'Z') or code_point == (u32)'_' or (code_point >= (u32)'a' and code_point <= (u32)'z') or (code_point >= 0xc0 and code_point <= 0xd6) or (code_point >= 0xd8 and code_point <= 0xf6) or (code_point >= 0xf8 and code_point <= 0x2ff) or (code_point >= 0x370 and code_point <= 0x37d) or (code_point >= 0x37f and code_point <= 0x1fff) or (code_point >= 0x200c and code_point <= 0x200d) or (code_point >= 0x2070 and code_point <= 0x218f) or (code_point >= 0x2c00 and code_point <= 0x2fef) or (code_point >= 0x3001 and code_point <= 0xD7ff) or (code_point >= 0xf900 and code_point <= 0xfdcf) or (code_point >= 0xfdf0 and code_point <= 0xfffd) or (code_point >= 0x10000 and code_point <= 0xeffff)

## Ported from Document.cpp:4106 Web::DOM::is_valid_name_character.
# https://www.w3.org/TR/xml/#NT-NameChar
func dom_is_valid_name_character(code_point: u32) -> bool:
    return dom_is_valid_name_start_character(code_point) or code_point == (u32)'-' or code_point == (u32)'.' or (code_point >= (u32)'0' and code_point <= (u32)'9') or code_point == 0xb7 or (code_point >= 0x300 and code_point <= 0x36f) or (code_point >= 0x203f and code_point <= 0x2040)

## Ported from Document.cpp:4118 Web::DOM::Document::is_valid_name.
# https://www.w3.org/TR/xml/#NT-Name
pub func dom_document_is_valid_name(name: ak.String) -> bool:
    if ak.string_is_empty(&name):
        return false
    let code_points = ak.string_code_points(&name)
    var it = ak.utf8_view_begin(&code_points)

    if not dom_is_valid_name_start_character(ak.utf8_code_point_iterator_deref(&it)):
        return false
    _ = ak.utf8_code_point_iterator_inc(&it)

    while not ak.utf8_code_point_iterator_done(&it):
        if not dom_is_valid_name_character(ak.utf8_code_point_iterator_deref(&it)):
            return false
        _ = ak.utf8_code_point_iterator_inc(&it)

    return true

## Ported from Document.cpp:4138 Web::DOM::Document::create_node_iterator.
# https://dom.spec.whatwg.org/#dom-document-createnodeiterator
pub func dom_document_create_node_iterator(this: DomDocument*, root: DomNode*, what_to_show: u32, filter: DomNodeFilter*?) -> DomNodeIterator*:
    return dom_node_iterator_create(dom_document_realm(this), root, what_to_show, filter)

## Ported from Document.cpp:4144 Web::DOM::Document::create_tree_walker.
# https://dom.spec.whatwg.org/#dom-document-createtreewalker
pub func dom_document_create_tree_walker(this: DomDocument*, root: DomNode*, what_to_show: u32, filter: DomNodeFilter*?) -> DomTreeWalker*:
    return dom_tree_walker_create(dom_document_realm(this), root, what_to_show, filter)

## Ported from Document.cpp:4149 Web::DOM::Document::register_node_iterator.
pub func dom_document_register_node_iterator(this: DomDocument*, node_iterator: DomNodeIterator*):
    let result = ak.hash_table_set(&this.m_node_iterators, node_iterator)
    assert(result == ak.HashSetResult.inserted_new_entry)

## Ported from Document.cpp:4155 Web::DOM::Document::unregister_node_iterator.
pub func dom_document_unregister_node_iterator(this: DomDocument*, node_iterator: DomNodeIterator*):
    let was_removed = ak.hash_table_remove_t(&this.m_node_iterators, node_iterator)
    assert(was_removed)

## Ported from Document.cpp:4161 Web::DOM::Document::register_document_observer.
pub func dom_document_register_document_observer(this: DomDocument*, document_observer: DomDocumentObserver*):
    let result = ak.hash_table_set(&this.m_document_observers, document_observer)
    assert(result == ak.HashSetResult.inserted_new_entry)

## Ported from Document.cpp:4167 Web::DOM::Document::unregister_document_observer.
pub func dom_document_unregister_document_observer(this: DomDocument*, document_observer: DomDocumentObserver*):
    let was_removed = ak.hash_table_remove_t(&this.m_document_observers, document_observer)
    assert(was_removed)

# mark: The load event ==========================================================================

## Ported from Document.cpp:4173 Web::DOM::Document::increment_number_of_things_delaying_the_load_event.
pub func dom_document_increment_number_of_things_delaying_the_load_event(this: DomDocument*):
    this.m_number_of_things_delaying_the_load_event += 1

    page_client_page_did_update_resource_count(page_client(dom_document_page(this)), (i32)this.m_number_of_things_delaying_the_load_event)

## Ported from Document.cpp:4180 Web::DOM::Document::decrement_number_of_things_delaying_the_load_event.
pub func dom_document_decrement_number_of_things_delaying_the_load_event(this: DomDocument*):
    assert(this.m_number_of_things_delaying_the_load_event != 0)
    this.m_number_of_things_delaying_the_load_event -= 1

    page_client_page_did_update_resource_count(page_client(dom_document_page(this)), (i32)this.m_number_of_things_delaying_the_load_event)

    dom_document_schedule_html_parser_end_check(this)

## Ported from Document.cpp:4190 Web::DOM::Document::set_html_parser_end_state.
pub func dom_document_set_html_parser_end_state(this: DomDocument*, state: HtmlParserEndState*?):
    this.m_html_parser_end_state = state

## Ported from Document.cpp:4195 Web::DOM::Document::schedule_html_parser_end_check.
pub func dom_document_schedule_html_parser_end_check(this: DomDocument*):
    if let end_state = this.m_html_parser_end_state:
        html_parser_end_state_schedule_progress_check(end_state)
    if let parser = this.m_parser:
        html_parser_schedule_resume_check(parser)

## Ported from Document.cpp:4203 Web::DOM::Document::set_ready_for_post_load_tasks.
pub func dom_document_set_ready_for_post_load_tasks(this: DomDocument*, ready: bool):
    this.m_ready_for_post_load_tasks = ready
    if ready:
        if let navigable = dom_document_navigable(this):
            # AD-HOC: Clear the navigation load event guard now that the document is ready.
            #         This guard was set in finalize_a_cross_document_navigation to prevent the parent's
            #         load event from firing while the about:blank was still the active document.
            html_navigable_clear_navigation_load_event_guard(navigable)

            if let container = html_navigable_container(navigable):
                dom_document_schedule_html_parser_end_check(dom_node_document(container.dom_node()))

## Ported from Document.cpp:4220 Web::DOM::Document::anything_is_delaying_the_load_event.
pub func dom_document_anything_is_delaying_the_load_event(this: DomDocument*) -> bool:
    if this.m_number_of_things_delaying_the_load_event > 0:
        return true

    var navigables = dom_document_descendant_navigables_const(this)
    for navigable in ak.vector_span(&navigables):
        let descendant = navigable else continue
        let container = html_navigable_container(descendant) else trap("a descendant navigable has a container")
        if html_navigable_container_currently_delays_the_load_event(container):
            return true

    # FIXME: Track down anything else that is supposed to delay the load event.

    return false

## Ported from Document.cpp:4235 Web::DOM::Document::set_page_showing.
pub func dom_document_set_page_showing(this: DomDocument*, page_showing: bool):
    if this.m_page_showing == page_showing:
        return

    this.m_page_showing = page_showing

    dom_document_notify_document_observers_of_page_showing(this, this.m_page_showing)

## Ported from Document.cpp:4248 Web::DOM::Document::invalidate_stacking_context_tree.
pub func dom_document_invalidate_stacking_context_tree(this: DomDocument*):
    # NB: Called during stacking context invalidation.
    if let paintable_box = dom_node_unsafe_paintable_box(this.dom_node()):
        paint_paintable_box_invalidate_stacking_context(paintable_box)