Skip to content

Truly independent web browser

24.3 KB
Raw Blame
/*
 * Copyright (c) 2021, Tim Flynn <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/QuickSort.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/IntersectionObserverEntry.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/BrowsingContext.h>
#include <LibWeb/HTML/LocalNavigable.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/IntersectionObserver/IntersectionObserver.h>
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/ValueParserRustFFI.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/CallbackType.h>

namespace Web::IntersectionObserver {

GC_DEFINE_ALLOCATOR(IntersectionObserver);

GC::Ref<WebIDL::CallbackType> create_lazy_load_intersection_observer_callback(DOM::Document& document)
{
    auto& realm = document.relevant_settings_object().realm();
    auto callback = JS::NativeFunction::create(realm, Utf16FlyString {}, GC::create_function(GC::Heap::the(), GC::captures(document), [](DOM::Document& document, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
        auto& entries = as<JS::Array>(vm.argument(0).as_object());
        auto entries_length = MUST(MUST(entries.get(vm.names.length)).to_length(vm));

        GC::RootVector<GC::Ref<IntersectionObserverEntry>> intersection_observer_entries;
        for (size_t i = 0; i < entries_length; ++i) {
            auto property_key = JS::PropertyKey { i };
            auto& entry_object = entries.get_without_side_effects(property_key).as_object();
            auto* entry = Bindings::impl_from<IntersectionObserverEntry>(&entry_object);
            VERIFY(entry);
            intersection_observer_entries.append(*entry);
        }

        document.process_lazy_load_intersection_observer_entries(intersection_observer_entries);
        return JS::js_undefined();
    }));

    return GC::Heap::the().allocate<WebIDL::CallbackType>(callback, realm);
}

void invoke_intersection_observer_callback(IntersectionObserver& observer, Vector<GC::Root<IntersectionObserverEntry>>& queue)
{
    auto& callback = observer.callback();
    auto& callback_realm = callback.callback_context->realm();

    auto wrapped_queue = MUST(JS::Array::create(callback_realm, 0));
    auto& wrapper_world = Bindings::host_defined_wrapper_world(callback_realm);
    for (size_t i = 0; i < queue.size(); ++i) {
        auto& record = queue.at(i);
        auto property_index = JS::PropertyKey { i };
        MUST(wrapped_queue->create_data_property(property_index, Bindings::wrap(wrapper_world, callback_realm, GC::Ref { *record })));
    }

    // NOTE: This does not follow the spec as written precisely, but this is the
    // same thing we do elsewhere and there is a WPT test that relies on this.
    auto wrapped_observer = Bindings::wrap(wrapper_world, callback_realm, GC::Ref { observer });
    (void)WebIDL::invoke_callback(callback, wrapped_observer, WebIDL::ExceptionBehavior::Report, { { wrapped_queue, wrapped_observer } });
}

WebIDL::ExceptionOr<GC::Ref<IntersectionObserver>> IntersectionObserver::create_with_implicit_root_document(GC::Ptr<WebIDL::CallbackType> callback, IntersectionObserverOptions options, DOM::Document& implicit_root_document)
{
    // https://w3c.github.io/IntersectionObserver/#initialize-a-new-intersectionobserver
    // 1. Let this be a new IntersectionObserver object
    // 2. Set this’s internal [[callback]] slot to callback.
    // NOTE: Steps 1 and 2 are handled by creating the IntersectionObserver at the very end of this function.

    // 3. Attempt to parse a margin from options.rootMargin. If a list is returned, set this’s internal [[rootMargin]] slot to that. Otherwise, throw a SyntaxError exception.
    auto root_margin = parse_a_margin(move(options.root_margin).to_utf8());
    if (!root_margin.has_value()) {
        return WebIDL::SyntaxError::create("IntersectionObserver: Cannot parse root margin as a margin."_utf16);
    }

    // 4. Attempt to parse a margin from options.scrollMargin. If a list is returned, set this’s internal [[scrollMargin]] slot to that. Otherwise, throw a SyntaxError exception.
    auto scroll_margin = parse_a_margin(move(options.scroll_margin).to_utf8());
    if (!scroll_margin.has_value()) {
        return WebIDL::SyntaxError::create("IntersectionObserver: Cannot parse scroll margin as a margin."_utf16);
    }

    // 5. Let thresholds be a list equal to options.threshold.
    Vector<double> thresholds;
    if (options.threshold.has<double>()) {
        thresholds.append(options.threshold.get<double>());
    } else {
        VERIFY(options.threshold.has<Vector<double>>());
        thresholds = move(options.threshold.get<Vector<double>>());
    }

    // 6. If any value in thresholds is less than 0.0 or greater than 1.0, throw a RangeError exception.
    for (auto value : thresholds) {
        if (value < 0.0 || value > 1.0)
            return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Threshold values must be between 0.0 and 1.0 inclusive"_utf16 };
    }

    // 7. Sort thresholds in ascending order.
    quick_sort(thresholds, [](double left, double right) {
        return left < right;
    });

    // 8. If thresholds is empty, append 0 to thresholds.
    if (thresholds.is_empty()) {
        thresholds.append(0);
    }

    // 9. The thresholds attribute getter will return this sorted thresholds list.
    // NOTE: Handled implicitly by passing it into the constructor at the end of this function

    // 10. Let delay be the value of options.delay.
    auto delay = options.delay;

    // 11. If options.trackVisibility is true and delay is less than 100, set delay to 100.
    if (options.track_visibility && delay < 100) {
        delay = 100;
    }

    // 12. Set this’s internal [[delay]] slot to options.delay to delay.
    // 13. Set this’s internal [[trackVisibility]] slot to options.trackVisibility.
    // 14. Return this.
    return GC::Heap::the().allocate<IntersectionObserver>(callback, options.root, implicit_root_document, move(root_margin.value()), move(scroll_margin.value()), move(thresholds), move(delay), options.track_visibility);
}

WebIDL::ExceptionOr<GC::Ref<IntersectionObserver>> IntersectionObserver::create_for_constructor(JS::Object& relevant_global_object, GC::Ptr<WebIDL::CallbackType> callback, IntersectionObserverOptions options)
{
    auto& window = HTML::relevant_window(relevant_global_object);
    // The implicit root is the top-level browsing context's document.
    // FIXME: Where another process hosts that document, the document rooting this process's part of the tree stands
    //        in, so intersections are not clipped by the viewports of the ancestors hosted there.
    // A window whose browsing context is gone (a removed iframe's) has no top-level browsing context either, so its own
    // document stands in. Nothing updates its observations.
    GC::Ptr<DOM::Document> implicit_root_document = window.associated_document();
    if (auto navigable = window.navigable())
        implicit_root_document = navigable->local_root()->active_document();
    VERIFY(implicit_root_document);
    return create_with_implicit_root_document(callback, options, *implicit_root_document);
}

IntersectionObserver::IntersectionObserver(GC::Ptr<WebIDL::CallbackType> callback, IntersectionObserverRoot const& root, GC::Ref<DOM::Document> implicit_root_document, Vector<CSS::LengthPercentage> root_margin, Vector<CSS::LengthPercentage> scroll_margin, Vector<double>&& thresholds, double delay, bool track_visibility)
    : m_callback(callback)
    , m_root_margin(root_margin)
    , m_scroll_margin(scroll_margin)
    , m_thresholds(move(thresholds))
    , m_delay(delay)
    , m_track_visibility(track_visibility)
{
    m_root = root.has<Empty>() ? nullptr : root.visit([](GC::Ref<DOM::Element> const& value) -> GC::Ptr<DOM::Node> { return value; }, [](GC::Ref<DOM::Document> const& value) -> GC::Ptr<DOM::Node> { return value; }, [](Empty) -> GC::Ptr<DOM::Node> { return nullptr; });

    if (m_root)
        m_document = m_root->document();
    else
        m_document = implicit_root_document;

    VERIFY(m_document);
    m_document->register_intersection_observer({}, *this);
}

IntersectionObserver::~IntersectionObserver() = default;

void IntersectionObserver::visit_edges(GC::Cell::Visitor& visitor)
{
    Base::visit_edges(visitor);
    visitor.visit(m_root);
    visitor.visit(m_callback);
    visitor.visit(m_queued_entries);
}

void IntersectionObserver::remove_dead_observation_targets()
{
    m_observation_targets.remove_all_matching([](auto const& observed_target) {
        return !observed_target.target;
    });
}

// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-observe
void IntersectionObserver::observe(DOM::Element& target)
{
    // Run the observe a target Element algorithm, providing this and target.
    // https://www.w3.org/TR/intersection-observer/#observe-a-target-element
    // 1. If target is in observer’s internal [[ObservationTargets]] slot, return.
    auto observed_target = m_observation_targets.find_if([&target](auto const& entry) {
        return entry.target == &target;
    });
    if (!observed_target.is_end())
        return;

    // 2. Let intersectionObserverRegistration be an IntersectionObserverRegistration record with an observer
    //    property set to observer, a previousThresholdIndex property set to -1, and a previousIsIntersecting
    //    property set to false.
    // NB: This implementation deviates from the spec's storage model. target's
    //     [[RegisteredIntersectionObservers]] only keeps a strong reference to the observer for lifetime
    //     management, while the mutable registration fields live in the observer-side observation target below.
    target.register_intersection_observer({}, *this);

    // 3. Append intersectionObserverRegistration to target’s internal [[RegisteredIntersectionObservers]] slot.
    // NB: Keeping previousThresholdIndex and previousIsIntersecting on the observer-side observation target lets
    //     the update loop read and write them without a second lookup through target’s registered observers.
    //
    // 4. Add target to observer’s internal [[ObservationTargets]] slot.
    m_observation_targets.append(ObservationTarget {
        .target = target,
        .previous_threshold_index = OptionalNone {},
        .previous_is_intersecting = false,
    });

    // AD-HOC: Registering an observation changes whether transforms can remain compositor driven. Bring any pending
    //         throttled animation state to a point where compositor eligibility can be updated by the requested frame.
    target.document().flush_throttled_animation_style_update_for_node(target);
    set_rendering_pending(*m_document, RenderingPendingReason::NeedsRenderingUpdate, 1);
    m_document->page().client().request_frame();
}

// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-unobserve
void IntersectionObserver::unobserve(DOM::Element& target)
{
    // Run the unobserve a target Element algorithm, providing this and target.
    // https://www.w3.org/TR/intersection-observer/#unobserve-a-target-element
    // 1. Remove the IntersectionObserverRegistration record whose observer property is equal to this from target’s internal [[RegisteredIntersectionObservers]] slot, if present.
    target.unregister_intersection_observer({}, *this);

    // 2. Remove target from this’s internal [[ObservationTargets]] slot, if present
    m_observation_targets.remove_first_matching([&target](ObservationTarget const& entry) {
        return entry.target == &target;
    });
}

// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-disconnect
void IntersectionObserver::disconnect()
{
    // For each target in this’s internal [[ObservationTargets]] slot:
    // 1. Remove the IntersectionObserverRegistration record whose observer property is equal to this from target’s internal
    //    [[RegisteredIntersectionObservers]] slot.
    // 2. Remove target from this’s internal [[ObservationTargets]] slot.
    for (auto& observed_target : m_observation_targets) {
        if (auto target = observed_target.target.ptr())
            target->unregister_intersection_observer({}, *this);
    }
    m_observation_targets.clear();
}

// https://www.w3.org/TR/intersection-observer/#dom-intersectionobserver-takerecords
Vector<GC::Root<IntersectionObserverEntry>> IntersectionObserver::take_records()
{
    // 1. Let queue be a copy of this’s internal [[QueuedEntries]] slot.
    Vector<GC::Root<IntersectionObserverEntry>> queue;
    for (auto& entry : m_queued_entries)
        queue.append(*entry);

    // 2. Clear this’s internal [[QueuedEntries]] slot.
    m_queued_entries.clear();

    // 3. Return queue.
    return queue;
}

NullableIntersectionObserverRoot IntersectionObserver::root() const
{
    if (!m_root)
        return Empty {};
    if (m_root->is_element())
        return GC::Ref { static_cast<DOM::Element&>(*m_root) };
    if (m_root->is_document())
        return GC::Ref { static_cast<DOM::Document&>(*m_root) };
    VERIFY_NOT_REACHED();
}

static void append_margin_value(Utf16StringBuilder& builder, CSS::LengthPercentage const& value)
{
    auto serialized = value.to_string(CSS::SerializationMode::ResolvedValue);
    builder.append_ascii(serialized.bytes_as_string_view());
}

// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin
Utf16String IntersectionObserver::root_margin() const
{
    // On getting, return the result of serializing the elements of [[rootMargin]] space-separated, where pixel
    // lengths serialize as the numeric value followed by "px", and percentages serialize as the numeric value
    // followed by "%". Note that this is not guaranteed to be identical to the options.rootMargin passed to the
    // IntersectionObserver constructor. If no rootMargin was passed to the IntersectionObserver
    // constructor, the value of this attribute is "0px 0px 0px 0px".
    Utf16StringBuilder builder;
    append_margin_value(builder, m_root_margin[0]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_root_margin[1]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_root_margin[2]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_root_margin[3]);
    return builder.to_string();
}

// https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-scrollmargin
Utf16String IntersectionObserver::scroll_margin() const
{
    // On getting, return the result of serializing the elements of [[scrollMargin]] space-separated, where pixel
    // lengths serialize as the numeric value followed by "px", and percentages serialize as the numeric value
    // followed by "%". Note that this is not guaranteed to be identical to the options.scrollMargin passed to the
    // IntersectionObserver constructor. If no scrollMargin was passed to the IntersectionObserver
    // constructor, the value of this attribute is "0px 0px 0px 0px".
    Utf16StringBuilder builder;
    append_margin_value(builder, m_scroll_margin[0]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_scroll_margin[1]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_scroll_margin[2]);
    builder.append_ascii(' ');
    append_margin_value(builder, m_scroll_margin[3]);
    return builder.to_string();
}

// https://www.w3.org/TR/intersection-observer/#intersectionobserver-intersection-root
Variant<GC::Ref<DOM::Element>, GC::Ref<DOM::Document>> IntersectionObserver::intersection_root() const
{
    auto root_node = intersection_root_node();
    if (root_node->is_element())
        return GC::Ref { static_cast<DOM::Element&>(*root_node) };
    return GC::Ref { static_cast<DOM::Document&>(*root_node) };
}

GC::Ref<DOM::Node> IntersectionObserver::intersection_root_node() const
{
    if (m_root)
        return *m_root;

    // The implicit root is the top-level browsing context’s document node.
    // FIXME: See create_for_constructor(): the document rooting this process's part of the tree stands in.
    // A document that has lost its navigable stands in for itself, as in create_for_constructor().
    VERIFY(m_document);
    auto navigable = m_document->navigable();
    if (!navigable)
        return *m_document;
    return *navigable->local_root()->active_document();
}

// https://www.w3.org/TR/intersection-observer/#intersectionobserver-root-intersection-rectangle
CSSPixelRect IntersectionObserver::root_intersection_rectangle(Layout::BegunRead const& read, Optional<MonotonicTime> visual_animation_sample_time) const
{
    // If the IntersectionObserver is an implicit root observer,
    //    it’s treated as if the root were the top-level browsing context’s document, according to the following rule for document.
    auto intersection_root = this->intersection_root();

    CSSPixelRect rect;
    bool intersection_root_is_scrollable = false;

    // If the intersection root is a document,
    //    it’s the size of the document's viewport (note that this processing step can only be reached if the document is fully active).
    if (intersection_root.has<GC::Ref<DOM::Document>>()) {
        auto document = intersection_root.get<GC::Ref<DOM::Document>>();

        // Since the spec says that this is only reach if the document is fully active, that means it must have a navigable.
        VERIFY(document->navigable());

        // NOTE: This rect is in the same layout viewport coordinate space as
        //       Element::getBoundingClientRect().
        rect = CSSPixelRect {
            CSSPixelPoint { 0, 0 },
            document->viewport_rect().size(),
        };

        // A local root another process embeds is the top-level viewport only where its embedder shows it, and a
        // margin cannot bring back what it shows none of.
        if (auto intersection = document->navigable()->viewport_intersection(); intersection.has_value()) {
            if (intersection->is_empty())
                return {};
            rect = *intersection;
        }
        intersection_root_is_scrollable = true;
    } else {
        VERIFY(intersection_root.has<GC::Ref<DOM::Element>>());
        auto element = intersection_root.get<GC::Ref<DOM::Element>>();

        // FIXME: Otherwise, if the intersection root has a content clip,
        //          it’s the element’s content area.

        // Otherwise,
        //    it’s the result of getting the bounding box for the intersection root.
        rect = visual_animation_sample_time.has_value()
            ? element->bounding_client_rect_assuming_layout_clean(read, *visual_animation_sample_time)
            : element->bounding_client_rect_assuming_layout_clean();
        if (auto const* layout_node = element->layout_node(read); layout_node && Painting::has_committed_box(*layout_node))
            intersection_root_is_scrollable = layout_node->is_scroll_container();
    }

    // When calculating the root intersection rectangle for a same-origin-domain target, the rectangle is then
    // expanded according to the offsets in the IntersectionObserver’s [[rootMargin]] slot in a manner similar
    // to CSS’s margin property, with the four values indicating the amount the top, right, bottom, and left
    // edges, respectively, are offset by, with positive lengths indicating an outward offset. Percentages
    // are resolved relative to the width of the undilated rectangle.
    DOM::Document* document = { nullptr };
    if (intersection_root.has<GC::Ref<DOM::Document>>()) {
        document = intersection_root.get<GC::Ref<DOM::Document>>().ptr();
    } else {
        document = &intersection_root.get<GC::Ref<DOM::Element>>()->document();
    }
    if (m_document && document->origin().is_same_origin(m_document->origin())) {
        auto const undilated_width = rect.width();
        CSSPixels top = m_root_margin[0].to_px(rect.height());
        CSSPixels right = m_root_margin[1].to_px(undilated_width);
        CSSPixels bottom = m_root_margin[2].to_px(rect.height());
        CSSPixels left = m_root_margin[3].to_px(undilated_width);

        // https://w3c.github.io/IntersectionObserver/#scrollmargin
        // NOTE: scrollMargin affects the clipping of target by all scrollable ancestors up to and including the
        //       intersection root. Both the scrollMargin and the rootMargin are applied to a scrollable intersection
        //       root's rectangle.
        if (intersection_root_is_scrollable) {
            top += m_scroll_margin[0].to_px(undilated_width);
            right += m_scroll_margin[1].to_px(undilated_width);
            bottom += m_scroll_margin[2].to_px(undilated_width);
            left += m_scroll_margin[3].to_px(undilated_width);
        }

        rect.inflate(top, right, bottom, left);
    }

    return rect;
}

void IntersectionObserver::queue_entry(Badge<DOM::Document>, GC::Ref<IntersectionObserverEntry> entry)
{
    m_queued_entries.append(entry);
}

// https://w3c.github.io/IntersectionObserver/#parse-a-margin
Optional<Vector<CSS::LengthPercentage>> IntersectionObserver::parse_a_margin(String margin_string)
{
    // 1. Parse a list of component values marginString, storing the result as tokens.
    // 2. Remove all whitespace tokens from tokens.
    // 3. If the length of tokens is greater than 4, return failure.
    // 4. If there are zero elements in tokens, set tokens to ["0px"].
    struct MarginParsingContext {
        Vector<CSS::LengthPercentage>* values;
        bool* valid;
    };

    // 5. Replace each token in tokens:
    // NOTE: In the spec, tokens miraculously changes type from a list of component values
    //       to a list of pixel lengths or percentages.
    Vector<CSS::LengthPercentage> tokens_length_percentage;
    bool valid = true;
    auto source = Utf16String::from_utf8(margin_string);
    auto source_view = source.utf16_view();
    CSS::Parser::ValueParserFFI::FfiUtf16View ffi_source {
        .latin1 = source_view.has_latin1_storage() ? source_view.latin1_span().data() : nullptr,
        .utf16 = source_view.has_latin1_storage() ? nullptr : reinterpret_cast<u16 const*>(source_view.utf16_span().data()),
        .length = source_view.length_in_code_units(),
    };
    auto visit = [](void* context, u8 type, double value, u16 const* unit, size_t unit_length) {
        auto& state = *static_cast<MarginParsingContext*>(context);
        if (type == 1) {
            // If token is a <percentage> token, replace it with an equivalent percentage.
            state.values->append(CSS::Percentage(value));
            return;
        }
        // If token is an absolute length dimension token, replace it with a an equivalent pixel length.
        auto unit_name = Utf16View { reinterpret_cast<char16_t const*>(unit), unit_length };
        if (auto length_unit = CSS::string_to_length_unit(unit_name); length_unit.has_value()) {
            if (auto length = CSS::Length(value, length_unit.release_value()); length.is_absolute()) {
                state.values->append(length);
                return;
            }
        }
        // Otherwise, return failure.
        *state.valid = false;
    };
    MarginParsingContext context { &tokens_length_percentage, &valid };
    if (!CSS::Parser::ValueParserFFI::rust_visit_margin_components(ffi_source, &context, visit) || !valid)
        return {};
    if (tokens_length_percentage.is_empty())
        tokens_length_percentage.append(CSS::Length::make_px(0));

    // 6.
    switch (tokens_length_percentage.size()) {
    // If there is one element in tokens, append three duplicates of that element to tokens.
    case 1:
        tokens_length_percentage.append(tokens_length_percentage.first());
        tokens_length_percentage.append(tokens_length_percentage.first());
        tokens_length_percentage.append(tokens_length_percentage.first());
        break;
    // Otherwise, if there are two elements are tokens, append a duplicate of each element to tokens.
    case 2:
        tokens_length_percentage.append(tokens_length_percentage.at(0));
        tokens_length_percentage.append(tokens_length_percentage.at(1));
        break;
    // Otherwise, if there are three elements in tokens, append a duplicate of the second element to tokens.
    case 3:
        tokens_length_percentage.append(tokens_length_percentage.at(1));
        break;
    }

    // 7. Return tokens.
    return tokens_length_percentage;
}

}