Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / navigable_container.lucb

#==============================================================================================
#
#   navigable_container - HTML::NavigableContainer: the element (iframe, frame, object) whose
#   content navigable is a child navigable of its node navigable
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/NavigableContainer.cpp (lines 1-426) with the inline
#       functions of NavigableContainer.h. all_instances and
#       navigable_container_with_content_navigable were taken ahead by region r43
#       (navigable_container_taken_ahead.lucb, now folded in here).
#
#       all_instances is a C-heap set of raw pointers (C++'s static HashTable of pointers): the
#       constructor adds a container and finalize removes it, so it never points at a dead cell
#       (DESIGN.md §3.3 rule 7).
#
#       Copyright (c) 2020-2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
#       Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: All instances ===========================================================================

## `static HashTable<NavigableContainer*> set` of all_instances(). Its storage is allocated from
## the C heap (memory.heap), which the collector does not scan; the containers are weak entries,
## as in C++ (a container leaves the set in its finalize).
var html_navigable_container_s_all_instances: ak.HashTable[HtmlNavigableContainer*?, ak.PtrTraits[HtmlNavigableContainer]]

## Ported from NavigableContainer.cpp:29 Web::HTML::NavigableContainer::all_instances.
pub func html_navigable_container_all_instances() -> ak.HashTable[HtmlNavigableContainer*?, ak.PtrTraits[HtmlNavigableContainer]]*:
    return &html_navigable_container_s_all_instances

## Ported from NavigableContainer.cpp:35 Web::HTML::NavigableContainer::NavigableContainer, with
## the default member initializers.
pub func html_navigable_container_construct(this: HtmlNavigableContainer*, document: DomDocument*, qualified_name: DomQualifiedName):
    html_element_construct(this.html_element(), document, qualified_name)
    html_navigable_container_init_fields(this)
    with memory.heap:
        _ = ak.hash_table_set(html_navigable_container_all_instances(), this)

## Ported from NavigableContainer.cpp:43 Web::HTML::NavigableContainer::finalize (override).
pub func html_navigable_container_finalize_impl(base: gc.Cell*):
    let this = (HtmlNavigableContainer*)base
    # Base::finalize(): HTMLElement inherits Node's.
    dom_node_finalize_impl(base)
    with memory.heap:
        _ = ak.hash_table_remove_t(html_navigable_container_all_instances(), this)

## Ported from NavigableContainer.cpp:49 Web::HTML::NavigableContainer::visit_edges (override).
pub func html_navigable_container_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigableContainer*)base
    html_element_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_content_navigable)

## Ported from NavigableContainer.cpp:55 Web::HTML::NavigableContainer::navigable_container_with_content_navigable.
pub func html_navigable_container_navigable_container_with_content_navigable(navigable: HtmlNavigable*) -> HtmlNavigableContainer*?:
    for entry in ak.hash_table_begin(html_navigable_container_all_instances()):
        let navigable_container = *entry else continue
        if html_navigable_container_content_navigable(navigable_container) == (HtmlNavigable*?)navigable:
            return navigable_container
    return none

# mark: Creating a new child navigable ==========================================================

## `heap().allocate<Navigable>(page, false)`: a navigable constructed under DeferGC.
func heap_allocate_html_navigable(heap: gc.Heap*, page: Page*, is_svg_page: bool) -> HtmlNavigable*:
    let navigable = (HtmlNavigable*)web_heap_allocate_cell(heap, &html_navigable_class)
    gc.heap_defer_gc(heap)
    html_navigable_construct(navigable, page, is_svg_page)
    gc.heap_undefer_gc(heap)
    return navigable

## The captures of create_new_child_navigable's traversal steps
## (`[this, navigable, parent_navigable, history_entry, traversable]`).
struct HtmlNavigableContainerChildNavigableSteps:
    var this: HtmlNavigableContainer*
    var navigable: HtmlNavigable*
    var parent_navigable: HtmlNavigable*
    var history_entry: HtmlSessionHistoryEntry*
    var traversable: HtmlTraversableNavigable*

## The captures of the second traversal steps (`[this, navigable]`).
struct HtmlNavigableContainerReadySteps:
    var this: HtmlNavigableContainer*
    var navigable: HtmlNavigable*

## create_new_child_navigable's second traversal steps: mark the content navigable ready.
func html_navigable_container_ready_steps(context: void*?, signal: CorePromise[ak.Empty, ak.AkError]*):
    let captures = (HtmlNavigableContainerReadySteps*)(context else trap("no captures"))
    let this = captures.this
    if html_navigable_has_been_destroyed(captures.navigable) or html_navigable_container_content_navigable(this) != (HtmlNavigable*?)captures.navigable:
        core_promise_resolve(signal, ak.Empty())
        return

    html_navigable_container_set_content_navigable_has_session_history_entry_and_ready_for_navigation(this)
    core_promise_resolve(signal, ak.Empty())

## The captures of step 12's update callback (`[signal]`).
struct HtmlNavigableContainerResolveSignal:
    var signal: CorePromise[ak.Empty, ak.AkError]*

## Step 12.7's update-for-navigable-creation callback: resolve the signal.
func html_navigable_container_resolve_signal(context: void*?, result: HtmlHistoryStepResult):
    let captures = (HtmlNavigableContainerResolveSignal*)(context else trap("no captures"))
    core_promise_resolve(captures.signal, ak.Empty())

## create_new_child_navigable's step 12: the session history traversal steps.
func html_navigable_container_child_navigable_steps(context: void*?, signal: CorePromise[ak.Empty, ak.AkError]*):
    let captures = (HtmlNavigableContainerChildNavigableSteps*)(context else trap("no captures"))
    let navigable = captures.navigable
    let parent_navigable = captures.parent_navigable
    let traversable = captures.traversable
    if html_navigable_has_been_destroyed(navigable) or html_navigable_has_been_destroyed(parent_navigable):
        core_promise_resolve(signal, ak.Empty())
        return

    # 1. Let parentDocState be parentNavigable's active session history entry's document state.
    let parent_doc_state = html_session_history_entry_document_state(html_navigable_active_session_history_entry(parent_navigable) else trap("no active session history entry")) else trap("no document state")

    # 2. Let parentNavigableEntries be the result of getting session history entries for parentNavigable.
    let parent_navigable_entries = html_navigable_get_session_history_entries(parent_navigable)

    # 3. Let targetStepSHE be the first session history entry in parentNavigableEntries whose document state equals parentDocState.
    var target_step_she: HtmlSessionHistoryEntry*? = none
    for entry in ak.vector_span(parent_navigable_entries):
        if html_session_history_entry_document_state(entry) == (HtmlDocumentState*?)parent_doc_state:
            target_step_she = entry
            break

    # 4. Set historyEntry's step to targetStepSHE's step.
    html_session_history_entry_set_step(captures.history_entry, html_session_history_entry_step(target_step_she else trap("no entry with the parent's document state")))

    # 5. Let nestedHistory be a new nested history whose id is navigable's id and entries list is « historyEntry ».
    var nested_history = HtmlDocumentStateNestedHistory(id = html_navigable_id(navigable), entries = ak.Vector[HtmlSessionHistoryEntry*]())
    ak.vector_append_t(&nested_history.entries, captures.history_entry)

    # 6. Append nestedHistory to parentDocState's nested histories.
    ak.vector_append_t(html_document_state_nested_histories(parent_doc_state), nested_history)

    # 7. Update for navigable creation/destruction given traversable
    let resolve = new HtmlNavigableContainerResolveSignal(signal = signal) else trap("out of memory")
    let traversable_heap = gc.cell_heap(traversable.cell())
    html_traversable_navigable_update_for_navigable_creation_or_destruction(traversable, gc.create_function1(traversable_heap, ak.Function1[HtmlHistoryStepResult, unit](call = html_navigable_container_resolve_signal, context = resolve)))

    let ready = new HtmlNavigableContainerReadySteps(this = captures.this, navigable = navigable) else trap("out of memory")
    html_traversable_navigable_append_session_history_traversal_steps(traversable, gc.create_function1(traversable_heap, ak.Function1[CorePromise[ak.Empty, ak.AkError]*, unit](call = html_navigable_container_ready_steps, context = ready)))

## Ported from NavigableContainer.cpp:65 Web::HTML::NavigableContainer::create_new_child_navigable.
# https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-new-child-navigable
pub func html_navigable_container_create_new_child_navigable(this: HtmlNavigableContainer*):
    let node_document = dom_node_document(this.dom_node())

    # 1. Let parentNavigable be element's node navigable.
    let parent_navigable = dom_node_navigable(this.dom_node())

    # 2. Let group be element's node document's browsing context's top-level browsing context's group.
    let node_browsing_context = dom_document_browsing_context(node_document) else trap("VERIFY: document().browsing_context()")
    let top_level_browsing_context = html_browsing_context_top_level_browsing_context(node_browsing_context) else trap("no top-level browsing context")
    let group = html_browsing_context_group(top_level_browsing_context) else trap("VERIFY: group")

    # 3. Let browsingContext and document be the result of creating a new browsing context and document given element's node document, element, and group.
    let page = dom_document_page(node_document)
    let created = html_browsing_context_create_a_new_browsing_context_and_document(page, node_document, this.dom_element(), group)
    let document = created.document

    # 4. Let targetName be null.
    var target_name: ak.String? = none

    # 5. If element has a name content attribute, then set targetName to the value of that attribute.
    if let name = dom_element_name(this.dom_element()):
        target_name = ak.fly_string_to_string_const(&name)

    # 6. Let documentState be a new document state, with
    #  - document: document
    #  - initiator origin: document's origin
    #  - origin: document's origin
    #  - navigable target name: targetName
    #  - about base URL: document's about base URL
    let document_state = html_document_state_create()
    html_document_state_set_initiator_origin(document_state, dom_document_origin(document))
    html_document_state_set_origin(document_state, dom_document_origin(document))
    if let name = target_name:
        html_document_state_set_navigable_target_name(document_state, name)
    html_document_state_set_about_base_url(document_state, dom_document_about_base_url(document))

    # 7. Let navigable be a new navigable.
    let navigable = heap_allocate_html_navigable(gc.cell_heap(this.cell()), page, false)

    # 8. Initialize the navigable navigable given documentState and parentNavigable.
    html_navigable_initialize_navigable(navigable, document_state, parent_navigable, document)

    # 9. Set element's content navigable to navigable.
    this.m_content_navigable = navigable

    # 10. Let historyEntry be navigable's active session history entry.
    let history_entry = html_navigable_active_session_history_entry(navigable) else trap("no active session history entry")

    # 11. Let traversable be parentNavigable's traversable navigable.
    let parent = parent_navigable else trap("no parent navigable")
    let traversable = html_navigable_traversable_navigable(parent) else trap("no traversable navigable")

    # 12. Append the following session history traversal steps to traversable:
    let captures = new HtmlNavigableContainerChildNavigableSteps(this = this, navigable = navigable, parent_navigable = parent, history_entry = history_entry, traversable = traversable) else trap("out of memory")
    html_traversable_navigable_append_session_history_traversal_steps(traversable, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[CorePromise[ak.Empty, ak.AkError]*, unit](call = html_navigable_container_child_navigable_steps, context = captures)))

# mark: Content document and window =============================================================

## Ported from NavigableContainer.cpp:162 Web::HTML::NavigableContainer::content_document.
# https://html.spec.whatwg.org/multipage/browsers.html#concept-bcc-content-document
pub func html_navigable_container_content_document(this: HtmlNavigableContainer*) -> DomDocument*?:
    # 1. If container's content navigable is null, then return null.
    let content_navigable = this.m_content_navigable else return none

    # 2. Let document be container's content navigable's active document.
    let active_document = html_navigable_active_document(content_navigable)

    # AD-HOC: The active document can be null during navigation, after the old document
    #         has been destroyed but before the new document has been set.
    let document = active_document else return none

    # 3. If document's origin and container's node document's origin are not same origin-domain, then return null.
    let document_origin = dom_document_origin(document)
    if not web_url.origin_is_same_origin_domain(&document_origin, dom_document_origin(dom_node_document(this.dom_node()))):
        return none

    # 4. Return document.
    return document

## Ported from NavigableContainer.cpp:184 Web::HTML::NavigableContainer::content_document_without_origin_check.
pub func html_navigable_container_content_document_without_origin_check(this: HtmlNavigableContainer*) -> DomDocument*?:
    let content_navigable = this.m_content_navigable else return none

    return html_navigable_active_document(content_navigable)

## Ported from NavigableContainer.cpp:193 Web::HTML::NavigableContainer::get_svg_document.
# https://html.spec.whatwg.org/multipage/embedded-content-other.html#dom-media-getsvgdocument
pub func html_navigable_container_get_svg_document(this: HtmlNavigableContainer*) -> DomDocument*?:
    # 1. Let document be this element's content document.
    let document = html_navigable_container_content_document(this)

    # 2. If document is non-null and was created by the page load processing model for XML files section because the computed type of the resource in the navigate algorithm was image/svg+xml, then return document.
    if let content_document = document:
        let content_type = dom_document_content_type(content_document)
        if ak.string_eq_string_view(&content_type, ak.sv("image/svg+xml")):
            return content_document
    # 3. Return null.
    return none

## Ported from NavigableContainer.cpp:205 Web::HTML::NavigableContainer::content_window.
pub func html_navigable_container_content_window(this: HtmlNavigableContainer*) -> HtmlWindowProxy*?:
    let content_navigable = this.m_content_navigable else return none
    return html_navigable_active_window_proxy(content_navigable)

# mark: Navigating iframes and frames ===========================================================

## Ported from NavigableContainer.cpp:213 Web::HTML::NavigableContainer::shared_attribute_processing_steps_for_iframe_and_frame.
# https://html.spec.whatwg.org/multipage/iframe-embed-object.html#shared-attribute-processing-steps-for-iframe-and-frame-elements
pub func html_navigable_container_shared_attribute_processing_steps_for_iframe_and_frame(this: HtmlNavigableContainer*, initial_insertion: HtmlInitialInsertion) -> web_url.Url?:
    if dom_node_navigable(this.dom_node()) == none:
        return none

    # AD-HOC: If the element was added and immediately removed, the content navigable will be null. Don't process the
    #         src attribute any further.
    let content_navigable = this.m_content_navigable else return none

    # AD-HOC: If the content navigable already has a navigation in progress or pending,
    #         skip the initial attribute processing. Without this, the about:blank URL update
    #         from perform_url_and_history_update_steps creates a state machine that clobbers the
    #         navigable's ongoing_navigation, causing the real navigation to be dropped when its
    #         populate completion callback checks ongoing_navigation != navigation_id.
    if initial_insertion == HtmlInitialInsertion.yes and (html_navigable_has_pending_navigations(content_navigable) or not html_ongoing_navigation_is_empty(html_navigable_ongoing_navigation(content_navigable))):
        return none

    let node_document = dom_node_document(this.dom_node())

    # 1. Let url be the URL record about:blank.
    var url = web_url.about_blank()

    # 2. If element has a src attribute specified, and its value is not the empty string, then:
    let src_attribute_value = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_src)
    if not ak.string_is_empty(&src_attribute_value):
        # 1. Let maybeURL be the result of encoding-parsing a URL given that attribute's value, relative to element's node document.
        let maybe_url = dom_document_encoding_parse_url(node_document, ak.string_bytes_as_string_view(&src_attribute_value))

        # 2. If maybeURL is not failure, then set url to maybeURL.
        if let parsed = maybe_url:
            url = parsed

    # 3. If the inclusive ancestor navigables of element's node navigable contains a navigable
    #    whose active document's URL equals url with exclude fragments set to true, then return null.
    let ancestors = dom_document_inclusive_ancestor_navigables(node_document)
    for ancestor in ak.vector_span_const(&ancestors):
        let navigable = ancestor else trap("no navigable")
        let active_document = html_navigable_active_document(navigable) else trap("VERIFY: navigable->active_document()")
        let active_url = dom_document_url(active_document)
        if web_url.url_equals(&active_url, url, web_url.ExcludeFragment.yes):
            return none

    # 4. If url matches about:blank and initialInsertion is true, then perform the URL and history update steps given element's content navigable's active document and url.
    if html_url_matches_about_blank(url) and initial_insertion == HtmlInitialInsertion.yes:
        let document = html_navigable_active_document(content_navigable) else trap("no active document")
        html_perform_url_and_history_update_steps(document, url)

    # 5. Return url.
    return url

## Ported from NavigableContainer.cpp:265 Web::HTML::NavigableContainer::navigate_an_iframe_or_frame.
# https://html.spec.whatwg.org/multipage/iframe-embed-object.html#navigate-an-iframe-or-frame
pub func html_navigable_container_navigate_an_iframe_or_frame(this: HtmlNavigableContainer*, url: web_url.Url, referrer_policy: ReferrerPolicyReferrerPolicy, srcdoc_string: ak.String? = none, initial_insertion: HtmlInitialInsertion = HtmlInitialInsertion.no):
    let content_navigable = this.m_content_navigable else trap("no content navigable")

    # 1. Let historyHandling be "auto".
    var history_handling = BindNavigationHistoryBehavior.auto

    # 2. If element's content navigable's active document is not completely loaded, then set historyHandling to "replace".
    # AD-HOC: Only apply this check during initial insertion. For subsequent attribute-driven navigations,
    #         the previous document may have parsed and run scripts but not yet fired its load event;
    #         forcing "replace" in that case would incorrectly discard the history entry.
    if initial_insertion == HtmlInitialInsertion.yes:
        if let active_document = html_navigable_active_document(content_navigable):
            if not dom_document_is_completely_loaded(active_document):
                history_handling = BindNavigationHistoryBehavior.replace

    # FIXME: 3. If element is an iframe, then set element's pending resource-timing start time to the current high resolution
    #           time given element's node document's relevant global object.

    # 4. Navigate element's content navigable to url using element's node document, with historyHandling set to historyHandling,
    #    referrerPolicy set to referrerPolicy, documentResource set to srcdocString, and initialInsertion set to
    #    initialInsertion.
    var document_resource = EmptyOrStringOrHtmlPostResource.empty
    if let srcdoc = srcdoc_string:
        document_resource = EmptyOrStringOrHtmlPostResource.string(srcdoc)

    html_navigable_navigate(content_navigable, HtmlNavigableNavigateParams(url = url, source_document = dom_node_document(this.dom_node()), document_resource = document_resource, history_handling = history_handling, referrer_policy = referrer_policy, initial_insertion = initial_insertion)) else trap("MUST: Navigable::navigate")

# mark: Destroying the child navigable ==========================================================

## The captures of destroy_the_child_navigable's afterDocumentDestruction (`[this, navigable]`).
struct HtmlNavigableContainerAfterDocumentDestruction:
    var this: HtmlNavigableContainer*
    var navigable: HtmlNavigable*

## The update-for-navigable-destruction traversal steps (`[traversable]`).
func html_navigable_container_destruction_steps(context: void*?, signal: CorePromise[ak.Empty, ak.AkError]*):
    let traversable = (HtmlTraversableNavigable*)(context else trap("no traversable"))
    # 1. Update for navigable creation/destruction given traversable.
    let resolve = new HtmlNavigableContainerResolveSignal(signal = signal) else trap("out of memory")
    html_traversable_navigable_update_for_navigable_creation_or_destruction(traversable, gc.create_function1(gc.cell_heap(traversable.cell()), ak.Function1[HtmlHistoryStepResult, unit](call = html_navigable_container_resolve_signal, context = resolve)))

## The remove_all_matching predicate of step 7 (`navigable->id() == nested_history.id`).
func html_navigable_container_is_nested_history_of(context: void*?, nested_history: const HtmlDocumentStateNestedHistory*) -> bool:
    let navigable = (HtmlNavigable*)(context else trap("no navigable"))
    let id = html_navigable_id(navigable)
    return ak.string_equals(&id, &nested_history.id)

## destroy_the_child_navigable's afterDocumentDestruction.
func html_navigable_container_after_document_destruction(context: void*?):
    let captures = (HtmlNavigableContainerAfterDocumentDestruction*)(context else trap("no captures"))
    let this = captures.this
    let navigable = captures.navigable

    # 3. Set container's content navigable to null.
    this.m_content_navigable = none
    dom_document_schedule_html_parser_end_check(dom_node_document(this.dom_node()))

    # Not in the spec:
    html_navigable_remove_from_all_navigables(navigable)

    # 6. Let parentDocState be container's node navigable's active session history entry's document state.
    let node_navigable = dom_node_navigable(this.dom_node()) else trap("no node navigable")
    let parent_doc_state = html_session_history_entry_document_state(html_navigable_active_session_history_entry(node_navigable) else trap("no active session history entry")) else trap("no document state")

    # 7. Remove the nested history from parentDocState's nested histories whose id equals navigable's id.
    _ = ak.vector_remove_all_matching(html_document_state_nested_histories(parent_doc_state), ak.Function1[const HtmlDocumentStateNestedHistory*, bool](call = html_navigable_container_is_nested_history_of, context = navigable))

    # 8. Let traversable be container's node navigable's traversable navigable.
    let traversable = html_navigable_traversable_navigable(node_navigable) else trap("no traversable navigable")

    # 9. Append the following session history traversal steps to traversable:
    html_traversable_navigable_append_session_history_traversal_steps(traversable, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[CorePromise[ak.Empty, ak.AkError]*, unit](call = html_navigable_container_destruction_steps, context = traversable)))

## Ported from NavigableContainer.cpp:299 Web::HTML::NavigableContainer::destroy_the_child_navigable.
# https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-child-navigable
pub func html_navigable_container_destroy_the_child_navigable(this: HtmlNavigableContainer*):
    # 1. Let navigable be container's content navigable.
    let content_navigable = html_navigable_container_content_navigable(this)

    # 2. If navigable is null, then return.
    let navigable = content_navigable else return

    # Not in the spec:
    # Setting container's content navigable makes document *not* be "fully active".
    # Therefore, it is moved to run in afterAllDestruction callback of "destroy a document and its descendants"
    # when all queued tasks are done.
    # "Has been destroyed" flag is used instead to check whether navigable is already destroyed.
    if html_navigable_has_been_destroyed(navigable):
        return
    html_navigable_set_has_been_destroyed(navigable)

    # AD-HOC: Clear the navigable's "is delaying load events" flag.
    #         This removes the DocumentLoadEventDelayer on the parent document that was
    #         created when the navigable started loading (navigate algorithm step 15).
    #         Without this, the delayer lingers until GC collects the Navigable, which can
    #         block the parent document's load event indefinitely.
    html_navigable_set_delaying_load_events(navigable, false)

    # AD-HOC: Clear the navigation load event guard that may have been set by
    #         finalize_a_cross_document_navigation. Without this, the guard's
    #         DocumentLoadEventDelayer on the parent document persists until GC,
    #         blocking the parent's load event indefinitely.
    html_navigable_clear_navigation_load_event_guard(navigable)

    # 4. Inform the navigation API about child navigable destruction given navigable.
    html_navigable_inform_the_navigation_api_about_child_navigable_destruction(navigable)

    let captures = new HtmlNavigableContainerAfterDocumentDestruction(this = this, navigable = navigable) else trap("out of memory")
    let after_document_destruction = gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_navigable_container_after_document_destruction, context = captures))

    # 5. Destroy a document and its descendants given navigable's active document.
    # AD-HOC: The spec assumes the active document is non-null here, but during an ancestor
    #         unload the child documents are unloaded (and destroyed) before the ancestor's
    #         pagehide fires. If that pagehide handler then removes a subtree containing this
    #         container, we reach step 5 with navigable's active document already null. We
    #         treat the destroy step as a no-op in that case and proceed with the remaining
    #         post-destruction cleanup.
    if let active_document = html_navigable_active_document(navigable):
        dom_document_destroy_a_document_and_its_descendants(active_document, after_document_destruction)
    else:
        ak.function0_call(&after_document_destruction.function)

# mark: Delaying the load event =================================================================

## Ported from NavigableContainer.cpp:375 Web::HTML::NavigableContainer::currently_delays_the_load_event.
# https://html.spec.whatwg.org/multipage/iframe-embed-object.html#potentially-delays-the-load-event
pub func html_navigable_container_currently_delays_the_load_event(this: HtmlNavigableContainer*) -> bool:
    if not html_navigable_container_content_navigable_has_session_history_entry_and_ready_for_navigation(this):
        return true

    if not this.m_potentially_delays_the_load_event:
        return false

    # If an element type potentially delays the load event, then for each element element of that type,
    # the user agent must delay the load event of element's node document if element's content navigable is non-null
    # and any of the following are true:
    let content_navigable = this.m_content_navigable else return false
    let active_document = html_navigable_active_document(content_navigable) else trap("no active document")

    # - element's content navigable's active document is not ready for post-load tasks;
    if not dom_document_ready_for_post_load_tasks(active_document):
        return true

    # - element's content navigable's is delaying load events is true; or
    if html_navigable_is_delaying_load_events(content_navigable):
        return true

    # - anything is delaying the load event of element's content navigable's active document.
    if dom_document_anything_is_delaying_the_load_event(active_document):
        return true

    return false

## Ported from NavigableContainer.cpp:404 Web::HTML::NavigableContainer::content_navigable_has_session_history_entry_and_ready_for_navigation.
pub func html_navigable_container_content_navigable_has_session_history_entry_and_ready_for_navigation(this: HtmlNavigableContainer*) -> bool:
    if html_navigable_container_content_navigable_const(this) == none:
        return false
    return html_navigable_has_session_history_entry_and_ready_for_navigation(this.m_content_navigable else trap("unreachable"))

## Ported from NavigableContainer.cpp:411 Web::HTML::NavigableContainer::set_potentially_delays_the_load_event.
pub func html_navigable_container_set_potentially_delays_the_load_event(this: HtmlNavigableContainer*, value: bool):
    this.m_potentially_delays_the_load_event = value
    if not value:
        dom_document_schedule_html_parser_end_check(dom_node_document(this.dom_node()))

## Ported from NavigableContainer.cpp:418 Web::HTML::NavigableContainer::set_content_navigable_has_session_history_entry_and_ready_for_navigation.
pub func html_navigable_container_set_content_navigable_has_session_history_entry_and_ready_for_navigation(this: HtmlNavigableContainer*):
    let content_navigable = html_navigable_container_content_navigable(this) else return
    html_navigable_set_has_session_history_entry_and_ready_for_navigation(content_navigable)
    dom_document_schedule_html_parser_end_check(dom_node_document(this.dom_node()))

# mark: NavigableContainer.h ====================================================================

## Ported from NavigableContainer.h:27 Web::HTML::NavigableContainer::content_navigable.
pub func html_navigable_container_content_navigable(this: HtmlNavigableContainer*) -> HtmlNavigable*?:
    return this.m_content_navigable

## Ported from NavigableContainer.h:28 Web::HTML::NavigableContainer::content_navigable.
pub func html_navigable_container_content_navigable_const(this: HtmlNavigableContainer*) -> HtmlNavigable*?:
    return this.m_content_navigable

## Ported from NavigableContainer.h:67 Web::HTML::NavigableContainer::is_navigable_container (override).
pub func html_navigable_container_is_navigable_container_impl(base: DomNode*) -> bool:
    return true