Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / navigate_event.lucb

#==============================================================================================
#
#   navigate_event - HTML::NavigateEvent, NavigationDestination, ErrorEvent and
#   extract_error_information
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/NavigateEvent.cpp (lines 1-297) without the JS-facing
#       intercept() and scroll() methods and their shared checks (phase 3: only a script's
#       intercept() moves an event's interception state off "none"), NavigationDestination.cpp
#       (lines 1-94, its JS getters excepted), ErrorEvent.cpp (lines 1-50) and
#       ErrorInformation.cpp (lines 14-70) for the values a page without script makes: a
#       DOMException, whose message is an accessor of its prototype (not an own property), so
#       the message is "Uncaught exception: " and the value as JS::Value's formatter writes an
#       object, and whose error data has no traceback before script runs.
#
#       Copyright (c) 2023, Andrew Kaster <akaster@serenityos.org>
#       Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: NavigationDestination ===================================================================

## Ported from NavigationDestination.cpp:17 Web::HTML::NavigationDestination::create.
pub func html_navigation_destination_create(realm: Realm*) -> HtmlNavigationDestination*:
    return realm_create_html_navigation_destination(realm, realm)

## Ported from NavigationDestination.cpp:22 Web::HTML::NavigationDestination::NavigationDestination.
pub func html_navigation_destination_construct(this: HtmlNavigationDestination*, realm: Realm*):
    bind_platform_object_construct_realm(this.bind_platform_object(), realm)

## Ported from NavigationDestination.cpp:29 Web::HTML::NavigationDestination::initialize (override).
pub func html_navigation_destination_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.navigation_destination)
    js_cell_initialize_impl(base, realm)

## Ported from NavigationDestination.cpp:35 Web::HTML::NavigationDestination::visit_edges (override).
pub func html_navigation_destination_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigationDestination*)base
    bind_platform_object_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_entry)

## Ported from NavigationDestination.h:32 Web::HTML::NavigationDestination::navigation_history_entry.
pub func html_navigation_destination_navigation_history_entry(this: HtmlNavigationDestination*) -> HtmlNavigationHistoryEntry*?:
    return this.m_entry

## Ported from NavigationDestination.h:35 Web::HTML::NavigationDestination::set_url.
pub func html_navigation_destination_set_url(this: HtmlNavigationDestination*, url: web_url.Url):
    this.m_url = url

## Ported from NavigationDestination.h:36 Web::HTML::NavigationDestination::set_entry.
pub func html_navigation_destination_set_entry(this: HtmlNavigationDestination*, entry: HtmlNavigationHistoryEntry*?):
    this.m_entry = entry

## Ported from NavigationDestination.h:37 Web::HTML::NavigationDestination::set_state.
pub func html_navigation_destination_set_state(this: HtmlNavigationDestination*, state: ak.Vector[u8]):
    this.m_state = state

## Ported from NavigationDestination.h:38 Web::HTML::NavigationDestination::set_is_same_document.
pub func html_navigation_destination_set_is_same_document(this: HtmlNavigationDestination*, b: bool):
    this.m_is_same_document = b

## Ported from NavigationDestination.cpp:72 Web::HTML::NavigationDestination::same_document.
pub func html_navigation_destination_same_document(this: HtmlNavigationDestination*) -> bool:
    # The sameDocument getter steps are to return this's is same document.
    return this.m_is_same_document

## Ported from NavigationDestination.h:42 Web::HTML::NavigationDestination::raw_url.
pub func html_navigation_destination_raw_url(this: HtmlNavigationDestination*) -> web_url.Url:
    return this.m_url

# mark: NavigateEvent ===========================================================================

## Ported from NavigateEvent.cpp:22 Web::HTML::NavigateEvent::create.
pub func html_navigate_event_create(realm: Realm*, event_name: ak.FlyString, event_init: HtmlNavigateEventInit) -> HtmlNavigateEvent*:
    let event = realm_create_html_navigate_event(realm, realm, event_name, event_init)
    dom_event_set_is_trusted(event.dom_event(), true)
    return event

## Ported from NavigateEvent.cpp:34 Web::HTML::NavigateEvent::NavigateEvent.
pub func html_navigate_event_construct(this: HtmlNavigateEvent*, realm: Realm*, event_name: ak.FlyString, event_init: HtmlNavigateEventInit):
    dom_event_construct_dom_event_init(this.dom_event(), realm, event_name, event_init.event_init)
    this.m_interception_state = HtmlNavigateEventInterceptionState.none_
    this.m_navigation_type = event_init.navigation_type
    this.m_destination = event_init.destination else trap("VERIFY: *event_init.destination")
    this.m_can_intercept = event_init.can_intercept
    this.m_user_initiated = event_init.user_initiated
    this.m_hash_change = event_init.hash_change
    this.m_signal = event_init.signal else trap("VERIFY: *event_init.signal")
    this.m_form_data = event_init.form_data
    this.m_download_request = event_init.download_request
    this.m_info = event_init.info else js_undefined()
    this.m_has_ua_visual_transition = event_init.has_ua_visual_transition
    this.m_source_element = event_init.source_element

## Ported from NavigateEvent.cpp:51 Web::HTML::NavigateEvent::initialize (override).
pub func html_navigate_event_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.navigate_event)
    dom_event_initialize_impl(base, realm)

## Ported from NavigateEvent.cpp:57 Web::HTML::NavigateEvent::visit_edges (override).
pub func html_navigate_event_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigateEvent*)base
    dom_event_visit_edges_impl(base, visitor)
    for handler in ak.vector_span(&this.m_navigation_handler_list):
        gc.cell_visitor_visit_t(visitor, handler)
    gc.cell_visitor_visit_t(visitor, this.m_abort_controller)
    gc.cell_visitor_visit_t(visitor, this.m_destination)
    gc.cell_visitor_visit_t(visitor, this.m_signal)
    # (XHR::FormData is opaque before phase 3: a cell by its header.)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_form_data)
    js_visit_value(visitor, this.m_info)
    gc.cell_visitor_visit_t(visitor, this.m_source_element)

## Ported from NavigateEvent.h:79 Web::HTML::NavigateEvent::abort_controller.
pub func html_navigate_event_abort_controller(this: HtmlNavigateEvent*) -> DomAbortController*:
    return this.m_abort_controller else trap("VERIFY: *m_abort_controller")

## Ported from NavigateEvent.cpp:202 Web::HTML::NavigateEvent::process_scroll_behavior.
## https://html.spec.whatwg.org/multipage/nav-history-apis.html#process-scroll-behavior
func html_navigate_event_process_scroll_behavior(this: HtmlNavigateEvent*):
    # To process scroll behavior given a NavigateEvent event:

    # 1. Assert: event's interception state is "committed".
    assert(this.m_interception_state == HtmlNavigateEventInterceptionState.committed)

    # 2. Set event's interception state to "scrolled".
    this.m_interception_state = HtmlNavigateEventInterceptionState.scrolled

    # FIXME: 3. If event's navigationType was initialized to "traverse" or "reload", then restore scroll position data
    #           given event's relevant global object's navigable's active session history entry.
    if this.m_navigation_type == BindNavigationType.traverse or this.m_navigation_type == BindNavigationType.reload:
        ak.dbgln("FIXME: restore scroll position data after traversal or reload navigation")
    else:
        # 4. Otherwise:
        # 1. Let document be event's relevant global object's associated Document.
        let document = html_window_associated_document((HtmlWindow*)html_relevant_global_object((JsObject*)this))

        # 2. If document's indicated part is null, then scroll to the beginning of the document given document. [CSSOMVIEW]
        var indicated_part_is_null = false
        match dom_document_determine_the_indicated_part(document):
            .dom_element(element):
                indicated_part_is_null = element == none
            _:
                indicated_part_is_null = false
        if indicated_part_is_null:
            dom_document_scroll_to_the_beginning_of_the_document(document)
        else:
            # 3. Otherwise, scroll to the fragment given document.
            # FIXME: This will re-determine the indicated part. Can we avoid this extra work?
            dom_document_scroll_to_the_fragment(document)

## Ported from NavigateEvent.cpp:234 Web::HTML::NavigateEvent::potentially_process_scroll_behavior.
## https://html.spec.whatwg.org/multipage/nav-history-apis.html#potentially-process-scroll-behavior
func html_navigate_event_potentially_process_scroll_behavior(this: HtmlNavigateEvent*):
    # 1. Assert: event's interception state is "committed" or "scrolled".
    assert(this.m_interception_state == HtmlNavigateEventInterceptionState.committed or this.m_interception_state == HtmlNavigateEventInterceptionState.scrolled)

    # 2. If event's interception state is "scrolled", then return.
    if this.m_interception_state == HtmlNavigateEventInterceptionState.scrolled:
        return

    # 3. If event's scroll behavior is "manual", then return.
    # NOTE: If it was left as null, then we treat that as "after-transition", and continue onward.
    if this.m_scroll_behavior == BindNavigationScrollBehavior.manual:
        return

    # 4. Process scroll behavior given event.
    html_navigate_event_process_scroll_behavior(this)

## Ported from NavigateEvent.cpp:252 Web::HTML::NavigateEvent::potentially_reset_the_focus.
## https://html.spec.whatwg.org/multipage/nav-history-apis.html#potentially-reset-the-focus
func html_navigate_event_potentially_reset_the_focus(this: HtmlNavigateEvent*):
    # 1. Assert: event's interception state is "committed" or "scrolled".
    assert(this.m_interception_state == HtmlNavigateEventInterceptionState.committed or this.m_interception_state == HtmlNavigateEventInterceptionState.scrolled)

    # 2. Let navigation be event's relevant global object's navigation API.
    let relevant_global_object = (HtmlWindow*)html_relevant_global_object((JsObject*)this)
    let navigation = html_window_navigation(relevant_global_object)

    # 3. Let focusChanged be navigation's focus changed during ongoing navigation.
    let focus_changed = html_navigation_focus_changed_during_ongoing_navigation(navigation)

    # 4. Set navigation's focus changed during ongoing navigation to false.
    html_navigation_set_focus_changed_during_ongoing_navigation(navigation, false)

    # 5. If focusChanged is true, then return.
    if focus_changed:
        return

    # 6. If event's focus reset behavior is "manual", then return.
    # NOTE: If it was left as null, then we treat that as "after-transition", and continue onward.
    if this.m_focus_reset_behavior == BindNavigationFocusReset.manual:
        return

    # 7. Let document be event's relevant global object's associated Document.
    let document = html_window_associated_document(relevant_global_object)

    # 8. FIXME: Let focusTarget be the autofocus delegate for document.
    var focus_target: DomNode*? = none

    # 9. If focusTarget is null, then set focusTarget to document's body element.
    if focus_target == none:
        if let body = dom_document_body(document):
            focus_target = body.dom_node()

    # 10. If focusTarget is null, then set focusTarget to document's document element.
    if focus_target == none:
        if let element = dom_document_document_element(document):
            focus_target = element.dom_node()

    # FIXME: 11. Run the focusing steps for focusTarget, with document's viewport as the fallback target.
    html_run_focusing_steps(focus_target, none)

    # FIXME: 12. Move the sequential focus navigation starting point to focusTarget.

## Ported from NavigateEvent.cpp:278 Web::HTML::NavigateEvent::finish.
## https://html.spec.whatwg.org/multipage/nav-history-apis.html#navigateevent-finish
pub func html_navigate_event_finish(this: HtmlNavigateEvent*, did_fulfill: bool):
    # 1. Assert: event's interception state is not "intercepted" or "finished".
    assert(this.m_interception_state != HtmlNavigateEventInterceptionState.intercepted and this.m_interception_state != HtmlNavigateEventInterceptionState.finished)

    # 2. If event's interception state is "none", then return.
    if this.m_interception_state == HtmlNavigateEventInterceptionState.none_:
        return

    # 3. Potentially reset the focus given event.
    html_navigate_event_potentially_reset_the_focus(this)

    # 4. If didFulfill is true, then potentially process scroll behavior given event.
    if did_fulfill:
        html_navigate_event_potentially_process_scroll_behavior(this)

    # 5. Set event's interception state to "finished".
    this.m_interception_state = HtmlNavigateEventInterceptionState.finished

# mark: ErrorEvent ==============================================================================

## `ErrorEventInit {}`: the dictionary with its defaults (error undefined).
pub func html_error_event_init_default() -> HtmlErrorEventInit:
    return HtmlErrorEventInit(event_init = DomEventInit(), message = ak.string_new(), filename = ak.string_new(), lineno = 0, colno = 0, error_ = js_undefined())

## Ported from ErrorEvent.cpp:16 Web::HTML::ErrorEvent::create.
pub func html_error_event_create(realm: Realm*, event_name: ak.FlyString, event_init: HtmlErrorEventInit) -> HtmlErrorEvent*:
    return realm_create_html_error_event(realm, realm, event_name, event_init)

## Ported from ErrorEvent.cpp:26 Web::HTML::ErrorEvent::ErrorEvent.
pub func html_error_event_construct(this: HtmlErrorEvent*, realm: Realm*, event_name: ak.FlyString, event_init: HtmlErrorEventInit):
    dom_event_construct_dom_event_init(this.dom_event(), realm, event_name, event_init.event_init)
    this.m_message = event_init.message
    this.m_filename = event_init.filename
    this.m_lineno = event_init.lineno
    this.m_colno = event_init.colno
    this.m_error = event_init.error_

## Ported from ErrorEvent.cpp:38 Web::HTML::ErrorEvent::initialize (override).
pub func html_error_event_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.error_event)
    dom_event_initialize_impl(base, realm)

## Ported from ErrorEvent.cpp:44 Web::HTML::ErrorEvent::visit_edges (override).
pub func html_error_event_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlErrorEvent*)base
    dom_event_visit_edges_impl(base, visitor)
    js_visit_value(visitor, this.m_error)

## Ported from ErrorInformation.cpp:14 Web::HTML::extract_error_information, for a DOMException (see
## the header); any other value is phase 3.
pub func html_extract_error_information(vm: Vm*, exception: JsValue) -> HtmlErrorInformation:
    # 1. Let attributes be an empty map keyed by IDL attributes.
    # 2. Set attributes[error] to exception.
    var attributes = HtmlErrorInformation(message = ak.string_new(), filename = ak.string_new(), error_ = exception, lineno = 0, colno = 0)

    # 3. Set attributes[message], attributes[filename], attributes[lineno], and attributes[colno] to
    #    implementation-defined values derived from exception.
    if not js_value_is_object(exception):
        trap("unported (P3): HTML::extract_error_information of a primitive value (JS::Value formatting)")
    let object = js_value_as_object(exception)
    if as_if_idl_dom_exception((gc.Cell*)object) == none:
        trap("unported (P3): HTML::extract_error_information of a JS object (get_without_side_effects, the error data's traceback)")
    # A DOMException's message is an accessor of its prototype, not an own property, so the message is
    # `String::formatted("Uncaught exception: {}", exception)`, an object formatted as "[object ClassName]".
    var builder = ak.string_builder_new()
    ak.string_builder_append(&builder, "Uncaught exception: [object DOMException]")
    attributes.message = ak.string_builder_to_string(&builder) else trap("MUST: String::formatted")

    # NB: If we got an Error object, then try and extract the information from the location the object was made.
    # (A DOMException is its own ErrorData; its traceback holds the frames of the script that made it, none before
    # phase 3, so no frame names a location.)
    _ = vm

    # 4. Return attributes.
    return attributes