File: ScrollTimeline.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (370 lines) | stat: -rw-r--r-- 14,059 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
 * Copyright (C) 2023 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ScrollTimeline.h"

#include "AnimationTimelinesController.h"
#include "DocumentInlines.h"
#include "Element.h"
#include "RenderLayerScrollableArea.h"
#include "RenderView.h"
#include "WebAnimation.h"

namespace WebCore {

Ref<ScrollTimeline> ScrollTimeline::create(Document& document, ScrollTimelineOptions&& options)
{
    // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-scrolltimeline

    // 1. Let timeline be the new ScrollTimeline object.
    auto timeline = adoptRef(*new ScrollTimeline);

    // 2. Set the source of timeline to:
    if (auto optionalSource = options.source) {
        // If the source member of options is present,
        // The source member of options.
        timeline->setSource(optionalSource->get());
    } else if (RefPtr scrollingElement = Ref { document }->scrollingElementForAPI()) {
        // Otherwise,
        // The scrollingElement of the Document associated with the Window that is the current global object.
        timeline->setSource(scrollingElement.get());
    }

    // 3. Set the axis property of timeline to the corresponding value from options.
    timeline->setAxis(options.axis);

    if (auto source = timeline->m_source.element()) {
        source->protectedDocument()->updateLayoutIgnorePendingStylesheets();
        timeline->cacheCurrentTime();
    }

    return timeline;
}

Ref<ScrollTimeline> ScrollTimeline::create(const AtomString& name, ScrollAxis axis)
{
    return adoptRef(*new ScrollTimeline(name, axis));
}

Ref<ScrollTimeline> ScrollTimeline::create(Scroller scroller, ScrollAxis axis)
{
    return adoptRef(*new ScrollTimeline(scroller, axis));
}

Ref<ScrollTimeline> ScrollTimeline::createInactiveStyleOriginatedTimeline(const AtomString& name)
{
    auto timeline = adoptRef(*new ScrollTimeline(name, ScrollAxis::Block));
    timeline->m_isInactiveStyleOriginatedTimeline = true;
    return timeline;
}

// https://drafts.csswg.org/web-animations-2/#timelines
// For a monotonic timeline, there is no upper bound on current time, and
// timeline duration is unresolved. For a non-monotonic (e.g. scroll) timeline,
// the duration has a fixed upper bound. In this case, the timeline is a
// progress-based timeline, and its timeline duration is 100%.
ScrollTimeline::ScrollTimeline()
    : AnimationTimeline(WebAnimationTime::fromPercentage(100))
{
}

ScrollTimeline::ScrollTimeline(const AtomString& name, ScrollAxis axis)
    : ScrollTimeline()
{
    m_axis = axis;
    m_name = name;
}

ScrollTimeline::ScrollTimeline(Scroller scroller, ScrollAxis axis)
    : ScrollTimeline()
{
    m_axis = axis;
    m_scroller = scroller;
}

Element* ScrollTimeline::source() const
{
    auto source = m_source.styleable();
    if (!source)
        return nullptr;

    switch (m_scroller) {
    case Scroller::Nearest: {
        if (CheckedPtr subjectRenderer = source->renderer()) {
            if (CheckedPtr nearestScrollableContainer = subjectRenderer->enclosingScrollableContainer()) {
                if (RefPtr nearestSource = nearestScrollableContainer->element()) {
                    auto document = nearestSource->protectedDocument();
                    RefPtr documentElement = document->documentElement();
                    if (nearestSource != documentElement)
                        return nearestSource.get();
                    // RenderObject::enclosingScrollableContainer() will return the document element even in
                    // quirks mode, but the scrolling element in that case is the <body> element, so we must
                    // make sure to return Document::scrollingElement() in case the document element is
                    // returned by enclosingScrollableContainer() but it was not explicitly set as the source.
                    return &source->element == documentElement ? nearestSource.get() : document->scrollingElement();
                }
            }
        }
        return nullptr;
    }
    case Scroller::Root:
        return source->element.protectedDocument()->scrollingElement();
    case Scroller::Self:
        return &source->element;
    }

    ASSERT_NOT_REACHED();
    return nullptr;
}

void ScrollTimeline::setSource(Element* source)
{
    if (source)
        setSource(Styleable::fromElement(*source));
    else {
        removeTimelineFromDocument(m_source.element().get());
        m_source = WeakStyleable();
    }
}

void ScrollTimeline::setSource(const Styleable& styleable)
{
    if (m_source == styleable)
        return;

    auto previousSource = m_source.element();
    m_source = styleable;

    if (previousSource && &previousSource->document() == &styleable.element.document())
        return;

    removeTimelineFromDocument(previousSource.get());

    styleable.element.protectedDocument()->ensureTimelinesController().addTimeline(*this);
}

void ScrollTimeline::removeTimelineFromDocument(Element* element)
{
    if (element) {
        if (CheckedPtr timelinesController = element->protectedDocument()->timelinesController())
            timelinesController->removeTimeline(*this);
    }
}

AnimationTimelinesController* ScrollTimeline::controller() const
{
    if (auto stylable = m_source.styleable())
        return &stylable->element.document().ensureTimelinesController();
    return nullptr;
}

std::optional<ScrollTimeline::ResolvedScrollDirection> ScrollTimeline::resolvedScrollDirection() const
{
    RefPtr source = this->source();
    if (!source)
        return { };

    CheckedPtr renderer = source->renderer();
    if (!renderer)
        return { };

    auto writingMode = renderer->style().writingMode();

    auto isVertical = [&] {
        switch (m_axis) {
        case ScrollAxis::Block:
            // https://drafts.csswg.org/scroll-animations-1/#valdef-scroll-block
            // Specifies to use the measure of progress along the block axis of the scroll container.
            // https://drafts.csswg.org/css-writing-modes-4/#block-axis
            // The axis in the block dimension, i.e. the vertical axis in horizontal writing modes and
            // the horizontal axis in vertical writing modes.
            return writingMode.isHorizontal();
        case ScrollAxis::Inline:
            // https://drafts.csswg.org/scroll-animations-1/#valdef-scroll-inline
            // Specifies to use the measure of progress along the inline axis of the scroll container.
            // https://drafts.csswg.org/css-writing-modes-4/#inline-axis
            // The axis in the inline dimension, i.e. the horizontal axis in horizontal writing modes and
            // the vertical axis in vertical writing modes.
            return writingMode.isVertical();
        case ScrollAxis::X:
            // https://drafts.csswg.org/scroll-animations-1/#valdef-scroll-x
            // Specifies to use the measure of progress along the horizontal axis of the scroll container.
            return false;
        case ScrollAxis::Y:
            // https://drafts.csswg.org/scroll-animations-1/#valdef-scroll-y
            // Specifies to use the measure of progress along the vertical axis of the scroll container.
            return true;
        }
        ASSERT_NOT_REACHED();
        return true;
    }();

    auto isReversed = (isVertical && !writingMode.isAnyTopToBottom()) || (!isVertical && !writingMode.isAnyLeftToRight());

    return { { isVertical, isReversed } };
}

void ScrollTimeline::cacheCurrentTime()
{
    auto previousMaxScrollOffset = m_cachedCurrentTimeData.maxScrollOffset;

    m_cachedCurrentTimeData = [&] -> CurrentTimeData {
        RefPtr source = this->source();
        if (!source)
            return { };
        auto* sourceScrollableArea = scrollableAreaForSourceRenderer(source->renderer(), source->document());
        if (!sourceScrollableArea)
            return { };
        auto scrollDirection = resolvedScrollDirection();
        if (!scrollDirection)
            return { };

        float scrollOffset = scrollDirection->isVertical ? sourceScrollableArea->scrollOffset().y() : sourceScrollableArea->scrollOffset().x();
        float maxScrollOffset = scrollDirection->isVertical ? sourceScrollableArea->maximumScrollOffset().y() : sourceScrollableArea->maximumScrollOffset().x();
        // Chrome appears to clip the current time of a scroll timeline in the [0-100] range.
        // We match this behavior for compatibility reasons, see https://github.com/w3c/csswg-drafts/issues/11033.
        if (maxScrollOffset > 0)
            scrollOffset = std::clamp(scrollOffset, 0.f, maxScrollOffset);
        return { scrollOffset, maxScrollOffset };
    }();

    if (previousMaxScrollOffset != m_cachedCurrentTimeData.maxScrollOffset) {
        for (auto& animation : m_animations)
            animation->progressBasedTimelineSourceDidChangeMetrics();
    }
}

AnimationTimeline::ShouldUpdateAnimationsAndSendEvents ScrollTimeline::documentWillUpdateAnimationsAndSendEvents()
{
    cacheCurrentTime();
    auto source = m_source.styleable();
    if (source && source->element.isConnected())
        return AnimationTimeline::ShouldUpdateAnimationsAndSendEvents::Yes;
    return AnimationTimeline::ShouldUpdateAnimationsAndSendEvents::No;
}

void ScrollTimeline::setTimelineScopeElement(const Element& element)
{
    m_timelineScopeElement = WeakPtr { &element };
}

ScrollableArea* ScrollTimeline::scrollableAreaForSourceRenderer(const RenderElement* renderer, Document& document)
{
    CheckedPtr renderBox = dynamicDowncast<RenderBox>(renderer);
    if (!renderBox)
        return nullptr;

    if (renderer->element() == Ref { document }->scrollingElement())
        return &renderer->view().frameView();

    return renderBox->hasLayer() ? renderBox->layer()->scrollableArea() : nullptr;
}

float ScrollTimeline::floatValueForOffset(const Length& offset, float maxValue)
{
    if (offset.isNormal() || offset.isAuto())
        return 0.f;
    return floatValueForLength(offset, maxValue);
}

TimelineRange ScrollTimeline::defaultRange() const
{
    return TimelineRange::defaultForScrollTimeline();
}

ScrollTimeline::Data ScrollTimeline::computeTimelineData() const
{
    if (!m_cachedCurrentTimeData.scrollOffset && !m_cachedCurrentTimeData.maxScrollOffset)
        return { };
    return {
        m_cachedCurrentTimeData.scrollOffset,
        0.f,
        m_cachedCurrentTimeData.maxScrollOffset
    };
}

std::pair<WebAnimationTime, WebAnimationTime> ScrollTimeline::intervalForAttachmentRange(const TimelineRange& attachmentRange) const
{
    auto maxScrollOffset = m_cachedCurrentTimeData.maxScrollOffset;
    if (!maxScrollOffset)
        return { WebAnimationTime::fromPercentage(0), WebAnimationTime::fromPercentage(100) };

    auto attachmentRangeOrDefault = attachmentRange.isDefault() ? defaultRange() : attachmentRange;

    auto computedPercentageIfNecessary = [&](const Length& length) {
        if (length.isPercent())
            return length.value();
        return floatValueForOffset(length, maxScrollOffset) / maxScrollOffset * 100;
    };

    return {
        WebAnimationTime::fromPercentage(computedPercentageIfNecessary(attachmentRangeOrDefault.start.offset)),
        WebAnimationTime::fromPercentage(computedPercentageIfNecessary(attachmentRangeOrDefault.end.offset))
    };
}

std::optional<WebAnimationTime> ScrollTimeline::currentTime()
{
    // https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress
    // Progress (the current time) for a scroll progress timeline is calculated as:
    // scroll offset ÷ (scrollable overflow size − scroll container size)
    auto data = computeTimelineData();
    auto range = data.rangeEnd - data.rangeStart;
    if (!range)
        return { };

    auto scrollDirection = resolvedScrollDirection();
    if (!scrollDirection)
        return { };

    auto distance = scrollDirection->isReversed ? data.rangeEnd - data.scrollOffset : data.scrollOffset - data.rangeStart;
    auto progress = distance / range;
    return WebAnimationTime::fromPercentage(progress * 100);
}

void ScrollTimeline::animationTimingDidChange(WebAnimation& animation)
{
    AnimationTimeline::animationTimingDidChange(animation);

    auto source = m_source.styleable();
    if (!source || !animation.pending() || animation.isEffectInvalidationSuspended())
        return;

    if (RefPtr page = source->element.protectedDocument()->page())
        page->scheduleRenderingUpdate(RenderingUpdateStep::Animations);
}

TextStream& operator<<(TextStream& ts, Scroller scroller)
{
    switch (scroller) {
    case Scroller::Nearest: ts << "nearest"; break;
    case Scroller::Root: ts << "root"; break;
    case Scroller::Self: ts << "self"; break;
    }
    return ts;
}

} // namespace WebCore