dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / docs / regions / r18.md
# Region r18: DOM leaves (CharacterData, Text, Attr, NamedNodeMap, ShadowRoot, slots, ranges, ...) โ what other regions need to know
Region r18 ports the DOM classes around Node and Element: `QualifiedName`, `CharacterData`,
`Text`, `Comment`, `CDATASection`, `ProcessingInstruction`, `DocumentType`, `DocumentFragment`,
`Attr`, `NamedNodeMap`, `ElementByIdMap`, `AnchorNameMap`, `AbstractElement`, `PseudoElement`,
`DocumentOrShadowRoot`, `ShadowRoot`, `Slot`, `SlotRegistry`, `Slottable`, `Utils` (retarget),
the collections (`NodeList`, `StaticNodeList`, `LiveNodeList`, `HTMLCollection`),
`DOMTokenList`, `DOMImplementation`, `XMLDocument`, the mutation observers (`MutationObserver`,
`RegisteredObserver`, `TransientRegisteredObserver`, `MutationRecord`, `MutationType`),
traversal (`NodeFilter`, `NodeIterator`, `TreeWalker`), ranges (`AbstractRange`,
`StaticRange`, `Range`), `Position`, `AccessibilityTreeNode`, `AdoptedStyleSheets`,
`DocumentLoadEventDelayer`, `DocumentObserver`, `EditingHostManager`, `InputEventsTarget`,
`RequestFullscreenError`, `SelectionchangeEventDispatching`, `StyleElementBase` and
`ViewportClient`. `FragmentSerializationMode.h` and `StyleInvalidationReason.h` hold only types.
The stub fragment `stubs/stub_r18_dom_leaves.lucb` is gone; all 577 of its functions are ported.
Every fragment's header names its donor lines; C++ order is kept, header inline functions follow
the `.cpp` functions in a `# mark: X.h` section.
## Fragments (all in `dom/`)
| Fragment | Donor |
| --- | --- |
| `qualified_name` | `QualifiedName.cpp/.h` |
| `character_data`, `text`, `comment`, `cdata_section`, `processing_instruction` | the matching `.cpp/.h` |
| `document_type`, `document_fragment`, `attr`, `named_node_map` | the matching `.cpp/.h` |
| `element_by_id_map`, `anchor_name_map`, `abstract_element`, `pseudo_element` | the matching `.cpp/.h` |
| `document_or_shadow_root` | `DocumentOrShadowRoot.h` |
| `shadow_root_1`, `shadow_root_2` | `ShadowRoot.cpp` 1-283 / 284-378 and `ShadowRoot.h` (with Node's shadow-including traversals) |
| `slot`, `slot_registry`, `slottable`, `utils` | the matching `.cpp/.h` |
| `node_list`, `static_node_list`, `live_node_list`, `html_collection`, `dom_token_list` | the matching `.cpp/.h` |
| `dom_implementation`, `xml_document` | the matching `.cpp/.h` |
| `mutation_observer`, `mutation_record`, `mutation_type` | the matching `.cpp/.h` |
| `node_filter`, `node_iterator`, `tree_walker` | the matching `.cpp/.h` (+ `JS::Value::to_i32` in `node_filter`) |
| `abstract_range`, `static_range` | the matching `.cpp/.h` |
| `range_1`, `range_2`, `range_3` | `Range.cpp` 1-475 / 476-924 / 925-1305 and `Range.h` |
| `position`, `accessibility_tree_node`, `adopted_style_sheets`, `document_load_event_delayer`, `document_observer` | the matching `.cpp/.h` |
| `editing_host_manager`, `input_events_target`, `request_fullscreen_error`, `selectionchange_event_dispatching`, `style_element_base`, `viewport_client` | the matching `.cpp/.h` |
| `tests_leaves_1`, `tests_leaves_2` | 32 tests (Ladybird has none for these files) |
## What other regions must know
### QualifiedName (r16 Element, r21 parser, r22 HTML elements, r38 selectors)
- `dom_qualified_name_construct(&qn, local_name, prefix, namespace_)` interns an Impl (local
name, lowercased local name, prefix, namespace, "prefix:local" string) in the module table
`dom_impls`, so equal triples share one `m_impl` pointer: comparing two qualified names is
comparing `m_impl`. Impls and the table live in `memory.heap` and are never released (as the
FlyString table; the C++ releases an Impl with its last reference).
- `dom_qualified_name_set_prefix` changes the shared Impl, as C++ does (every holder sees it;
neither the table hash nor `as_string` change).
### Nodes
- Constructors of the node classes work through `realm_create_*` with a document whose platform
object has a realm. `Text`/`CDATASection` constructors point the SlottableMixin vtable at their
own table (C++'s secondary vptr); `EditingHostManager` likewise for InputEventsTarget.
- `dom_mutation_type_initialize_strings` interns "attributes", "characterData", "childList";
`web_initialize_strings` runs it.
- `dom_character_data_replace_data` and everything that sets or removes an attribute queue a
mutation record, which reads the document's page (region r17 stub: traps until r17 lands).
### Live ranges
- `dom_range_live_ranges()` is the module table `dom_range_s_live_ranges` (in `memory.heap`, not
scanned); a Range adds itself in its constructor and removes itself in `finalize`.
### Callbacks and generics replaced by concrete types (signature changes)
- `dom_calculate_active_element(self_: DomNode*)`, `dom_calculate_get_animations(self_: DomNode*)`
(were generic over Document/ShadowRoot).
- `dom_schedule_a_selectionchange_event(target: DomNode*, document)` and
`dom_fire_a_selectionchange_event(target: DomNode*, document)` (were generic over the target);
the target's "has scheduled selectionchange event" flag is the Document's or the
HTMLInputElement/HTMLTextAreaElement text control mixin's.
- `dom_element_by_id_map_for_each_id(this, callback: ak.Function1[ak.FlyString, unit])`,
`dom_slot_registry_for_each_slot` / `dom_shadow_root_for_each_registered_slot(this, callback:
ak.Function1[HtmlSlotElement*, unit])`, `dom_range_for_each_contained(_const)(this, callback:
ak.Function1[DomNode*, ak.IterationDecision])`, `dom_anchor_name_map_visit_edges(this,
visitor: gc.CellVisitor*)` (were `[TCallback]` / `[TVisitor]` generics).
- `dom_shadow_root_part_element_map(this) -> const ak.HashMap[...]*` (C++ `const&`; was a copy).
- `dom_document_observer_document_readiness_observer` / `_visibility_state_observer` /
`_page_showing_observer` take only `this` (the generator had added the callback's argument).
- `dom_accessibility_tree_node_children_2` answers a clone of the vector (C++ returns a copy).
- New: `dom_document_load_event_delayer_construct_move`, `_move_assign` and `_destruct` (the
C++ move operations and destructor, which releases the hold on the load event): an owner of
an `Optional<DocumentLoadEventDelayer>` calls `_destruct` where C++ destroys the value
(emplace over a value, clear); `StyleElementBase` does.
- C++-private members are module-private (`*_associated_element`, `remove_attribute_at_index`,
`calculate_part_element_map`, `parse_exportparts_attribute`, the Range/NodeIterator/TreeWalker
helpers, `DOMTokenList`'s validation and ordered-set helpers, `ensure_impl`, `hash_impl`).
### Types filled (generator left them opaque)
- `DomQualifiedNameImpl` and `DomImplTraits`' methods; `DomElementByIdMapMapEntry`
(`cached_first_element: gc.Weak[DomElement]`, `elements: ak.Vector[gc.Weak[DomElement]]`);
`DomAbstractElementTreeCountingFunctionResolutionContext` (`sibling_count`, `sibling_index`);
`DomAbstractElementTraits` (generated/types_traits.lucb) now hashes and compares.
### Declarations added outside the phase-1 closure (`stubs/stub_closure.lucb`, namemap rows)
- `animations_animatable_set_has_css_defined_animations` (trap stub).
- `geometry_dom_rect_create`, `geometry_dom_rect_list_length`, `geometry_dom_rect_list_item`,
`geometry_dom_rect_read_only_x/y/width/height` (trap stubs; Range's client rects).
- The Selection API EditingHostManager uses: `selection_selection_anchor_node`, `_anchor_offset`,
`_focus_node`, `_collapse`, `_set_base_and_extent`, `_scroll_focus_into_view`,
`_move_offset_to_{next,previous}_{character,word,line}` (trap stubs).
- FlyStrings `editing_command_names_{delete,forward_delete,insert_line_break,insert_paragraph,insert_text}`
and `ui_events_input_types_{delete_content_backward,insert_line_break,insert_paragraph}` (zero
until whoever ports Editing/CommandNames and UIEvents/InputTypes interns them).
## Deviations and notes
- **Phase 3 (JS)**: `NodeFilter`'s constructor (a PlatformObject over `%Object.prototype%`),
`ShadowRoot::set_adopted_style_sheets` after clearing (JS iteration), `calculate_get_animations`'
`get_animations_internal` and its composite-order sort (Animations, P4) trap with
`unported (P3/P4)`. The adoptedStyleSheets callbacks are fallible in C++; r14's ObservableArray
slots take non-fallible functions, so an exception from them traps (P3).
- `DOMTokenList::run_validation_steps`' static `HashMap<SupportedTokenKey, Vector<StringView>>`
is a constant lookup (`dom_token_list_supported_tokens`) answering the same lists.
- `ElementByIdMap::for_each_element_with_id` looks the FlyString-keyed map up by a StringView
through a private `HashCompatibleTraits[FlyString, StringView]` (`DomFlyStringStringViewTraits`;
ak has the String one only).
- `Range::get_bounding_client_rect` unites in f64 with a private `Gfx::Rect<double>` (gfx has no
double rect); `Utf16String::formatted` messages are built with UTF-16 StringBuilders.
- `SlotRegistry`: `m_slot_count -= m_slots.remove_all_matching(...)` subtracts the bool, as in C++
(donor quirk, kept).
- `AbstractElement::style_scope` keeps the generated by-value signature (r16's caller uses it).
- `JS::Value::to_i32` is ported into `node_filter` (`dom_js_value_to_i32`, the non-FJCVTZS path,
which computes the same ToInt32).
## Tests
`dom/tests_leaves_1.lucb` and `dom/tests_leaves_2.lucb` (32 tests, run by `./test.sh`): QualifiedName
interning, derived strings and the Impl hash (403277409 for "div", 94087268 with the HTML
namespace, 33809017 for xlink:href, from a local driver over the reference build's AK), the
set_prefix quirk, the mutation type names; Text/Comment/CDATASection/ProcessingInstruction made
in a realm and their names and mixin tables; substringData and its IndexSizeError; wholeText;
text directionality; DocumentType and valid doctype names; DOMImplementation.createDocumentType;
DocumentFragment's host; Attr names, value without an element and clone; NamedNodeMap's item
and lookups by name / namespace and the NotFoundError messages; DOMTokenList's ordered sets,
validation errors and supported tokens; ElementByIdMap and AnchorNameMap; AbstractElement's
traits and tree-counting context; boundary-point positions; live ranges (start/end, collapse,
select, compare, contain, intersect, stringify, clone, the errors, the offset mutators,
for_each_contained); StaticRange; TreeWalker over whatToShow; LiveNodeList and StaticNodeList;
MutationObserver's option checks, registration, transient observers and disconnect; SlotRegistry
tree order; slottables; retarget; NodeFilter flag operators; ToInt32; the fullscreen error
messages; Position.
Nodes are made in r14's test realm with a hand-built document (r15's `test_document` given the
realm) because Document's constructor is r17's. Scenario tests to add once r17 (Document) and
r29 (event loop) land: replaceData / appendData / splitText with live-range fix-ups and mutation
records; the attribute API end to end (setAttribute โ NamedNodeMap set/append/replace/remove โ
attribute changed steps; DOMTokenList add/remove/toggle/replace writing the attribute back);
HTMLCollection over a document (its cache keys on the DOM tree version); ShadowRoot creation
(registers with the document), innerHTML, the part element map, slot assignment
(find/assign slottables, signal a slot change); NodeIterator (registers with the document);
DOMImplementation.createDocument / createHTMLDocument (XMLDocument / HTMLDocument constructors);
Range insertNode / surroundContents / extractContents / cloneContents / deleteContents across
text and elements; the shadow-root event parent and retarget across shadow trees.
## Compiler issues
None found. (Notes: `try f(g() else trap(...))` is rejected because the fallible `g()` is
already covered by the `try`, as base.md ยง11.1 says; `x else trap(..) == y` parses as
`x else (trap(..) == y)`, so such comparisons are parenthesised.)