Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / traversable_navigable_2.lucb

#==============================================================================================
#
#   traversable_navigable_2 - HTML::TraversableNavigable: deactivating a document, and the state
#   machine that applies a history step (construction, start, progress)
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/TraversableNavigable.cpp lines 375-829
#       (deactivate_a_document_for_cross_document_navigation, ChangingNavigableContinuationState,
#       ApplyHistoryStepState's constructor, did_receive_continuation, signal_progress,
#       visit_edges, try_advance and start).
#
#       Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2023-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Deactivating a document =================================================================

## Ported from TraversableNavigable.cpp:376 Web::HTML::deactivate_a_document_for_cross_document_navigation.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#deactivate-a-document-for-a-cross-document-navigation
func html_deactivate_a_document_for_cross_document_navigation(displayed_document: DomDocument*, arg1: HtmlUserNavigationInvolvement?, target_entry: HtmlSessionHistoryEntry*, populated_document: DomDocument*?, after_potential_unloads: gc.Function0[unit]*):
    # 1. Let navigable be displayedDocument's node navigable.
    let navigable = dom_document_navigable(displayed_document) else trap("the displayed document has no navigable")

    # 2. Let potentiallyTriggerViewTransition be false.
    let potentially_trigger_view_transition = false

    # FIXME: 3. Let isBrowserUINavigation be true if userNavigationInvolvement is "browser UI"; otherwise false.

    # FIXME: 4. Set potentiallyTriggerViewTransition to the result of calling can navigation trigger a cross-document
    #           view-transition? given displayedDocument, targetEntry's document, navigationType, and isBrowserUINavigation.

    # 5. If potentiallyTriggerViewTransition is false, then:
    if not potentially_trigger_view_transition:
        # FIXME: 1. Let firePageSwapBeforeUnload be the following step
        #            1. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and null.

        # 2. Set the ongoing navigation for navigable to null.
        html_navigable_set_ongoing_navigation(navigable, EmptyOrHtmlNavigableTraversalOrString.empty)

        # 3. Unload a document and its descendants given displayedDocument, targetEntry's document, afterPotentialUnloads, and firePageSwapBeforeUnload.
        _ = target_entry  # FIXME: Used by pageswap and view-transition steps above.
        dom_document_unload_a_document_and_its_descendants(displayed_document, populated_document, after_potential_unloads)
    # FIXME: 6. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
    else:
        # FIXME: 1. Let proceedWithNavigationAfterViewTransitionCapture be the following step:
        #            1. Append the following session history traversal steps to navigable's traversable navigable:
        #               1. Set the ongoing navigation for navigable to null.
        #               2. Unload a document and its descendants given displayedDocument, targetEntry's document, and afterPotentialUnloads.

        # FIXME: 2. Let viewTransition be the result of setting up a cross-document view-transition given displayedDocument,
        #           targetEntry's document, navigationType, and proceedWithNavigationAfterViewTransitionCapture.

        # FIXME: 3. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and viewTransition.

        # FIXME: 4. If viewTransition is null, then run proceedWithNavigationAfterViewTransitionCapture.

        trap("TODO")

# mark: ChangingNavigableContinuationState ======================================================

## `heap().allocate<ChangingNavigableContinuationState>()`: a continuation cell with its default
## member initializers.
func heap_allocate_html_changing_navigable_continuation_state(heap: gc.Heap*) -> HtmlChangingNavigableContinuationState*:
    let state = (HtmlChangingNavigableContinuationState*)web_heap_allocate_cell(heap, &html_changing_navigable_continuation_state_class)
    state.update_only = false
    return state

## Ported from TraversableNavigable.cpp:433 Web::HTML::ChangingNavigableContinuationState::visit_edges (override).
pub func html_changing_navigable_continuation_state_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlChangingNavigableContinuationState*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.displayed_document)
    gc.cell_visitor_visit_t(visitor, this.navigable)
    gc.cell_visitor_visit_t(visitor, this.population_output)
    gc.cell_visitor_visit_t(visitor, this.resolved_document)

# mark: ApplyHistoryStepState ===================================================================

## The ApplyHistoryStepState timeout's handler (the constructor's lambda).
func html_apply_history_step_state_timed_out(context: void*?):
    let this = (HtmlApplyHistoryStepState*)(context else trap("no state"))
    if this.m_phase != HtmlApplyHistoryStepStatePhase.completed:
        var url = web_url.url_empty()
        if let document = html_navigable_active_document(this.m_traversable.html_navigable()):
            url = dom_document_url(document)
        let serialized = web_url.url_serialize(&url)
        let changing = ak.vector_size(&this.m_changing_navigables)
        ak.dbgln(f"FIXME: ApplyHistoryStepState timed out in phase {(i32)this.m_phase} step={this.m_step} changing={changing}/{changing} completed={this.m_completed_change_jobs}/{changing} cont={this.m_continuation_index}/{ak.vector_size(&this.m_continuations)} non_changing={this.m_completed_non_changing_jobs}/{ak.vector_size(&this.m_non_changing_navigables)} url={ak.string_view_text(ak.string_bytes_as_string_view(&serialized))}")

## Ported from TraversableNavigable.cpp:452 Web::HTML::ApplyHistoryStepState::ApplyHistoryStepState, with
## the default member initializers.
pub func html_apply_history_step_state_construct(this: HtmlApplyHistoryStepState*, traversable: HtmlTraversableNavigable*, step: i32, target_step: i32, source_snapshot_params: HtmlSourceSnapshotParams*?, user_involvement: HtmlUserNavigationInvolvement, navigation_type: BindNavigationType?, synchronous_navigation: HtmlTraversableNavigableSynchronousNavigation, pending_document: DomDocument*?, on_complete: gc.Function1[HtmlHistoryStepResult, unit]*):
    this.m_phase = HtmlApplyHistoryStepStatePhase.waiting_for_document_population
    this.m_traversable = traversable
    this.m_step = step
    this.m_target_step = target_step
    this.m_source_snapshot_params = source_snapshot_params
    this.m_user_involvement = user_involvement
    this.m_navigation_type = navigation_type
    this.m_synchronous_navigation = synchronous_navigation
    this.m_pending_document = pending_document
    this.m_on_complete = on_complete
    let heap = gc.cell_heap(this.cell())
    this.m_timeout = platform_timer_create_single_shot(heap, html_apply_history_step_state_timeout_ms, gc.create_function0(heap, ak.Function0[unit](call = html_apply_history_step_state_timed_out, context = this)))
    platform_timer_start(this.m_timeout)

## `heap().allocate<ApplyHistoryStepState>(...)`: a state cell constructed under DeferGC.
func heap_allocate_html_apply_history_step_state(heap: gc.Heap*, traversable: HtmlTraversableNavigable*, step: i32, target_step: i32, source_snapshot_params: HtmlSourceSnapshotParams*?, user_involvement: HtmlUserNavigationInvolvement, navigation_type: BindNavigationType?, synchronous_navigation: HtmlTraversableNavigableSynchronousNavigation, pending_document: DomDocument*?, on_complete: gc.Function1[HtmlHistoryStepResult, unit]*) -> HtmlApplyHistoryStepState*:
    let state = (HtmlApplyHistoryStepState*)web_heap_allocate_cell(heap, &html_apply_history_step_state_class)
    gc.heap_defer_gc(heap)
    html_apply_history_step_state_construct(state, traversable, step, target_step, source_snapshot_params, user_involvement, navigation_type, synchronous_navigation, pending_document, on_complete)
    gc.heap_undefer_gc(heap)
    return state

## Ported from TraversableNavigable.cpp:486 Web::HTML::ApplyHistoryStepState::did_receive_continuation.
pub func html_apply_history_step_state_did_receive_continuation(this: HtmlApplyHistoryStepState*, continuation: HtmlChangingNavigableContinuationState*):
    ak.vector_append_t(&this.m_continuations, continuation)
    html_apply_history_step_state_signal_progress(this)

## Ported from TraversableNavigable.cpp:492 Web::HTML::ApplyHistoryStepState::signal_progress.
pub func html_apply_history_step_state_signal_progress(this: HtmlApplyHistoryStepState*):
    match this.m_phase:
        .waiting_for_document_population:
            # Population progress is tracked by m_continuations.size() + m_completed_change_jobs.
            # The caller either appended a continuation or incremented m_completed_change_jobs before calling.
            _ = 0
        .processing_continuations, .waiting_for_change_job_completion:
            this.m_completed_change_jobs += 1
        .waiting_for_non_changing_jobs:
            this.m_completed_non_changing_jobs += 1
        .completed:
            return
        _:
            trap("VERIFY_NOT_REACHED")
    html_apply_history_step_state_try_advance(this)

## Ported from TraversableNavigable.cpp:521 Web::HTML::ApplyHistoryStepState::visit_edges (override).
pub func html_apply_history_step_state_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlApplyHistoryStepState*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t_2(visitor, this.m_traversable)
    gc.cell_visitor_visit_t(visitor, this.m_source_snapshot_params)
    gc.cell_visitor_visit_t(visitor, this.m_pending_document)
    gc.cell_visitor_visit_t(visitor, this.m_on_complete)
    gc.cell_visitor_visit_t_2(visitor, this.m_timeout)
    gc.cell_visitor_visit_vector(visitor, &this.m_changing_navigables)
    gc.cell_visitor_visit_vector(visitor, &this.m_non_changing_navigables)
    gc.cell_visitor_visit_vector(visitor, &this.m_continuations)
    for navigable in ak.hash_table_begin_const(&this.m_navigables_that_must_wait_before_handling_sync_navigation):
        gc.cell_visitor_visit_t_2(visitor, *navigable)

## Ported from TraversableNavigable.cpp:536 Web::HTML::ApplyHistoryStepState::try_advance.
pub func html_apply_history_step_state_try_advance(this: HtmlApplyHistoryStepState*):
    match this.m_phase:
        .waiting_for_document_population:
            if ak.vector_size(&this.m_continuations) + this.m_completed_change_jobs == ak.vector_size(&this.m_changing_navigables):
                this.m_phase = HtmlApplyHistoryStepStatePhase.processing_continuations
                html_apply_history_step_state_process_continuations(this)
        .processing_continuations, .waiting_for_change_job_completion:
            if this.m_completed_change_jobs == ak.vector_size(&this.m_changing_navigables) and this.m_continuation_index >= ak.vector_size(&this.m_continuations):
                this.m_phase = HtmlApplyHistoryStepStatePhase.waiting_for_non_changing_jobs
                html_apply_history_step_state_enter_waiting_for_non_changing_jobs(this)
        .waiting_for_non_changing_jobs:
            if this.m_completed_non_changing_jobs == ak.vector_size(&this.m_non_changing_navigables):
                html_apply_history_step_state_complete(this)
        .completed:
            _ = 0
        _:
            trap("VERIFY_NOT_REACHED")

## The captures of start's per-navigable task (step 12).
struct HtmlApplyHistoryStepStateChangeTask:
    var this: HtmlApplyHistoryStepState*
    var navigable: HtmlNavigable*

## The captures of start's afterDocumentPopulated.
struct HtmlApplyHistoryStepStateAfterDocumentPopulated:
    var this: HtmlApplyHistoryStepState*
    var old_origin: web_url.Origin?
    var changing_navigable_continuation: HtmlChangingNavigableContinuationState*
    var target_entry: HtmlSessionHistoryEntry*
    var navigable: HtmlNavigable*

## start's afterDocumentPopulated.
func html_apply_history_step_state_after_document_populated(context: void*?, output: HtmlPopulateSessionHistoryEntryDocumentOutput*?):
    let captures = (HtmlApplyHistoryStepStateAfterDocumentPopulated*)(context else trap("no captures"))
    let this = captures.this
    let navigable = captures.navigable
    let changing_navigable_continuation = captures.changing_navigable_continuation
    changing_navigable_continuation.population_output = output
    changing_navigable_continuation.old_origin = captures.old_origin

    # Compute the resolved document: pending_document (from finalize path),
    # population output (from traversal path), or active document (same-document).
    var resolved_document: DomDocument*? = none
    var output_document: DomDocument*? = none
    if let populated = output:
        output_document = populated.document
    if this.m_pending_document != none:
        resolved_document = this.m_pending_document
    elif output_document != none:
        resolved_document = output_document
    else:
        resolved_document = html_navigable_active_document(navigable)
    changing_navigable_continuation.resolved_document = resolved_document

    # 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
    let has_fresh_document = this.m_pending_document != none or output_document != none
    if not has_fresh_document and html_document_state_document_id(html_session_history_entry_document_state(captures.target_entry) else trap("no document state")) != html_navigable_active_document_id(navigable):
        changing_navigable_continuation.update_only = true

    # 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).
    # 3. If all of the following are true:
    #     - navigable's parent is null;
    #     - targetEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
    #     - targetEntry's document's origin is not oldOrigin,
    #    then set targetEntry's document state's navigable target name to the empty string.
    # NOTE: Steps 2-3 are deferred to after_potential_unload to avoid exposing mutations during unload.

    # 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
    html_apply_history_step_state_did_receive_continuation(this, changing_navigable_continuation)

## The captures of start's in-parallel population (step 8.7) of a target entry.
struct HtmlApplyHistoryStepStatePopulate:
    var this: HtmlApplyHistoryStepState*
    var input_url: web_url.Url
    var input_document_resource: EmptyOrStringOrHtmlPostResource
    var input_request_referrer: FetchRequestReferrerType
    var input_request_referrer_policy: ReferrerPolicyReferrerPolicy
    var input_initiator_origin: web_url.Origin?
    var input_origin: web_url.Origin?
    var input_history_policy_container: HtmlSerializedPolicyContainerOrHtmlDocumentStateClient
    var input_about_base_url: web_url.Url?
    var input_navigable_target_name: ak.String
    var input_ever_populated: bool
    var potentially_target_specific_source_snapshot_params: HtmlSourceSnapshotParams*?
    var target_snapshot_params: HtmlTargetSnapshotParams
    var allow_POST: bool
    var navigable: HtmlNavigable*
    var after_document_populated: gc.Function1[HtmlPopulateSessionHistoryEntryDocumentOutput*?, unit]*
    var user_involvement: HtmlUserNavigationInvolvement

## The captures of the task that runs afterDocumentPopulated with a population's output.
struct HtmlApplyHistoryStepStatePopulated:
    var after_document_populated: gc.Function1[HtmlPopulateSessionHistoryEntryDocumentOutput*?, unit]*
    var output: HtmlPopulateSessionHistoryEntryDocumentOutput*?

## The queued task that runs afterDocumentPopulated.
func html_apply_history_step_state_run_after_document_populated(context: void*?):
    let captures = (HtmlApplyHistoryStepStatePopulated*)(context else trap("no captures"))
    ak.function1_call(&captures.after_document_populated.function, captures.output)

## The population's completion steps: queue a global task to run afterDocumentPopulated.
func html_apply_history_step_state_population_complete(context: void*?, output: HtmlPopulateSessionHistoryEntryDocumentOutput*?):
    let captures = (HtmlApplyHistoryStepStatePopulate*)(context else trap("no captures"))
    let this = captures.this
    let window = html_navigable_active_window(this.m_traversable.html_navigable()) else trap("VERIFY: m_traversable->active_window()")
    let populated = new HtmlApplyHistoryStepStatePopulated(after_document_populated = captures.after_document_populated, output = output) else trap("out of memory")
    _ = html_queue_global_task(HtmlTaskSource.navigation_and_traversal, (JsObject*)window, gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_run_after_document_populated, context = populated)))

## start's step 8.7: in parallel, attempt to populate the history entry's document.
func html_apply_history_step_state_populate(context: void*?):
    let captures = (HtmlApplyHistoryStepStatePopulate*)(context else trap("no captures"))
    html_navigable_populate_session_history_entry_document(captures.navigable, captures.input_url, captures.input_document_resource, captures.input_request_referrer, captures.input_request_referrer_policy, captures.input_initiator_origin, captures.input_origin, captures.input_history_policy_container, captures.input_about_base_url, captures.input_navigable_target_name, false, captures.input_ever_populated, captures.potentially_target_specific_source_snapshot_params else trap("no source snapshot params"), captures.target_snapshot_params, captures.user_involvement, none, HtmlNavigableNavigationParamsVariant.optional_string(none), ContentSecurityPolicyNavigationType.other, captures.allow_POST, gc.create_function1(gc.cell_heap(captures.this.cell()), ak.Function1[HtmlPopulateSessionHistoryEntryDocumentOutput*?, unit](call = html_apply_history_step_state_population_complete, context = captures)))

## start's step 12 task for one changing navigable.
func html_apply_history_step_state_change_navigable(context: void*?):
    let captures = (HtmlApplyHistoryStepStateChangeTask*)(context else trap("no captures"))
    let this = captures.this
    let navigable = captures.navigable

    # NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
    if html_navigable_has_been_destroyed(navigable):
        this.m_completed_change_jobs += 1
        html_apply_history_step_state_signal_progress(this)
        return

    # 1. Let displayedEntry be navigable's active session history entry.
    let displayed_entry = html_navigable_active_session_history_entry(navigable) else trap("no active session history entry")

    # 2. Let targetEntry be navigable's current session history entry.
    let target_entry = html_navigable_current_session_history_entry(navigable) else trap("no current session history entry")
    let target_state = html_session_history_entry_document_state(target_entry) else trap("no document state")

    # 3. Let changingNavigableContinuation be a changing navigable continuation state with:
    let changing_navigable_continuation = heap_allocate_html_changing_navigable_continuation_state(gc.cell_heap(this.cell()))
    changing_navigable_continuation.displayed_document = html_navigable_active_document(navigable)
    changing_navigable_continuation.displayed_document_id = html_navigable_active_document_id(navigable)
    changing_navigable_continuation.target_entry = target_entry
    changing_navigable_continuation.navigable = navigable
    changing_navigable_continuation.update_only = false
    changing_navigable_continuation.population_output = none

    # 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
    if this.m_synchronous_navigation == HtmlTraversableNavigableSynchronousNavigation.yes and not html_document_state_reload_pending(target_state):
        # 1. Set changingNavigableContinuation's update-only to true.
        changing_navigable_continuation.update_only = true
        changing_navigable_continuation.resolved_document = html_navigable_active_document(navigable)

        # 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
        html_apply_history_step_state_did_receive_continuation(this, changing_navigable_continuation)

        # 3. Abort these steps.
        return

    # 5. Switch on navigationType:
    if let navigation_type = this.m_navigation_type:
        match navigation_type:
            .reload:
                # - "reload": Assert: targetEntry's document state's reload pending is true.
                assert(html_document_state_reload_pending(target_state))
            .traverse:
                # - "traverse": Assert: targetEntry's document state's ever populated is true.
                assert(html_document_state_ever_populated(target_state))
            .replace:
                # FIXME: Add ever populated check
                # - "replace": Assert: targetEntry's step is displayedEntry's step and targetEntry's document state's ever populated is false.
                assert(html_session_history_entry_step_equals(html_session_history_entry_step(target_entry), html_session_history_entry_step(displayed_entry)))
            .push:
                # FIXME: Add ever populated check, and fix the bug where top level traversable's step is not updated when a child navigable navigates
                # - "push": Assert: targetEntry's step is displayedEntry's step + 1 and targetEntry's document state's ever populated is false.
                assert(target_entry != displayed_entry)
                assert(html_traversable_entry_step(target_entry) > html_traversable_entry_step(displayed_entry))
            _:
                _ = 0

    # 6. Let oldOrigin be targetEntry's document state's origin.
    let old_origin = html_document_state_origin(target_state)

    # 7. If all of the following are true:
    #   * navigable is not traversable;
    #   * targetEntry is not navigable's current session history entry; and
    #   * oldOrigin is the same as navigable's current session history entry's document state's origin,
    # then:
    let current_entry = html_navigable_current_session_history_entry(navigable) else trap("no current session history entry")
    if not html_navigable_is_traversable(navigable) and target_entry != current_entry and html_optional_origin_equals(old_origin, html_document_state_origin(html_session_history_entry_document_state(current_entry) else trap("no document state"))):
        # 1. Let navigation be navigable's active window's navigation API.
        let navigation = html_window_navigation(html_navigable_active_window(this.m_traversable.html_navigable()) else trap("no active window"))

        # 2. Fire a traverse navigate event at navigation given targetEntry and userInvolvement.
        _ = html_navigation_fire_a_traverse_navigate_event(navigation, target_entry, this.m_user_involvement)

    let populated_captures = new HtmlApplyHistoryStepStateAfterDocumentPopulated(this = this, old_origin = old_origin, changing_navigable_continuation = changing_navigable_continuation, target_entry = target_entry, navigable = navigable) else trap("out of memory")
    let after_document_populated = gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[HtmlPopulateSessionHistoryEntryDocumentOutput*?, unit](call = html_apply_history_step_state_after_document_populated, context = populated_captures))

    # 8. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
    let needs_population = this.m_pending_document == none and (html_document_state_document_id(target_state) != html_navigable_active_document_id(navigable) or html_document_state_reload_pending(target_state))
    if needs_population:
        # FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".

        # 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
        let target_snapshot_params = html_navigable_snapshot_target_snapshot_params(navigable)

        # 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
        var potentially_target_specific_source_snapshot_params = this.m_source_snapshot_params

        # 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
        if potentially_target_specific_source_snapshot_params == none:
            potentially_target_specific_source_snapshot_params = dom_document_snapshot_source_snapshot_params(html_navigable_active_document(navigable) else trap("no active document"))

        # 5. Set targetEntry's document state's reload pending to false.
        html_document_state_set_reload_pending(target_state, false)

        # 6. Let allowPOST be targetEntry's document state's reload pending.
        let allow_POST = html_document_state_reload_pending(target_state)

        # https://github.com/whatwg/html/issues/9869
        # Population runs in a deferred task, during which sync navigations can mutate
        # the live entry. Snapshot the input fields now so population reads stable values.
        # 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
        #    targetSnapshotParams, userInvolvement, with allowPOST set to allowPOST and completionSteps set to
        #    queue a global task on the navigation and traversal task source given navigable's active window to
        #    run afterDocumentPopulated.
        let populate = new HtmlApplyHistoryStepStatePopulate(this = this, input_url = html_session_history_entry_url(target_entry), input_document_resource = html_document_state_resource(target_state), input_request_referrer = html_document_state_request_referrer(target_state), input_request_referrer_policy = html_document_state_request_referrer_policy(target_state), input_initiator_origin = html_document_state_initiator_origin(target_state), input_origin = html_document_state_origin(target_state), input_history_policy_container = html_document_state_history_policy_container(target_state), input_about_base_url = html_document_state_about_base_url(target_state), input_navigable_target_name = html_document_state_navigable_target_name(target_state), input_ever_populated = html_document_state_ever_populated(target_state), potentially_target_specific_source_snapshot_params = potentially_target_specific_source_snapshot_params, target_snapshot_params = target_snapshot_params, allow_POST = allow_POST, navigable = navigable, after_document_populated = after_document_populated, user_involvement = this.m_user_involvement) else trap("out of memory")
        platform_event_loop_plugin_deferred_invoke(platform_event_loop_plugin_the(), gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_populate, context = populate)))
    # Otherwise, run afterDocumentPopulated immediately.
    else:
        ak.function1_call(&after_document_populated.function, none)

## `a == b` on two Variant<int, Pending> steps.
func html_session_history_entry_step_equals(a: I32OrHtmlSessionHistoryEntryPending, b: I32OrHtmlSessionHistoryEntryPending) -> bool:
    match a:
        .i32_(a_step):
            match b:
                .i32_(b_step):
                    return a_step == b_step
                _:
                    return false
        .html_session_history_entry_pending(_):
            match b:
                .html_session_history_entry_pending(_):
                    return true
                _:
                    return false

## `a == b` on two Optional<URL::Origin>: both empty, or both present and equal.
pub func html_optional_origin_equals(a: web_url.Origin?, b: web_url.Origin?) -> bool:
    if let a_origin = a:
        if let b_origin = b:
            return web_url.origin_eq(&a_origin, b_origin)
        return false
    return b == none

## Ported from TraversableNavigable.cpp:592 Web::HTML::ApplyHistoryStepState::start.
pub func html_apply_history_step_state_start(this: HtmlApplyHistoryStepState*):
    # 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
    var non_changing_navigables = html_traversable_navigable_get_all_navigables_that_only_need_history_object_length_index_update(this.m_traversable, this.m_target_step)
    for nav in ak.vector_span(&non_changing_navigables):
        ak.vector_append_t(&this.m_non_changing_navigables, nav else trap("no navigable"))

    # 8. For each navigable of changingNavigables:
    var changing_navigables = html_traversable_navigable_get_all_navigables_whose_current_session_history_entry_will_change_or_reload(this.m_traversable, this.m_target_step)
    for maybe_navigable in ak.vector_span(&changing_navigables):
        let navigable = maybe_navigable else trap("no navigable")

        # AD-HOC: For a synchronous (same-document) application of a history step, skip a navigable that has just
        #         been claimed by a fresh ongoing navigation. Apply the history step would otherwise transition the
        #         navigable's ongoing navigation through "traversal" and back to null, which informs the navigation
        #         API about aborting (cancelling the in-flight navigation's navigate event) and then trips the
        #         "ongoing navigation is no longer navigationId" bail-out in navigate's deferred steps, leaving the
        #         in-flight navigation stranded.
        #
        #         The race shows up when a click capture handler calls history.replaceState and the link's
        #         cross-document activation behavior runs in the same task: the replaceState's queued sync step
        #         finalizes after the link nav has already entered begin_navigation, and wipes its id. Real-world
        #         example: Shopify storefronts running hCaptcha (which hooks click and replaceStates to the current
        #         URL for analytics). The page silently never moves.
        #
        #         No major engine reproduces this. Chromium runs sync same-document nav entirely in-task and never
        #         enters a parallel traversal queue, WebKit doesn't track navigation IDs at all, and Gecko routes
        #         sync replaceState directly through history without entering SetOngoingNavigation. The strictly
        #         correct long-term fix is to bypass the traversal queue for sync same-document navigations to
        #         match Chromium; until then, skipping the transient when the navigable is already mid-navigation
        #         matches the observable behavior of all three.
        #
        #         Cross-document and traversal applications still process every changing navigable: the "traversal"
        #         transition there is not transient. It precedes an actual document switch that takes ownership.
        if this.m_synchronous_navigation == HtmlTraversableNavigableSynchronousNavigation.yes:
            match html_navigable_ongoing_navigation(navigable):
                .string(_):
                    continue
                _:
                    _ = 0

        # 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
        let target_entry = html_navigable_get_the_target_history_entry(navigable, this.m_target_step)

        # 2. Set navigable's current session history entry to targetEntry.
        html_navigable_set_current_session_history_entry(navigable, target_entry)

        # 3. Set navigable's ongoing navigation to "traversal".
        html_navigable_set_ongoing_navigation(navigable, EmptyOrHtmlNavigableTraversalOrString.html_navigable_traversal(HtmlNavigableTraversal.tag))

        ak.vector_append_t(&this.m_changing_navigables, navigable)

    # 12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source.
    for navigable in ak.vector_span(&this.m_changing_navigables):
        # AD-HOC: If the navigable has been destroyed, or has no active window, skip it.
        #         We must increment completed_change_jobs here rather than relying on the queued
        #         task, because Document::destroy() removes tasks associated with a document from
        #         the task queue, which can cause those tasks to never run.
        if html_navigable_has_been_destroyed(navigable) or html_navigable_active_window(navigable) == none:
            this.m_completed_change_jobs += 1
            html_apply_history_step_state_signal_progress(this)
            continue
        let task = new HtmlApplyHistoryStepStateChangeTask(this = this, navigable = navigable) else trap("out of memory")
        _ = html_queue_global_task(HtmlTaskSource.navigation_and_traversal, (JsObject*)(html_navigable_active_window(navigable) else trap("unreachable: checked above")), gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_change_navigable, context = task)))

    html_apply_history_step_state_try_advance(this)