dymokomi/luce-browser-engine
Source of release 0.6.0
0.6.0 / docs / regions / r17.md
# Region r17: DOM::Document and DocumentLoading — what other regions need to know
Region r17 ports `DOM::Document` (`Document.cpp`, 8,270 lines, and the inline functions of
`Document.h`), `DOM/DocumentLoading.cpp/.h` and the `DOM::Document` methods of
`Editing/ExecCommand.cpp`. The stub fragment `stubs/stub_r17_dom_document.lucb` is gone; every
one of its functions is ported (two that `Document.h` declares but the donor never defines are
dropped, see below). Every fragment's header names its donor lines; C++ order and comments are
kept; header inline functions follow the `.cpp` functions.
## Fragments
| Fragment | Donor |
| --- | --- |
| `dom/document_1` … `dom/document_15` | `Document.cpp` 218-8270, in order (each header gives its line range and contents) |
| `dom/document_h_1`, `dom/document_h_2` | the inline functions of `Document.h` (226-650 / 656-1121) and `notify_each_document_observer` |
| `dom/document_loading_1`, `dom/document_loading_2` | `DocumentLoading.cpp` 40-302 / 304-557 and `DocumentLoading.h` |
| `editing/exec_command` | `Editing/ExecCommand.cpp` (all of it) |
| `dom/tests_document` | 21 tests (Ladybird has no unit tests for these files) |
## What other regions must know
### Creating a document (r28 navigation, r27 HTMLDocument, r29 event loop)
`dom_document_create(realm, url)`, `dom_document_construct_impl`, `dom_document_create_for_fragment_parsing`
and `dom_document_create_and_initialize(type, content_type, navigation_params)` are ported in full,
but in phase 1 they trap on their way through other regions' stubs. In `Document::Document`, in
order: `css_style_computer_construct` (r39), `css_font_computer_construct` and
`css_font_face_set_create` (r41), `css_parsing_params_construct_realm_css_parsing_mode` /
`parse_css_stylesheet` (r30b), `css_style_scope_construct` (r39), then
`html_event_loop_register_document` / `html_main_thread_event_loop` (r29); `finalize` calls
`html_event_loop_unregister_document` (r29). `create_and_initialize` additionally needs the
Fetch response accessors (`fetch_response_url`, `_header_list`, `_monotonic_response_time`,
`fetch_request_*`: P2 closure stubs), `html_document_create` (r27) for HTML documents, the
navigable / browsing-context / window functions (r28), `realm_create_html_custom_element_registry`
(P3 closure stub) and CSP initialization (`content_security_policy_*`, P2). `initialize` skips
`m_selection = realm.create<Selection>` (Selection is P4; `dom_document_get_selection` answers
none) and calls `page_client_page_did_create_new_document`. Until those land, tests build a
document by hand: see `test_document_in_realm` in `dom/tests_document.lucb` (an off-heap
document given the constructor's phase-1 steps, a hand-built Page and a test PageClient vtable).
New allocation helpers (namemap rows added): `heap_allocate_css_style_computer`,
`heap_allocate_css_font_computer`, `heap_allocate_css_style_invalidator`,
`heap_allocate_html_policy_container`, `heap_allocate_html_navigation_params` (`heap.allocate<T>`
under DeferGC).
### The event parent (r19 dispatch)
`dom_document_get_parent_impl` is ported: a `load` event has no parent, any other event goes to
the document's window (`m_window`). It compares against `html_event_names_load`, which stays zero
until r22 interns `HTML::EventNames` (the test interns it itself).
### Readiness, observers (r21 parser, r28)
`dom_document_update_readiness` fires `readystatechange` through `dom_event_create`, whose Event
constructor reads the relevant global object (r29 stub): updating the readiness to a new value
traps in phase 1; setting it to the current value returns first. Document observers are
notified through the module-private `dom_document_notify_document_observers_of_readiness`,
`_completely_loaded`, `_became_active`, `_became_inactive`, `_of_visibility_state` and
`_of_page_showing` (the private template `notify_each_document_observer`, one function per
notifier, in `document_h_2`).
### Signature changes (stub signatures that were wrong or generic)
- `dom_document_supported_color_schemes(this) -> ak.Vector[ak.String]?` (by value; was a pointer
to an optional).
- Const references now returned as const pointers (C++ `const&`): `dom_document_style_scope_const`,
`_map_of_preloaded_resources_const`, `_script_blocking_style_sheet_set_const`,
`_showing_auto_popover_list_const`, `_showing_hint_popover_list_const`,
`_top_layer_elements`, `_potentially_named_elements`; and in r43's stub
`layout_node_with_style_background_layers -> const ak.Vector[CssBackgroundLayerData]*`.
- Generics replaced: `dom_document_for_each_shadow_root(_const)(this, callback:
ak.Function1[DomShadowRoot*, unit])`; `dom_document_set_needs_repaint_t` is not generic;
`create_document_for_inline_content(..., mutate_document: ak.Function1[DomDocument*, unit])`.
- `can_load_document_with_type(type_: const MimeType*)`.
- `dom_document_destroy_a_document_and_its_descendants` / `_unload_a_document_and_its_descendants`:
the callback defaults to none, as in C++.
- `dom_retarget_from_ua_internal_shadow_root` returns `DomElement*` (never null).
- New in r44's stub: `layout_block_formatting_context_destruct(this)` (BlockFormattingContext's
destructor has effects; `update_layout` calls it with `defer`).
- C++-private and internal-linkage functions are module-private (the DocumentLoading loaders,
`convert_to_xml_error_document`, `tear_down_layout_tree`, `run_the_document_write_steps`,
`update_active_element`, `run_unloading_cleanup_steps`, `evaluate_media_rules`,
`run_csp_initialization`, `flatten_element_creation_options`, the static helpers of
Document.cpp, …). Five private functions whose only callers are phase 3/4 code stay public
with a note (`dispatch_events_for_transition` / `_animation_if_necessary`,
`queue_intersection_observer_task`, `queue_an_intersection_observer_entry`,
`compute_intersection`), so that `-W` does not report them unused.
- Dropped: `dom_document_invalidate_style_of_elements_affected_by_has` and
`dom_document_build_counter_style_cache` (declared in Document.h, never defined; namemap rows
removed).
### Types filled (generator left them opaque)
`DomDocumentPendingScrollEvent` (`event_target`, `event_type`), `DomDocumentPendingAnimationEvent`
(`event`, `animation`, `target`, `scheduled_event_time`),
`DomDocumentStepsToFireBeforeunloadResult`, `DomDocumentRegistryAndIs` (`registry`, `is`),
`HttpVersionedCookie` (`cookie_version: u64?`, `cookie`), `LayoutViewportTextPosition`
(`dom_node: DomText*`, `start_offset`) and `LayoutViewportTextBlock` (`text`, `positions`).
### Declarations added outside the phase-1 closure (`stubs/stub_closure.lucb`, namemap rows)
All trap with `unported (P2/P3/P4): ...` and are listed in `docs/namemap.tsv` (kind `stub`,
`struct`, `opaque`, `enum`): HTTP header lists and cookies (`http_header_list_get`,
`http_parse_cookie`, `http_cookie_canonicalize_domain`); Fetch responses, requests and bodies
(`fetch_response_url/_header_list/_monotonic_response_time/_body/_url_list`,
`fetch_infrastructure_response_create`, `fetch_body_length/_source_byte_buffer/_fully_read`,
`fetch_extract_mime_type`, `fetch_request_*`, `FetchHeadersGuard`, `FetchJsResponse`,
`fetch_js_response_create`); `domurl_parse` (ported except the blob step); TrustedTypes;
Selection (`range`, `cursor_position`, `is_collapsed`); Animations (effects, timelines,
update contexts, replace state, `animations_document_timeline_create`); HTMLAllCollection;
UIEvents inits and event factories (mouse, pointer, focus, keyboard, composition, text, UI,
input); HashChange/PopState/BeforeUnload/Message/Storage/Drag/MediaQueryList events; History;
SourceSnapshotParams; WindowOrWorkerGlobalScope cleanup; FileAPI unloading cleanup;
MessagePort; PermissionsPolicy; IntersectionObserver unobserve; structured deserialize; the
Navigation API entry updates; CSP policies and directives; ViewTransition; XPath
(`xpath_create_expression`, `xpath_evaluate`); Core::Resource; the XML parser with
XMLDocumentBuilder (`xml_parse_with_document_builder`, `XmlParserOptions`, P2); Editing
(`EditingCommandDefinition`, `editing_find_command_definition`, `editing_active_range`,
`editing_effective_command_value`, `editing_is_formattable_node`,
`editing_for_each_node_effectively_contained_in_range`, `editing_record_current_overrides`,
`editing_restore_states_and_values`, `editing_font_size_to_pixel_size`,
`editing_legacy_font_size`, `EditingRecordedOverride`, P4).
## Deviations and notes
- **Phase 2/3/4 traps inside Document.cpp** (reached only when the feature is in use):
ResizeObserver (register/unregister, gathering and broadcasting observations — trap only when
the observer list is non-empty), IntersectionObserver tasks, entries and `compute_intersection`
(the update steps trap only with observers), the declarative refresh's navigation (P2), CSS
transition/animation event dispatch and removing replaced animations (P4, only when an
animation is replaceable), the adopted style sheets' JS iteration (P3), and
`contains_named_namespace` (needs `CSS::Selector::CompoundSelector`, r38; it traps only for a
non-empty selector list, which `parse_or_cache_selector_list` reaches through r30b anyway).
- `dump_display_list`'s recursive lambdas are free functions over a capture struct;
`shared_declarative_refresh_steps`' `goto`s are flags.
- `environment_variable_value` builds its tokens with `token_create_number(number_create(Number, 1))`
and `token_create_dimension_f64(0, "px")`, as C++'s overloads do.
- `exec_command`'s `is_one_of(CommandNames::…)` checks compare against the command names'
literal text (the `editing_command_names_*` FlyStrings are zero until Editing interns them);
FlyString equality is by content, so this is the C++ behaviour.
- DocumentLoading: the XML parse (`XML::Parser` + `XMLDocumentBuilder`) is one P2 closure stub
returning the parse error and the builder's error flag; `load_pdf_document`'s
`static s_viewer_bytes` is a module variable loaded on first use.
- HTML `TagNames`/`AttributeNames`/`EventNames` are not interned in phase 1 (r21 adds tag and
attribute names, r22 event names); Document code comparing against them sees empty names
until then.
## Tests
`dom/tests_document.lucb` (21 tests, run by `./test.sh`): a new document's defaults (content
type, readyState, compatMode, type, URL, no document element/head/body/doctype); html, head,
title and body found through the tree and title's whitespace collapsing; title without a
document element (empty; setting it does nothing); a non-html document element hides head and
body; the body is the first body or frameset child; getElementById by tree walk and through the
id map of a connected document; document.embeds/plugins as one live collection and
getElementsByName; readyState names and update_readiness to the same value; quirks mode and
compatMode; the event parent (window, none for load); createTextNode/createComment/
createDocumentFragment; createCDATASection's NotSupportedError and `]]>` error;
createProcessingInstruction's target and `?>` errors; createElement's InvalidCharacterError and
createAttribute's lowercasing in HTML documents; is_valid_name; the CSS environment variables;
registered custom properties (registered set before the @property cache); the to_string of the
layout reasons; can_load_document_with_type; execCommand/queryCommand* InvalidStateError outside
HTML documents and the recursion guard; the backColor/hiliteColor value-override mirroring.
Trees are built with `TreeNode::append_child`: `Node::append_child`'s insertion steps invalidate
style through r42's `invalidate_node_style` stub. Elements whose `finalize` is another region's
stub (HTMLImageElement, r26) cannot live in the test heap. Scenario tests to add once r29 (event
loop), r39/r41/r30b (style), r42 and r28 land: `Document::create` and `create_and_initialize` end
to end; update_readiness firing readystatechange; set_title through `string_replace_all`;
`populate_with_html_head_and_body`; getElementById with ids set by `setAttribute`; load_document
for each MIME type (needs Fetch, P2).
## Compiler issues
None found. (Workarounds of known language limits: `let x = f() else:` blocks are written as
`if x == none:` blocks; `if let x = f() catch: recover none` is split into a typed `let`;
local `let a: str[] = [...]` arrays are module-level `let a: str[N]` constants.)