Skip to content

Truly independent web browser

8.7 KB
Raw Blame
/*
 * Copyright (c) 2020, the SerenityOS developers.
 * Copyright (c) 2023, Tim Flynn <[email protected]>
 * Copyright (c) 2025, Shannon Booth <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibGC/RootHashTable.h>
#include <LibGC/RootVector.h>
#include <LibWeb/Bindings/HTMLSlotElement.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/HTMLSlotElement.h>
#include <LibWeb/Page/Page.h>

namespace Web::HTML {

GC_DEFINE_ALLOCATOR(HTMLSlotElement);

HTMLSlotElement::HTMLSlotElement(DOM::Document& document, DOM::QualifiedName qualified_name)
    : HTMLElement(document, move(qualified_name))
{
}

HTMLSlotElement::~HTMLSlotElement() = default;

void HTMLSlotElement::visit_edges(JS::Cell::Visitor& visitor)
{
    Base::visit_edges(visitor);
    Slot::visit_edges(visitor);
    visitor.visit(m_manually_assigned_nodes);
}

static HTMLSlotElement::AssignedNodesFlatten assigned_nodes_flatten(Bindings::AssignedNodesOptions const& options)
{
    return options.flatten ? HTMLSlotElement::AssignedNodesFlatten::Yes : HTMLSlotElement::AssignedNodesFlatten::No;
}

// https://html.spec.whatwg.org/multipage/scripting.html#dom-slot-assignednodes
Vector<GC::Root<DOM::Node>> HTMLSlotElement::assigned_nodes(AssignedNodesFlatten flatten) const
{
    // 1. If options["flatten"] is false, then return this's assigned nodes.
    if (flatten == AssignedNodesFlatten::No) {
        assign_slottables_if_needed();
        Vector<GC::Root<DOM::Node>> assigned_nodes;
        assigned_nodes.ensure_capacity(assigned_nodes_internal().size());

        for (auto const& node : assigned_nodes_internal()) {
            node.visit([&](auto const& node) {
                assigned_nodes.unchecked_append(*node);
            });
        }

        return assigned_nodes;
    }

    // 2. Return the result of finding flattened slottables with this.
    // FIXME: Make this a lot less awkward!
    auto nodes = DOM::find_flattened_slottables(const_cast<HTMLSlotElement&>(*this));
    Vector<GC::Root<DOM::Node>> assigned_nodes;
    assigned_nodes.ensure_capacity(nodes.size());
    for (auto const& node : nodes) {
        node.visit([&](auto const& slottable) {
            assigned_nodes.unchecked_append(*slottable);
        });
    }
    return assigned_nodes;
}

Vector<GC::Root<DOM::Node>> HTMLSlotElement::assigned_nodes(Bindings::AssignedNodesOptions const& options) const
{
    return assigned_nodes(assigned_nodes_flatten(options));
}

// https://html.spec.whatwg.org/multipage/scripting.html#dom-slot-assignedelements
Vector<GC::Root<DOM::Element>> HTMLSlotElement::assigned_elements(AssignedNodesFlatten flatten) const
{
    // 1. If options["flatten"] is false, then return this's assigned nodes, filtered to contain only Element nodes.
    if (flatten == AssignedNodesFlatten::No) {
        assign_slottables_if_needed();
        Vector<GC::Root<DOM::Element>> assigned_nodes;

        for (auto const& node : assigned_nodes_internal()) {
            if (auto const* element = node.get_pointer<GC::Ref<DOM::Element>>())
                assigned_nodes.append(*element);
        }

        return assigned_nodes;
    }

    // 2. Return the result of finding flattened slottables with this, filtered to contain only Element nodes.
    auto result = DOM::find_flattened_slottables(const_cast<HTMLSlotElement&>(*this));
    Vector<GC::Root<DOM::Element>> assigned_nodes;
    for (auto const& node : result) {
        if (auto const* element = node.get_pointer<GC::Ref<DOM::Element>>())
            assigned_nodes.append(*element);
    }
    return assigned_nodes;
}

Vector<GC::Root<DOM::Element>> HTMLSlotElement::assigned_elements(Bindings::AssignedNodesOptions const& options) const
{
    return assigned_elements(assigned_nodes_flatten(options));
}

void HTMLSlotElement::assign_slottables_if_needed() const
{
    if (auto* shadow_root = as_if<DOM::ShadowRoot>(const_cast<HTMLSlotElement&>(*this).root()))
        shadow_root->assign_slottables_if_needed();
}

// https://html.spec.whatwg.org/multipage/scripting.html#dom-slot-assign
void HTMLSlotElement::assign(GC::RootVector<SlottableHandle> nodes)
{
    // AD-HOC: Assigned nodes are recomputed lazily.
    assign_slottables_if_needed();

    // A name that comes from content can come from the nodes assigned to a slot.
    if (document().page().accessibility_interested())
        document().invalidate_cached_accessibility_data(*this);

    // 1. For each node of this's manually assigned nodes, set node's manual slot assignment to null.
    for (auto& node : m_manually_assigned_nodes) {
        node.visit([&](auto& node) {
            node->set_manual_slot_assignment(nullptr);
        });
    }

    // 2. Let nodesSet be a new ordered set.
    GC::RootVector<DOM::Slottable> nodes_set;
    GC::RootHashTable<GC::Ref<DOM::Node const>> nodes_in_nodes_set;

    // INTEROP: The spec only assigns slottables for this's root below, so a slot in another tree that loses a node
    //          to this slot keeps it as an assigned node and fires no slotchange event. Browsers also assign
    //          slottables for the trees of those slots, and so do we.
    GC::RootVector<GC::Ref<DOM::Node>> roots_of_previous_slots;

    // 3. For each node of nodes:
    for (auto& node_handle : nodes) {
        auto& node = node_handle.visit([](auto& node) -> DOM::SlottableMixin& { return *node; });
        auto slottable = node_handle.visit([](auto& node) { return node->as_slottable(); });

        // 1. If node's manual slot assignment refers to a slot, then remove node from that slot's manually assigned nodes.
        if (node.manual_slot_assignment() != nullptr) {
            auto& previous_slot = *node.manual_slot_assignment();
            previous_slot.m_manually_assigned_nodes.remove_all_matching([&](auto const& manually_assigned_node) {
                return slottable == manually_assigned_node;
            });

            auto& previous_slot_root = previous_slot.root();
            if (&previous_slot_root != &root() && !roots_of_previous_slots.contains_slow(GC::Ref { previous_slot_root }))
                roots_of_previous_slots.append(previous_slot_root);
        }

        // 2. Set node's manual slot assignment to this.
        node.set_manual_slot_assignment(this);

        // 3. Append node to nodesSet.
        // NB: nodesSet is an ordered set, so a node that is already in it is not appended again.
        if (nodes_in_nodes_set.set(node_handle.visit([](auto& node) -> GC::Ref<DOM::Node const> { return *node; })) == HashSetResult::InsertedNewEntry)
            nodes_set.append(slottable);
    }

    // 4. Set this's manually assigned nodes to nodesSet.
    m_manually_assigned_nodes = move(nodes_set);

    // 5. Run assign slottables for a tree for this's root.
    assign_slottables_for_a_tree(root());

    // INTEROP: See roots_of_previous_slots above.
    for (auto const& previous_slot_root : roots_of_previous_slots)
        assign_slottables_for_a_tree(previous_slot_root);
}

// https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-change-ext
void HTMLSlotElement::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_)
{
    Base::attribute_changed(local_name, old_value, value, namespace_);

    // 1. If element is a slot, localName is name, and namespace is null, then:
    if (local_name == AttributeNames::name && !namespace_.has_value()) {
        // 1. If value is oldValue, then return.
        if (value == old_value)
            return;

        // 2. If value is null and oldValue is the empty string, then return.
        if (!value.has_value() && old_value == Utf16String {})
            return;

        // 3. If value is the empty string and oldValue is null, then return.
        if (value == Utf16String {} && !old_value.has_value())
            return;

        // AD-HOC: Assigned nodes are recomputed lazily.
        assign_slottables_if_needed();

        // OPTIMIZATION: Update the slot registry before changing the name.
        auto* shadow_root = as_if<DOM::ShadowRoot>(root());
        if (shadow_root)
            shadow_root->unregister_slot(*this);

        // 4. If value is null or the empty string, then set element’s name to the empty string.
        if (!value.has_value())
            set_slot_name({});
        // 5. Otherwise, set element’s name to value.
        else
            set_slot_name(*value);

        // OPTIMIZATION: Register the slot with its new name.
        if (shadow_root)
            shadow_root->register_slot(*this);

        // 6. Run assign slottables for a tree with element’s root.
        DOM::assign_slottables_for_a_tree(root());
    }
}

}