Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / document_10.lucb

#==============================================================================================
#
#   document_10 - DOM::Document: observers, declarative refresh, history
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 5293-5993): registering intersection and resize
#       observers, the intersection observer tasks and update steps, lazy loading, the shared
#       declarative refresh steps, the paintable accessors, and restoring the history object
#       state and updating a document for history step application, readiness to run scripts,
#       the deferred parser start, the latest entry and shared resource requests.
#
#==============================================================================================

# mark: Intersection and resize observers =======================================================

## Ported from Document.cpp:5293 Web::DOM::Document::register_intersection_observer.
pub func dom_document_register_intersection_observer(this: DomDocument*, observer: IntersectionObserverIntersectionObserver*):
    let result = ak.ordered_hash_table_set(&this.m_intersection_observers, observer)
    assert(result == ak.HashSetResult.inserted_new_entry)

## Ported from Document.cpp:5299 Web::DOM::Document::unregister_intersection_observer.
pub func dom_document_unregister_intersection_observer(this: DomDocument*, observer: IntersectionObserverIntersectionObserver*):
    let was_removed = ak.ordered_hash_table_remove_t(&this.m_intersection_observers, observer)
    assert(was_removed)

## Ported from Document.cpp:5305 Web::DOM::Document::register_resize_observer.
pub func dom_document_register_resize_observer(this: DomDocument*, observer: ResizeObserverResizeObserver*):
    # m_resize_observers.append(observer): the intrusive list goes through ResizeObserver's list node, and
    # ResizeObserver is outside the phase-1 closure.
    trap("unported (P3): Web::DOM::Document::register_resize_observer (ResizeObserver)")

## Ported from Document.cpp:5310 Web::DOM::Document::unregister_resize_observer.
pub func dom_document_unregister_resize_observer(this: DomDocument*, observer: ResizeObserverResizeObserver*):
    # m_resize_observers.remove(observer): see register_resize_observer.
    trap("unported (P3): Web::DOM::Document::unregister_resize_observer (ResizeObserver)")

## Ported from Document.cpp:5316 Web::DOM::Document::queue_intersection_observer_task.
# https://www.w3.org/TR/intersection-observer/#queue-an-intersection-observer-task
## (Private in C++; public until the phase-3/4 code that calls it is ported.)
pub func dom_document_queue_intersection_observer_task(this: DomDocument*):
    if dom_document_window(this) == none:
        return

    # 1. If document’s IntersectionObserverTaskQueued flag is set to true, return.
    if this.m_intersection_observer_task_queued:
        return

    # 2. Set document’s IntersectionObserverTaskQueued flag to true.
    this.m_intersection_observer_task_queued = true

    # 3. Queue a task on the IntersectionObserver task source associated with the document's event loop to notify intersection observers.
    #    (The task takes each observer's records, wraps them in a JS array and invokes the observer's callback.)
    trap("unported (P3): Web::DOM::Document::queue_intersection_observer_task (notify intersection observers)")

## Ported from Document.cpp:5368 Web::DOM::Document::queue_an_intersection_observer_entry.
# https://www.w3.org/TR/intersection-observer/#queue-an-intersectionobserverentry
## (Private in C++; public until the phase-3/4 code that calls it is ported.)
pub func dom_document_queue_an_intersection_observer_entry(this: DomDocument*, observer: IntersectionObserverIntersectionObserver*, time: f64, root_bounds: GeometryDomRectReadOnly*, bounding_client_rect: GeometryDomRectReadOnly*, intersection_rect: GeometryDomRectReadOnly*, is_intersecting: bool, intersection_ratio: f64, target: DomElement*):
    # 1. Construct an IntersectionObserverEntry, passing in time, rootBounds, boundingClientRect, intersectionRect, isIntersecting, and target.
    # 2. Append it to observer’s internal [[QueuedEntries]] slot.
    # 3. Queue an intersection observer task for document.
    trap("unported (P3): Web::DOM::Document::queue_an_intersection_observer_entry (IntersectionObserverEntry)")

## Ported from Document.cpp:5383 Web::DOM::compute_intersection.
# https://www.w3.org/TR/intersection-observer/#compute-the-intersection
## (Private in C++; public until the phase-3/4 code that calls it is ported.)
pub func dom_compute_intersection(target: DomElement*, observer: IntersectionObserverIntersectionObserver*, root_paintable: PaintPaintableBox*?, root_bounds: gfx.CssPixelRect) -> gfx.CssPixelRect:
    # 1. Let intersectionRect be the result of getting the bounding box for target, 2.-3. clip it by each
    #    containing block with a content clip (expanded by the observer's scroll margin for scroll containers),
    #    5. intersect it with the root intersection rectangle, 7. return it. The observer's scroll margin is
    #    IntersectionObserver state, outside the phase-1 closure.
    trap("unported (P3): Web::DOM::compute_intersection (IntersectionObserver)")

## Ported from Document.cpp:5443 Web::DOM::Document::run_the_update_intersection_observations_steps.
# https://www.w3.org/TR/intersection-observer/#run-the-update-intersection-observations-steps
pub func dom_document_run_the_update_intersection_observations_steps(this: DomDocument*, time: f64):
    # 1. Let observer list be a list of all IntersectionObservers whose root is in the DOM tree of document.
    #    For the top-level browsing context, this includes implicit root observers.
    # 2. For each observer in observer list:

    # NOTE: We make a copy of the intersection observers list to avoid modifying it while iterating.
    let intersection_observers = ak.ordered_hash_table_values(&this.m_intersection_observers)

    # Each observer's targets are compared with its root intersection rectangle and thresholds, which are
    # IntersectionObserver state outside the phase-1 closure: a document has no observer until it is ported.
    if not ak.vector_is_empty(&intersection_observers):
        trap("unported (P3): Web::DOM::Document::run_the_update_intersection_observations_steps (IntersectionObserver)")

## Ported from Document.cpp:5568 Web::DOM::Document::start_intersection_observing_a_lazy_loading_element.
# https://html.spec.whatwg.org/multipage/urls-and-fetching.html#start-intersection-observing-a-lazy-loading-element
pub func dom_document_start_intersection_observing_a_lazy_loading_element(this: DomDocument*, element: DomElement*):
    assert(dom_node_is_lazy_loading(element.dom_node()))

    # 1. Let doc be element's node document.
    assert(dom_node_document(element.dom_node()) == this)

    # 2. If doc's lazy load intersection observer is null, set it to a new IntersectionObserver instance (whose
    #    callback runs the lazy load resumption steps of the intersecting entries), and
    # 3. call doc's lazy load intersection observer's observe method with element as the argument.
    trap("unported (P3): Web::DOM::Document::start_intersection_observing_a_lazy_loading_element (IntersectionObserver)")

## Ported from Document.cpp:5634 Web::DOM::Document::stop_intersection_observing_a_lazy_loading_element.
# https://html.spec.whatwg.org/multipage/urls-and-fetching.html#stop-intersection-observing-a-lazy-loading-element
pub func dom_document_stop_intersection_observing_a_lazy_loading_element(this: DomDocument*, element: DomElement*):
    # 1. Let doc be element's node document.
    # NOTE: It's `this`.

    # 2. Assert: doc's lazy load intersection observer is not null.
    let observer = this.m_lazy_load_intersection_observer else trap("VERIFY: no lazy load intersection observer")

    # 3. Call doc's lazy load intersection observer unobserve method with element as the argument.
    intersection_observer_intersection_observer_unobserve(observer, element)

# mark: Declarative refresh =====================================================================

## `is_ascii_digit` as a GenericLexer predicate.
struct DomDocumentIsAsciiDigit: ak.CharPredicate:
    var unused: u8

    func matches(ch: u8) -> bool:
        return ak.is_ascii_digit((u32)ch)

## The lambda `is_ascii_digit(c) || c == '.'` of the shared declarative refresh steps.
struct DomDocumentIsAsciiDigitOrFullStop: ak.CharPredicate:
    var unused: u8

    func matches(ch: u8) -> bool:
        return ak.is_ascii_digit((u32)ch) or ch == '.'

## The lambda `!quote.has_value() || c != quote.value()` of the shared declarative refresh steps.
struct DomDocumentIsNotQuote: ak.CharPredicate:
    var quote: u8?

    func matches(ch: u8) -> bool:
        let quote_value = self.quote else return true
        return ch != quote_value

## The captures of the refresh timer: `[this, has_meta_element, url_record]`.
struct DomDocumentRefreshTimer:
    var this: DomDocument*
    var has_meta_element: bool
    var url_record: web_url.Url

## The refresh timer's handler: navigate document's node navigable to urlRecord.
func dom_document_refresh_timer_fired(context: void*?):
    let captures = (DomDocumentRefreshTimer*)(context else trap("no captures"))
    let this = captures.this
    if captures.has_meta_element and html_has_flag(dom_document_active_sandboxing_flag_set(this), HtmlSandboxingFlagSet.sandboxed_automatic_features):
        return

    let navigable = dom_document_navigable(this) else return
    if html_navigable_has_been_destroyed(navigable):
        return

    html_navigable_navigate(navigable, HtmlNavigableNavigateParams(url = captures.url_record, source_document = this, history_handling = BindNavigationHistoryBehavior.replace)) else trap("MUST: Navigable::navigate")

## Ported from Document.cpp:5647 Web::DOM::Document::shared_declarative_refresh_steps.
# https://html.spec.whatwg.org/multipage/semantics.html#shared-declarative-refresh-steps
pub func dom_document_shared_declarative_refresh_steps(this: DomDocument*, input: ak.StringView, meta_element: HtmlMetaElement*? = none):
    # 1. If document's will declaratively refresh is true, then return.
    if this.m_will_declaratively_refresh:
        return

    # 2. Let position point at the first code point of input.
    var lexer = ak.generic_lexer_new(input)
    let is_ascii_whitespace = DomElementIsAsciiWhitespace(unused = 0)

    # 3. Skip ASCII whitespace within input given position.
    ak.generic_lexer_ignore_while(&lexer, &is_ascii_whitespace)

    # 4. Let time be 0.
    var time: u32 = 0

    # 5. Collect a sequence of code points that are ASCII digits from input given position, and let timeString be the result.
    let is_ascii_digit = DomDocumentIsAsciiDigit(unused = 0)
    let time_string = ak.generic_lexer_consume_while(&lexer, &is_ascii_digit)

    # 6. If timeString is the empty string, then:
    if ak.string_view_is_empty(&time_string):
        # 1. If the code point in input pointed to by position is not U+002E (.), then return.
        if ak.generic_lexer_peek(&lexer) != '.':
            return

    # 7. Otherwise, set time to the result of parsing timeString using the rules for parsing non-negative integers.
    let maybe_time = html_parse_non_negative_integer(time_string)

    # FIXME: Since we only collected ASCII digits, this can only fail because of overflow. What do we do when that happens? For now, default to 0.
    if let parsed_time = maybe_time:
        if parsed_time < (u32)ak.i32_max and (i32(parsed_time) *? 1000) != none:
            time = parsed_time

    # 8. Collect a sequence of code points that are ASCII digits and U+002E FULL STOP characters (.) from input given
    #    position. Ignore any collected characters.
    let is_ascii_digit_or_full_stop = DomDocumentIsAsciiDigitOrFullStop(unused = 0)
    ak.generic_lexer_ignore_while(&lexer, &is_ascii_digit_or_full_stop)

    # 9. Let urlRecord be document's URL.
    var url_record = dom_document_url(this)

    # 10. If position is not past the end of input, then:
    if not ak.generic_lexer_is_eof(&lexer):
        # 1. If the code point in input pointed to by position is not U+003B (;), U+002C (,), or ASCII whitespace, then return.
        let next = ak.generic_lexer_peek(&lexer)
        if next != ';' and next != ',' and not web_infra.is_ascii_whitespace((u32)next):
            return

        # 2. Skip ASCII whitespace within input given position.
        ak.generic_lexer_ignore_while(&lexer, &is_ascii_whitespace)

        # 3. If the code point in input pointed to by position is U+003B (;) or U+002C (,), then advance position to the next code point.
        if ak.generic_lexer_peek(&lexer) == ';' or ak.generic_lexer_peek(&lexer) == ',':
            ak.generic_lexer_ignore(&lexer, 1)

        # 4. Skip ASCII whitespace within input given position.
        ak.generic_lexer_ignore_while(&lexer, &is_ascii_whitespace)

    # 11. If position is not past the end of input, then:
    if not ak.generic_lexer_is_eof(&lexer):
        # 1. Let urlString be the substring of input from the code point at position to the end of the string.
        var url_string = ak.generic_lexer_remaining(&lexer)

        # C++ jumps forward with `goto skip_quotes` and `goto parse`; the jump targets are kept as flags.
        var jump_to_skip_quotes = false
        var jump_to_parse = false

        # 2. If the code point in input pointed to by position is U+0055 (U) or U+0075 (u), then advance position to the next code point. Otherwise, jump to the step labeled skip quotes.
        if ak.generic_lexer_peek(&lexer) == 'U' or ak.generic_lexer_peek(&lexer) == 'u':
            ak.generic_lexer_ignore(&lexer, 1)
        else:
            jump_to_skip_quotes = true

        # 3. If the code point in input pointed to by position is U+0052 (R) or U+0072 (r), then advance position to the next code point. Otherwise, jump to the step labeled parse.
        if not jump_to_skip_quotes:
            if ak.generic_lexer_peek(&lexer) == 'R' or ak.generic_lexer_peek(&lexer) == 'r':
                ak.generic_lexer_ignore(&lexer, 1)
            else:
                jump_to_parse = true

        # 4. If the code point in input pointed to by position is U+004C (L) or U+006C (l), then advance position to the next code point. Otherwise, jump to the step labeled parse.
        if not jump_to_skip_quotes and not jump_to_parse:
            if ak.generic_lexer_peek(&lexer) == 'L' or ak.generic_lexer_peek(&lexer) == 'l':
                ak.generic_lexer_ignore(&lexer, 1)
            else:
                jump_to_parse = true

        if not jump_to_skip_quotes and not jump_to_parse:
            # 5. Skip ASCII whitespace within input given position.
            ak.generic_lexer_ignore_while(&lexer, &is_ascii_whitespace)

            # 6. If the code point in input pointed to by position is U+003D (=), then advance position to the next code point. Otherwise, jump to the step labeled parse.
            if ak.generic_lexer_peek(&lexer) == '=':
                ak.generic_lexer_ignore(&lexer, 1)
            else:
                jump_to_parse = true

        if not jump_to_skip_quotes and not jump_to_parse:
            # 7. Skip ASCII whitespace within input given position.
            ak.generic_lexer_ignore_while(&lexer, &is_ascii_whitespace)

        # skip_quotes:
        if not jump_to_parse:
            # 8. Skip quotes: If the code point in input pointed to by position is U+0027 (') or U+0022 ("), then let
            #    quote be that code point, and advance position to the next code point. Otherwise, let quote be the empty
            #    string.
            var is_not_quote = DomDocumentIsNotQuote(quote = none)
            if ak.generic_lexer_peek(&lexer) == '\'' or ak.generic_lexer_peek(&lexer) == '"':
                is_not_quote.quote = ak.generic_lexer_consume(&lexer)

            # 9. Set urlString to the substring of input from the code point at position to the end of the string.
            # 10. If quote is not the empty string, and there is a code point in urlString equal to quote, then truncate
            #     urlString at that code point, so that it and all subsequent code points are removed.
            url_string = ak.generic_lexer_consume_while(&lexer, &is_not_quote)

        # parse:
        # 11. Parse: Set urlRecord to the result of encoding-parsing a URL given urlString, relative to document.
        # 12. If urlRecord is failure, then return.
        let maybe_url_record = dom_document_encoding_parse_url(this, url_string) else return

        url_record = maybe_url_record

        # 13. If urlRecord's scheme is "javascript", then return.
        let scheme = web_url.url_scheme(&url_record)
        if ak.string_eq_string_view(&scheme, ak.sv("javascript")):
            return

    # 12. Set document's will declaratively refresh to true.
    this.m_will_declaratively_refresh = true

    # 13. Perform one or more of the following steps:
    # - After the refresh has come due (as defined below), if the user has not canceled the redirect and, if meta is
    #   given, document's active sandboxing flag set does not have the sandboxed automatic features browsing context
    #   flag set, then navigate document's node navigable to urlRecord using document, with historyHandling set to
    #   "replace".
    let captures = new DomDocumentRefreshTimer(this = this, has_meta_element = meta_element != none, url_record = url_record) else trap("out of memory")
    let refresh_timer = core_timer_create_single_shot((i32)(time * 1000), ak.Function0[unit](call = dom_document_refresh_timer_fired, context = captures))
    this.m_active_refresh_timer = refresh_timer

    # For the purposes of the previous paragraph, a refresh is said to have come due as soon as the later of the
    # following two conditions occurs:

    # - At least time seconds have elapsed since document's completely loaded time, adjusted to take into
    #   account user or user agent preferences.
    # m_active_refresh_timer is started in completely_finished_loading after setting the completely loaded time.

    # - If meta is given, at least time seconds have elapsed since meta was inserted into the document document,
    # adjusted to take into account user or user agent preferences.
    # NOTE: This is only done if completely loaded time has a value because shared_declarative_refresh_steps is called
    # by HTMLMetaElement::inserted and if the document hasn't finished loading when the meta element was inserted,
    # then the document completely finishing loading will _always_ come after inserting the meta element.
    if meta_element != none and this.m_completely_loaded_time != none:
        core_timer_start(refresh_timer)

# mark: Paintables ==============================================================================

## Ported from Document.cpp:5807 Web::DOM::Document::paintable.
pub func dom_document_paintable_const(this: DomDocument*) -> PaintViewportPaintable*?:
    return (PaintViewportPaintable*?)dom_node_paintable(this.dom_node())

## Ported from Document.cpp:5812 Web::DOM::Document::paintable.
pub func dom_document_paintable(this: DomDocument*) -> PaintViewportPaintable*?:
    return (PaintViewportPaintable*?)dom_node_paintable(this.dom_node())

## Ported from Document.cpp:5817 Web::DOM::Document::unsafe_paintable.
pub func dom_document_unsafe_paintable_const(this: DomDocument*) -> PaintViewportPaintable*?:
    return (PaintViewportPaintable*?)dom_node_unsafe_paintable(this.dom_node())

## Ported from Document.cpp:5822 Web::DOM::Document::unsafe_paintable.
pub func dom_document_unsafe_paintable(this: DomDocument*) -> PaintViewportPaintable*?:
    return (PaintViewportPaintable*?)dom_node_unsafe_paintable(this.dom_node())

# mark: History =================================================================================

## Ported from Document.cpp:5828 Web::DOM::Document::restore_the_history_object_state.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#restore-the-history-object-state
pub func dom_document_restore_the_history_object_state(this: DomDocument*, entry: HtmlSessionHistoryEntry*):
    # 1. Let targetRealm be document's relevant realm.
    let target_realm = html_relevant_realm((JsObject*)this)

    # 2. Let state be StructuredDeserialize(entry's classic history API state, targetRealm). If this throws an exception, catch it and let state be null.
    # 3. Set document's history object's state to state.
    let history = this.m_history else trap("the document has no history object")
    let state: JsValue? = html_structured_deserialize(realm_vm(target_realm), html_session_history_entry_classic_history_api_state(entry), target_realm) catch: recover none
    if let deserialized = state:
        html_history_set_state(history, deserialized)
    else:
        html_history_set_state(history, js_null())

## The captures of the hashchange task: `[hashchange_event, &relevant_global_object]`.
struct DomDocumentHashChangeTask:
    var hashchange_event: DomEvent*
    var relevant_global_object: HtmlWindow*

## The hashchange task: fire the event at the relevant global object.
func dom_document_hash_change_task(context: void*?):
    let captures = (DomDocumentHashChangeTask*)(context else trap("no captures"))
    _ = dom_event_target_dispatch_event(captures.relevant_global_object.dom_event_target(), captures.hashchange_event)

## `Optional<String> != Optional<String>` (AK's Optional operator!=).
func dom_document_optional_strings_differ(a: ak.String?, b: ak.String?) -> bool:
    let a_value = a else return b != none
    let b_value = b else return true
    return not ak.string_equals(&a_value, &b_value)

## Ported from Document.cpp:5843 Web::DOM::Document::update_for_history_step_application.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-document-for-history-step-application
pub func dom_document_update_for_history_step_application(this: DomDocument*, entry: HtmlSessionHistoryEntry*, do_not_reactivate: bool, script_history_length: usize, script_history_index: usize, navigation_type: BindNavigationType?, entries_for_navigation_api: ak.Vector[HtmlSessionHistoryEntry*]?, previous_entry_for_activation: HtmlSessionHistoryEntry*? = none, update_navigation_api: bool = true):
    # (void)previous_entry_for_activation;

    # 1. Let documentIsNew be true if document's latest entry is null; otherwise false.
    let document_is_new = this.m_latest_entry == none

    # 2. Let documentsEntryChanged be true if document's latest entry is not entry; otherwise false.
    let documents_entry_changed = this.m_latest_entry != entry

    # 3. Set document's history object's index to scriptHistoryIndex.
    html_history_set_index(dom_document_history(this), script_history_index)

    # 4. Set document's history object's length to scriptHistoryLength.
    html_history_set_length(dom_document_history(this), script_history_length)

    # 5. Let navigation be history's relevant global object's navigation API.
    let navigation = html_window_navigation(as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this)))

    # 6. If documentsEntryChanged is true, then:
    # NOTE: documentsEntryChanged can be false for one of two reasons: either we are restoring from bfcache,
    #      or we are asynchronously finishing up a synchronous navigation which already synchronously set document's latest entry.
    #      The doNotReactivate argument distinguishes between these two cases.
    if documents_entry_changed:
        # 1. Let oldURL be document's latest entry's URL.
        var old_url = web_url.url_empty()
        if let latest_entry = this.m_latest_entry:
            old_url = html_session_history_entry_url(latest_entry)

        # 2. Set document's latest entry to entry.
        this.m_latest_entry = entry

        # 3. Restore the history object state given document and entry.
        dom_document_restore_the_history_object_state(this, entry)

        # 4. If documentIsNew is false, then:
        if not document_is_new:
            # NOTE: Not in the spec, but otherwise document's url won't be updated in case of a same-document back/forward navigation.
            dom_document_set_url(this, html_session_history_entry_url(entry))

            # AD HOC: Skip this in situations the spec steps don't account for
            if update_navigation_api:
                # 1. Assert: navigationType is not null.
                let type_ = navigation_type else trap("VERIFY: navigationType is not null")
                # 2. Update the navigation API entries for a same-document navigation given navigation, entry, and navigationType.
                html_navigation_update_the_navigation_api_entries_for_a_same_document_navigation(navigation, entry, type_)

            # 3. Fire an event named popstate at document's relevant global object, using PopStateEvent,
            #    with the state attribute initialized to document's history object's state and hasUAVisualTransition initialized to true
            #    if a visual transition, to display a cached rendered state of the latest entry, was done by the user agent.
            # FIXME: Initialise hasUAVisualTransition
            var popstate_event_init = HtmlPopStateEventInit()
            popstate_event_init.state = html_history_unsafe_state(dom_document_history(this))
            let relevant_global_object = as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this))
            let pop_state_event = html_pop_state_event_create(dom_document_realm(this), ak.fly_string_from_str("popstate"), popstate_event_init)
            _ = dom_event_target_dispatch_event(relevant_global_object.dom_event_target(), pop_state_event.dom_event())

            # FIXME: 4. Restore persisted state given entry.

            # 5. If oldURL's fragment is not equal to entry's URL's fragment, then queue a global task on the DOM manipulation task source
            #    given document's relevant global object to fire an event named hashchange at document's relevant global object,
            #    using HashChangeEvent, with the oldURL attribute initialized to the serialization of oldURL and the newURL attribute
            #    initialized to the serialization of entry's URL.
            let entry_url = html_session_history_entry_url(entry)
            if dom_document_optional_strings_differ(web_url.url_fragment(&old_url), web_url.url_fragment(&entry_url)):
                var hashchange_event_init = HtmlHashChangeEventInit()
                hashchange_event_init.old_url = web_url.url_serialize(&old_url)
                hashchange_event_init.new_url = web_url.url_serialize(&entry_url)
                let hashchange_event = html_hash_change_event_create(dom_document_realm(this), ak.fly_string_from_str("hashchange"), hashchange_event_init)
                let captures = new DomDocumentHashChangeTask(hashchange_event = hashchange_event.dom_event(), relevant_global_object = relevant_global_object) else trap("out of memory")
                _ = html_queue_global_task(HtmlTaskSource.dom_manipulation, (JsObject*)relevant_global_object, gc.create_function0[unit](gc.cell_heap(this.cell()), ak.Function0[unit](call = dom_document_hash_change_task, context = captures)))

        # 5. Otherwise:
        else:
            # 1. Assert: entriesForNavigationAPI is given.
            let entries = entries_for_navigation_api else trap("VERIFY: entriesForNavigationAPI is given")

            # FIXME: 2. Restore persisted state given entry.

            # 3. Initialize the navigation API entries for a new document given navigation, entriesForNavigationAPI, and entry.
            html_navigation_initialize_the_navigation_api_entries_for_a_new_document(navigation, entries, entry)

    # FIXME: 7. If all the following are true:
    #    - previousEntryForActivation is given;
    #    - navigationType is non-null; and
    #    - navigationType is "reload" or previousEntryForActivation's document is not document, then:
    #        FIXME: 1. If navigation's activation is null, then set navigation's activation to a new NavigationActivation object in navigation's relevant realm.
    #        FIXME: 2. Let previousEntryIndex be the result of getting the navigation API entry index of previousEntryForActivation within navigation.
    #        FIXME: 3. If previousEntryIndex is non-negative, then set activation's old entry to navigation's entry list[previousEntryIndex].
    #        FIXME: 4. Otherwise, if all the following are true:
    #           - navigationType is "replace";
    #           - previousEntryForActivation's document state's origin is same origin with document's origin; and
    #           - previousEntryForActivation's document's initial about:blank is false,
    #           then set activation's old entry to a new NavigationHistoryEntry in navigation's relevant realm, whose session history entry is previousEntryForActivation.
    #        FIXME: 5. Set activation's new entry to navigation's current entry.
    #        FIXME: 6. Set activation's navigation type to navigationType.

    # 8. If documentIsNew is true, then:
    if document_is_new:
        # FIXME: 1. Assert: document's during-loading navigation ID for WebDriver BiDi is not null.
        # FIXME: 2. Invoke WebDriver BiDi navigation committed with navigable and a new WebDriver BiDi navigation
        #           status whose id is document's during-loading navigation ID for WebDriver BiDi, status is "committed", and url is document's URL

        # 3. Try to scroll to the fragment for document.
        dom_document_try_to_scroll_to_the_fragment(this)

        # 4. At this point scripts may run for the newly-created document document.
        dom_document_set_ready_to_run_scripts(this)

    # 9. Otherwise, if documentsEntryChanged is false and doNotReactivate is false, then:
    # NOTE: This is for bfcache restoration
    #     FIXME: 1. Assert: entriesForNavigationAPI is given.
    #     FIXME: 2. Reactivate document given entry and entriesForNavigationAPI.
    # (C++ keeps the empty `if (!documents_entry_changed && !do_not_reactivate)` around the two FIXMEs.)

## Ported from Document.cpp:5968 Web::DOM::Document::set_ready_to_run_scripts.
pub func dom_document_set_ready_to_run_scripts(this: DomDocument*):
    this.m_ready_to_run_scripts = true
    if let callback = this.m_deferred_parser_start:
        this.m_deferred_parser_start = none
        ak.function0_call(&callback.function)

## Ported from Document.cpp:5977 Web::DOM::Document::set_deferred_parser_start.
pub func dom_document_set_deferred_parser_start(this: DomDocument*, callback: gc.Function0[unit]*):
    assert(this.m_deferred_parser_start == none)
    this.m_deferred_parser_start = callback

## Ported from Document.cpp:5983 Web::DOM::Document::set_latest_entry.
pub func dom_document_set_latest_entry(this: DomDocument*, entry: HtmlSessionHistoryEntry*?):
    this.m_latest_entry = entry

## Ported from Document.cpp:5988 Web::DOM::Document::shared_resource_requests.
pub func dom_document_shared_resource_requests(this: DomDocument*) -> ak.HashMap[web_url.Url, HtmlSharedResourceRequest*?, web_url.UrlTraits]*:
    return &this.m_shared_resource_requests