Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / traversable_navigable_4.lucb

#==============================================================================================
#
#   traversable_navigable_4 - HTML::TraversableNavigable: checking if unloading is canceled, the
#   navigation API's entries, the forward session history and traversing by a delta
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/TraversableNavigable.cpp lines 1166-1564
#       (CheckUnloadingCanceledState, check_if_unloading_is_canceled,
#       get_session_history_entries_for_the_navigation_api, clear_the_forward_session_history,
#       can_go_forward, traverse_the_history_by_delta).
#
#       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: CheckUnloadingCanceledState =============================================================

## The CheckUnloadingCanceledState timeout's handler (the constructor's lambda).
func html_check_unloading_canceled_state_timed_out(context: void*?):
    let this = (HtmlCheckUnloadingCanceledState*)(context else trap("no state"))
    if not this.m_completed:
        ak.dbgln("FIXME: check_if_unloading_is_canceled timed out")
        html_check_unloading_canceled_state_finish(this, HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.continue_)

## Ported from TraversableNavigable.cpp:1168 Web::HTML::CheckUnloadingCanceledState::CheckUnloadingCanceledState, with
## the default member initializers.
pub func html_check_unloading_canceled_state_construct(this: HtmlCheckUnloadingCanceledState*, traversable: HtmlTraversableNavigable*?, user_involvement: HtmlUserNavigationInvolvement?, callback: gc.Function1[HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult, unit]*):
    this.m_final_status = HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.continue_
    this.m_unload_prompt_shown = false
    this.m_completed = false
    this.m_needs_beforeunload = false
    this.m_remaining_phase2_tasks = 0
    this.m_traversable = traversable
    this.m_user_involvement = user_involvement
    this.m_callback = callback
    let heap = gc.cell_heap(this.cell())
    this.m_timeout = platform_timer_create_single_shot(heap, html_check_unloading_canceled_state_timeout_ms, gc.create_function0(heap, ak.Function0[unit](call = html_check_unloading_canceled_state_timed_out, context = this)))
    platform_timer_start(this.m_timeout)

## `heap().allocate<CheckUnloadingCanceledState>(...)`: a state cell constructed under DeferGC.
func heap_allocate_html_check_unloading_canceled_state(heap: gc.Heap*, traversable: HtmlTraversableNavigable*?, user_involvement: HtmlUserNavigationInvolvement?, callback: gc.Function1[HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult, unit]*) -> HtmlCheckUnloadingCanceledState*:
    let state = (HtmlCheckUnloadingCanceledState*)web_heap_allocate_cell(heap, &html_check_unloading_canceled_state_class)
    gc.heap_defer_gc(heap)
    html_check_unloading_canceled_state_construct(state, traversable, user_involvement, callback)
    gc.heap_undefer_gc(heap)
    return state

## Ported from TraversableNavigable.cpp:1185 Web::HTML::CheckUnloadingCanceledState::visit_edges (override).
pub func html_check_unloading_canceled_state_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlCheckUnloadingCanceledState*)base
    gc.cell_visit_edges_impl(base, visitor)
    for doc in ak.vector_span(&this.m_phase2_documents):
        gc.cell_visitor_visit_t_2(visitor, doc)
    gc.cell_visitor_visit_t(visitor, this.m_traversable)
    gc.cell_visitor_visit_t_2(visitor, this.m_callback)
    gc.cell_visitor_visit_t_2(visitor, this.m_timeout)

## Ported from TraversableNavigable.cpp:1196 Web::HTML::CheckUnloadingCanceledState::start.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#checking-if-unloading-is-canceled
pub func html_check_unloading_canceled_state_start(this: HtmlCheckUnloadingCanceledState*, navigables_that_need_before_unload: ak.Vector[HtmlNavigable*?], target_step: i32?):
    var navigables = navigables_that_need_before_unload

    # 1. Let documentsToFireBeforeunload be the active document of each item in navigablesThatNeedBeforeUnload.
    for navigable in ak.vector_span(&navigables):
        ak.vector_append_t(&this.m_phase2_documents, html_navigable_active_document(navigable else trap("no navigable")) else trap("no active document"))

    # 2. Let unloadPromptShown be false.

    # 3. Let finalStatus be "continue".

    # 4. If traversable was given, then:
    if let traversable = this.m_traversable:
        # 1. Assert: targetStep and userInvolvementForNavigateEvent were given.
        # NOTE: This assertion is enforced by the caller.

        # 2. Let targetEntry be the result of getting the target history entry given traversable and targetStep.
        let target_entry = html_navigable_get_the_target_history_entry(traversable.html_navigable(), target_step else trap("Optional::value() on an empty optional")) else trap("no target entry")
        this.m_target_entry = target_entry

        # 3. If targetEntry is not traversable's current session history entry, and targetEntry's document state's origin is not the same as
        #    traversable's current session history entry's document state's origin, then:
        let current_entry = html_navigable_current_session_history_entry(traversable.html_navigable()) else trap("no current session history entry")
        if target_entry != current_entry and not html_optional_origin_equals(html_document_state_origin(html_session_history_entry_document_state(target_entry) else trap("no document state")), html_document_state_origin(html_session_history_entry_document_state(current_entry) else trap("no document state"))):
            # 1. Let eventsFired be false.

            # 2. Let needsBeforeunload be true if navigablesThatNeedBeforeUnload contains traversable; otherwise false.
            this.m_needs_beforeunload = false
            for navigable in ak.vector_span(&navigables):
                if navigable == traversable.html_navigable():
                    this.m_needs_beforeunload = true
                    break

            # 3. If needsBeforeunload is true, then remove traversable's active document from documentsToFireBeforeunload.
            if this.m_needs_beforeunload:
                let active_document = html_navigable_active_document(traversable.html_navigable())
                for i in 0..<ak.vector_size(&this.m_phase2_documents):
                    if (DomDocument*?)*ak.vector_at(&this.m_phase2_documents, i) == active_document:
                        ak.vector_remove(&this.m_phase2_documents, i)
                        break

            html_check_unloading_canceled_state_start_phase1(this)
            return

    html_check_unloading_canceled_state_start_phase2(this)

## start_phase1's queued task (step 4).
func html_check_unloading_canceled_state_phase1_task(context: void*?):
    let this = (HtmlCheckUnloadingCanceledState*)(context else trap("no state"))
    let traversable = this.m_traversable else trap("no traversable")

    # 1. if needsBeforeunload is true, then:
    if this.m_needs_beforeunload:
        # 1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given traversable's active document and false.
        let result = dom_document_steps_to_fire_beforeunload(html_navigable_active_document(traversable.html_navigable()) else trap("no active document"), false)

        # 2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.
        if result.unload_prompt_shown:
            this.m_unload_prompt_shown = true

        # 3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".
        if result.unload_prompt_canceled:
            this.m_final_status = HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_before_unload

    # 2. If finalStatus is "canceled-by-beforeunload", then abort these steps.
    if this.m_final_status == HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_before_unload:
        html_check_unloading_canceled_state_finish(this, this.m_final_status)
        return

    # 3. Let navigation be traversable's active window's navigation API.
    let navigation = html_window_navigation(html_navigable_active_window(traversable.html_navigable()) else trap("VERIFY: m_traversable->active_window()"))

    # 4. Let navigateEventResult be the result of firing a traverse navigate event at navigation given targetEntry and userInvolvementForNavigateEvent.
    let target_entry = this.m_target_entry else trap("VERIFY: m_target_entry")
    let navigate_event_result = html_navigation_fire_a_traverse_navigate_event(navigation, target_entry, this.m_user_involvement else trap("Optional::operator*() on an empty optional"))

    # 5. If navigateEventResult is false, then set finalStatus to "canceled-by-navigate".
    if not navigate_event_result:
        this.m_final_status = HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_navigate

    # 6. Set eventsFired to true.

    html_check_unloading_canceled_state_phase1_completed(this)

## Ported from TraversableNavigable.cpp:1241 Web::HTML::CheckUnloadingCanceledState::start_phase1.
func html_check_unloading_canceled_state_start_phase1(this: HtmlCheckUnloadingCanceledState*):
    # 4. Queue a global task on the navigation and traversal task source given traversable's active window to perform the following steps:
    let traversable = this.m_traversable else trap("no traversable")
    let window = html_navigable_active_window(traversable.html_navigable()) else trap("VERIFY: m_traversable->active_window()")
    _ = html_queue_global_task(HtmlTaskSource.navigation_and_traversal, (JsObject*)window, gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_check_unloading_canceled_state_phase1_task, context = this)))

## Ported from TraversableNavigable.cpp:1284 Web::HTML::CheckUnloadingCanceledState::phase1_completed.
func html_check_unloading_canceled_state_phase1_completed(this: HtmlCheckUnloadingCanceledState*):
    # 5. Wait for eventsFired to be true.

    # 6. If finalStatus is not "continue", then return finalStatus.
    if this.m_final_status != HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.continue_:
        html_check_unloading_canceled_state_finish(this, this.m_final_status)
        return
    html_check_unloading_canceled_state_start_phase2(this)

## The captures of start_phase2's task for one document.
struct HtmlCheckUnloadingCanceledStatePhase2Task:
    var this: HtmlCheckUnloadingCanceledState*
    var document: DomDocument*

## start_phase2's task for one document (step 7).
func html_check_unloading_canceled_state_phase2_task(context: void*?):
    let captures = (HtmlCheckUnloadingCanceledStatePhase2Task*)(context else trap("no captures"))
    let this = captures.this
    let document = captures.document
    if dom_document_has_been_destroyed(document) or not dom_document_is_fully_active(document):
        html_check_unloading_canceled_state_did_complete_phase2_task(this)
        return

    # 1. Let (unloadPromptShownForThisDocument, unloadPromptCanceledByThisDocument) be the result of running the steps to fire beforeunload given document and unloadPromptShown.
    let result = dom_document_steps_to_fire_beforeunload(document, this.m_unload_prompt_shown)

    # 2. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true.
    if result.unload_prompt_shown:
        this.m_unload_prompt_shown = true

    # 3. If unloadPromptCanceledByThisDocument is true, then set finalStatus to "canceled-by-beforeunload".
    if result.unload_prompt_canceled:
        this.m_final_status = HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_before_unload

    # 4. Increment completedTasks.
    html_check_unloading_canceled_state_did_complete_phase2_task(this)

## Ported from TraversableNavigable.cpp:1296 Web::HTML::CheckUnloadingCanceledState::start_phase2.
func html_check_unloading_canceled_state_start_phase2(this: HtmlCheckUnloadingCanceledState*):
    if ak.vector_is_empty(&this.m_phase2_documents):
        html_check_unloading_canceled_state_finish(this, this.m_final_status)
        return

    # 5. Let totalTasks be the size of documentsToFireBeforeunload.

    # 6. Let completedTasks be 0.
    this.m_remaining_phase2_tasks = ak.vector_size(&this.m_phase2_documents)

    # 7. For each document of documentsToFireBeforeunload, queue a global task on the navigation and traversal task source given document's relevant global object to run the steps:
    for document in ak.vector_span(&this.m_phase2_documents):
        # AD-HOC: Queue with a null document instead of using queue_global_task. Tasks associated with a document
        #         are only runnable when fully active. In the async state machine, documents can become non
        #         fully-active between queue and execution time, causing the task to be permanently stuck.
        #         A null-document task is always runnable; we check validity inside.
        let task = new HtmlCheckUnloadingCanceledStatePhase2Task(this = this, document = document) else trap("out of memory")
        _ = html_queue_a_task(HtmlTaskSource.navigation_and_traversal, none, none, gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_check_unloading_canceled_state_phase2_task, context = task)))

## Ported from TraversableNavigable.cpp:1337 Web::HTML::CheckUnloadingCanceledState::did_complete_phase2_task.
func html_check_unloading_canceled_state_did_complete_phase2_task(this: HtmlCheckUnloadingCanceledState*):
    assert(this.m_remaining_phase2_tasks > 0)
    this.m_remaining_phase2_tasks -= 1
    if this.m_remaining_phase2_tasks > 0:
        return

    # 8. Wait for completedTasks to be totalTasks.

    # 9. Return finalStatus.
    html_check_unloading_canceled_state_finish(this, this.m_final_status)

## Ported from TraversableNavigable.cpp:1349 Web::HTML::CheckUnloadingCanceledState::finish.
func html_check_unloading_canceled_state_finish(this: HtmlCheckUnloadingCanceledState*, final_result: HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult):
    if this.m_completed:
        return
    this.m_completed = true
    platform_timer_stop(this.m_timeout)
    ak.function1_call(&this.m_callback.function, final_result)

# mark: Checking if unloading is canceled =======================================================

## Ported from TraversableNavigable.cpp:1374 Web::HTML::TraversableNavigable::check_if_unloading_is_canceled.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#checking-if-unloading-is-canceled
func html_traversable_navigable_check_if_unloading_is_canceled_html_traversable_navigable(this: HtmlTraversableNavigable*, navigables_that_need_before_unload: ak.Vector[HtmlNavigable*?], traversable: HtmlTraversableNavigable*?, target_step: i32?, user_involvement_for_navigate_events: HtmlUserNavigationInvolvement?, callback: gc.Function1[HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult, unit]*):
    let state = heap_allocate_html_check_unloading_canceled_state(gc.cell_heap(this.cell()), traversable, user_involvement_for_navigate_events, callback)
    html_check_unloading_canceled_state_start(state, navigables_that_need_before_unload, target_step)

## Ported from TraversableNavigable.cpp:1388 Web::HTML::TraversableNavigable::check_if_unloading_is_canceled.
pub func html_traversable_navigable_check_if_unloading_is_canceled_function1(this: HtmlTraversableNavigable*, navigables_that_need_before_unload: ak.Vector[HtmlNavigable*?], callback: gc.Function1[HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult, unit]*):
    html_traversable_navigable_check_if_unloading_is_canceled_html_traversable_navigable(this, navigables_that_need_before_unload, none, none, none, callback)

# mark: Session history entries for the navigation API ==========================================

## Ported from TraversableNavigable.cpp:1393 Web::HTML::TraversableNavigable::get_session_history_entries_for_the_navigation_api.
func html_traversable_navigable_get_session_history_entries_for_the_navigation_api(this: HtmlTraversableNavigable*, navigable: HtmlNavigable*, target_step: i32) -> ak.Vector[HtmlSessionHistoryEntry*]:
    # 1. Let rawEntries be the result of getting session history entries for navigable.
    let raw_entries = ak.vector_clone(html_navigable_get_session_history_entries(navigable))

    if ak.vector_is_empty(&raw_entries):
        return ak.Vector[HtmlSessionHistoryEntry*]()

    # 2. Let entriesForNavigationAPI be a new empty list.
    var entries_for_navigation_api = ak.Vector[HtmlSessionHistoryEntry*]()

    # 3. Let startingIndex be the index of the session history entry in rawEntries who has the greatest step less than or equal to targetStep.
    # FIXME: Use min/max_element algorithm or some such here
    var starting_index: i32 = 0
    let max_step: i32 = 0
    for i in 0..<ak.vector_size(&raw_entries):
        let entry = *ak.vector_at_const(&raw_entries, i)
        match html_session_history_entry_step(entry):
            .i32_(step):
                if step <= target_step and step > max_step:
                    starting_index = (i32)i
            _:
                _ = 0

    # 4. Append rawEntries[startingIndex] to entriesForNavigationAPI.
    ak.vector_append_t(&entries_for_navigation_api, *ak.vector_at_const(&raw_entries, usize(starting_index)))

    # 5. Let startingOrigin be rawEntries[startingIndex]'s document state's origin.
    let starting_origin = html_document_state_origin(html_session_history_entry_document_state(*ak.vector_at_const(&raw_entries, usize(starting_index))) else trap("no document state"))

    # 6. Let i be startingIndex − 1.
    var i = starting_index - 1

    # 7. While i > 0:
    while i > 0:
        let entry = *ak.vector_at_const(&raw_entries, usize(i))
        # 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
        let entry_origin = html_document_state_origin(html_session_history_entry_document_state(entry) else trap("no document state"))
        if html_origins_both_present_and_not_same_origin(entry_origin, starting_origin):
            break

        # 2. Prepend rawEntries[i] to entriesForNavigationAPI.
        ak.vector_prepend_u(&entries_for_navigation_api, entry)

        # 3. Set i to i − 1.
        i -= 1

    # 8. Set i to startingIndex + 1.
    i = starting_index + 1

    # 9. While i < rawEntries's size:
    while i < (i32)ak.vector_size(&raw_entries):
        let entry = *ak.vector_at_const(&raw_entries, usize(i))
        # 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
        let entry_origin = html_document_state_origin(html_session_history_entry_document_state(entry) else trap("no document state"))
        if html_origins_both_present_and_not_same_origin(entry_origin, starting_origin):
            break

        # 2. Append rawEntries[i] to entriesForNavigationAPI.
        ak.vector_append_t(&entries_for_navigation_api, entry)

        # 3. Set i to i + 1.
        i += 1

    # 10. Return entriesForNavigationAPI.
    return entries_for_navigation_api

## `starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin)`.
func html_origins_both_present_and_not_same_origin(entry_origin: web_url.Origin?, starting_origin: web_url.Origin?) -> bool:
    let entry = entry_origin else return false
    let starting = starting_origin else return false
    return not web_url.origin_is_same_origin(&entry, starting)

# mark: The forward session history =============================================================

## Ported from TraversableNavigable.cpp:1465 Web::HTML::TraversableNavigable::clear_the_forward_session_history.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
pub func html_traversable_navigable_clear_the_forward_session_history(this: HtmlTraversableNavigable*):
    # FIXME: 1. Assert: this is running within navigable's session history traversal queue.

    # 2. Let step be the navigable's current session history step.
    let step = html_traversable_navigable_current_session_history_step(this)

    # 3. Let entryLists be the ordered set « navigable's session history entries ».
    var entry_lists = ak.Vector[ak.Vector[HtmlSessionHistoryEntry*]*]()
    ak.vector_append_t(&entry_lists, html_traversable_navigable_session_history_entries(this))

    # 4. For each entryList of entryLists:
    while not ak.vector_is_empty(&entry_lists):
        let entry_list = ak.vector_take_first(&entry_lists)

        # 1. Remove every session history entry from entryList that has a step greater than step.
        var kept = ak.Vector[HtmlSessionHistoryEntry*]()
        for entry in ak.vector_span(entry_list):
            if html_traversable_entry_step(entry) <= step:
                ak.vector_append_t(&kept, entry)
        ak.vector_clear(entry_list)
        ak.vector_extend(entry_list, &kept)

        # 2. For each entry of entryList:
        for entry in ak.vector_span(entry_list):
            # 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
            for nested_history in &ak.vector_span(html_document_state_nested_histories(html_session_history_entry_document_state(entry) else trap("no document state"))):
                ak.vector_append_t(&entry_lists, &nested_history.entries)

## Ported from TraversableNavigable.cpp:1495 Web::HTML::TraversableNavigable::can_go_forward.
func html_traversable_navigable_can_go_forward(this: HtmlTraversableNavigable*) -> bool:
    let step = html_traversable_navigable_current_session_history_step(this)

    var entry_lists = ak.Vector[ak.Vector[HtmlSessionHistoryEntry*]]()
    ak.vector_append_t(&entry_lists, html_traversable_navigable_session_history_entries_const(this))

    while not ak.vector_is_empty(&entry_lists):
        var entry_list = ak.vector_take_first(&entry_lists)

        for entry in ak.vector_span(&entry_list):
            if html_traversable_entry_step(entry) > step:
                return true

            for nested_history in ak.vector_span(html_document_state_nested_histories(html_session_history_entry_document_state(entry) else trap("no document state"))):
                ak.vector_append_t(&entry_lists, nested_history.entries)

    return false

# mark: Traversing the history by a delta =======================================================

## The captures of traverse_the_history_by_delta's traversal steps.
struct HtmlTraversableNavigableTraverseByDelta:
    var this: HtmlTraversableNavigable*
    var delta: i32
    var source_snapshot_params: HtmlSourceSnapshotParams*?
    var initiator_to_check: HtmlNavigable*?
    var user_involvement: HtmlUserNavigationInvolvement

## traverse_the_history_by_delta's step 4: the session history traversal steps.
func html_traversable_navigable_traverse_by_delta_steps(context: void*?, signal: CorePromise[ak.Empty, ak.AkError]*):
    let captures = (HtmlTraversableNavigableTraverseByDelta*)(context else trap("no captures"))
    let this = captures.this

    # 1. Let allSteps be the result of getting all used history steps for traversable.
    var all_steps = html_traversable_navigable_get_all_used_history_steps(this)

    # 2. Let currentStepIndex be the index of traversable's current session history step within allSteps.
    let current_step_index = ak.vector_find_first_index(&all_steps, html_traversable_navigable_current_session_history_step(this)) else trap("Optional::operator*() on an empty optional")

    # 3. Let targetStepIndex be currentStepIndex plus delta
    # (C++ adds the int delta to the size_t index, wrapping as size_t.)
    let target_step_index = current_step_index +% (usize)(isize)captures.delta

    # 4. If allSteps[targetStepIndex] does not exist, then abort these steps.
    if target_step_index >= ak.vector_size(&all_steps):
        core_promise_resolve(signal, ak.Empty())
        return

    # 5. Apply the traverse history step allSteps[targetStepIndex] to traversable, given sourceSnapshotParams,
    #    initiatorToCheck, and userInvolvement.
    let resolve = new HtmlNavigableResolveSignal(signal = signal) else trap("out of memory")
    html_traversable_navigable_apply_the_traverse_history_step(this, *ak.vector_at(&all_steps, target_step_index), captures.source_snapshot_params, captures.initiator_to_check, captures.user_involvement, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[HtmlHistoryStepResult, unit](call = html_navigable_resolve_signal, context = resolve)))

## Ported from TraversableNavigable.cpp:1518 Web::HTML::TraversableNavigable::traverse_the_history_by_delta.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history-by-a-delta
pub func html_traversable_navigable_traverse_the_history_by_delta(this: HtmlTraversableNavigable*, delta: i32, source_document: DomDocument*? = none):
    # 1. Let sourceSnapshotParams and initiatorToCheck be null.
    var source_snapshot_params: HtmlSourceSnapshotParams*? = none
    var initiator_to_check: HtmlNavigable*? = none

    # 2. Let userInvolvement be "browser UI".
    var user_involvement = HtmlUserNavigationInvolvement.browser_ui

    # 1. If sourceDocument is given, then:
    if let document = source_document:
        # 1. Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument.
        source_snapshot_params = dom_document_snapshot_source_snapshot_params(document)

        # 2. Set initiatorToCheck to sourceDocument's node navigable.
        initiator_to_check = dom_document_navigable(document)

        # 3. Set userInvolvement to "none".
        user_involvement = HtmlUserNavigationInvolvement.none_

    # 4. Append the following session history traversal steps to traversable:
    let captures = new HtmlTraversableNavigableTraverseByDelta(this = this, delta = delta, source_snapshot_params = source_snapshot_params, initiator_to_check = initiator_to_check, user_involvement = user_involvement) else trap("out of memory")
    html_traversable_navigable_append_session_history_traversal_steps(this, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[CorePromise[ak.Empty, ak.AkError]*, unit](call = html_traversable_navigable_traverse_by_delta_steps, context = captures)))