Skip to content

Truly independent web browser

1.5 KB
Raw Blame
/*
 * Copyright (c) 2020, Luke Wilde <[email protected]>
 * Copyright (c) 2024, circl <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibWeb/DOM/Element.h>
#include <LibWeb/DOM/EventTarget.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/ShadowRoot.h>
#include <LibWeb/DOM/Utils.h>

namespace Web::DOM {

// https://dom.spec.whatwg.org/#retarget
EventTarget* retarget(EventTarget* a, EventTarget* b)
{
    // To retarget an object A against an object B, repeat these steps until they return an object:
    for (;;) {
        // 1. If one of the following is true then return A.
        // - A is not a node
        auto* a_node = as_if<Node>(a);
        if (!a_node)
            return a;

        // - A’s root is not a shadow root
        auto& a_root = a_node->root();
        if (!is<ShadowRoot>(a_root))
            return a;

        // - B is a node and A’s root is a shadow-including inclusive ancestor of B
        if (auto* b_node = as_if<Node>(b); b_node && a_root.is_shadow_including_inclusive_ancestor_of(*b_node))
            return a;

        // 2. Set A to A’s root’s host.
        auto& a_shadow_root = as<ShadowRoot>(a_root);
        a = a_shadow_root.host();
    }
}

Element* retarget_from_ua_internal_shadow_root(Element& element)
{
    auto* result = &element;
    while (auto shadow_root = result->containing_shadow_root()) {
        if (!shadow_root->is_user_agent_internal())
            break;
        result = shadow_root->host();
    }
    return result;
}

}