Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / document_14.lucb

#==============================================================================================
#
#   document_14 - DOM::Document: beforeunload, CSP, view transitions, registries, dumps
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 7609-8066): the steps to fire beforeunload, CSP
#       initialization, flattening element creation options, event handler attributes, view
#       transitions and their page-visibility change steps, custom element registries and
#       upgrading particular elements, element_by_id, the display list and stacking context
#       tree dumps, and the CSS environment variables.
#
#==============================================================================================

# mark: beforeunload and CSP ====================================================================

## Ported from Document.cpp:7609 Web::DOM::Document::steps_to_fire_beforeunload.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#steps-to-fire-beforeunload
pub func dom_document_steps_to_fire_beforeunload(this: DomDocument*, unload_prompt_shown: bool) -> DomDocumentStepsToFireBeforeunloadResult:
    # 1. Let unloadPromptCanceled be false.
    let unload_prompt_canceled = false

    # 2. Increase the document's unload counter by 1.
    this.m_unload_counter += 1

    # 3. Increase document's relevant agent's event loop's termination nesting level by 1.
    let event_loop = html_relevant_agent((JsObject*)this).event_loop else trap("the relevant agent has no event loop")
    html_event_loop_increment_termination_nesting_level(event_loop)

    # 4. Let eventFiringResult be the result of firing an event named beforeunload at document's relevant global object,
    #    using BeforeUnloadEvent, with the cancelable attribute initialized to true.
    let global_object = html_relevant_global_object((JsObject*)this)
    let window = as_html_window((gc.Cell*)global_object)
    let beforeunload_event = html_before_unload_event_create(dom_document_realm(this), html_event_names_beforeunload)
    dom_event_set_cancelable(beforeunload_event.dom_event(), true)
    _ = dom_event_target_dispatch_event(window.dom_event_target(), beforeunload_event.dom_event())

    # 5. Decrease document's relevant agent's event loop's termination nesting level by 1.
    html_event_loop_decrement_termination_nesting_level(event_loop)

    # FIXME: 6. If all of the following are true:
    #    - unloadPromptShown is false;
    #    - document's active sandboxing flag set does not have its sandboxed modals flag set;
    #    - document's relevant global object has sticky activation;
    #    - eventFiringResult is false, or the returnValue attribute of event is not the empty string; and
    #    - FIXME: showing an unload prompt is unlikely to be annoying, deceptive, or pointless
    #    (C++ guards the condition with `if (false && ...)`, so it is never evaluated.)
    #     FIXME: 1. Set unloadPromptShown to true.
    #     FIXME: 2. Invoke WebDriver BiDi user prompt opened with document's relevant global object, "beforeunload", and "".
    #     FIXME: 3. Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response.
    #     FIXME: 4. If the user did not confirm the page navigation, set unloadPromptCanceled to true.
    #     FIXME: 5. Invoke WebDriver BiDi user prompt closed with document's relevant global object and true if unloadPromptCanceled is false or false otherwise.

    # 7. Decrease document's unload counter by 1.
    this.m_unload_counter -= 1

    # 8. Return (unloadPromptShown, unloadPromptCanceled).
    return DomDocumentStepsToFireBeforeunloadResult(unload_prompt_shown = unload_prompt_shown, unload_prompt_canceled = unload_prompt_canceled)

## Ported from Document.cpp:7659 Web::DOM::Document::run_csp_initialization.
# https://w3c.github.io/webappsec-csp/#run-document-csp-initialization
func dom_document_run_csp_initialization(this: DomDocument*):
    # 1. For each policy of document’s policy container's CSP list:
    var policies = content_security_policy_policy_list_policies(dom_document_policy_container(this).csp_list)
    for policy in ak.vector_span(&policies):
        # 1. For each directive of policy:
        var directives = content_security_policy_policy_directives(policy)
        for directive in ak.vector_span(&directives):
            # 1. Execute directive’s initialization algorithm on document, and assert: its returned value is "Allowed".
            let result = content_security_policy_directive_initialization(directive, DomDocumentOrHtmlWorkerGlobalScope.dom_document(this), policy)
            assert(result == ContentSecurityPolicyResult.allowed)

## Ported from Document.cpp:7673 Web::DOM::Document::flatten_element_creation_options.
# https://dom.spec.whatwg.org/#flatten-element-creation-options
func dom_document_flatten_element_creation_options(this: DomDocument*, options: StringOrDomElementCreationOptions) -> DomDocumentRegistryAndIs!:
    # 1. Let registry be the result of looking up a custom element registry given document.
    var registry = html_look_up_a_custom_element_registry(this.dom_node())

    # 2. Let is be null.
    var is_value: ak.String? = none

    # 3. If options is a dictionary:
    match options:
        .dom_element_creation_options(dictionary):
            # 1. If options["is"] exists, then set is to it.
            if dictionary.is != none:
                is_value = dictionary.is

            # 2. If options["customElementRegistry"] exists:
            # (C++'s Optional<GC::Ptr<CustomElementRegistry>> is a nullable pointer here: a null registry is
            # "does not exist".)
            if dictionary.custom_element_registry != none:
                # 1. If is is non-null, then throw a "NotSupportedError" DOMException.
                if is_value != none:
                    return try dom_document_throw(idl_not_supported_error_create(dom_document_realm(this), ak.utf16_string_from_str("Cannot specify both 'is' and 'customElementRegistry' in ElementCreationOptions.")))

                # 2. Set registry to options["customElementRegistry"].
                registry = dictionary.custom_element_registry

            # 3. If registry is non-null, registry’s is scoped is false, and registry is not document’s custom element
            #    registry, then throw a "NotSupportedError" DOMException.
            if let given_registry = registry:
                if not html_custom_element_registry_is_scoped(given_registry) and registry != dom_document_custom_element_registry(this):
                    return try dom_document_throw(idl_not_supported_error_create(dom_document_realm(this), ak.utf16_string_from_str("'customElementRegistry' in ElementCreationOptions must either be scoped or the document's custom element registry.")))
        .string(_): _ = options

    # 4. Return registry and is.
    return DomDocumentRegistryAndIs(registry = registry, is = is_value)

# mark: Event handler attributes ================================================================

## Ported from Document.cpp:7707 Web::DOM::Document::onreadystatechange.
pub func dom_document_onreadystatechange(this: DomDocument*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_readystatechange)

## Ported from Document.cpp:7712 Web::DOM::Document::set_onreadystatechange.
pub func dom_document_set_onreadystatechange(this: DomDocument*, value: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_readystatechange, value)

## Ported from Document.cpp:7717 Web::DOM::Document::onvisibilitychange.
pub func dom_document_onvisibilitychange(this: DomDocument*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_visibilitychange)

## Ported from Document.cpp:7722 Web::DOM::Document::set_onvisibilitychange.
pub func dom_document_set_onvisibilitychange(this: DomDocument*, value: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_visibilitychange, value)

## Ported from Document.cpp:7727 Web::DOM::Document::onfullscreenchange.
pub func dom_document_onfullscreenchange(this: DomDocument*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenchange)

## Ported from Document.cpp:7732 Web::DOM::Document::set_onfullscreenchange.
pub func dom_document_set_onfullscreenchange(this: DomDocument*, value: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenchange, value)

## Ported from Document.cpp:7737 Web::DOM::Document::onfullscreenerror.
pub func dom_document_onfullscreenerror(this: DomDocument*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenerror)

## Ported from Document.cpp:7742 Web::DOM::Document::set_onfullscreenerror.
pub func dom_document_set_onfullscreenerror(this: DomDocument*, value: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenerror, value)

# mark: View transitions ========================================================================

## Ported from Document.cpp:7748 Web::DOM::Document::start_view_transition.
# https://drafts.csswg.org/css-view-transitions-1/#dom-document-startviewtransition
pub func dom_document_start_view_transition(this: DomDocument*, update_callback: IdlCallbackType*?) -> ViewTransitionViewTransition*?:
    # The method steps for startViewTransition(updateCallback) are as follows:

    # 1. Let transition be a new ViewTransition object in this’s relevant Realm.
    let realm = dom_document_realm(this)
    let transition = view_transition_view_transition_create(realm)

    # 2. If updateCallback is provided, set transition’s update callback to updateCallback.
    if update_callback != none:
        view_transition_view_transition_set_update_callback(transition, update_callback)

    # 3. Let document be this’s relevant global object’s associated document.
    let document = html_window_associated_document(as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this)))

    # 4. If document’s visibility state is "hidden", then skip transition with an "InvalidStateError" DOMException,
    #    and return transition.
    if this.m_visibility_state == HtmlVisibilityState.hidden:
        view_transition_view_transition_skip_the_view_transition(transition, js_value_from_object((JsObject*)idl_invalid_state_error_create(realm, ak.utf16_string_from_str("The document's visibility state is \"hidden\""))))
        return transition

    # 5. If document’s active view transition is not null, then skip that view transition with an "AbortError"
    #    DOMException in this’s relevant Realm.
    if let active_view_transition = document.m_active_view_transition:
        view_transition_view_transition_skip_the_view_transition(active_view_transition, js_value_from_object((JsObject*)idl_abort_error_create(realm, ak.utf16_string_from_str("Document.startViewTransition() was called"))))

    # 6. Set document’s active view transition to transition.
    this.m_active_view_transition = transition

    # 7. Return transition.
    return transition

## Ported from Document.cpp:7783 Web::DOM::Document::perform_pending_transition_operations.
# https://drafts.csswg.org/css-view-transitions-1/#perform-pending-transition-operations
pub func dom_document_perform_pending_transition_operations(this: DomDocument*):
    # To perform pending transition operations given a Document document, perform the following steps:

    # 1. If document’s active view transition is not null, then:
    if let active_view_transition = this.m_active_view_transition:
        # 1. If document’s active view transition’s phase is "pending-capture", then setup view transition for
        #    document’s active view transition.
        if view_transition_view_transition_phase(active_view_transition) == ViewTransitionViewTransitionPhase.pending_capture:
            view_transition_view_transition_setup_view_transition(active_view_transition)
        # 2. Otherwise, if document’s active view transition’s phase is "animating", then handle transition frame for
        #    document’s active view transition.
        elif view_transition_view_transition_phase(active_view_transition) == ViewTransitionViewTransitionPhase.animating:
            view_transition_view_transition_handle_transition_frame(active_view_transition)

## Ported from Document.cpp:7801 Web::DOM::Document::flush_the_update_callback_queue.
# https://drafts.csswg.org/css-view-transitions-1/#flush-the-update-callback-queue
pub func dom_document_flush_the_update_callback_queue(this: DomDocument*):
    # To flush the update callback queue given a Document document:

    # 1. For each transition in document’s update callback queue, call the update callback given transition.
    for transition in ak.vector_span(&this.m_update_callback_queue):
        view_transition_view_transition_call_the_update_callback(transition else trap("a null view transition"))

    # 2. Set document’s update callback queue to an empty list.
    ak.vector_clear(&this.m_update_callback_queue)

## Ported from Document.cpp:7814 Web::DOM::Document::set_rendering_suppression_for_view_transitions.
pub func dom_document_set_rendering_suppression_for_view_transitions(this: DomDocument*, value: bool):
    if this.m_rendering_suppression_for_view_transitions == value:
        return

    this.m_rendering_suppression_for_view_transitions = value

    if not value:
        page_client_request_frame(page_client(dom_document_page(this)))

## The captures of the page-visibility task: `[&]` (the document).
struct DomDocumentViewTransitionVisibilityTask:
    var this: DomDocument*

## The view transition page-visibility change task.
func dom_document_view_transition_visibility_task(context: void*?):
    let this = ((DomDocumentViewTransitionVisibilityTask*)(context else trap("no captures"))).this
    var temporary_execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&temporary_execution_context, dom_document_realm(this))
    defer html_temporary_execution_context_destruct(&temporary_execution_context)
    # 1. If document’s visibility state is "hidden", then:
    if this.m_visibility_state == HtmlVisibilityState.hidden:
        # 1. If document’s active view transition is not null, then skip document’s active view transition with an
        #    "InvalidStateError" DOMException.
        if let active_view_transition = this.m_active_view_transition:
            view_transition_view_transition_skip_the_view_transition(active_view_transition, js_value_from_object((JsObject*)idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("The document's visibility state is \"hidden\"."))))
    # 2. Otherwise, assert: active view transition is null.
    else:
        assert(this.m_active_view_transition == none)

## Ported from Document.cpp:7826 Web::DOM::Document::view_transition_page_visibility_change_steps.
# https://drafts.csswg.org/css-view-transitions-1/#view-transition-page-visibility-change-steps
pub func dom_document_view_transition_page_visibility_change_steps(this: DomDocument*):
    # The view transition page-visibility change steps given Document document are:

    # 1. Queue a global task on the DOM manipulation task source, given document’s relevant global object, to
    #    perform the following steps:
    let captures = new DomDocumentViewTransitionVisibilityTask(this = this) else trap("out of memory")
    _ = html_queue_global_task(HtmlTaskSource.dom_manipulation, html_relevant_global_object((JsObject*)this), gc.create_function0[unit](realm_heap(dom_document_realm(this)), ak.Function0[unit](call = dom_document_view_transition_visibility_task, context = captures)))

# mark: Custom element registries ===============================================================

## Ported from Document.cpp:7850 Web::DOM::Document::custom_element_registry.
# https://dom.spec.whatwg.org/#dom-documentorshadowroot-customelementregistry
pub func dom_document_custom_element_registry(this: DomDocument*) -> HtmlCustomElementRegistry*?:
    # 1. If this is a document, then return this’s custom element registry.
    # NB: Always true.
    return this.m_custom_element_registry

    # 2. Assert: this is a ShadowRoot node.
    # 3. Return this’s custom element registry.

## Ported from Document.cpp:7861 Web::DOM::Document::effective_global_custom_element_registry.
# https://dom.spec.whatwg.org/#effective-global-custom-element-registry
pub func dom_document_effective_global_custom_element_registry(this: DomDocument*) -> HtmlCustomElementRegistry*?:
    # A document document’s effective global custom element registry is:

    # 1. If document’s custom element registry is a global custom element registry, then return document’s custom
    #    element registry.
    if html_is_a_global_custom_element_registry(dom_document_custom_element_registry(this)):
        return dom_document_custom_element_registry(this)

    # 2. Return null.
    return none

## The captures of upgrade_particular_elements' walk: `[&]`.
struct DomDocumentUpgradeParticularElements:
    var registry: HtmlCustomElementRegistry*
    var definition: HtmlCustomElementDefinition*
    var local_name: ak.String
    var name: ak.String

## upgrade_particular_elements' walk over the shadow-including descendants.
func dom_document_upgrade_particular_element(context: void*?, inclusive_descendant: DomNode*) -> TraversalDecision:
    let captures = (DomDocumentUpgradeParticularElements*)(context else trap("no captures"))
    let element = as_if_dom_element(inclusive_descendant) else return TraversalDecision.continue_
    if dom_element_custom_element_registry(element) != captures.registry:
        return TraversalDecision.continue_
    if not dom_node_optional_fly_string_is(dom_element_namespace_uri(element), namespace_html):
        return TraversalDecision.continue_
    let element_local_name = dom_element_local_name(element)
    if not ak.fly_string_eq_string(&element_local_name, &captures.local_name):
        return TraversalDecision.continue_

    if not ak.string_equals(&captures.name, &captures.local_name):
        let is_value = dom_element_is_value(element) else return TraversalDecision.continue_
        if not ak.string_equals(&is_value, &captures.name):
            return TraversalDecision.continue_

    # 2. For each element element of upgradeCandidates:
    #    enqueue a custom element upgrade reaction given element and definition.
    dom_element_enqueue_a_custom_element_upgrade_reaction(element, captures.definition)
    return TraversalDecision.continue_

## Ported from Document.cpp:7875 Web::DOM::Document::upgrade_particular_elements.
# https://html.spec.whatwg.org/multipage/custom-elements.html#upgrade-particular-elements-within-a-document
pub func dom_document_upgrade_particular_elements(this: DomDocument*, registry: HtmlCustomElementRegistry*, definition: HtmlCustomElementDefinition*, local_name: ak.String, maybe_name: ak.String? = none):
    # To upgrade particular elements within a document given a CustomElementRegistry object registry, a Document
    # object document, a custom element definition definition, a string localName, and optionally a string name
    # (default localName):
    let name = maybe_name else local_name

    # 1. Let upgradeCandidates be all elements that are shadow-including descendants of document, whose custom element
    #    registry is registry, whose namespace is the HTML namespace, and whose local name is localName, in
    #    shadow-including tree order.
    #    Additionally, if name is not localName, only include elements whose is value is equal to name.
    var captures = DomDocumentUpgradeParticularElements(registry = registry, definition = definition, local_name = local_name, name = name)
    _ = dom_node_for_each_shadow_including_descendant(this.dom_node(), ak.Function1[DomNode*, TraversalDecision](call = dom_document_upgrade_particular_element, context = &captures))

## Ported from Document.cpp:7906 Web::DOM::Document::element_by_id.
pub func dom_document_element_by_id(this: DomDocument*) -> DomElementByIdMap*:
    if this.m_element_by_id == none:
        this.m_element_by_id = new DomElementByIdMap() else trap("out of memory")
    return this.m_element_by_id else trap("unreachable: set above")

# mark: Dumps ===================================================================================

## `builder.appendff("{}@{}", command.command_name, item.context_index.value())`.
func dom_document_append_command_name(builder: ak.StringBuilder*, command_name: str, context_index: u64):
    ak.string_builder_append(builder, command_name)
    ak.string_builder_append(builder, "@")
    ak.format_u64(builder, context_index)

## `item.command.visit([&](auto const& command) { builder.appendff("{}@{}", command.command_name, item.context_index.value()); command.dump(builder); })`.
func dom_document_dump_display_list_command(builder: ak.StringBuilder*, item: const display_list.DisplayListCommandListItem*):
    match item.command:
        .draw_glyph_run(command):
            dom_document_append_command_name(builder, display_list.draw_glyph_run_command_name, item.context_index)
            display_list.draw_glyph_run_dump(&command, builder)
        .fill_rect(command):
            dom_document_append_command_name(builder, display_list.fill_rect_command_name, item.context_index)
            display_list.fill_rect_dump(&command, builder)
        .draw_scaled_immutable_bitmap(command):
            dom_document_append_command_name(builder, display_list.draw_scaled_immutable_bitmap_command_name, item.context_index)
            display_list.draw_scaled_immutable_bitmap_dump(&command, builder)
        .draw_repeated_immutable_bitmap(command):
            dom_document_append_command_name(builder, display_list.draw_repeated_immutable_bitmap_command_name, item.context_index)
            display_list.draw_repeated_immutable_bitmap_dump(&command, builder)
        .draw_external_content(command):
            dom_document_append_command_name(builder, display_list.draw_external_content_command_name, item.context_index)
            display_list.draw_external_content_dump(&command, builder)
        .save(command):
            dom_document_append_command_name(builder, display_list.save_command_name, item.context_index)
            display_list.save_dump(&command, builder)
        .save_layer(command):
            dom_document_append_command_name(builder, display_list.save_layer_command_name, item.context_index)
            display_list.save_layer_dump(&command, builder)
        .restore(command):
            dom_document_append_command_name(builder, display_list.restore_command_name, item.context_index)
            display_list.restore_dump(&command, builder)
        .translate(command):
            dom_document_append_command_name(builder, display_list.translate_command_name, item.context_index)
            display_list.translate_dump(&command, builder)
        .add_clip_rect(command):
            dom_document_append_command_name(builder, display_list.add_clip_rect_command_name, item.context_index)
            display_list.add_clip_rect_dump(&command, builder)
        .paint_linear_gradient(command):
            dom_document_append_command_name(builder, display_list.paint_linear_gradient_command_name, item.context_index)
            display_list.paint_linear_gradient_dump(&command, builder)
        .paint_radial_gradient(command):
            dom_document_append_command_name(builder, display_list.paint_radial_gradient_command_name, item.context_index)
            display_list.paint_radial_gradient_dump(&command, builder)
        .paint_conic_gradient(command):
            dom_document_append_command_name(builder, display_list.paint_conic_gradient_command_name, item.context_index)
            display_list.paint_conic_gradient_dump(&command, builder)
        .paint_outer_box_shadow(command):
            dom_document_append_command_name(builder, display_list.paint_outer_box_shadow_command_name, item.context_index)
            display_list.paint_outer_box_shadow_dump(&command, builder)
        .paint_inner_box_shadow(command):
            dom_document_append_command_name(builder, display_list.paint_inner_box_shadow_command_name, item.context_index)
            display_list.paint_inner_box_shadow_dump(&command, builder)
        .paint_text_shadow(command):
            dom_document_append_command_name(builder, display_list.paint_text_shadow_command_name, item.context_index)
            display_list.paint_text_shadow_dump(&command, builder)
        .fill_rect_with_rounded_corners(command):
            dom_document_append_command_name(builder, display_list.fill_rect_with_rounded_corners_command_name, item.context_index)
            display_list.fill_rect_with_rounded_corners_dump(&command, builder)
        .fill_path(command):
            dom_document_append_command_name(builder, display_list.fill_path_command_name, item.context_index)
            display_list.fill_path_dump(&command, builder)
        .stroke_path(command):
            dom_document_append_command_name(builder, display_list.stroke_path_command_name, item.context_index)
            display_list.stroke_path_dump(&command, builder)
        .draw_ellipse(command):
            dom_document_append_command_name(builder, display_list.draw_ellipse_command_name, item.context_index)
            display_list.draw_ellipse_dump(&command, builder)
        .fill_ellipse(command):
            dom_document_append_command_name(builder, display_list.fill_ellipse_command_name, item.context_index)
            display_list.fill_ellipse_dump(&command, builder)
        .draw_line(command):
            dom_document_append_command_name(builder, display_list.draw_line_command_name, item.context_index)
            display_list.draw_line_dump(&command, builder)
        .apply_backdrop_filter(command):
            dom_document_append_command_name(builder, display_list.apply_backdrop_filter_command_name, item.context_index)
            display_list.apply_backdrop_filter_dump(&command, builder)
        .draw_rect(command):
            dom_document_append_command_name(builder, display_list.draw_rect_command_name, item.context_index)
            display_list.draw_rect_dump(&command, builder)
        .add_rounded_rect_clip(command):
            dom_document_append_command_name(builder, display_list.add_rounded_rect_clip_command_name, item.context_index)
            display_list.add_rounded_rect_clip_dump(&command, builder)
        .paint_nested_display_list(command):
            dom_document_append_command_name(builder, display_list.paint_nested_display_list_command_name, item.context_index)
            display_list.paint_nested_display_list_dump(&command, builder)
        .paint_scroll_bar(command):
            dom_document_append_command_name(builder, display_list.paint_scroll_bar_command_name, item.context_index)
            display_list.paint_scroll_bar_dump(&command, builder)
        .apply_effects(command):
            dom_document_append_command_name(builder, display_list.apply_effects_command_name, item.context_index)
            display_list.apply_effects_dump(&command, builder)

## `item.command.visit([](auto const& cmd) { return cmd.nesting_level_change if it has one, else 0; })`.
func dom_document_command_nesting_level_change(command: const display_list.DisplayListCommand*) -> i32:
    match *command:
        .save(_): return display_list.save_nesting_level_change
        .save_layer(_): return display_list.save_layer_nesting_level_change
        .restore(_): return display_list.restore_nesting_level_change
        .apply_effects(_): return display_list.apply_effects_nesting_level_change
        _: return 0

## The state the recursive lambdas of dump_display_list capture by reference.
struct DomDocumentDumpDisplayList:
    var builder: ak.StringBuilder*
    var visual_context_tree: const display_list.AccumulatedVisualContextTree*
    var context_id_to_paintable: ak.HashMap[u64, PaintPaintableBox*, ak.U64Traits]*
    var children: ak.HashMap[u64, ak.Vector[u64], ak.U64Traits]*

## dump_display_list's `dump_context` lambda (recursive).
func dom_document_dump_context(state: DomDocumentDumpDisplayList*, node_index: u64, indent: usize):
    let builder = state.builder
    ak.string_builder_append_repeated_u8(builder, ' ', indent * 2)
    ak.string_builder_append(builder, "[")
    ak.format_u64(builder, node_index)
    ak.string_builder_append(builder, "] ")
    display_list.accumulated_visual_context_tree_dump(state.visual_context_tree, node_index, builder)
    if let paintable_box = ak.hash_map_get_k(state.context_id_to_paintable, node_index):
        ak.string_builder_append(builder, " (")
        let description = paint_paintable_debug_description((*paintable_box).paint_paintable())
        ak.string_builder_append_string_view(builder, ak.string_bytes_as_string_view(&description))
        ak.string_builder_append(builder, ")")
    ak.string_builder_append_u8(builder, '\n')
    if let child_indices = ak.hash_map_get_k(state.children, node_index):
        for child_node_index in ak.vector_span(child_indices):
            dom_document_dump_context(state, child_node_index, indent + 1)

## dump_display_list's `dump_commands` lambda (recursive).
func dom_document_dump_commands(builder: ak.StringBuilder*, list: const display_list.DisplayList*, base_indent: i32):
    var indent = base_indent
    for item in ak.vector_span_const(display_list.display_list_commands(list)):
        let nesting_change = dom_document_command_nesting_level_change(&item.command)

        if nesting_change < 0:
            indent = indent + nesting_change
            if indent < base_indent:
                indent = base_indent

        ak.string_builder_append_repeated_u8(builder, ' ', (usize)indent * 2)
        dom_document_dump_display_list_command(builder, &item)
        ak.string_builder_append_u8(builder, '\n')

        match item.command:
            .paint_nested_display_list(nested):
                if let nested_display_list = nested.display_list:
                    dom_document_dump_commands(builder, nested_display_list, indent + 1)
            _: _ = nesting_change

        if nesting_change > 0:
            indent += nesting_change

## Ported from Document.cpp:7913 Web::DOM::Document::dump_display_list.
pub func dom_document_dump_display_list(this: DomDocument*) -> ak.String:
    dom_document_update_layout(this, DomUpdateLayoutReason.dump_display_list)

    let viewport_paintable = dom_document_paintable(this) else return ak.string_from_str("No paintable")

    let recorded_display_list = dom_document_record_display_list(this, HtmlPaintConfig()) else return ak.string_from_str("No display list")

    var context_id_to_paintable: ak.HashMap[u64, PaintPaintableBox*, ak.U64Traits]
    for paintable in paint_paintable_inclusive_subtree(viewport_paintable.paint_paintable()):
        let paintable_box = as_if_paint_paintable_box(paintable) else continue
        let visual_context_index = paint_paintable_box_accumulated_visual_context_index(paintable_box)
        if visual_context_index != 0:
            _ = ak.hash_map_try_set(&context_id_to_paintable, visual_context_index, paintable_box) else ak.HashSetResult.inserted_new_entry

    var builder = ak.string_builder_new()
    ak.string_builder_append(&builder, "AccumulatedVisualContext Tree:\n")

    let visual_context_tree = display_list.display_list_visual_context_tree(recorded_display_list)
    var visited: ak.HashTable[u64, ak.U64Traits]
    var children: ak.HashMap[u64, ak.Vector[u64], ak.U64Traits]
    var root_contexts: ak.Vector[u64]

    for item in ak.vector_span_const(display_list.display_list_commands(recorded_display_list)):
        if item.context_index == 0:
            continue
        var node_index = item.context_index
        while node_index != 0 and not ak.hash_table_contains_t(&visited, node_index):
            _ = ak.hash_table_set(&visited, node_index)
            let parent = display_list.accumulated_visual_context_tree_node_at(visual_context_tree, node_index).parent_index
            if parent != 0:
                ak.vector_append_t(ak.hash_map_ensure(&children, parent), node_index)
            elif not ak.vector_contains_slow[u64, ak.U64Traits](&root_contexts, node_index):
                ak.vector_append_t(&root_contexts, node_index)
            node_index = display_list.accumulated_visual_context_tree_node_at(visual_context_tree, node_index).parent_index

    var state = DomDocumentDumpDisplayList(builder = &builder, visual_context_tree = visual_context_tree, context_id_to_paintable = &context_id_to_paintable, children = &children)
    for root in ak.vector_span(&root_contexts):
        dom_document_dump_context(&state, root, 1)

    ak.string_builder_append(&builder, "\nDisplayList:\n")

    dom_document_dump_commands(&builder, recorded_display_list, 0)

    return ak.string_builder_to_string_without_validation(&builder)

## Ported from Document.cpp:8005 Web::DOM::Document::dump_stacking_context_tree.
pub func dom_document_dump_stacking_context_tree(this: DomDocument*) -> ak.String:
    dom_document_update_layout(this, DomUpdateLayoutReason.dump_display_list)

    let viewport_paintable = dom_document_paintable(this) else return ak.string_from_str("No paintable")

    paint_viewport_paintable_build_stacking_context_tree_if_needed(viewport_paintable)

    let stacking_context = paint_paintable_box_stacking_context(viewport_paintable.paint_paintable_box()) else return ak.string_from_str("No stacking context")

    var builder = ak.string_builder_new()
    paint_stacking_context_dump(stacking_context, &builder)
    return ak.string_builder_to_string_without_validation(&builder)

# mark: Environment variables ===================================================================

## environment_variable_value's `invalid` lambda: a guaranteed-invalid value.
func dom_document_invalid_environment_variable() -> ak.Vector[css_syntax.ComponentValue]:
    var value: css_syntax.ComponentValue = ---
    css_syntax.component_value_construct_guaranteed_invalid_value(&value, css_syntax.GuaranteedInvalidValue())
    var values: ak.Vector[css_syntax.ComponentValue]
    ak.vector_append_t(&values, value)
    return values

## Ported from Document.cpp:8024 Web::DOM::Document::environment_variable_value.
pub func dom_document_environment_variable_value(this: DomDocument*, environment_variable: css_data.EnvironmentVariable, indices: i32[]) -> ak.Vector[css_syntax.ComponentValue]?:
    match environment_variable:
        .preferred_text_scale:
            # FIXME: Report the user's preferred text scale, once we have that as a setting.
            if indices.length != 0:
                return dom_document_invalid_environment_variable()
            var value: css_syntax.ComponentValue = ---
            css_syntax.component_value_construct_token(&value, css_syntax.token_create_number(css_syntax.number_create(css_syntax.NumberType.number, 1.0), ak.String()))
            var values: ak.Vector[css_syntax.ComponentValue]
            ak.vector_append_t(&values, value)
            return values
        .safe_area_inset_bottom, .safe_area_inset_left, .safe_area_inset_right, .safe_area_inset_top, .safe_area_max_inset_bottom, .safe_area_max_inset_left, .safe_area_max_inset_right, .safe_area_max_inset_top:
            # FIXME: Report the safe area, once we can detect our display's shape (and it's not rectangular).
            if indices.length != 0:
                return dom_document_invalid_environment_variable()
            var value: css_syntax.ComponentValue = ---
            css_syntax.component_value_construct_token(&value, css_syntax.token_create_dimension_f64(0.0, ak.fly_string_from_str("px"), ak.String()))
            var values: ak.Vector[css_syntax.ComponentValue]
            ak.vector_append_t(&values, value)
            return values
        .viewport_segment_bottom, .viewport_segment_height, .viewport_segment_left, .viewport_segment_right, .viewport_segment_top, .viewport_segment_width:
            # "These variables are only defined when there are at least two such segments."
            # https://drafts.csswg.org/css-env/#viewport-segments
            # FIXME: Report the viewport segment areas, once we can detect that and there are multiple of them.
            return dom_document_invalid_environment_variable()
        _: trap("VERIFY_NOT_REACHED")