Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / event_target_2.lucb

#==============================================================================================
#
#   event_target_2 - DOM::EventTarget: event handlers, dispatch_event and the listener queries
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/DOM/EventTarget.cpp (lines 376-890): getting the current value
#       of an event handler, the event handler IDL attribute setter, activating and
#       deactivating an event handler (its listener is a native function, which works before
#       scripting), the event handler processing algorithm, the content attribute change steps,
#       dispatch_event's user activation and the listener queries. Compiling an event handler's
#       uncompiled body and invoking a JS callback are phase 3; ErrorEvent, BeforeUnloadEvent,
#       KeyboardEvent and PointerEvent are outside the phase-1 closure (no event is one yet).
#
#       Copyright (c) 2020-2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Event handler values ====================================================================

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:377 Web::DOM::EventTarget::get_current_value_of_event_handler.
## https://html.spec.whatwg.org/multipage/webappapis.html#getting-the-current-value-of-the-event-handler
pub func dom_event_target_get_current_value_of_event_handler(this: DomEventTarget*, name: ak.FlyString) -> IdlCallbackType*?:
    # 1. Let handlerMap be eventTarget's event handler map. (NOTE: Not necessary)
    let handler_map = &dom_event_target_ensure_data(this).event_handler_map

    # 2. Let eventHandler be handlerMap[name].
    # Optimization: The spec creates all the event handlers exposed on an object up front and has the initial value of the handler set to null.
    #               If the event handler hasn't been set, null would be returned in step 4.
    #               However, this would be very allocation heavy. For example, each DOM::Element includes GlobalEventHandlers, which defines 60+(!) event handler attributes.
    #               Plus, the vast majority of these allocations would be likely wasted, as I imagine web content will only use a handful of these attributes on certain elements, if any at all.
    #               Thus, we treat the event handler not being in the event handler map as being equivalent to an event handler with an initial null value.
    let event_handler = *(ak.hash_map_get_k(handler_map, name) else return none)

    match event_handler.value:
        # 3. If eventHandler's value is an internal raw uncompiled handler, then:
        .byte_string(body):
            # 1. If eventTarget is an element, then let element be eventTarget, and document be element's node document.
            #    Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget's associated Document.
            var document: DomDocument*? = none
            if let element_event_target = as_if_dom_element(this):
                document = dom_node_document(element_event_target.dom_node())
            else:
                let window_event_target = as_html_window(this)
                document = html_window_associated_document(window_event_target)

            let handler_document = document else trap("VERIFY: an event handler without a document")

            # 2. If scripting is disabled for document, then return null.
            if dom_node_is_scripting_disabled(handler_document.dom_node()):
                return none

            # 3. Let body be the uncompiled script body in eventHandler's value.
            # FIXME: 4. Let location be the location where the script body originated, as given by eventHandler's value.
            # 5. If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.
            # 6. Let settings object be the relevant settings object of document.
            # Build source text and parameter strings for the event handler function: "function {name}(event) {\n{body}\n}"
            # (or with "event, source, lineno, colno, error" for onerror on a Window).
            # 7. If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:
            #    1. Set eventHandler's value to null. FIXME: 2. Report the error. 3. Return null.
            # 8. Push settings object's realm execution context onto the JavaScript execution context stack.
            # 9. Let function be the result of calling OrdinaryFunctionCreate, with the scope of the
            #    document, form owner and element object environments.
            # 10. Remove settings object's realm execution context from the JavaScript execution context stack.
            # 11. Set function.[[ScriptOrModule]] to null.
            # 12. Set eventHandler's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object.
            _ = body
            trap("unported (P3): compiling an event handler's uncompiled body (EventTarget::get_current_value_of_event_handler)")
        # 4. Return eventHandler's value.
        .idl_callback_type(callback):
            return callback

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:514 Web::DOM::EventTarget::set_event_handler_attribute.
## https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:event-handler-idl-attributes-3
pub func dom_event_target_set_event_handler_attribute(this: DomEventTarget*, name: ak.FlyString, value: IdlCallbackType*?):
    # 1. Let eventTarget be the result of determining the target of an event handler given this object and name.
    # 2. If eventTarget is null, then return.
    let event_target = dom_determine_target_of_event_handler(this, name) else return

    # 3. If the given value is null, then deactivate an event handler given eventTarget and name.
    if value == none:
        dom_event_target_deactivate_event_handler(event_target, name)
        return
    let callback = value else return

    # 4. Otherwise:
    #  1. Let handlerMap be eventTarget's event handler map.
    let handler_map = &dom_event_target_ensure_data(event_target).event_handler_map

    #  2. Let eventHandler be handlerMap[name].
    #  3. Set eventHandler's value to the given value.
    if let existing = ak.hash_map_get_k(handler_map, name):
        let event_handler = *existing

        event_handler.value = .idl_callback_type(callback)

        #  4. Activate an event handler given eventTarget and name.
        #  NOTE: See the optimization comment above.
        dom_event_target_activate_event_handler(event_target, name, event_handler)
        return

    # NOTE: See the optimization comment in get_current_value_of_event_handler about why this is done.
    let new_event_handler = heap_allocate_html_event_handler_callback_type(gc.cell_heap(this.cell()), callback)

    #  4. Activate an event handler given eventTarget and name.
    # Optimization: We pass in the event handler here instead of having activate_event_handler do another hash map lookup just to get the same object.
    #               This handles a new event handler while the other path handles an existing event handler. As such, both paths must have their own
    #               unique call to activate_event_handler.
    dom_event_target_activate_event_handler(event_target, name, new_event_handler)

    _ = ak.hash_map_set(handler_map, name, new_event_handler)

# mark: Activating event handlers ===============================================================

## The captures of the native function activate_event_handler creates (EventTarget.cpp:582).
## NOTE: The callback must keep `this` alive. For example:
##          document.body.onunload = () => { console.log("onunload called!"); }
##          document.body.remove();
##          location.reload();
##       The body element is no longer in the DOM and there is no variable holding onto it. However, the onunload handler is still called, meaning the callback keeps the body element alive.
struct DomEventTargetActivateEventHandlerCallback:
    var event_target: DomEventTarget*
    var name: ak.FlyString

    static func call(context: void*?, vm: Vm*) -> JsValue!:
        let captures = (DomEventTargetActivateEventHandlerCallback*)(context else trap("activate_event_handler: no captures"))

        # The event dispatcher should only call this with one argument.
        assert(vm_argument_count(vm) == 1)

        # The argument must be an object and it must be an Event.
        let event = as_dom_event((gc.Cell*)js_value_as_object(vm_argument(vm, 0)))

        try dom_event_target_process_event_handler_for_event(captures.event_target, captures.name, event)
        return js_undefined()

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:561 Web::DOM::EventTarget::activate_event_handler.
## https://html.spec.whatwg.org/multipage/webappapis.html#activate-an-event-handler
pub func dom_event_target_activate_event_handler(this: DomEventTarget*, name: ak.FlyString, event_handler: HtmlEventHandler*):
    # 1. Let handlerMap be eventTarget's event handler map.
    # 2. Let eventHandler be handlerMap[name].
    # NOTE: These are achieved by using the passed in event handler.

    # 3. If eventHandler's listener is not null, then return.
    if event_handler.listener != none:
        return

    let realm = bind_platform_object_realm(this.bind_platform_object())

    # 4. Let callback be the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm, given eventTarget, name, and its argument.
    #    The EventListener's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm. [DOM]
    let captures = new DomEventTargetActivateEventHandlerCallback(event_target = this, name = name) else trap("out of memory")
    let callback_function = js_native_function_create(realm, JsNativeFunctionBehaviour(call = DomEventTargetActivateEventHandlerCallback.call, context = captures), 0, ak.utf16_fly_string_new(), realm)

    # NOTE: As per the spec, the callback context is arbitrary.
    # realm.heap().allocate<WebIDL::CallbackType>(*callback_function, realm) (CallbackType's initialize is JS::Cell's, empty).
    let callback = realm_create_idl_callback_type_realm(realm, (JsObject*)callback_function, realm, IdlOperationReturnsPromise.no)

    # 5. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback.
    let listener = heap_allocate_dom_event_listener(realm_heap(realm))
    listener.type_ = name
    listener.callback = dom_idl_event_listener_create(realm, callback)

    # 6. Add an event listener with eventTarget and listener.
    dom_event_target_add_an_event_listener(this, listener)

    # 7. Set eventHandler's listener to listener.
    event_handler.listener = listener

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:609 Web::DOM::EventTarget::deactivate_event_handler.
pub func dom_event_target_deactivate_event_handler(this: DomEventTarget*, name: ak.FlyString):
    # 1. Let handlerMap be eventTarget's event handler map.
    let handler_map = &dom_event_target_ensure_data(this).event_handler_map

    # 2. Let eventHandler be handlerMap[name].
    # NOTE: See the optimization comment in get_current_value_of_event_handler about why this is done.
    let event_handler = *(ak.hash_map_get_k(handler_map, name) else return)

    # 4. Let listener be eventHandler's listener. (NOTE: Not necessary)

    # 5. If listener is not null, then remove an event listener with eventTarget and listener.
    if let listener = event_handler.listener:
        dom_event_target_remove_an_event_listener(this, listener)

    # 6. Set eventHandler's listener to null.
    event_handler.listener = none

    # 3. Set eventHandler's value to null.
    # NOTE: This is done out of order since our equivalent of setting value to null is removing the event handler from the map.
    #       Given that event_handler is a reference to an entry, this would invalidate event_handler if we did it in order.
    _ = ak.hash_map_remove_k(handler_map, name)

# mark: Processing an event handler =============================================================

## is<HTML::ErrorEvent>(event): ErrorEvent is outside the phase-1 closure, so no event is one.
func dom_event_target_is_error_event(event: DomEvent*) -> bool:
    return false

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:640 Web::DOM::EventTarget::process_event_handler_for_event.
## https://html.spec.whatwg.org/multipage/webappapis.html#the-event-handler-processing-algorithm
## Fails with js_exception (a JS::ThrowCompletionOr), the completion stored in the VM.
pub func dom_event_target_process_event_handler_for_event(this: DomEventTarget*, name: ak.FlyString, event: DomEvent*) -> !:
    # 1. Let callback be the result of getting the current value of the event handler given eventTarget and name.
    # 2. If callback is null, then return.
    let callback = dom_event_target_get_current_value_of_event_handler(this, name) else return

    # 3. Let special error event handling be true if event is an ErrorEvent object, event's type is error, and event's currentTarget implements the WindowOrWorkerGlobalScope mixin.
    #    Otherwise, let special error event handling be false.
    var special_error_event_handling = false
    if dom_event_target_is_error_event(event) and ak.fly_string_eq_fly_string(&event.m_type, &html_event_names_error):
        if let current_target = dom_event_current_target(event):
            special_error_event_handling = as_if_window_or_worker_global_scope_mixin(current_target) != none

    # 4. Process the Event object event as follows:
    var return_value_or_error: JsCompletion

    if special_error_event_handling:
        # -> If special error event handling is true
        #    Invoke callback with five arguments, the first one having the value of event's message attribute, the second having the value of event's filename attribute, the third having the value of event's lineno attribute,
        #    the fourth having the value of event's colno attribute, the fifth having the value of event's error attribute, and with the callback this value set to event's currentTarget.
        #    Let return value be the callback's return value. [WEBIDL]
        trap("unported: HTML::ErrorEvent (outside the phase-1 closure)")
    else:
        # -> Otherwise
        # Invoke callback with one argument, the value of which is the Event object event, with the callback this value set to event's currentTarget. Let return value be the callback's return value. [WEBIDL]

        # FIXME: This has the same rewrapping issue as this_value.
        let wrapped_event = js_value_from_object((JsObject*)event)

        # FIXME: The comments about this in the special_error_event_handling path also apply here.
        let this_value = js_value_from_object((JsObject*?)dom_event_current_target(event))

        let arguments: JsValue[1] = [wrapped_event]
        return_value_or_error = idl_invoke_callback_span_js_value(callback, this_value, arguments)

    # If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic, which will then report the exception.)
    if js_completion_is_error(&return_value_or_error):
        vm_set_pending_exception(js_cell_vm(this.js_cell()), .js_completion(js_completion_release_error(&return_value_or_error)))
        error(js_exception, "")

    # FIXME: Ideally, invoke_callback would convert JS::Value to the appropriate return type for us as per the spec, but it doesn't currently.
    let return_value = js_completion_value(&return_value_or_error)

    let is_beforeunload = ak.fly_string_eq_fly_string(&event.m_type, &html_event_names_beforeunload)

    # 5. Process return value as follows:
    if is_html_before_unload_event(event) and is_beforeunload:
        # ->  If event is a BeforeUnloadEvent object and event's type is "beforeunload"
        #         If return value is not null, then:
        if not js_value_is_nullish(return_value):
            # 1. Set event's canceled flag.
            dom_event_set_cancelled(event, true)

            # 2. If event's returnValue attribute's value is the empty string, then set event's returnValue attribute's value to return value.
            let before_unload_event = (HtmlBeforeUnloadEvent*)event
            let current_return_value = html_before_unload_event_return_value(before_unload_event)
            if ak.string_is_empty(&current_return_value):
                html_before_unload_event_set_return_value(before_unload_event, try js_value_to_string(return_value, js_cell_vm(this.js_cell())))

    if special_error_event_handling:
        # -> If special error event handling is true
        #      If return value is true, then set event's canceled flag.
        # NB: the return type of EventHandler is `any`, so no coercion happens, meaning we have to check if it's a
        #     boolean first.
        if js_value_is_boolean(return_value) and js_value_as_bool(return_value):
            dom_event_set_cancelled(event, true)
    else:
        # -> Otherwise
        #      If return value is false, then set event's canceled flag.
        # NB: the return type of EventHandler is `any`, so no coercion happens, meaning we have to check if it's a
        #     boolean first.
        # NOTE: If we've gotten to this "Otherwise" clause because event's type is "beforeunload" but event is not a
        #       BeforeUnloadEvent object, then return value will never be false, since in such cases return value will
        #       have been coerced into either null or a DOMString.
        if js_value_is_boolean(return_value) and not js_value_as_bool(return_value) and not is_beforeunload:
            dom_event_set_cancelled(event, true)

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:735 Web::DOM::EventTarget::element_event_handler_attribute_changed.
## https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes:concept-element-attributes-change-ext
pub func dom_event_target_element_event_handler_attribute_changed(this: DomEventTarget*, local_name: ak.FlyString, value: ak.String?):
    # NOTE: Step 1 of this algorithm was handled in HTMLElement::attribute_changed.

    # 2. Let eventTarget be the result of determining the target of an event handler given element and localName.
    # NOTE: element is `this`.
    # 3. If eventTarget is null, then return.
    let event_target = dom_determine_target_of_event_handler(this, local_name) else return

    # 4. If value is null, then deactivate an event handler given eventTarget and localName.
    if value == none:
        dom_event_target_deactivate_event_handler(event_target, local_name)
        return
    let source = value else return

    # 5. Otherwise:
    #  1. If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon element, "script attribute", and value, then return. [CSP]
    let this_as_element = as_dom_element(this)
    if content_security_policy_should_elements_inline_type_behavior_be_blocked_by_content_security_policy(bind_platform_object_realm(this.bind_platform_object()), this_as_element, ContentSecurityPolicyInlineType.script_attribute, source) == ContentSecurityPolicyResult.blocked:
        ak.dbgln("EventTarget: Refusing to add inline event handler as it violates the Content Security Policy.")
        return

    #  2. Let handlerMap be eventTarget's event handler map.
    let handler_map = &dom_event_target_ensure_data(event_target).event_handler_map

    #  3. Let eventHandler be handlerMap[localName].
    #  FIXME: 4. Let location be the script location that triggered the execution of these steps.

    #  FIXME: 5. Set eventHandler's value to the internal raw uncompiled handler value/location.
    #            (This currently sets the value to the uncompiled source code instead of the named struct)

    # NOTE: See the optimization comments in set_event_handler_attribute.

    if let existing = ak.hash_map_get_k(handler_map, local_name):
        let event_handler = *existing

        #  6. Activate an event handler given eventTarget and name.
        event_handler.value = .byte_string(ak.string_to_byte_string(&source))
        dom_event_target_activate_event_handler(event_target, local_name, event_handler)
        return

    let new_event_handler = heap_allocate_html_event_handler_byte_string(gc.cell_heap(this.cell()), ak.string_to_byte_string(&source))

    #  6. Activate an event handler given eventTarget and name.
    dom_event_target_activate_event_handler(event_target, local_name, new_event_handler)

    _ = ak.hash_map_set(handler_map, local_name, new_event_handler)

# mark: Dispatching =============================================================================

## The `is_activation_triggering_input_event` lambda of EventTarget::dispatch_event (EventTarget.cpp:794).
## https://html.spec.whatwg.org/multipage/interaction.html#activation-triggering-input-event
func dom_event_target_is_activation_triggering_input_event(event: DomEvent*) -> bool:
    # An activation triggering input event is any event whose isTrusted attribute is true and whose type is one of:
    if not dom_event_is_trusted(event):
        return false

    # keydown, provided the key is neither the Esc key nor a shortcut key reserved by the user agent.
    if ak.fly_string_eq_fly_string(&event.m_type, &ui_events_event_names_keydown):
        return ui_events_keyboard_event_key_code((UiEventsKeyboardEvent*)event) != ui_events_key_code_value(UiEventsKeyCode.key_escape)

    # mousedown.
    if ak.fly_string_eq_fly_string(&event.m_type, &ui_events_event_names_mousedown):
        return true

    # pointerdown, provided the event's pointerType is "mouse".
    if ak.fly_string_eq_fly_string(&event.m_type, &ui_events_event_names_pointerdown):
        # as_if<UIEvents::PointerEvent>(&event) (Event::fast_is<PointerEvent> is is_pointer_event())
        if dom_event_is_pointer_event(event):
            return ak.string_eq_string_view(&((UiEventsPointerEvent*)event).m_pointer_type, ak.sv("mouse"))

    # pointerup, provided the event's pointerType is not "mouse".
    if ak.fly_string_eq_fly_string(&event.m_type, &ui_events_event_names_pointerup):
        if dom_event_is_pointer_event(event):
            return not ak.string_eq_string_view(&((UiEventsPointerEvent*)event).m_pointer_type, ak.sv("mouse"))

    # FIXME: touchend

    return false

## The window of the activation notification in EventTarget::dispatch_event (EventTarget.cpp:842).
func dom_event_target_activation_window(this: DomEventTarget*) -> HtmlWindow*?:
    if is_html_window(this):
        return (HtmlWindow*)this

    if let element = as_if_dom_element(this):
        return dom_document_window(dom_node_document(element.dom_node()))

    if let document = as_if_dom_document(this):
        return dom_document_window(document)

    return none

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:791 Web::DOM::EventTarget::dispatch_event (virtual).
pub func dom_event_target_dispatch_event_impl(this: DomEventTarget*, event: DomEvent*) -> bool:
    # https://html.spec.whatwg.org/multipage/interaction.html#user-activation-processing-model
    # When a user interaction causes firing of an activation triggering input event in a Document document,
    # the user agent must perform the following activation notification steps before dispatching the event:

    # FIXME: 1. Assert: document is fully active.
    # FIXME: 2. Let windows be « document's relevant global object ».
    # FIXME: 3. Extend windows with the active window of each of document's ancestor navigables.
    # FIXME: 4. Extend windows with the active window of each of document's descendant navigables,
    #           filtered to include only those navigables whose active document's origin is same origin with document's origin.
    # FIXME: 5. For each window in windows:
    # FIXME: 5.1 Set window's last activation timestamp to the current high resolution time.
    # FIXME: 5.2 Notify the close watcher manager about user activation given window.

    # FIXME: This is ad-hoc, but works for now.
    if dom_event_target_is_activation_triggering_input_event(event):
        let unsafe_shared_time = high_resolution_time_unsafe_shared_current_time()
        let current_time = high_resolution_time_relative_high_resolution_time(unsafe_shared_time, realm_global_object(bind_platform_object_realm(this.bind_platform_object())))

        if let window = dom_event_target_activation_window(this):
            html_window_set_last_activation_timestamp(window, current_time)
            html_close_watcher_manager_notify_about_user_activation(html_window_close_watcher_manager(window))

    return dom_event_dispatcher_dispatch(this, event)

# mark: Listener queries and data ===============================================================

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:864 Web::DOM::EventTarget::has_event_listener.
pub func dom_event_target_has_event_listener(this: DomEventTarget*, type_: ak.FlyString) -> bool:
    let data = this.m_data else return false
    for listener in ak.vector_span(&data.event_listener_list):
        if ak.fly_string_eq_fly_string(&listener.type_, &type_):
            return true
    return false

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:869 Web::DOM::EventTarget::has_event_listeners.
pub func dom_event_target_has_event_listeners(this: DomEventTarget*) -> bool:
    let data = this.m_data else return false
    return not ak.vector_is_empty(&data.event_listener_list)

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:874 Web::DOM::EventTarget::has_activation_behavior (virtual).
pub func dom_event_target_has_activation_behavior_impl(this: DomEventTarget*) -> bool:
    return false

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:879 Web::DOM::EventTarget::activation_behavior (virtual).
pub func dom_event_target_activation_behavior_impl(this: DomEventTarget*, arg0: DomEvent*):
    return

## Ported from Libraries/LibWeb/DOM/EventTarget.cpp:883 Web::DOM::EventTarget::ensure_data: the
## Data (an OwnPtr) is managed memory the target's bytes point to.
pub func dom_event_target_ensure_data(this: DomEventTarget*) -> DomEventTargetData*:
    if let data = this.m_data:
        return data
    let data = new DomEventTargetData else trap("out of memory")
    this.m_data = data
    return data