Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / docs / regions / r19.md

# Region r19: DOM events (Event, EventTarget, EventDispatcher, AbortSignal, ...) — what other regions need to know

Region r19 ports `DOM::Event`, `DOM::EventTarget`, `DOM::EventDispatcher`, `DOM::CustomEvent`,
`DOM::DOMEventListener`, `DOM::IDLEventListener`, `DOM::AbortSignal` and `DOM::AbortController`.
The stub fragment `stubs/stub_r19_dom_events.lucb` is gone; every one of its functions is ported.
To make native (C++-side) listeners and the dispatch algorithm work before scripting, it also
ports the pieces of LibJS, HTML and HighResolutionTime they call that no region owned.

## Fragments

| Fragment | Donor |
| --- | --- |
| `dom/abort_controller` | `AbortController.cpp/.h` |
| `dom/abort_signal` | `AbortSignal.cpp/.h` |
| `dom/custom_event` | `CustomEvent.cpp/.h` (+ `dom_custom_event_init_default`, `CustomEventInit {}`) |
| `dom/dom_event_listener` | `DOMEventListener.cpp/.h` (+ `heap_allocate_dom_event_listener`) |
| `dom/event` | `Event.cpp/.h` |
| `dom/event_dispatcher` | `EventDispatcher.cpp/.h` |
| `dom/event_target_1` | `EventTarget.cpp` 51-375 and `EventTarget.h`: construction, listeners, dispatchEvent(), handler targets |
| `dom/event_target_2` | `EventTarget.cpp` 376-890: event handler values, (de)activation, processing, attribute changes, dispatch_event, queries |
| `dom/idl_event_listener` | `IDLEventListener.cpp/.h` |
| `external/lib_js/native_function` | LibJS: `NativeFunction::create`/`[[Call]]`/`call` (CapturingNativeFunction folded in), `JS::call`, `VM::argument(_count)`/`this_value`, `Completion`, `throw_completion`, `Object::is_function`, `shape().realm()` |
| `html/event_handler` | `HTML/EventHandler.cpp/.h` (was outside the phase-1 closure) |
| `high_resolution_time/time_origin` | `HighResolutionTime/TimeOrigin.cpp/.h` (was outside the closure) |
| `ui_events/event_names` | `UIEvents/EventNames.cpp/.h` (was outside the closure) |
| `dom/tests_events` | 26 tests (Ladybird has no unit tests for these files) |

## What other regions must know

### Creating nodes and other event targets

- `dom_event_target_construct(this, realm)` is the base constructor of every node; Node's
  constructor (r15) already calls it, so `realm_create_*` of any node class reaches its own
  constructor body. `dom_event_target_initialize_impl` is the Base::initialize of every node and
  event target class; `dom_event_target_visit_edges_impl` calls
  `bind_platform_object_visit_edges_impl` and visits the listener list and handler map.
- `heap.allocate<DOMEventListener>()` is `heap_allocate_dom_event_listener(heap)`;
  `heap.allocate<HTML::EventHandler>(...)` is `heap_allocate_html_event_handler_byte_string` /
  `_callback_type`.

### Native listeners (C++ lambdas listening to events)

The C++ pattern `JS::NativeFunction::create(realm, [captures](JS::VM& vm) {...}, 0, {}, &realm)`
→ `heap.allocate<WebIDL::CallbackType>(function, realm)` → `IDLEventListener::create(realm, callback)`
→ `add_event_listener(_without_options)` is:

```luce
struct MyListenerCaptures:            # the lambda's captures, allocated with `new` (they escape)
    var this: HtmlFoo*
    static func call(context: void*?, vm: Vm*) -> JsValue!:
        let captures = (MyListenerCaptures*)(context else trap("no captures"))
        let event = as_dom_event((gc.Cell*)js_value_as_object(vm_argument(vm, 0)))   # vm.argument(0).as<Event>()
        ...
        return js_undefined()

let function = js_native_function_create(realm, JsNativeFunctionBehaviour(call = MyListenerCaptures.call, context = captures), 0, ak.utf16_fly_string_new(), realm)
let callback = realm_create_idl_callback_type_realm(realm, (JsObject*)function, realm, IdlOperationReturnsPromise.no)
dom_event_target_add_event_listener_without_options(target, name, dom_idl_event_listener_create(realm, callback))
```

`JsNativeFunctionBehaviour` is `{ call: (func(void*?, Vm*) -> JsValue!)?, context: void*? }` (a
non-fallible `-> JsValue` function converts). The function is a cell (class `js_native_function_class`,
sharing JS::Cell's class id; `is_js_native_function` tests the ClassInfo); its captures are
scanned conservatively. `WebIDL::call_user_object_operation` now calls a callable object through
`js_call` (the steps that `Get(O, "handleEvent")` on a callback interface object trap P3), so a
native listener runs as soon as r29's `principal_realm_settings_object`, `prepare_to_run_script`,
`prepare_to_run_callback` and the two clean-ups are ported.

### JS values, completions (phase-1 forms; DESIGN.md §2.10, §3.6)

- `JS::Value(Object*)` is `js_value_from_object(object)` (an object-tagged pointer to the cell, as
  LibJS encodes it; `none` gives null) and `value.as_object()` is `js_value_as_object`. Platform
  objects pass as `(JsObject*)cell` (r15's convention). Phase 3 maps a platform object to its
  wrapper inside these two functions. Visit a `JsValue` field with `js_visit_value(visitor, v)`.
  `js_value_is_null`, `js_value_is_nullish`, `js_value_as_bool` were added.
- `JsCompletion` is filled (`m_type: JsCompletionType`, `m_value`): `js_completion_create`,
  `_from_value`, `_type`, `_value`, `_is_abrupt`, `_is_error`, `_release_error`,
  `js_throw_completion(value)`. A failed `T!` (js_exception or webidl_exception) becomes a JS
  completion with `vm_take_throw_completion(vm)`. The pending-exception cell visits a JS
  completion's value. `Web::throw_completion(DOMException)` (r14) is now implemented, and r16's
  closure stubs `js_completion_release_value` and `js_take_pending_exception_value` are too.
- `JsExecutionContext` gained `this_value` and `arguments` (the VM roots and visits them):
  `vm_argument`, `vm_argument_count`, `vm_this_value`.

### Signature and type changes

- **Types filled**: `DomEventPathEntry`, `DomEventTargetData` (`event_listener_list:
  ak.Vector[DomEventListener*]`, `event_handler_map: ak.HashMap[ak.FlyString, HtmlEventHandler*,
  ak.FlyStringTraits]`), `HtmlEventHandler` (a cell, + `ByteStringOrIdlCallbackType`),
  `JsNativeFunction`, `JsCompletion` (+ `JsCompletionType`), `JsExecutionContext` (see above);
  the `init_fields` of AbortSignal (`m_abort_reason` undefined) and CustomEvent(Init) (`detail`
  null), which the constructors call. New enums `ContentSecurityPolicyResult`,
  `ContentSecurityPolicyInlineType` (`types_directive.lucb`).
- This region's functions: `dom_event_create(realm, name, event_init = DomEventInit())` (C++
  default); `dom_event_path_const` answers `const ak.Vector[DomEventPathEntry]*` (was a copy);
  `dom_event_dispatcher_invoke`/`inner_invoke` and the anonymous-namespace helpers
  (`dom_flatten_*`, `dom_default_passive_value`, `dom_is_window_event_handler`,
  `dom_determine_target_of_event_handler`) are private.
- **r16's** `js_native_function_create` closure stub (taking `ak.Function1[Vm*, JsValue]`) is
  replaced by the real function; element_9's call site passes a `JsNativeFunctionBehaviour`.
- **r14's** `idl_call_user_object_operation` and `idl_clean_up_on_return` are ported up to their
  JS-only steps (Get on a callback interface object; the rejected promise).
- **Closure stubs added** (`stubs/stub_closure.lucb`, namemap rows):
  `html_window_or_worker_global_scope_mixin_run_steps_after_a_timeout`,
  `html_close_watcher_manager_notify_about_user_activation`,
  `content_security_policy_should_elements_inline_type_behavior_be_blocked_by_content_security_policy`
  (r16 had already added `..._report_an_exception`).
- `web_initialize_strings` runs `ui_events_event_names_initialize_strings`.

## Deviations and what is not ported yet

- **Blocked on other regions** (runtime traps until they land): creating an Event through
  `realm.create` (the time stamp needs r29's `relevant_global_object` and
  `relevant_settings_object`), dispatching (r18's `retarget`, `is_an_assigned_slottable`; r17's
  `Document::window` when no ancestor listens), calling any listener (r29), and therefore
  `signal_abort` (it fires `abort`) and `AbortController::abort`. The HTML event names
  (`html_event_names_*`) are zero until r22 interns them.
- **Phase 3**: compiling an event handler's uncompiled body (`get_current_value_of_event_handler`
  returns null when scripting is disabled, as in P1; otherwise traps), invoking a JS callback
  (`process_event_handler_for_event` goes through r14's `invoke_callback`), Event's unforgeable
  `isTrusted`, the JS prototype of IDLEventListener and NativeFunction, `length`/`name`.
- **Outside the phase-1 closure** (no instance can exist, so the C++ type tests are `false`):
  `is<HTML::ErrorEvent>` and `is<HTML::BeforeUnloadEvent>` in the event handler processing
  algorithm (private helpers; their branches trap); a trusted `keydown` or a PointerEvent in
  `dispatch_event`'s activation check traps P4 (KeyboardEvent/PointerEvent types).
  `is<UIEvents::MouseEvent>` is `Event::is_mouse_event()`, as C++'s `fast_is`.
- composedPath()'s hidden levels wrap below zero as C++'s `size_t` does (`+%`/`-%`).
- The touch-target loop of dispatch step 11 treats a null entry as "not a node" (C++ dereferences).
- WEB_PLATFORM_OBJECT's `interface_name`/`implements_interface` are not added for these classes.

## Tests

`dom/tests_events.lucb` (26 tests): EventTarget made by `new EventTarget()` and as the base of
nodes made in a realm (Node's constructor + EventTarget's initialize); addEventListener's
de-duplication, options, default passive value and removal; abort signals on listeners;
dispatchEvent()'s InvalidStateErrors; the event handler map; the Window handler sets; Event's
flags, preventDefault/returnValue/cancelBubble/stopImmediatePropagation, initEvent; the event
path and composedPath() across a closed shadow root; CustomEvent; inner invoke's filtering and
invoke's target/relatedTarget/touch list; AbortSignal's algorithms, throwIfAborted, abort(),
any() and dependent signals; AbortController; `JS::call` of a native function (arguments,
this, realm, failure, the context stack); completions; object values; GC (listeners and their
native functions, an abort reason held only as a JS value); coarsen time; the UI event names.
Once r18 and r29 land, add scenario tests: dispatch to a native listener on a node tree
(capture, target, bubble, once, passive, stopPropagation), signal_abort firing `abort`, event
handler attributes (set_event_handler_attribute → native listener → process_event_handler).