Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / document_2.lucb

#==============================================================================================
#
#   document_2 - DOM::Document: document.write/open/close, the structure queries, title
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 768-1308): the realm and WebIDL-throw helpers,
#       write(), writeln() and the document write steps, open() and close(), defaultView,
#       origin, the children a document allows, the document element and the
#       html/head/title/body elements, dir, document.body and document.title (get and set),
#       tearing down the layout tree and the canvas background.
#
#==============================================================================================

# mark: Helpers =================================================================================

## `realm()` of a document: its platform object's realm.
func dom_document_realm(this: DomDocument*) -> Realm*:
    return bind_platform_object_realm(this.bind_platform_object())

## `return WebIDL::<Name>Error::create(realm(), message)` from a function returning ExceptionOr.
func dom_document_throw(exception: IdlDomException*) -> never!:
    return try idl_throw(.idl_dom_exception(exception))

# mark: Dynamic markup insertion ================================================================

## Ported from Document.cpp:769 Web::DOM::Document::write.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-write
pub func dom_document_write(this: DomDocument*, text: ak.Vector[TrustedTypesTrustedHtmlOrString]) -> !:
    # The document.write(...text) method steps are to run the document write steps with this, text, false, and "Document write".
    return try dom_document_run_the_document_write_steps(this, text, DomDocumentAddLineFeed.no, TrustedTypesInjectionSink.document_write)

## Ported from Document.cpp:776 Web::DOM::Document::writeln.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
pub func dom_document_writeln(this: DomDocument*, text: ak.Vector[TrustedTypesTrustedHtmlOrString]) -> !:
    # The document.writeln(...text) method steps are to run the document write steps with this, text, true, and "Document writeln".
    return try dom_document_run_the_document_write_steps(this, text, DomDocumentAddLineFeed.yes, TrustedTypesInjectionSink.document_writeln)

## Ported from Document.cpp:783 Web::DOM::Document::run_the_document_write_steps.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document-write-steps
func dom_document_run_the_document_write_steps(this: DomDocument*, text: ak.Vector[TrustedTypesTrustedHtmlOrString], line_feed: DomDocumentAddLineFeed, sink: TrustedTypesInjectionSink) -> !:
    var values = text
    # 1. Let string be the empty string.
    var string = ak.string_builder_new()

    # 2. Let isTrusted be false if text contains a string; otherwise true.
    var is_trusted = true
    for value in ak.vector_span(&values):
        match value:
            .utf16_string(_):
                is_trusted = false
                break
            .trusted_types_trusted_html(_): continue

    # 3. For each value of text:
    for value in ak.vector_span(&values):
        let utf16 = match value:
            # 1. If value is a TrustedHTML object, then append value's associated data to string.
            .trusted_types_trusted_html(trusted_html) => trusted_types_trusted_html_to_string(trusted_html else trap("a null TrustedHTML"))
            # 2. Otherwise, append value to string.
            .utf16_string(string_value) => string_value
        let view = ak.utf16_string_base_utf16_view(&utf16.utf16_string_base)
        let utf8 = ak.utf16_view_to_utf8_but_should_be_ported_to_utf16(&view)
        ak.string_builder_append_string_view(&string, ak.string_bytes_as_string_view(&utf8))

    # 4. If isTrusted is false, set string to the result of invoking the Get Trusted Type compliant string algorithm
    #    with TrustedHTML, this's relevant global object, string, sink, and "script".
    if not is_trusted:
        let string_so_far = ak.string_builder_to_string(&string) else trap("MUST: StringBuilder::to_string")
        # (TrustedTypes::Script.to_string() is "'script'".)
        let new_string = try trusted_types_get_trusted_type_compliant_string(
            TrustedTypesTrustedTypeName.trusted_html,
            html_relevant_global_object((JsObject*)this),
            .utf16_string(ak.utf16_string_from_utf8_string(&string_so_far)),
            sink,
            ak.string_from_str("'script'"),
        )
        ak.string_builder_clear(&string)
        let new_view = ak.utf16_string_base_utf16_view(&new_string.utf16_string_base)
        let new_utf8 = ak.utf16_view_to_utf8_but_should_be_ported_to_utf16(&new_view)
        ak.string_builder_append_string_view(&string, ak.string_bytes_as_string_view(&new_utf8))

    # 5. If lineFeed is true, append U+000A LINE FEED to string.
    if line_feed == DomDocumentAddLineFeed.yes:
        ak.string_builder_append_u8(&string, '\n')

    # 6. If document is an XML document, then throw an "InvalidStateError" DOMException.
    if this.m_type == DocumentDomDocumentType.xml:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("write() called on XML document.")))

    # 7. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
    if this.m_throw_on_dynamic_markup_insertion_counter > 0:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("throw-on-dynamic-markup-insertion-counter greater than zero.")))

    # 8. If document's active parser was aborted is true, then return.
    if this.m_active_parser_was_aborted:
        return

    # 9. If the insertion point is undefined, then:
    var insertion_point_is_defined = false
    if let parser = this.m_parser:
        insertion_point_is_defined = html_syntax.html_tokenizer_is_insertion_point_defined(html_parser_tokenizer(parser))
    if not insertion_point_is_defined:
        # 1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
        if this.m_unload_counter > 0 or this.m_ignore_destructive_writes_counter > 0:
            return

        # 2. Run the document open steps with document.
        _ = try dom_document_open_optional_string(this)

    # 10. Insert string into the input stream just before the insertion point.
    let parser = this.m_parser else trap("the document open steps left no parser")
    html_syntax.html_tokenizer_insert_input_at_insertion_point(html_parser_tokenizer(parser), ak.string_builder_string_view(&string))

    # 11. If document's pending parsing-blocking script is null, then have the HTML parser process string, one code
    #     point at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches
    #     the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this
    #     can happen if a script end tag token is emitted by the tokenizer).
    if not dom_document_has_pending_parsing_blocking_script(this):
        html_parser_run_html_tokenizer_stop_at_inserti(parser, html_syntax.HtmlTokenizerStopAtInsertionPoint.yes)

## Ported from Document.cpp:860 Web::DOM::Document::open.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open
pub func dom_document_open_optional_string(this: DomDocument*, arg0: ak.String? = none, arg1: ak.String? = none) -> DomDocument*?!:
    # 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
    if this.m_type == DocumentDomDocumentType.xml:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("open() called on XML document.")))

    # 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
    if this.m_throw_on_dynamic_markup_insertion_counter > 0:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("throw-on-dynamic-markup-insertion-counter greater than zero.")))

    # 3. Let entryDocument be the entry global object's associated Document.
    let entry_document = html_window_associated_document(as_html_window((gc.Cell*)html_entry_global_object()))

    # 4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.
    let origin = dom_document_origin(this)
    if not web_url.origin_eq(&origin, dom_document_origin(entry_document)):
        return try dom_document_throw(idl_security_error_create(dom_document_realm(this), ak.utf16_string_from_str("Document.origin() not the same as entryDocument's.")))

    # 5. If document has an active parser whose script nesting level is greater than 0, then return document.
    if let parser = this.m_parser:
        if html_parser_script_nesting_level(parser) > 0:
            return this

    # 6. Similarly, if document's unload counter is greater than 0, then return document.
    if this.m_unload_counter > 0:
        return this

    # 7. If document's active parser was aborted is true, then return document.
    if this.m_active_parser_was_aborted:
        return this

    # 8. If document's node navigable is non-null and document's node navigable's ongoing navigation is a navigation ID, then stop loading document's node navigable.
    # AD-HOC: Pending navigations can also sit in m_pending_navigations, so we need to cancel those too.
    if let navigable = dom_document_navigable(this):
        html_navigable_clear_pending_navigations(navigable)
        match html_navigable_ongoing_navigation(navigable):
            .string(_): html_navigable_stop_loading(navigable)
            _: _ = navigable

    # FIXME: 9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.

    # FIXME: 10. If document is the associated Document of document's relevant global object, then erase all event listeners and handlers given document's relevant global object.

    # 11. Replace all with null within document, without firing any mutation events.
    dom_node_replace_all(this.dom_node(), none)

    # https://w3c.github.io/editing/docs/execCommand/#state-override
    # When document.open() is called and a document's singleton objects are all replaced by new instances of those
    # objects, editing state associated with that document (including the CSS styling flag, default single-line
    # container name, and any state overrides or value overrides) must be reset.
    dom_document_set_css_styling_flag(this, false)
    dom_document_set_default_single_line_container_name(this, html_tag_names_div)
    dom_document_reset_command_state_overrides(this)
    dom_document_reset_command_value_overrides(this)

    # 12. If document is fully active, then:
    if dom_document_is_fully_active(this):
        # 1. Let newURL be a copy of entryDocument's URL.
        var new_url = dom_document_url(entry_document)
        # 2. If entryDocument is not document, then set newURL's fragment to null.
        if entry_document != this:
            web_url.url_set_fragment(&new_url, none)

        # 3. Run the URL and history update steps with document and newURL.
        html_perform_url_and_history_update_steps(this, new_url)

    # AD-HOC: Record that this document was an initial about:blank before document.open() cleared the flag, so the
    #         Navigation API can keep entries and events disabled.
    if dom_document_is_initial_about_blank(this):
        let window = as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this))
        html_navigation_set_was_initial_about_blank_opened(html_window_navigation(window), true)

    # 13. Set document's is initial about:blank to false.
    dom_document_set_is_initial_about_blank(this, false)

    # FIXME: 14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.

    # 15. Set document to no-quirks mode.
    dom_document_set_quirks_mode(this, DomQuirksMode.no)

    # 16. Create a new HTML parser and associate it with document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.
    let parser = html_parser_create_for_scripting(this)
    this.m_parser = parser

    # 17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
    html_syntax.html_tokenizer_update_insertion_point(html_parser_tokenizer(parser))

    # 18. Update the current document readiness of document to "loading".
    dom_document_update_readiness(this, HtmlDocumentReadyState.loading)

    # 19. Return document.
    return this

## Ported from Document.cpp:952 Web::DOM::Document::open.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open-window
pub func dom_document_open_string_view(this: DomDocument*, url: ak.StringView, name: ak.StringView, features: ak.StringView) -> HtmlWindowProxy*?!:
    # 1. If this is not fully active, then throw an "InvalidAccessError" DOMException.
    if not dom_document_is_fully_active(this):
        return try dom_document_throw(idl_invalid_access_error_create(dom_document_realm(this), ak.utf16_string_from_str("Cannot perform open on a document that isn't fully active.")))

    # 2. Return the result of running the window open steps with url, name, and features.
    let window = dom_document_window(this) else trap("a fully active document without a window")
    return try html_window_window_open_steps(window, url, name, features)

## The captures of close()'s post-parse action: `[this] { completely_finish_loading(); }`.
struct DomDocumentCloseFinishLoading:
    var this: DomDocument*

## close()'s post-parse action.
func dom_document_close_finish_loading(context: void*?):
    let captures = (DomDocumentCloseFinishLoading*)(context else trap("no captures"))
    dom_document_completely_finish_loading(captures.this)

## Ported from Document.cpp:963 Web::DOM::Document::close.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#closing-the-input-stream
pub func dom_document_close(this: DomDocument*) -> !:
    # 1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.
    if this.m_type == DocumentDomDocumentType.xml:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("close() called on XML document.")))

    # 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.
    if this.m_throw_on_dynamic_markup_insertion_counter > 0:
        return try dom_document_throw(idl_invalid_state_error_create(dom_document_realm(this), ak.utf16_string_from_str("throw-on-dynamic-markup-insertion-counter greater than zero.")))

    # 3. If there is no script-created parser associated with the document, then return.
    let parser = this.m_parser else return
    if not html_parser_is_script_created(parser):
        return

    # 4. Insert an explicit "EOF" character at the end of the parser's input stream.
    html_syntax.html_tokenizer_insert_eof(html_parser_tokenizer(parser))

    # 5. If there is a pending parsing-blocking script, then return.
    if dom_document_has_pending_parsing_blocking_script(this):
        let captures = new DomDocumentCloseFinishLoading(this = this) else trap("out of memory")
        html_parser_set_post_parse_action(parser, ak.Function0[unit](call = dom_document_close_finish_loading, context = captures))
        return

    # 6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.
    html_parser_run_html_tokenizer_stop_at_inserti(parser)

    # run() may have paused on a blocking script (e.g. from document.write inside an inline script).
    if dom_document_has_pending_parsing_blocking_script(this):
        let captures = new DomDocumentCloseFinishLoading(this = this) else trap("out of memory")
        html_parser_set_post_parse_action(parser, ak.Function0[unit](call = dom_document_close_finish_loading, context = captures))
        return

    # AD-HOC: This ensures that a load event is fired if the node navigable's container is an iframe.
    dom_document_completely_finish_loading(this)

# mark: defaultView and origin ==================================================================

## Ported from Document.cpp:1002 Web::DOM::Document::default_view.
# https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-defaultview
pub func dom_document_default_view(this: DomDocument*) -> HtmlWindowProxy*?:
    # If this's browsing context is null, then return null.
    let browsing_context = dom_document_browsing_context(this) else return none

    # 2. Return this's browsing context's WindowProxy object.
    return html_browsing_context_window_proxy(browsing_context)

## Ported from Document.cpp:1012 Web::DOM::Document::default_view.
pub func dom_document_default_view_const(this: DomDocument*) -> HtmlWindowProxy*?:
    return dom_document_default_view(this)

## Ported from Document.cpp:1017 Web::DOM::Document::origin.
pub func dom_document_origin(this: DomDocument*) -> web_url.Origin:
    return this.m_origin

## Ported from Document.cpp:1022 Web::DOM::Document::set_origin.
pub func dom_document_set_origin(this: DomDocument*, origin: web_url.Origin):
    this.m_origin = origin

# mark: Structure ===============================================================================

## Ported from Document.cpp:1027 Web::DOM::Document::is_child_allowed (override).
pub func dom_document_is_child_allowed_impl(base: DomNode*, node: DomNode*) -> bool:
    match dom_node_type(node):
        .document_node, .text_node: return false
        .comment_node, .processing_instruction_node: return true
        .document_type_node: return tree_node_first_child_of_type(base, &dom_document_type_class) == none
        .element_node: return tree_node_first_child_of_type(base, &dom_element_class) == none
        _: return false

## Ported from Document.cpp:1045 Web::DOM::Document::document_element.
pub func dom_document_document_element(this: DomDocument*) -> DomElement*?:
    return (DomElement*?)tree_node_first_child_of_type(this.dom_node(), &dom_element_class)

## Ported from Document.cpp:1050 Web::DOM::Document::document_element.
pub func dom_document_document_element_const(this: DomDocument*) -> DomElement*?:
    return (DomElement*?)tree_node_first_child_of_type(this.dom_node(), &dom_element_class)

## Ported from Document.cpp:1056 Web::DOM::Document::root_element.
# https://www.w3.org/TR/SVG2/struct.html#InterfaceDocumentExtensions
pub func dom_document_root_element(this: DomDocument*) -> SvgSvgsvgElement*?:
    let document_element = dom_document_document_element(this) else return none
    return as_if_svg_svgsvg_element(document_element)

## Ported from Document.cpp:1062 Web::DOM::Document::html_element.
# https://html.spec.whatwg.org/multipage/dom.html#the-html-element-2
pub func dom_document_html_element(this: DomDocument*) -> HtmlHtmlElement*?:
    # The html element of a document is its document element, if it's an html element, and null otherwise.
    let html = dom_document_document_element(this) else return none
    return as_if_html_html_element(html)

## Ported from Document.cpp:1070 Web::DOM::Document::head.
# https://html.spec.whatwg.org/multipage/dom.html#the-head-element-2
pub func dom_document_head(this: DomDocument*) -> HtmlHeadElement*?:
    # The head element of a document is the first head element that is a child of the html element, if there is one,
    # or null otherwise.
    let html = dom_document_html_element(this) else return none
    return (HtmlHeadElement*?)tree_node_first_child_of_type(html.dom_node(), &html_head_element_class)

## Ported from Document.cpp:1081 Web::DOM::Document::title_element.
# https://html.spec.whatwg.org/multipage/dom.html#the-title-element-2
pub func dom_document_title_element(this: DomDocument*) -> HtmlTitleElement*?:
    # The title element of a document is the first title element in the document (in tree order), if there is one, or
    # null otherwise.
    # for_each_in_subtree_of_type<HTML::HTMLTitleElement>: the first one breaks the walk.
    for node in dom_node_subtree(this.dom_node()):
        if let title_element_in_tree = as_if_html_title_element(node):
            return title_element_in_tree
    return none

## Ported from Document.cpp:1096 Web::DOM::Document::dir.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-dir
pub func dom_document_dir(this: DomDocument*) -> ak.StringView:
    # The dir IDL attribute on Document objects must reflect the dir content attribute of the html
    # element, if any, limited to only known values. If there is no such element, then the
    # attribute must return the empty string and do nothing on setting.
    if let html = dom_document_html_element(this):
        return html_element_dir(html.html_element())

    return ak.sv("")

## Ported from Document.cpp:1108 Web::DOM::Document::set_dir.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-dir
pub func dom_document_set_dir(this: DomDocument*, dir: ak.String):
    # The dir IDL attribute on Document objects must reflect the dir content attribute of the html
    # element, if any, limited to only known values. If there is no such element, then the
    # attribute must return the empty string and do nothing on setting.
    if let html = dom_document_html_element(this):
        html_element_set_dir(html.html_element(), dir)

## Ported from Document.cpp:1118 Web::DOM::Document::body.
# https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2
pub func dom_document_body(this: DomDocument*) -> HtmlElement*?:
    # The body element of a document is the first of the html element's children that is either
    # a body element or a frameset element, or null if there is no such element.
    let html = dom_document_html_element(this) else return none
    for child in dom_node_children(html.dom_node()):
        if is_html_body_element(child) or is_html_frame_set_element(child):
            return (HtmlElement*)child
    return none

## Ported from Document.cpp:1133 Web::DOM::Document::set_body.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
pub func dom_document_set_body(this: DomDocument*, new_body: HtmlElement*?) -> !:
    var new_body_is_body_or_frameset = false
    if let body_candidate = new_body:
        new_body_is_body_or_frameset = is_html_body_element(body_candidate) or is_html_frame_set_element(body_candidate)
    if not new_body_is_body_or_frameset:
        return try dom_document_throw(idl_hierarchy_request_error_create(dom_document_realm(this), ak.utf16_string_from_str("Invalid document body element, must be 'body' or 'frameset'")))
    let body = new_body else trap("unreachable: checked above")

    if let existing_body = dom_document_body(this):
        let parent = tree_node_parent(existing_body.dom_node()) else trap("the body has no parent")
        _ = try dom_node_replace_child(parent, body.dom_node(), existing_body.dom_node())
        return

    let document_element = dom_document_document_element(this) else return try dom_document_throw(idl_hierarchy_request_error_create(dom_document_realm(this), ak.utf16_string_from_str("Missing document element")))

    _ = try dom_node_append_child(document_element.dom_node(), body.dom_node())

# mark: Title ===================================================================================

## Ported from Document.cpp:1153 Web::DOM::Document::title.
# https://html.spec.whatwg.org/multipage/dom.html#document.title
pub func dom_document_title(this: DomDocument*) -> ak.Utf16String:
    var value = ak.utf16_string_new()

    # 1. If the document element is an SVG svg element, then let value be the child text content of the first SVG title
    #    element that is a child of the document element.
    let document_element = dom_document_document_element(this)
    var document_element_is_svg_svg = false
    if let element = document_element:
        document_element_is_svg_svg = is_svg_svgsvg_element(element)
    if document_element_is_svg_svg:
        let element = document_element else trap("unreachable: checked above")
        if let title_element = tree_node_first_child_of_type(element.dom_node(), &svg_title_element_class):
            value = dom_node_child_text_content(title_element)

    # 2. Otherwise, let value be the child text content of the title element, or the empty string if the title element
    #    is null.
    elif let title_element = dom_document_title_element(this):
        value = dom_node_text_content(title_element.dom_node()) else ak.utf16_string_new()

    # 3. Strip and collapse ASCII whitespace in value.
    let title = web_infra.strip_and_collapse_whitespace_utf16_string(value)

    # 4. Return value.
    return title

## Ported from Document.cpp:1178 Web::DOM::Document::set_title.
# https://html.spec.whatwg.org/multipage/dom.html#document.title
pub func dom_document_set_title(this: DomDocument*, title: ak.Utf16String) -> !:
    let maybe_document_element = dom_document_document_element(this)

    var document_element_is_svg_svg = false
    var document_element_is_html = false
    if let element = maybe_document_element:
        document_element_is_svg_svg = is_svg_svgsvg_element(element)
        document_element_is_html = dom_node_optional_fly_string_is(dom_element_namespace_uri(element), namespace_html)

    # -> If the document element is an SVG svg element
    if document_element_is_svg_svg:
        let document_element = maybe_document_element else trap("unreachable: checked above")
        var element: DomElement*? = none

        # 1. If there is an SVG title element that is a child of the document element, let element be the first such
        #    element.
        if let title_element = tree_node_first_child_of_type(document_element.dom_node(), &svg_title_element_class):
            element = (DomElement*)title_element
        # 2. Otherwise:
        else:
            # 1. Let element be the result of creating an element given the document element's node document, "title",
            #    and the SVG namespace.
            let new_element = try dom_create_element(this, html_tag_names_title, namespace_svg)
            element = new_element

            # 2. Insert element as the first child of the document element.
            dom_node_insert_before(document_element.dom_node(), new_element.dom_node(), tree_node_first_child(document_element.dom_node()))

        # 3. String replace all with the given value within element.
        let target = element else trap("unreachable: set above")
        dom_node_string_replace_all(target.dom_node(), title)

    # -> If the document element is in the HTML namespace
    elif document_element_is_html:
        let title_element = dom_document_title_element(this)
        let head_element = dom_document_head(this)

        # 1. If the title element is null and the head element is null, then return.
        if title_element == none and head_element == none:
            return

        var element: DomElement*? = none

        # 2. If the title element is non-null, let element be the title element.
        if let existing_title_element = title_element:
            element = existing_title_element.dom_element()
        # 3. Otherwise:
        else:
            # 1. Let element be the result of creating an element given the document element's node document, "title",
            #    and the HTML namespace.
            let new_element = try dom_create_element(this, html_tag_names_title, namespace_html)
            element = new_element

            # 2. Append element to the head element.
            let head = head_element else trap("unreachable: checked above")
            _ = try dom_node_append_child(head.dom_node(), new_element.dom_node())

        # 4. String replace all with the given value within element.
        let target = element else trap("unreachable: set above")
        dom_node_string_replace_all(target.dom_node(), title)

    # -> Otherwise
    else:
        # Do nothing.
        return

# mark: Layout tree and the canvas background ===================================================

## Ported from Document.cpp:1243 Web::DOM::Document::tear_down_layout_tree.
func dom_document_tear_down_layout_tree(this: DomDocument*):
    this.m_layout_root = none
    this.dom_node().m_paintable = none
    this.m_needs_full_layout_tree_update = true

## Ported from Document.cpp:1250 Web::DOM::Document::clear_layout_and_paintable_nodes_for_inactive_document.
func dom_document_clear_layout_and_paintable_nodes_for_inactive_document(this: DomDocument*):
    for node in dom_node_inclusive_subtree(this.dom_node()):
        dom_node_clear_layout_node_and_paintable(node)
        if let element = as_if_dom_element(node):
            dom_element_clear_pseudo_element_layout_nodes(element)

## Ported from Document.cpp:1260 Web::DOM::Document::background_color.
pub func dom_document_background_color(this: DomDocument*) -> gfx.Color:
    # CSS2 says we should use the HTML element's background color unless it's transparent...
    # NB: Called during painting inside update_layout().
    if let html_element = dom_document_html_element(this):
        if let layout_node = dom_element_unsafe_layout_node(html_element.dom_element()):
            let computed_values = layout_node_with_style_computed_values(layout_node)
            let color = css_computed_values_background_color(&computed_values.computed_values)
            if gfx.color_alpha(&color) != 0:
                return color

    # ...in which case we use the BODY element's background color.
    if let body_element = dom_document_body(this):
        if let layout_node = dom_element_unsafe_layout_node(body_element.dom_element()):
            let computed_values = layout_node_with_style_computed_values(layout_node)
            let color = css_computed_values_background_color(&computed_values.computed_values)
            return color

    # By default, the document is transparent.
    # The outermost canvas is colored by the PageHost.
    return gfx.color_new_named_color(gfx.ColorNamedColor.transparent)

## Ported from Document.cpp:1281 Web::DOM::Document::background_layers.
pub func dom_document_background_layers(this: DomDocument*) -> const ak.Vector[CssBackgroundLayerData]*?:
    let body_element = dom_document_body(this) else return none

    # NB: Called during painting inside update_layout().
    let body_layout_node = dom_element_unsafe_layout_node(body_element.dom_element()) else return none

    return layout_node_with_style_background_layers(body_layout_node)

## Ported from Document.cpp:1295 Web::DOM::Document::background_image_rendering.
pub func dom_document_background_image_rendering(this: DomDocument*) -> css_data.ImageRendering:
    let body_element = dom_document_body(this) else return css_data.ImageRendering.auto

    # NB: Called during painting inside update_layout().
    let body_layout_node = dom_element_unsafe_layout_node(body_element.dom_element()) else return css_data.ImageRendering.auto

    let computed_values = layout_node_with_style_computed_values(body_layout_node)
    return css_computed_values_image_rendering(&computed_values.computed_values)