Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / dom / node_3.lucb

#==============================================================================================
#
#   node_3 - DOM::Node: replace, clone and move
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Node.cpp (lines 987-1356): the replace algorithm, cloning a node
#       (with its subtree and a clonable shadow root) and the move algorithm behind
#       moveBefore().
#
#==============================================================================================

# mark: Replace =================================================================================

## Ported from Node.cpp:988 Web::DOM::Node::replace_child.
# https://dom.spec.whatwg.org/#concept-node-replace
pub func dom_node_replace_child(this: DomNode*, node: DomNode*, child: DomNode*) -> DomNode*!:
    let realm = bind_platform_object_realm(this.bind_platform_object())

    # 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError"
    #    DOMException.
    if not is_dom_document(this) and not is_dom_document_fragment(this) and not is_dom_element(this):
        return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Can only insert into a document, document fragment or element"))))

    # 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
    if dom_node_is_host_including_inclusive_ancestor_of(node, this):
        return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("New node is an ancestor of this node"))))

    # 3. If child’s parent is not parent, then throw a "NotFoundError" DOMException.
    if tree_node_parent(child) != this:
        return try idl_throw(.idl_dom_exception(idl_not_found_error_create(realm, ak.utf16_string_from_str("This node is not the parent of the given child"))))

    # FIXME: All the following "Invalid node type for insertion" messages could be more descriptive.

    # 4. If node is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
    if not is_dom_document_fragment(node) and not is_dom_document_type(node) and not is_dom_element(node) and not is_dom_text(node) and not is_dom_comment(node) and not is_dom_processing_instruction(node):
        return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # 5. If either node is a Text node and parent is a document, or node is a doctype and parent is not a document, then throw a "HierarchyRequestError" DOMException.
    if (is_dom_text(node) and is_dom_document(this)) or (is_dom_document_type(node) and not is_dom_document(this)):
        return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # If parent is a document, and any of the statements below, switched on the interface node implements, are true, then throw a "HierarchyRequestError" DOMException.
    if is_dom_document(this):
        # DocumentFragment
        if is_dom_document_fragment(node):
            # If node has more than one element child or has a Text node child.
            # Otherwise, if node has one element child and either parent has an element child that is not child or a doctype is following child.
            let node_element_child_count = dom_parent_node_child_element_count(as_dom_document_fragment(node).dom_parent_node())
            if (node_element_child_count > 1 or tree_node_has_child_of_type(node, &dom_text_class)) or (node_element_child_count == 1 and (tree_node_first_child_of_type(this, &dom_element_class) != child or tree_node_has_following_node_of_type_in_tree_order(child, &dom_document_type_class))):
                return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))
        elif is_dom_element(node):
            # Element
            # parent has an element child that is not child or a doctype is following child.
            if tree_node_first_child_of_type(this, &dom_element_class) != child or tree_node_has_following_node_of_type_in_tree_order(child, &dom_document_type_class):
                return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))
        elif is_dom_document_type(node):
            # DocumentType
            # parent has a doctype child that is not child, or an element is preceding child.
            if tree_node_first_child_of_type(this, &dom_document_type_class) != child or tree_node_has_preceding_node_of_type_in_tree_order(child, &dom_element_class):
                return try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # 7. Let referenceChild be child’s next sibling.
    var reference_child = tree_node_next_sibling(child)

    # 8. If referenceChild is node, then set referenceChild to node’s next sibling.
    if reference_child == node:
        reference_child = tree_node_next_sibling(node)

    # 9. Let previousSibling be child’s previous sibling.
    let previous_sibling = tree_node_previous_sibling(child)

    # 10. Let removedNodes be the empty set.
    var removed_nodes: ak.Vector[DomNode*?]

    # 11. If child’s parent is non-null:
    # NOTE: The above can only be false if child is node.
    if tree_node_parent(child) != none:
        # 1. Set removedNodes to « child ».
        ak.vector_append_t(&removed_nodes, child)

        # 2. Remove child with suppressObservers set to true.
        dom_node_remove(child, true)

    # 12. Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ».
    var nodes: ak.Vector[DomNode*?]
    if is_dom_document_fragment(node):
        nodes = dom_node_children_as_vector(node)
    else:
        ak.vector_append_t(&nodes, node)

    # AD-HOC: Since removing the child may have executed arbitrary code, we have to verify
    #         the sanity of inserting `node` before `reference_child` again, as well as
    #         `child` not being reinserted elsewhere.
    var reinsert = true
    if let reference = reference_child:
        reinsert = tree_node_parent(reference) == this and dom_node_parent_node(child) == none
    if reinsert:
        # 13. Insert node into parent before referenceChild with suppressObservers set to true.
        dom_node_insert_before(this, node, reference_child, true)

    # 14. Queue a tree mutation record for parent with nodes, removedNodes, previousSibling, and referenceChild.
    dom_node_queue_tree_mutation_record(this, nodes, removed_nodes, previous_sibling, reference_child)

    # 15. Return child.
    return child

# mark: Clone ===================================================================================

## Ported from Node.cpp:1083 Web::DOM::Node::clone_node.
# https://dom.spec.whatwg.org/#concept-node-clone
pub func dom_node_clone_node(this: DomNode*, document: DomDocument*? = none, subtree: bool = false, parent: DomNode*? = none, fallback_registry: HtmlCustomElementRegistry*? = none) -> DomNode*!:
    # To clone a node given a node node and an optional document document (default node’s node document),
    # boolean subtree (default false), node-or-null parent (default null), and null or a CustomElementRegistry object
    # fallbackRegistry (default null):
    var maybe_document = document
    if maybe_document == none:
        maybe_document = this.m_document
    let clone_document = maybe_document else trap("Node::clone_node: no node document")

    # 1. Assert: node is not a document or node is document.
    assert(not dom_node_is_document(this) or this == clone_document.dom_node())

    # 2. Let copy be the result of cloning a single node given node, document, and fallbackRegistry.
    let copy = try dom_node_clone_single_node(this, clone_document, fallback_registry)

    # 3. Run any cloning steps defined for node in other applicable specifications and pass node, copy, and subtree as
    #    parameters.
    try dom_node_cloned(this, copy, subtree)

    # 4. If parent is non-null, then append copy to parent.
    if let parent_node = parent:
        _ = try dom_node_append_child(parent_node, copy)

    # 5. If subtree is true, then for each child of node’s children, in tree order:
    #    clone a node given child with document set to document, subtree set to subtree, parent set to copy, and
    #    fallbackRegistry set to fallbackRegistry.
    if subtree:
        var child = tree_node_first_child(this)
        while let child_node = child:
            _ = try dom_node_clone_node(child_node, clone_document, subtree, copy, fallback_registry)
            child = tree_node_next_sibling(child_node)

    # 6. If node is an element, node is a shadow host, and node’s shadow root’s clonable is true:
    if let node_element = as_if_dom_element(this):
        if dom_element_is_shadow_host(node_element):
            let node_shadow_root = dom_element_shadow_root(node_element) else trap("shadow host without a shadow root")
            if dom_shadow_root_clonable(node_shadow_root):
                # 1. Assert: copy is not a shadow host.
                let copy_element = as_dom_element(copy)
                assert(not dom_element_is_shadow_host(copy_element))

                # 2. Let shadowRootRegistry be node’s shadow root’s custom element registry.
                var shadow_root_registry = dom_shadow_root_custom_element_registry(node_shadow_root)

                # 3. If shadowRootRegistry is a global custom element registry, then set shadowRootRegistry to document’s
                #    effective global custom element registry.
                if html_is_a_global_custom_element_registry(shadow_root_registry):
                    shadow_root_registry = dom_document_effective_global_custom_element_registry(clone_document)

                # 4. Attach a shadow root with copy, node’s shadow root’s mode, true, node’s shadow root’s serializable,
                #    node’s shadow root’s delegates focus, node’s shadow root’s slot assignment, and shadowRootRegistry.
                try dom_element_attach_a_shadow_root(copy_element, dom_shadow_root_mode(node_shadow_root), true, dom_shadow_root_serializable(node_shadow_root), dom_shadow_root_delegates_focus(node_shadow_root), dom_shadow_root_slot_assignment(node_shadow_root), shadow_root_registry)

                let copy_shadow_root = dom_element_shadow_root(copy_element) else trap("attach_a_shadow_root left no shadow root")

                # 5. Set copy’s shadow root’s declarative to node’s shadow root’s declarative.
                dom_shadow_root_set_declarative(copy_shadow_root, dom_shadow_root_declarative(node_shadow_root))

                # 6. Set copy’s shadow root’s keep custom element registry null to node’s shadow root’s keep custom element
                #    registry null.
                dom_shadow_root_set_keep_custom_element_registry_null(copy_shadow_root, dom_shadow_root_keep_custom_element_registry_null(node_shadow_root))

                # 7. For each child of node’s shadow root’s children, in tree order:
                #    clone a node given child with document set to document, subtree set to subtree, and parent set to copy’s
                #    shadow root.
                var child = tree_node_first_child(node_shadow_root.dom_node())
                while let child_node = child:
                    _ = try dom_node_clone_node(child_node, clone_document, subtree, copy_shadow_root.dom_node())
                    child = tree_node_next_sibling(child_node)

    # 7. Return copy.
    return copy

# mark: Move ====================================================================================

## The captures of Node::move_node's step 24 lambda.
struct DomNodeMoveNodeInclusiveDescendantSteps:
    var this: DomNode*
    var new_parent: DomNode*
    var old_parent: DomNode*

## Node::move_node's step 24 lambda, run for each shadow-including inclusive descendant of the
## moved node.
func dom_node_move_node_inclusive_descendant_steps(context: void*?, inclusive_descendant: DomNode*) -> TraversalDecision:
    let captures = (DomNodeMoveNodeInclusiveDescendantSteps*)(context else trap("no captures"))

    # 1. Let isSubtreeRoot be true if inclusiveDescendant is node; otherwise false.
    let is_subtree_root = DomNodeIsSubtreeRoot.yes if inclusive_descendant == captures.this else DomNodeIsSubtreeRoot.no

    # 2. Run the moving steps with inclusiveDescendant, isSubtreeRoot, and oldParent.
    dom_node_moved_from(inclusive_descendant, is_subtree_root, captures.old_parent)

    # NOTE: Because the move algorithm is a separate primitive from insert and remove, it does not invoke the
    #       insertion steps or removing steps for inclusiveDescendant.

    # 3. If inclusiveDescendant is custom and newParent is connected, then enqueue a custom element callback
    #    reaction with inclusiveDescendant, callback name "connectedMoveCallback", and « ».
    if let element = as_if_dom_element(inclusive_descendant):
        if dom_element_is_custom(element) and dom_node_is_connected(captures.new_parent):
            var empty_arguments: ak.Vector[JsValue]
            dom_element_enqueue_a_custom_element_callback_reaction(element, html_custom_element_reaction_names_connected_move_callback, empty_arguments)
    return TraversalDecision.continue_

## Ported from Node.cpp:1152 Web::DOM::Node::move_node.
# https://dom.spec.whatwg.org/#move
pub func dom_node_move_node(this: DomNode*, new_parent: DomNode*, child: DomNode*?) -> !:
    let realm = bind_platform_object_realm(new_parent.bind_platform_object())

    # 1. If newParent’s shadow-including root is not the same as node’s shadow-including root, then throw a "HierarchyRequestError" DOMException.
    if dom_node_shadow_including_root(new_parent) != dom_node_shadow_including_root(this):
        try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("New parent is not in the same shadow tree"))))

    # NOTE: This has the side effect of ensuring that a move is only performed if newParent’s connected is node’s connected.

    # 2. If node is a host-including inclusive ancestor of newParent, then throw a "HierarchyRequestError" DOMException.
    if dom_node_is_host_including_inclusive_ancestor_of(this, new_parent):
        try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("New parent is an ancestor of this node"))))

    # 3. If child is non-null and its parent is not newParent, then throw a "NotFoundError" DOMException.
    if let child_node = child:
        if tree_node_parent(child_node) != new_parent:
            try idl_throw(.idl_dom_exception(idl_not_found_error_create(realm, ak.utf16_string_from_str("Child does not belong to the new parent"))))

    # 4. If node is not an Element or a CharacterData node, then throw a "HierarchyRequestError" DOMException.
    if not is_dom_element(this) and not is_dom_character_data(this):
        try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # 5. If node is a Text node and newParent is a document, then throw a "HierarchyRequestError" DOMException.
    if is_dom_text(this) and is_dom_document(new_parent):
        try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # 6. If newParent is a document, node is an Element node, and either newParent has an element child, child is a doctype,
    #    or child is non-null and a doctype is following child then throw a "HierarchyRequestError" DOMException.
    if is_dom_document(new_parent) and is_dom_element(this):
        if tree_node_has_child_of_type(new_parent, &dom_element_class) or dom_node_is_doctype_or_has_following_doctype(child):
            try idl_throw(.idl_dom_exception(idl_hierarchy_request_error_create(realm, ak.utf16_string_from_str("Invalid node type for insertion"))))

    # 7. Let oldParent be node’s parent.
    # 8. Assert: oldParent is non-null.
    let old_parent = tree_node_parent(this) else trap("VERIFY: old_parent")
    let is_same_parent_move = old_parent == new_parent

    # 9. Run the live range pre-remove steps, given node.
    dom_node_live_range_pre_remove(this)

    # 10. For each NodeIterator object iterator whose root’s node document is node’s node document:
    #     run the NodeIterator pre-remove steps given node and iterator.
    dom_document_for_each_node_iterator(dom_node_document(this), ak.Function1[DomNodeIterator*, unit](call = dom_node_run_node_iterator_pre_removing_steps, context = this))

    # 11. Let oldPreviousSibling be node’s previous sibling.
    let old_previous_sibling = tree_node_previous_sibling(this)

    # 12. Let oldNextSibling be node’s next sibling.
    let old_next_sibling = tree_node_next_sibling(this)

    if dom_node_is_connected(old_parent):
        # Since the tree structure is about to change, we need to invalidate both style and layout.
        # In the future, we should find a way to only invalidate the parts that actually need it.
        if is_same_parent_move:
            css_invalidation_invalidate_style_after_same_parent_move(this, DomStyleInvalidationReason.node_remove)
        else:
            dom_node_invalidate_style(this, DomStyleInvalidationReason.node_remove)

        # NOTE: If we didn’t have a layout node before, rebuilding the layout tree isn’t gonna give us one
        #       after we’ve been removed from the DOM.
        # NB: Called during DOM node move, layout is not up to date.
        if dom_node_unsafe_layout_node(this) != none:
            dom_node_set_needs_layout_tree_update(old_parent, true, DomSetNeedsLayoutTreeUpdateReason.node_remove)

    # 13. Remove node from oldParent’s children.
    dom_node_remove_child_impl(old_parent, this)

    # 14. If node is assigned, then run assign slottables for node’s assigned slot.
    if let assigned_slot = dom_assigned_slot_for_node(this):
        dom_assign_slottables(assigned_slot)

    # 15. If oldParent’s root is a shadow root, and oldParent is a slot whose assigned nodes is empty, then run signal a slot change for oldParent.
    let old_parent_root = tree_node_root(old_parent)
    if let old_parent_slot_element = as_if_html_slot_element(old_parent):
        if dom_node_is_shadow_root(old_parent_root):
            if dom_slot_assigned_nodes_internal(&old_parent_slot_element.slot).length == 0:
                dom_signal_a_slot_change(old_parent_slot_element)

    # 16. If node has an inclusive descendant that is a slot:
    var has_descendent_slot = false
    let shadow_root = as_if_dom_shadow_root(old_parent_root)

    # for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>
    for inclusive_descendant in dom_node_inclusive_subtree(this):
        let slot = as_if_html_slot_element(inclusive_descendant) else continue
        has_descendent_slot = true
        let root = shadow_root else break
        # AD-HOC: Unregister slot from the shadow root's registry before assign_slottables_for_a_tree.
        dom_shadow_root_unregister_slot(root, slot)

    if has_descendent_slot:
        # 1. Run assign slottables for a tree with oldParent’s root.
        dom_assign_slottables_for_a_tree(old_parent_root)

        # 2. Run assign slottables for a tree with node.
        dom_assign_slottables_for_a_tree(this)

    # 17. If child is non-null:
    if let child_node = child:
        # 1. For each live range whose start node is newParent and start offset is greater than child’s index:
        #    increase its start offset by 1.
        for entry in ak.hash_table_begin(dom_range_live_ranges()):
            let range = *entry else continue
            if dom_abstract_range_start_container(range.dom_abstract_range()) == new_parent and (usize)dom_abstract_range_start_offset(range.dom_abstract_range()) > tree_node_index(child_node):
                dom_range_increase_start_offset(range, 1)

        # 2. For each live range whose end node is newParent and end offset is greater than child’s index:
        #    increase its end offset by 1.
        for entry in ak.hash_table_begin(dom_range_live_ranges()):
            let range = *entry else continue
            if dom_abstract_range_end_container(range.dom_abstract_range()) == new_parent and (usize)dom_abstract_range_end_offset(range.dom_abstract_range()) > tree_node_index(child_node):
                dom_range_increase_end_offset(range, 1)

    # 18. Let newPreviousSibling be child’s previous sibling if child is non-null, and newParent’s last child otherwise.
    var new_previous_sibling: DomNode*? = none
    if let child_node = child:
        new_previous_sibling = tree_node_previous_sibling(child_node)
    else:
        new_previous_sibling = tree_node_last_child(new_parent)

    # 19. If child is null, then append node to newParent’s children.
    if child == none:
        dom_node_append_child_impl(new_parent, this)
    # 20. Otherwise, insert node into newParent’s children before child’s index.
    else:
        dom_node_insert_before_impl(new_parent, this, child)

    if is_same_parent_move:
        css_invalidation_invalidate_style_after_same_parent_move(this, DomStyleInvalidationReason.node_insert_before)
    else:
        dom_node_invalidate_style(this, DomStyleInvalidationReason.node_insert_before)
    if dom_node_is_connected(this):
        dom_node_set_needs_layout_tree_update(new_parent, true, DomSetNeedsLayoutTreeUpdateReason.node_insert_before)

    # 21. If newParent is a shadow host whose shadow root’s slot assignment is "named" and node is a slottable, then assign a slot for node.
    if is_dom_element(new_parent) and is_dom_element(this):
        let new_parent_element = (DomElement*)new_parent

        let is_named_shadow_host = dom_node_is_named_shadow_host(new_parent_element)

        if is_named_shadow_host and dom_node_is_slottable(this):
            dom_assign_a_slot(dom_node_as_slottable(this))

    # AD-HOC: Register any slot elements in the moved subtree with the shadow root's slot registry so the registry is
    #         up-to-date.
    if let new_shadow_root = as_if_dom_shadow_root(tree_node_root(this)):
        # for_each_in_inclusive_subtree_of_type<HTML::HTMLSlotElement>
        for inclusive_descendant in dom_node_inclusive_subtree(this):
            if let slot = as_if_html_slot_element(inclusive_descendant):
                dom_shadow_root_register_slot(new_shadow_root, slot)

    # 22. If newParent’s root is a shadow root, and newParent is a slot whose assigned nodes is empty, then run signal a slot change for newParent.
    if let new_parent_slot_element = as_if_html_slot_element(new_parent):
        if dom_node_is_shadow_root(tree_node_root(new_parent)):
            if dom_slot_assigned_nodes_internal(&new_parent_slot_element.slot).length == 0:
                dom_signal_a_slot_change(new_parent_slot_element)

    # 23. Run assign slottables for a tree with node’s root.
    dom_assign_slottables_for_a_tree(tree_node_root(this))

    # 24. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
    var inclusive_descendant_steps = DomNodeMoveNodeInclusiveDescendantSteps(this = this, new_parent = new_parent, old_parent = old_parent)
    _ = dom_node_for_each_shadow_including_inclusive_descendant(this, ak.Function1[DomNode*, TraversalDecision](call = dom_node_move_node_inclusive_descendant_steps, context = &inclusive_descendant_steps))

    # 25. Queue a tree mutation record for oldParent with « », « node », oldPreviousSibling, and oldNextSibling.
    dom_node_queue_tree_mutation_record(old_parent, dom_node_no_nodes(), dom_node_one_node(this), old_previous_sibling, old_next_sibling)

    # 26. Queue a tree mutation record for newParent with « node », « », newPreviousSibling, and child.
    dom_node_queue_tree_mutation_record(new_parent, dom_node_one_node(this), dom_node_no_nodes(), new_previous_sibling, child)

    dom_document_bump_dom_tree_version(dom_node_document(this))