Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / document_1.lucb

#==============================================================================================
#
#   document_1 - DOM::Document: creation, construction, edges, populating html/head/body
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 218-767): the style-invalidation counter dump,
#       obtaining a browsing context for a navigation response, creating and initializing a
#       Document object from navigation params, the constructors and the cell-creation helpers
#       they need, the style-invalidation counters, finalize, initialize, populating a
#       document with html/head/body, visit_edges and getSelection().
#
#==============================================================================================

# mark: Style invalidation counters =============================================================

## Ported from Document.cpp:222 Web::DOM::dump_style_invalidation_counters.
func dom_dump_style_invalidation_counters(document: DomDocument*):
    let counters = dom_document_style_invalidation_counters(document)
    let url = dom_document_url_string(document)
    ak.dbgln(f"Style invalidation counters for {ak.string_view_text(ak.string_bytes_as_string_view(&url))}: styleInvalidations={counters.style_invalidations}, fullStyleInvalidations={counters.full_style_invalidations}, elementStyleRecomputations={counters.element_style_recomputations}, elementStyleNoopRecomputations={counters.element_style_noop_recomputations}, elementInheritedStyleRecomputations={counters.element_inherited_style_recomputations}, elementInheritedStyleNoopRecomputations={counters.element_inherited_style_noop_recomputations}, previousSiblingInvalidationWalkVisits={counters.previous_sibling_invalidation_walk_visits}, hasAncestorWalkInvocations={counters.has_ancestor_walk_invocations}, hasAncestorWalkVisits={counters.has_ancestor_walk_visits}, hasAncestorSiblingElementChecks={counters.has_ancestor_sibling_element_checks}, hasInvalidationMetadataCandidates={counters.has_invalidation_metadata_candidates}, hasMatchInvocations={counters.has_match_invocations}, hasResultCacheHits={counters.has_result_cache_hits}, hasResultCacheMisses={counters.has_result_cache_misses}")

# mark: Creating and initializing a Document ====================================================

## Ported from Document.cpp:244 Web::DOM::obtain_a_browsing_context_to_use_for_a_navigation_response.
# https://html.spec.whatwg.org/multipage/origin.html#obtain-browsing-context-navigation
func dom_obtain_a_browsing_context_to_use_for_a_navigation_response(navigation_params: HtmlNavigationParams*) -> HtmlBrowsingContext*:
    # 1. Let browsingContext be navigationParams's navigable's active browsing context.
    let navigable = navigation_params.navigable else trap("navigation params without a navigable")
    let browsing_context = html_navigable_active_browsing_context(navigable) else trap("the navigable has no active browsing context")

    # 2. If browsingContext is not a top-level browsing context, return browsingContext.
    if not html_browsing_context_is_top_level(browsing_context):
        return browsing_context

    # 3. Let coopEnforcementResult be navigationParams's COOP enforcement result.
    let coop_enforcement_result = &navigation_params.coop_enforcement_result

    # 4. Let swapGroup be coopEnforcementResult's needs a browsing context group switch.
    let swap_group = coop_enforcement_result.needs_a_browsing_context_group_switch

    # 5. Let sourceOrigin be browsingContext's active document's origin.
    # 6. Let destinationOrigin be navigationParams's origin.
    #    (sourceOrigin, browsingContext's active document's origin, is only read by step 7's empty branch.)

    # 7. If sourceOrigin is not same site with destinationOrigin:
    #    (C++ keeps an empty `if (!source_origin.is_same_site(destination_origin))` around the two FIXMEs.)
    #    FIXME: 1. If either of sourceOrigin or destinationOrigin have a scheme that is not an HTTP(S) scheme
    #    and the user agent considers it necessary for sourceOrigin and destinationOrigin to be
    #    isolated from each other (for implementation-defined reasons), optionally set swapGroup to true.
    #    FIXME: 2. If navigationParams's user involvement is "browser UI", optionally set swapGroup to true.

    # FIXME: 8. If browsingContext's group's browsing context set's size is 1, optionally set swapGroup to true.

    # 9. If swapGroup is false, then:
    if not swap_group:
        # 1. If coopEnforcementResult's would need a browsing context group switch due to report-only is true,
        #    set browsingContext's virtual browsing context group ID to a new unique identifier.
        #    FIXME: set browsingContext's virtual browsing context group ID to a new unique identifier.
        #    (C++ keeps the empty `if` on would_need_a_browsing_context_group_switch_due_to_report_only.)

        # 2. Return browsingContext.
        return browsing_context

    # 10. Let newBrowsingContext be the first return value of creating a new top-level browsing context and document.
    let browsing_context_and_document = html_create_a_new_top_level_browsing_context_and_document(html_browsing_context_page(browsing_context))
    let new_browsing_context = browsing_context_and_document.browsing_context

    # 11. Let navigationCOOP be navigationParams's cross-origin opener policy.
    let navigation_coop = navigation_params.opener_policy

    # FIXME: 12. If navigationCOOP's value is "same-origin-plus-COEP", then set newBrowsingContext's group's cross-origin
    #     isolation mode to either "logical" or "concrete". The choice of which is implementation-defined.

    # 13. Let sandboxFlags be a clone of navigationParams's final sandboxing flag set.
    let sandbox_flags = navigation_params.final_sandboxing_flag_set

    # 14. If sandboxFlags is not empty, then:
    if not html_is_empty(sandbox_flags):
        # 1. Assert: navigationCOOP's value is "unsafe-none".
        assert(navigation_coop.value == HtmlOpenerPolicyValue.unsafe_none)

        # 2. Assert: newBrowsingContext's popup sandboxing flag set is empty.
        assert(html_is_empty(html_browsing_context_popup_sandboxing_flag_set(new_browsing_context)))

        # 3. Set newBrowsingContext's popup sandboxing flag set to sandboxFlags.
        html_browsing_context_set_popup_sandboxing_flag_set(new_browsing_context, sandbox_flags)

    # 15. Return newBrowsingContext.
    return new_browsing_context

## The captures of create_and_initialize's two realm customizations: `window` by reference
## and the browsing context.
struct DomDocumentCreateAndInitializeRealmCustomizations:
    var window: HtmlWindow*?
    var browsing_context: HtmlBrowsingContext*

## create_and_initialize's first realm customization: for the global object, a new Window.
func dom_document_create_and_initialize_create_global_object(context: void*?, realm: Realm*) -> JsObject*?:
    let captures = (DomDocumentCreateAndInitializeRealmCustomizations*)(context else trap("no captures"))
    # - For the global object, create a new Window object.
    let window = html_window_create(realm)
    captures.window = window
    return (JsObject*)window

## create_and_initialize's second realm customization: the browsing context's WindowProxy.
func dom_document_create_and_initialize_create_global_this_value(context: void*?, realm: Realm*) -> JsObject*?:
    let captures = (DomDocumentCreateAndInitializeRealmCustomizations*)(context else trap("no captures"))
    # - For the global this binding, use browsingContext's WindowProxy object.
    return (JsObject*?)html_browsing_context_window_proxy(captures.browsing_context)

## Ported from Document.cpp:318 Web::DOM::Document::create_and_initialize.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
pub func dom_document_create_and_initialize(type_: DocumentDomDocumentType, content_type: ak.String, navigation_params: HtmlNavigationParams*) -> DomDocument*!:
    # 1. Let browsingContext be the result of obtaining a browsing context to use for a navigation response given navigationParams.
    let browsing_context = dom_obtain_a_browsing_context_to_use_for_a_navigation_response(navigation_params)

    # FIXME: 2. Let permissionsPolicy be the result of creating a permissions policy from a response given navigationParams's navigable's container, navigationParams's origin, and navigationParams's response.

    # 3. Let creationURL be navigationParams's response's URL.
    let response = navigation_params.response else trap("navigation params without a response")
    var creation_url = fetch_response_url(response)

    # 4. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.
    if let request = navigation_params.request:
        creation_url = fetch_request_current_url(request)

    # 5. Let window be null.
    var captures = DomDocumentCreateAndInitializeRealmCustomizations(window = none, browsing_context = browsing_context)

    # 6. If browsingContext's active document's is initial about:blank is true,
    #    and browsingContext's active document's origin is same origin-domain with navigationParams's origin,
    #    then set window to browsingContext's active window.
    # FIXME: still_on_its_initial_about_blank_document() is not in the spec anymore.
    #        However, replacing this with the spec-mandated is_initial_about_blank() results in the browsing context
    #        holding an incorrect active document for the replace from initial about:blank to the real document.
    #        See #22293 for more details.
    # (C++ guards this branch with `if (false && ...)`: it is never taken, so only the else branch is ported.)

    # 7. Otherwise:
    # FIXME: 1. Let oacHeader be the result of getting a structured field value given `Origin-Agent-Cluster` and "item" from response's header list.

    # FIXME: 2. Let requestsOAC be true if oacHeader is not null and oacHeader[0] is the boolean true; otherwise false.

    # FIXME: 3. If navigationParams's reserved environment is a non-secure context, then set requestsOAC to false.

    # FIXME: 4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOAC.

    # 5. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
    let realm_execution_context = bind_create_a_new_javascript_realm(
        bind_main_thread_vm(),
        ak.Function1[Realm*, JsObject*?](call = dom_document_create_and_initialize_create_global_object, context = &captures),
        ak.Function1[Realm*, JsObject*?](call = dom_document_create_and_initialize_create_global_this_value, context = &captures),
    )

    # 6. Set window to the global object of realmExecutionContext's Realm component.
    let execution_realm = realm_execution_context.realm else trap("the realm execution context has no realm")
    let window = as_html_window((gc.Cell*)realm_global_object(execution_realm))
    captures.window = window

    # 7. Let topLevelCreationURL be creationURL.
    var top_level_creation_url = creation_url

    # 8. Let topLevelOrigin be navigationParams's origin.
    var top_level_origin = navigation_params.origin

    # 9. If navigable's container is not null, then:
    let navigable = navigation_params.navigable else trap("navigation params without a navigable")
    if let container = html_navigable_container(navigable):
        # 1. Let parentEnvironment be navigable's container's relevant settings object.
        let parent_environment = html_relevant_settings_object_dom_node(container.dom_node())

        # 2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.
        top_level_creation_url = parent_environment.environment.top_level_creation_url

        # 3. Set topLevelOrigin to parentEnvironment's top-level origin.
        top_level_origin = parent_environment.environment.top_level_origin else trap("the parent environment has no top-level origin")

    # 10. Set up a window environment settings object with creationURL, realm execution context,
    #    navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.

    # FIXME: Why do we assume `creation_url` is non-empty here? Is this a spec bug?
    # FIXME: Why do we assume `top_level_creation_url` is non-empty here? Is this a spec bug?
    html_window_environment_settings_object_setup(
        html_browsing_context_page(browsing_context),
        creation_url else trap("VERIFY: the creation URL is empty"),
        realm_execution_context,
        navigation_params.reserved_environment,
        top_level_creation_url else trap("VERIFY: the top-level creation URL is empty"),
        top_level_origin,
    )

    # 8. Let loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams's response's timing info's start time.
    var load_timing_info = DomDocumentLoadTimingInfo()
    # AD-HOC: The response object no longer has an associated timing info object. For now, we use response's non-standard response time property,
    #         which represents the time that the time that the response object was created.
    let monotonic_response_time = fetch_response_monotonic_response_time(response)
    let response_creation_time = f64(ak.monotonic_time_nanoseconds(&monotonic_response_time)) / 1e6
    load_timing_info.navigation_start_time = high_resolution_time_coarsen_time(response_creation_time, html_environment_settings_object_cross_origin_isolated_capability(html_relevant_settings_object_js_object((JsObject*)window)))

    # 9. Let document be a new Document, with
    #    type: type
    #    content type: contentType
    #    origin: navigationParams's origin
    #    browsing context: browsingContext
    #    policy container: navigationParams's policy container
    #    FIXME: permissions policy: permissionsPolicy
    #    active sandboxing flag set: navigationParams's final sandboxing flag set
    #    FIXME: opener policy: navigationParams's opener policy
    #    load timing info: loadTimingInfo
    #    FIXME: was created via cross-origin redirects: navigationParams's response's has cross-origin redirects
    #    during-loading navigation ID for WebDriver BiDi: navigationParams's id
    #    URL: creationURL
    #    current document readiness: "loading"
    #    about base URL: navigationParams's about base URL
    #    allow declarative shadow roots: true
    #    custom element registry: A new CustomElementRegistry object.
    let realm = bind_platform_object_realm(window.bind_platform_object())
    let document = html_document_create(realm, web_url.about_blank()).dom_document()
    document.m_type = type_
    document.m_content_type = content_type
    dom_document_set_origin(document, navigation_params.origin)
    dom_document_set_browsing_context(document, browsing_context)
    document.m_policy_container = navigation_params.policy_container
    document.m_active_sandboxing_flag_set = navigation_params.final_sandboxing_flag_set
    document.m_navigation_id = navigation_params.id
    dom_document_set_load_timing_info(document, load_timing_info)
    dom_document_set_url(document, creation_url else trap("VERIFY: the creation URL is empty"))
    document.m_readiness = HtmlDocumentReadyState.loading
    document.m_about_base_url = navigation_params.about_base_url
    dom_document_set_allow_declarative_shadow_roots(document, true)
    dom_document_set_custom_element_registry(document, realm_create_html_custom_element_registry(realm, realm))

    document.m_window = window

    # NOTE: Non-standard: Pull out the Last-Modified header for use in the lastModified property.
    if let maybe_last_modified = http_header_list_get(fetch_response_header_list(response), ak.sv("Last-Modified")):
        # rfc9110, 8.8.2: The Last-Modified header field must be in GMT time zone.
        # document->m_last_modified is in local time zone.
        document.m_last_modified = ak.unix_date_time_parse(ak.sv("%a, %d %b %Y %H:%M:%S GMT"), ak.byte_string_view(&maybe_last_modified), true)

    # NOTE: Non-standard: Pull out the Content-Language header to determine the document's language.
    if let maybe_http_content_language = http_header_list_get(fetch_response_header_list(response), ak.sv("Content-Language")):
        let maybe_content_language: ak.String? = ak.string_from_byte_string(maybe_http_content_language) catch: recover none
        if let content_language = maybe_content_language:
            document.m_http_content_language = content_language

    # 10. Set window's associated Document to document.
    html_window_set_associated_document(window, document)

    # 11. Run CSP initialization for a Document given document.
    dom_document_run_csp_initialization(document)

    # 12. If navigationParams's request is non-null, then:
    if let request = navigation_params.request:
        # 1. Set document's referrer to the empty string.
        document.m_referrer = ak.String()

        # 2. Let referrer be navigationParams's request's referrer.
        let referrer = fetch_request_referrer(request)

        # 3. If referrer is a URL record, then set document's referrer to the serialization of referrer.
        if let referrer_url = fetch_request_referrer_type_as_url(referrer):
            document.m_referrer = web_url.url_serialize(&referrer_url)

    # FIXME: 13: If navigationParams's fetch controller is not null, then:

    # FIXME: 14. Create the navigation timing entry for document, with navigationParams's response's timing info, redirectCount, navigationParams's navigation timing type, and
    #            navigationParams's response's service worker timing info.

    # 15. If navigationParams's response has a `Refresh` header, then:
    if let maybe_refresh = http_header_list_get(fetch_response_header_list(response), ak.sv("Refresh")):
        # 1. Let value be the isomorphic decoding of the value of the header.
        let value = text_codec.isomorphic_decode(ak.byte_string_view(&maybe_refresh))

        # 2. Run the shared declarative refresh steps with document and value.
        dom_document_shared_declarative_refresh_steps(document, ak.string_bytes_as_string_view(&value), none)

    # FIXME: 16. If navigationParams's commit early hints is not null, then call navigationParams's commit early hints with document.

    # FIXME: 17. Process link headers given document, navigationParams's response, and "pre-media".

    # FIXME: 18. Potentially free deferred fetch quota for document.

    # 19. Return document.
    return document

## Ported from Document.cpp:507 Web::DOM::Document::construct_impl.
# https://dom.spec.whatwg.org/#dom-document-document
pub func dom_document_construct_impl(realm: Realm*) -> DomDocument*:
    # The new Document() constructor steps are to set this’s origin to the origin of current global object’s associated Document. [HTML]
    let document = dom_document_create(realm, web_url.about_blank())
    let current_window = as_html_window((gc.Cell*)html_current_global_object())
    dom_document_set_origin(document, dom_document_origin(html_window_associated_document(current_window)))
    return document

## Ported from Document.cpp:515 Web::DOM::Document::create.
## C++'s default `url` is `URL::about_blank()`.
pub func dom_document_create(realm: Realm*, url: web_url.Url) -> DomDocument*:
    return realm_create_dom_document(realm, realm, url, DomDocumentTemporaryDocumentForFragmentParsing.no)

## Ported from Document.cpp:520 Web::DOM::Document::create_for_fragment_parsing.
pub func dom_document_create_for_fragment_parsing(realm: Realm*) -> DomDocument*:
    return realm_create_dom_document(realm, realm, web_url.about_blank(), DomDocumentTemporaryDocumentForFragmentParsing.yes)

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

## heap.allocate<CSS::StyleComputer>(document): a StyleComputer cell constructed under DeferGC.
pub func heap_allocate_css_style_computer(heap: gc.Heap*, document: DomDocument*) -> CssStyleComputer*:
    let this = (CssStyleComputer*)web_heap_allocate_cell(heap, &css_style_computer_class)
    gc.heap_defer_gc(heap)
    css_style_computer_construct(this, document)
    gc.heap_undefer_gc(heap)
    return this

## heap.allocate<CSS::FontComputer>(document): a FontComputer cell constructed under DeferGC.
pub func heap_allocate_css_font_computer(heap: gc.Heap*, document: DomDocument*) -> CssFontComputer*:
    let this = (CssFontComputer*)web_heap_allocate_cell(heap, &css_font_computer_class)
    gc.heap_defer_gc(heap)
    css_font_computer_construct(this, document)
    gc.heap_undefer_gc(heap)
    return this

## heap.allocate<CSS::Invalidation::StyleInvalidator>(): its implicit constructor leaves the
## zeroed cell as it is.
pub func heap_allocate_css_style_invalidator(heap: gc.Heap*) -> CssStyleInvalidator*:
    return (CssStyleInvalidator*)web_heap_allocate_cell(heap, &css_style_invalidator_class)

## The captures of the cursor blink timer's handler.
struct DomDocumentCursorBlinkTimerCaptures:
    var this: DomDocument*

## The cursor blink timer's handler (the lambda of Document::Document).
func dom_document_cursor_blink_timer_fired(context: void*?):
    let this = ((DomDocumentCursorBlinkTimerCaptures*)(context else trap("no captures"))).this
    let cursor_position = dom_document_cursor_position(this) else return

    let navigable = dom_document_navigable(this) else return
    if not html_navigable_is_focused(navigable):
        return

    let node = dom_position_node(cursor_position)
    if dom_node_unsafe_paintable(node) != none:
        this.m_cursor_blink_state = not this.m_cursor_blink_state
        dom_node_set_needs_repaint(node)

## Ported from Document.cpp:525 Web::DOM::Document::Document.
pub func dom_document_construct(this: DomDocument*, realm: Realm*, url: web_url.Url, temporary_document_for_fragment_parsing: DomDocumentTemporaryDocumentForFragmentParsing = DomDocumentTemporaryDocumentForFragmentParsing.no):
    dom_parent_node_construct_realm(this.dom_parent_node(), realm, this, DomNodeType.document_node)
    # The GlobalEventHandlers mixin base follows; its vtable is Document's until a derived class's
    # constructor moves it on (DESIGN.md §2.5).
    this.global_event_handlers.vtable = &dom_document_global_event_handlers_vtable
    this.global_event_handlers.class_id = this.cell().class_id

    # The default member initializers.
    dom_document_init_fields(this)
    this.m_content_type = ak.string_from_str("application/xml")
    this.m_origin = web_url.origin_create_opaque()
    this.m_default_single_line_container_name = html_tag_names_div
    # m_cookie_version's default, Core::INVALID_SHARED_VERSION, is 0: the zeroed cell's.

    # The member initializers, in declaration order.
    let heap = realm_heap(realm)
    this.m_page = bind_principal_host_defined_page(realm)
    this.m_style_computer = heap_allocate_css_style_computer(heap, this)
    this.m_font_computer = heap_allocate_css_font_computer(heap, this)
    this.m_url = url
    this.m_fonts = css_font_face_set_create(realm)
    this.m_temporary_document_for_fragment_parsing = temporary_document_for_fragment_parsing
    this.m_editing_host_manager = dom_editing_host_manager_create(realm, this)
    var parsing_params: CssParsingParams = ---
    css_parsing_params_construct_realm_css_parsing_mode(&parsing_params, realm)
    this.m_dynamic_view_transition_style_sheet = parse_css_stylesheet(parsing_params, ak.sv(""), none)
    this.m_style_invalidator = heap_allocate_css_style_invalidator(heap)
    css_style_scope_construct(&this.m_style_scope, this.dom_node())

    this.bind_platform_object().m_legacy_platform_object_flags = BindPlatformObjectLegacyPlatformObjectFlags(
        supports_named_properties = 1,
        has_legacy_override_built_ins_interface_extended_attribute = 1,
    )

    this.m_is_decoded_svg = page_client_is_svg_page_client(page_client(this.m_page))

    let captures = new DomDocumentCursorBlinkTimerCaptures(this = this) else trap("out of memory")
    this.m_cursor_blink_timer = core_timer_create_repeating(500, ak.Function0[unit](call = dom_document_cursor_blink_timer_fired, context = captures))

    html_event_loop_register_document(html_main_thread_event_loop(), this)

## Ported from Document.cpp:566 Web::DOM::Document::set_style_invalidation_counter_dump_interval.
pub func dom_document_set_style_invalidation_counter_dump_interval(interval: u64?):
    dom_s_style_invalidation_counter_dump_interval = interval

## Ported from Document.cpp:571 Web::DOM::Document::reset_style_invalidation_counters.
pub func dom_document_reset_style_invalidation_counters(this: DomDocument*):
    this.m_style_invalidation_counters = DomDocumentStyleInvalidationCounters()
    this.m_style_invalidations_since_last_counter_dump = 0

## Ported from Document.cpp:577 Web::DOM::Document::record_style_invalidation.
pub func dom_document_record_style_invalidation(this: DomDocument*):
    this.m_style_invalidation_counters.style_invalidations += 1

    let interval = dom_s_style_invalidation_counter_dump_interval else return

    this.m_style_invalidations_since_last_counter_dump += 1
    if this.m_style_invalidations_since_last_counter_dump < interval:
        return

    this.m_style_invalidations_since_last_counter_dump = 0
    dom_dump_style_invalidation_counters(this)

## Ported from Document.cpp:591 Web::DOM::Document::record_full_style_invalidation.
pub func dom_document_record_full_style_invalidation(this: DomDocument*):
    this.m_style_invalidation_counters.full_style_invalidations += 1

    let interval = dom_s_style_invalidation_counter_dump_interval else return

    this.m_style_invalidations_since_last_counter_dump += 1
    if this.m_style_invalidations_since_last_counter_dump < interval:
        return

    this.m_style_invalidations_since_last_counter_dump = 0
    dom_dump_style_invalidation_counters(this)

## Ported from Document.cpp:605 Web::DOM::Document::finalize (override).
pub func dom_document_finalize_impl(base: gc.Cell*):
    let this = (DomDocument*)base
    dom_node_finalize_impl(base)
    html_event_loop_unregister_document(html_main_thread_event_loop(), this)

## Ported from Document.cpp:611 Web::DOM::Document::initialize (override).
pub func dom_document_initialize_impl(base: JsCell*, realm: Realm*):
    let this = (DomDocument*)base
    web_set_prototype_for_interface(base, realm, BindInterfaceName.document)
    # Base::initialize(realm): ParentNode and Node inherit EventTarget's.
    dom_event_target_initialize_impl(base, realm)
    # Bindings::DocumentPrototype::define_unforgeable_attributes(realm, *this): the JS prototype
    # comes with the bindings (phase 3).

    this.m_selection = realm_create_selection_selection(realm, realm, this)

    this.m_list_of_available_images = realm_create_html_list_of_available_images(realm)

    page_client_page_did_create_new_document(page_client(dom_document_page(this)), this)

    dom_document_ensure_cookie_version_index(this, this.m_url, web_url.url_empty())

# mark: Populating html/head/body ===============================================================

## Ported from Document.cpp:627 Web::DOM::Document::populate_with_html_head_and_body.
# https://html.spec.whatwg.org/multipage/document-lifecycle.html#populate-with-html/head/body
pub func dom_document_populate_with_html_head_and_body(this: DomDocument*) -> !:
    # 1. Let html be the result of creating an element given document, "html", and the HTML namespace.
    let html = try dom_create_element(this, html_tag_names_html, namespace_html)

    # 2. Let head be the result of creating an element given document, "head", and the HTML namespace.
    let head = try dom_create_element(this, html_tag_names_head, namespace_html)

    # 3. Let body be the result of creating an element given document, "body", and the HTML namespace.
    let body = try dom_create_element(this, html_tag_names_body, namespace_html)

    # 4. Append html to document.
    _ = try dom_node_append_child(this.dom_node(), html.dom_node())

    # 5. Append head to html.
    _ = try dom_node_append_child(html.dom_node(), head.dom_node())

    # 6. Append body to html.
    _ = try dom_node_append_child(html.dom_node(), body.dom_node())

# mark: Edges ===================================================================================

## Ported from Document.cpp:650 Web::DOM::Document::visit_edges (override).
pub func dom_document_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (DomDocument*)base
    dom_parent_node_visit_edges_impl(base, visitor)
    css_style_scope_visit_edges(&this.m_style_scope, visitor)
    gc.cell_visitor_visit_hash_table(visitor, &this.m_pending_css_import_rules)
    gc.cell_visitor_visit_t_2(visitor, this.m_page)
    gc.cell_visitor_visit_t(visitor, this.m_window)
    gc.cell_visitor_visit_t(visitor, this.m_layout_root)
    gc.cell_visitor_visit_t(visitor, this.m_style_sheets)
    gc.cell_visitor_visit_t(visitor, this.m_hovered_node)
    gc.cell_visitor_visit_t(visitor, this.m_inspected_node)
    gc.cell_visitor_visit_t(visitor, this.m_highlighted_node)
    gc.cell_visitor_visit_t(visitor, this.m_active_favicon)
    gc.cell_visitor_visit_t(visitor, this.m_browsing_context)
    gc.cell_visitor_visit_t(visitor, this.m_focused_area)
    gc.cell_visitor_visit_t(visitor, this.m_active_element)
    gc.cell_visitor_visit_t(visitor, this.m_target_element)
    gc.cell_visitor_visit_vector(visitor, &this.m_autofocus_candidates)
    gc.cell_visitor_visit_t(visitor, this.m_implementation)
    gc.cell_visitor_visit_t(visitor, this.m_current_script)
    gc.cell_visitor_visit_t(visitor, this.m_associated_inert_template_document)
    gc.cell_visitor_visit_t(visitor, this.m_appropriate_template_contents_owner_document)
    gc.cell_visitor_visit_t(visitor, this.m_pending_parsing_blocking_script)
    gc.cell_visitor_visit_t(visitor, this.m_pending_parsing_blocking_svg_script)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_history)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.m_html_parser_end_state)
    gc.cell_visitor_visit_t(visitor, this.m_style_computer)
    gc.cell_visitor_visit_t(visitor, this.m_font_computer)
    gc.cell_visitor_visit_t(visitor, this.m_browsing_context)

    gc.cell_visitor_visit_t(visitor, this.m_applets)
    gc.cell_visitor_visit_t(visitor, this.m_anchors)
    gc.cell_visitor_visit_t(visitor, this.m_images)
    gc.cell_visitor_visit_t(visitor, this.m_embeds)
    gc.cell_visitor_visit_t(visitor, this.m_links)
    gc.cell_visitor_visit_t(visitor, this.m_forms)
    gc.cell_visitor_visit_t(visitor, this.m_scripts)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_all)  # opaque in phase 1
    gc.cell_visitor_visit_t_2(visitor, this.m_fonts)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_selection)
    gc.cell_visitor_visit_t(visitor, this.m_first_base_element_with_href_in_tree_order)
    gc.cell_visitor_visit_t(visitor, this.m_first_base_element_with_target_in_tree_order)
    gc.cell_visitor_visit_t(visitor, this.m_parser)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_lazy_load_intersection_observer)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.m_visual_viewport)
    gc.cell_visitor_visit_t(visitor, this.m_default_timeline)
    gc.cell_visitor_visit_vector(visitor, &this.m_scripts_to_execute_when_parsing_has_finished)
    gc.cell_visitor_visit_vector(visitor, &this.m_scripts_to_execute_in_order_as_soon_as_possible)
    gc.cell_visitor_visit_vector(visitor, &this.m_scripts_to_execute_as_soon_as_possible)
    gc.cell_visitor_visit_hash_table_nullable(visitor, &this.m_node_iterators)
    gc.cell_visitor_visit_vector(visitor, &this.m_document_observers_being_notified)
    for pending_scroll_event in ak.vector_span(&this.m_pending_scroll_events):
        gc.cell_visitor_visit_t_2(visitor, pending_scroll_event.event_target)
    # for (auto& resize_observer : m_resize_observers) visitor.visit(resize_observer): ResizeObserver
    # is outside the phase-1 closure (its list node is not declared), so the list is always empty.

    gc.cell_visitor_visit_hash_table(visitor, &this.m_svg_roots_needing_relayout)

    for entry in ak.hash_map_begin(&this.m_shared_resource_requests):
        gc.cell_visitor_visit_t(visitor, entry.value)

    for timeline in ak.hash_table_begin(&this.m_associated_animation_timelines):
        gc.cell_visitor_visit_cell_2(visitor, (*timeline).cell())
    gc.cell_visitor_visit_t(visitor, this.m_list_of_available_images)
    for entry in ak.hash_map_begin(&this.m_map_of_preloaded_resources):
        gc.cell_visitor_visit_cell_2(visitor, (gc.Cell*)entry.value)  # opaque in phase 1

    for form_associated_element in ak.vector_span(&this.m_form_associated_elements_with_form_attribute):
        let element = form_associated_element else trap("a null form-associated element")
        gc.cell_visitor_visit_t_2(visitor, html_form_associated_element_form_associated_element_to_html_element(element))

    gc.cell_visitor_visit_vector(visitor, &this.m_potentially_named_elements)
    dom_anchor_name_map_visit_edges(&this.m_anchor_name_map, visitor)

    for event in ak.vector_span(&this.m_pending_animation_event_queue):
        gc.cell_visitor_visit_t_2(visitor, event.event)
        gc.cell_visitor_visit_t_2(visitor, event.animation)
        gc.cell_visitor_visit_t_2(visitor, event.target)

    for event in ak.vector_span(&this.m_pending_fullscreen_events):
        gc.cell_visitor_visit_t_2(visitor, event.element)

    gc.cell_visitor_visit_t(visitor, this.m_adopted_style_sheets)
    gc.cell_visitor_visit_hash_table(visitor, &this.m_script_blocking_style_sheet_set)

    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_active_view_transition)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.m_dynamic_view_transition_style_sheet)

    for view_transition in ak.vector_span(&this.m_update_callback_queue):
        gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)view_transition)  # opaque in phase 1

    gc.cell_visitor_visit_opaque_2(visitor, &this.m_top_layer_elements)
    gc.cell_visitor_visit_opaque_2(visitor, &this.m_top_layer_pending_removals)
    gc.cell_visitor_visit_vector(visitor, &this.m_showing_auto_popover_list)
    gc.cell_visitor_visit_vector(visitor, &this.m_showing_hint_popover_list)
    gc.cell_visitor_visit_t(visitor, this.m_popover_pointerdown_target)
    gc.cell_visitor_visit_vector(visitor, &this.m_open_dialogs_list)
    gc.cell_visitor_visit_t(visitor, this.m_dialog_pointerdown_target)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_console_client)  # opaque in phase 1
    gc.cell_visitor_visit_t_2(visitor, this.m_editing_host_manager)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_local_storage_holder)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_session_storage_holder)  # opaque in phase 1
    gc.cell_visitor_visit_hash_table(visitor, &this.m_render_blocking_elements)
    gc.cell_visitor_visit_t(visitor, this.m_policy_container)
    gc.cell_visitor_visit_t_2(visitor, this.m_style_invalidator)
    gc.cell_visitor_visit_t(visitor, this.m_deferred_parser_start)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_custom_element_registry)  # opaque in phase 1

# mark: Selection ===============================================================================

## Ported from Document.cpp:759 Web::DOM::Document::get_selection.
# https://w3c.github.io/selection-api/#dom-document-getselection
pub func dom_document_get_selection(this: DomDocument*) -> SelectionSelection*?:
    # The method must return the selection associated with this if this has an associated browsing context,
    # and it must return null otherwise.
    if dom_document_browsing_context(this) == none:
        return none
    return this.m_selection