-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
css_animations.cc
3192 lines (2826 loc) · 127 KB
/
css_animations.cc
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2013 Google 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* OWNER 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 "third_party/blink/renderer/core/animation/css/css_animations.h"
#include <algorithm>
#include <bitset>
#include <tuple>
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_computed_effect_timing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_cssnumericvalue_double.h"
#include "third_party/blink/renderer/core/animation/animation.h"
#include "third_party/blink/renderer/core/animation/animation_utils.h"
#include "third_party/blink/renderer/core/animation/compositor_animations.h"
#include "third_party/blink/renderer/core/animation/css/compositor_keyframe_value_factory.h"
#include "third_party/blink/renderer/core/animation/css/css_animation.h"
#include "third_party/blink/renderer/core/animation/css/css_keyframe_effect_model.h"
#include "third_party/blink/renderer/core/animation/css/css_transition.h"
#include "third_party/blink/renderer/core/animation/css_default_interpolation_type.h"
#include "third_party/blink/renderer/core/animation/css_interpolation_types_map.h"
#include "third_party/blink/renderer/core/animation/document_animations.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/animation/inert_effect.h"
#include "third_party/blink/renderer/core/animation/interpolation.h"
#include "third_party/blink/renderer/core/animation/interpolation_environment.h"
#include "third_party/blink/renderer/core/animation/interpolation_type.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect_model.h"
#include "third_party/blink/renderer/core/animation/timing.h"
#include "third_party/blink/renderer/core/animation/timing_calculations.h"
#include "third_party/blink/renderer/core/animation/transition_interpolation.h"
#include "third_party/blink/renderer/core/animation/worklet_animation_base.h"
#include "third_party/blink/renderer/core/css/css_keyframe_rule.h"
#include "third_party/blink/renderer/core/css/css_property_equality.h"
#include "third_party/blink/renderer/core/css/css_value_list.h"
#include "third_party/blink/renderer/core/css/parser/css_variable_parser.h"
#include "third_party/blink/renderer/core/css/post_style_update_scope.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/properties/css_property.h"
#include "third_party/blink/renderer/core/css/properties/css_property_ref.h"
#include "third_party/blink/renderer/core/css/properties/longhands.h"
#include "third_party/blink/renderer/core/css/property_registry.h"
#include "third_party/blink/renderer/core/css/resolver/css_to_style_map.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/events/event_path.h"
#include "third_party/blink/renderer/core/dom/layout_tree_builder_traversal.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/animation_event.h"
#include "third_party/blink/renderer/core/events/transition_event.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/style_property_shorthand.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/instrumentation/histogram.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
namespace blink {
using PropertySet = HashSet<CSSPropertyName>;
namespace {
class CSSAnimationProxy : public AnimationProxy {
public:
CSSAnimationProxy(AnimationTimeline* timeline,
CSSAnimation* animation,
bool is_paused,
const absl::optional<TimelineOffset>& range_start,
const absl::optional<TimelineOffset>& range_end,
const Timing& timing);
// AnimationProxy interface.
bool AtScrollTimelineBoundary() const override {
return at_scroll_timeline_boundary_;
}
absl::optional<AnimationTimeDelta> TimelineDuration() const override {
return timeline_duration_;
}
AnimationTimeDelta IntrinsicIterationDuration() const override {
return intrinsic_iteration_duration_;
}
double PlaybackRate() const override { return playback_rate_; }
bool Paused() const override { return is_paused_; }
absl::optional<AnimationTimeDelta> InheritedTime() const override {
return inherited_time_;
}
private:
absl::optional<AnimationTimeDelta> CalculateInheritedTime(
AnimationTimeline* timeline,
CSSAnimation* animation,
const absl::optional<TimelineOffset>& range_start,
const absl::optional<TimelineOffset>& range_end,
const Timing& timing);
double playback_rate_ = 1;
absl::optional<AnimationTimeDelta> inherited_time_;
AnimationTimeDelta intrinsic_iteration_duration_;
absl::optional<AnimationTimeDelta> timeline_duration_;
bool is_paused_;
bool at_scroll_timeline_boundary_ = false;
};
CSSAnimationProxy::CSSAnimationProxy(
AnimationTimeline* timeline,
CSSAnimation* animation,
bool is_paused,
const absl::optional<TimelineOffset>& range_start,
const absl::optional<TimelineOffset>& range_end,
const Timing& timing)
: is_paused_(is_paused) {
absl::optional<TimelineOffset> adjusted_range_start;
absl::optional<TimelineOffset> adjusted_range_end;
if (animation) {
playback_rate_ = animation->playbackRate();
adjusted_range_start = animation->GetIgnoreCSSRangeStart()
? animation->GetRangeStartInternal()
: range_start;
adjusted_range_end = animation->GetIgnoreCSSRangeEnd()
? animation->GetRangeEndInternal()
: range_end;
} else {
adjusted_range_start = range_start;
adjusted_range_end = range_end;
}
intrinsic_iteration_duration_ =
timeline ? timeline->CalculateIntrinsicIterationDuration(
adjusted_range_start, adjusted_range_end, timing)
: AnimationTimeDelta();
inherited_time_ = CalculateInheritedTime(
timeline, animation, adjusted_range_start, adjusted_range_end, timing);
timeline_duration_ = timeline ? timeline->GetDuration() : absl::nullopt;
if (timeline && timeline->IsProgressBased() && timeline->CurrentTime()) {
AnimationTimeDelta timeline_time = timeline->CurrentTime().value();
at_scroll_timeline_boundary_ =
timeline_time.is_zero() ||
IsWithinAnimationTimeTolerance(timeline_time,
timeline_duration_.value());
}
}
absl::optional<AnimationTimeDelta> CSSAnimationProxy::CalculateInheritedTime(
AnimationTimeline* timeline,
CSSAnimation* animation,
const absl::optional<TimelineOffset>& range_start,
const absl::optional<TimelineOffset>& range_end,
const Timing& timing) {
absl::optional<AnimationTimeDelta> inherited_time;
// Even in cases where current time is "preserved" the internal value may
// change if using a scroll-driven animation since preserving the progress and
// not the actual underlying time.
absl::optional<double> previous_progress;
AnimationTimeline* previous_timeline = nullptr;
if (animation) {
// A cancelled CSS animation does not become active again due to an
// animation update.
if (animation->CalculateAnimationPlayState() == Animation::kIdle) {
return absl::nullopt;
}
// In most cases, current time is preserved on an animation update.
inherited_time = animation->UnlimitedCurrentTime();
if (inherited_time) {
previous_progress =
animation->TimeAsAnimationProgress(inherited_time.value());
}
previous_timeline = animation->TimelineInternal();
}
bool range_changed =
!animation || ((range_start != animation->GetRangeStartInternal() ||
range_end != animation->GetRangeEndInternal()) &&
!animation->StartTimeInternal());
if (timeline && timeline->IsProgressBased()) {
if (is_paused_ && timeline != previous_timeline) {
if (!previous_progress) {
return absl::nullopt;
}
// Preserve current animation progress.
AnimationTimeDelta iteration_duration =
timeline->CalculateIntrinsicIterationDuration(animation, timing);
AnimationTimeDelta active_duration =
iteration_duration * timing.iteration_count;
// TODO(kevers): Revisit once % delays are supported.
return previous_progress.value() * active_duration;
}
if ((timeline == previous_timeline) && !range_changed) {
return inherited_time;
}
// Running animation with an update that potentially affects the
// animation's start time. Need to compute a new value for
// inherited_time_.
double relative_offset;
TimelineRange timeline_range = timeline->GetTimelineRange();
if (playback_rate_ >= 0) {
relative_offset =
range_start ? timeline_range.ToFractionalOffset(range_start.value())
: 0;
} else {
relative_offset =
range_end ? timeline_range.ToFractionalOffset(range_end.value()) : 1;
}
if (timeline->CurrentTime()) {
// This might not be correct for an animation with a sticky start time.
AnimationTimeDelta pending_start_time =
timeline->GetDuration().value() * relative_offset;
return (timeline->CurrentTime().value() - pending_start_time) *
playback_rate_;
}
return absl::nullopt;
}
if (previous_timeline && previous_timeline->IsProgressBased() &&
previous_progress) {
// Going from a progress-based timeline to a document or null timeline.
// In this case, we preserve the animation progress to avoid a
// discontinuity.
AnimationTimeDelta end_time = std::max(
timing.start_delay.AsTimeValue() +
MultiplyZeroAlwaysGivesZero(
timing.iteration_duration.value_or(AnimationTimeDelta()),
timing.iteration_count) +
timing.end_delay.AsTimeValue(),
AnimationTimeDelta());
return previous_progress.value() * end_time;
}
if (!timeline) {
// If changing from a monotonic-timeline to a null-timeline, current time
// may become null.
// TODO(https://github.com/w3c/csswg-drafts/issues/6412): Update once the
// issue is resolved.
if (previous_timeline && previous_timeline->IsMonotonicallyIncreasing() &&
!is_paused_ && animation->StartTimeInternal() &&
animation->CalculateAnimationPlayState() == Animation::kRunning) {
return absl::nullopt;
}
// A new animation with a null timeline will be stuck in the play or pause
// pending state.
if (!inherited_time && !animation) {
return AnimationTimeDelta();
}
}
// A timeline attached to a monotonic timeline that does not currently have a
// time will start in either the play or paused state.
if (timeline && timeline->IsMonotonicallyIncreasing() && !inherited_time) {
return AnimationTimeDelta();
}
return inherited_time;
}
class CSSTransitionProxy : public AnimationProxy {
public:
explicit CSSTransitionProxy(absl::optional<AnimationTimeDelta> current_time)
: current_time_(current_time) {}
// AnimationProxy interface.
bool AtScrollTimelineBoundary() const override { return false; }
absl::optional<AnimationTimeDelta> TimelineDuration() const override {
return absl::nullopt;
}
AnimationTimeDelta IntrinsicIterationDuration() const override {
return AnimationTimeDelta();
}
double PlaybackRate() const override { return 1; }
bool Paused() const override { return false; }
absl::optional<AnimationTimeDelta> InheritedTime() const override {
return current_time_;
}
private:
absl::optional<AnimationTimeDelta> current_time_;
};
// A keyframe can have an offset as a fixed percent or as a
// <timeline-range percent>. In the later case, we store the specified
// offset on the Keyframe, and delay the resolution that offset until later.
// (See ResolveTimelineOffset).
bool SetOffsets(Keyframe& keyframe, const KeyframeOffset& offset) {
if (offset.name == TimelineOffset::NamedRange::kNone) {
keyframe.SetOffset(offset.percent);
return false;
}
TimelineOffset timeline_offset(offset.name,
Length::Percent(100 * offset.percent));
keyframe.SetOffset(absl::nullopt);
keyframe.SetTimelineOffset(timeline_offset);
return true;
}
// Processes keyframe rules, extracting the timing function and properties being
// animated for each keyframe. The extraction process is doing more work that
// strictly required for the setup to step 6 in the spec
// (https://drafts.csswg.org/css-animations-2/#keyframes) as an optimization
// to avoid needing to process each rule multiple times to extract different
// properties.
StringKeyframeVector ProcessKeyframesRule(
const StyleRuleKeyframes* keyframes_rule,
const TreeScope* tree_scope,
const Document& document,
const ComputedStyle* parent_style,
TimingFunction* default_timing_function,
WritingMode writing_mode,
TextDirection text_direction,
bool& has_named_range_keyframes) {
StringKeyframeVector keyframes;
const HeapVector<Member<StyleRuleKeyframe>>& style_keyframes =
keyframes_rule->Keyframes();
for (wtf_size_t i = 0; i < style_keyframes.size(); ++i) {
const StyleRuleKeyframe* style_keyframe = style_keyframes[i].Get();
auto* keyframe = MakeGarbageCollected<StringKeyframe>(tree_scope);
const Vector<KeyframeOffset>& offsets = style_keyframe->Keys();
DCHECK(!offsets.empty());
has_named_range_keyframes |= SetOffsets(*keyframe, offsets[0]);
keyframe->SetEasing(default_timing_function);
const CSSPropertyValueSet& properties = style_keyframe->Properties();
for (unsigned j = 0; j < properties.PropertyCount(); j++) {
CSSPropertyValueSet::PropertyReference property_reference =
properties.PropertyAt(j);
CSSPropertyRef ref(property_reference.Name(), document);
const CSSProperty& property = ref.GetProperty();
if (RuntimeEnabledFeatures::CSSAnimationCompositionEnabled() &&
property.PropertyID() == CSSPropertyID::kAnimationComposition) {
if (const auto* value_list =
DynamicTo<CSSValueList>(property_reference.Value())) {
if (const auto* identifier_value =
DynamicTo<CSSIdentifierValue>(value_list->Item(0))) {
keyframe->SetComposite(
identifier_value->ConvertTo<EffectModel::CompositeOperation>());
}
}
} else if (property.PropertyID() ==
CSSPropertyID::kAnimationTimingFunction) {
const CSSValue& value = property_reference.Value();
scoped_refptr<TimingFunction> timing_function;
if (value.IsInheritedValue() && parent_style->Animations()) {
timing_function = parent_style->Animations()->TimingFunctionList()[0];
} else if (auto* value_list = DynamicTo<CSSValueList>(value)) {
timing_function =
CSSToStyleMap::MapAnimationTimingFunction(value_list->Item(0));
} else {
DCHECK(value.IsCSSWideKeyword());
timing_function = CSSTimingData::InitialTimingFunction();
}
keyframe->SetEasing(std::move(timing_function));
} else if (!CSSAnimations::IsAnimationAffectingProperty(property)) {
// Map Logical to physical property name.
const CSSProperty& physical_property =
property.ResolveDirectionAwareProperty(text_direction,
writing_mode);
const CSSPropertyName& name = physical_property.GetCSSPropertyName();
keyframe->SetCSSPropertyValue(name, property_reference.Value());
}
}
keyframes.push_back(keyframe);
// The last keyframe specified at a given offset is used.
for (wtf_size_t j = 1; j < offsets.size(); ++j) {
StringKeyframe* clone = To<StringKeyframe>(keyframe->Clone());
has_named_range_keyframes |= SetOffsets(*clone, offsets[j]);
keyframes.push_back(clone);
}
}
for (wtf_size_t i = 0; i < keyframes.size(); i++) {
keyframes[i]->SetIndex(i);
}
std::stable_sort(keyframes.begin(), keyframes.end(), &Keyframe::LessThan);
return keyframes;
}
// Finds the index of a keyframe with matching offset and easing.
absl::optional<int> FindIndexOfMatchingKeyframe(
const StringKeyframeVector& keyframes,
wtf_size_t start_index,
absl::optional<double> offset,
absl::optional<TimelineOffset> timeline_offset,
const TimingFunction& easing,
const absl::optional<EffectModel::CompositeOperation>& composite) {
for (wtf_size_t i = start_index; i < keyframes.size(); i++) {
StringKeyframe* keyframe = keyframes[i];
// Keyframes are sorted by offset. Search can stop once we hit and offset
// that exceeds the target value.
if (offset && keyframe->Offset() && offset < keyframe->Offset()) {
break;
}
// Timeline offsets do not need to be consecutive.
if (timeline_offset != keyframe->GetTimelineOffset()) {
continue;
}
if (easing.ToString() != keyframe->Easing().ToString()) {
continue;
}
if (composite == keyframe->Composite()) {
return i;
}
}
return absl::nullopt;
}
StringKeyframeEffectModel* CreateKeyframeEffectModel(
StyleResolver* resolver,
Element& element,
const Element& animating_element,
WritingDirectionMode writing_direction,
const ComputedStyle* parent_style,
const AtomicString& name,
TimingFunction* default_timing_function,
EffectModel::CompositeOperation composite,
size_t animation_index) {
// The algorithm for constructing string keyframes for a CSS animation is
// covered in the following spec:
// https://drafts.csswg.org/css-animations-2/#keyframes
// For a given target (pseudo-)element, element, animation name, and
// position of the animation in element’s animation-name list, keyframe
// objects are generated as follows:
// 1. Let default timing function be the timing function at the position
// of the resolved value of the animation-timing-function for element,
// repeating the list as necessary as described in CSS Animations 1 §4.2
// The animation-name property.
// 2. Let default composite be replace.
// 3. Find the last @keyframes at-rule in document order with <keyframes-name>
// matching name.
// If there is no @keyframes at-rule with <keyframes-name> matching name,
// abort this procedure. In this case no animation is generated, and any
// existing animation matching name is canceled.
StyleResolver::FindKeyframesRuleResult find_result =
resolver->FindKeyframesRule(&element, &animating_element, name);
const StyleRuleKeyframes* keyframes_rule = find_result.rule;
DCHECK(keyframes_rule);
// 4. Let keyframes be an empty sequence of keyframe objects.
StringKeyframeVector keyframes;
// 5. Let animated properties be an empty set of longhand CSS property names.
PropertySet animated_properties;
// Start and end properties are also tracked to simplify the process of
// determining if the first and last keyframes are missing properties.
PropertySet start_properties;
PropertySet end_properties;
PropertySet fixed_offset_properties;
HashMap<String, PropertySet> timeline_offset_properties_map;
// Properties that have already been processed at the current keyframe.
PropertySet* current_offset_properties;
// 6. Perform a stable sort of the keyframe blocks in the @keyframes rule by
// the offset specified in the keyframe selector, and iterate over the
// result in reverse applying the following steps:
bool has_named_range_keyframes = false;
keyframes = ProcessKeyframesRule(
keyframes_rule, find_result.tree_scope, element.GetDocument(),
parent_style, default_timing_function, writing_direction.GetWritingMode(),
writing_direction.Direction(), has_named_range_keyframes);
absl::optional<double> last_offset;
wtf_size_t merged_frame_count = 0;
for (wtf_size_t i = keyframes.size(); i > 0; --i) {
// 6.1 Let keyframe offset be the value of the keyframe selector converted
// to a value in the range 0 ≤ keyframe offset ≤ 1.
int source_index = i - 1;
StringKeyframe* rule_keyframe = keyframes[source_index];
absl::optional<double> keyframe_offset = rule_keyframe->Offset();
absl::optional<TimelineOffset> timeline_offset =
rule_keyframe->GetTimelineOffset();
if (!timeline_offset) {
current_offset_properties = &fixed_offset_properties;
} else {
String key = timeline_offset->ToString();
auto it = timeline_offset_properties_map.find(key);
if (it == timeline_offset_properties_map.end()) {
auto add_result =
timeline_offset_properties_map.insert(key, PropertySet());
current_offset_properties = &add_result.stored_value->value;
} else {
current_offset_properties = &it.Get()->value;
}
}
// 6.2 Let keyframe timing function be the value of the last valid
// declaration of animation-timing-function specified on the keyframe
// block, or, if there is no such valid declaration, default timing
// function.
const TimingFunction& easing = rule_keyframe->Easing();
// 6.3 Let keyframe composite be the value of the last valid declaration of
// animation-composition specified on the keyframe block,
// or, if there is no such valid declaration, default composite.
absl::optional<EffectModel::CompositeOperation> keyframe_composite =
rule_keyframe->Composite();
// 6.4 After converting keyframe timing function to its canonical form (e.g.
// such that step-end becomes steps(1, end)) let keyframe refer to the
// existing keyframe in keyframes with matching keyframe offset and
// timing function, if any.
// If there is no such existing keyframe, let keyframe be a new empty
// keyframe with offset, keyframe offset, and timing function, keyframe
// timing function, and prepend it to keyframes.
// Prevent stomping a rule override by tracking properties applied at
// the current offset.
if (last_offset != keyframe_offset && !timeline_offset) {
fixed_offset_properties.clear();
last_offset = keyframe_offset;
}
// TODO(crbug.com/1408702): we should merge keyframes to the most left one,
// not the most right one.
// Avoid unnecessary creation of extra keyframes by merging into
// existing keyframes.
absl::optional<int> existing_keyframe_index = FindIndexOfMatchingKeyframe(
keyframes, source_index + merged_frame_count + 1, keyframe_offset,
timeline_offset, easing, keyframe_composite);
int target_index;
if (existing_keyframe_index) {
// Merge keyframe propoerties.
target_index = existing_keyframe_index.value();
merged_frame_count++;
} else {
target_index = source_index + merged_frame_count;
if (target_index != source_index) {
// Move keyframe to fill the gap.
keyframes[target_index] = keyframes[source_index];
source_index = target_index;
}
}
// 6.5 Iterate over all declarations in the keyframe block and add them to
// keyframe such that:
// * All variable references are resolved to their current values.
// * Each shorthand property is expanded to its longhand subproperties.
// * All logical properties are converted to their equivalent physical
// properties.
// * For any expanded physical longhand properties that appear more than
// once, only the last declaration in source order is added.
// Note, since multiple keyframe blocks may specify the same keyframe
// offset, and since this algorithm iterates over these blocks in
// reverse, this implies that if any properties are encountered that
// have already added at this same keyframe offset, they should be
// skipped.
// * All property values are replaced with their computed values.
// 6.6 Add each property name that was added to keyframe
// to animated properties.
StringKeyframe* keyframe = keyframes[target_index];
for (const auto& property : rule_keyframe->Properties()) {
CSSPropertyName property_name = property.GetCSSPropertyName();
// Since processing keyframes in reverse order, skipping properties that
// have already been inserted prevents overwriting a later merged
// keyframe.
if (current_offset_properties->Contains(property_name)) {
continue;
}
if (source_index != target_index) {
keyframe->SetCSSPropertyValue(
property.GetCSSPropertyName(),
rule_keyframe->CssPropertyValue(property));
}
current_offset_properties->insert(property_name);
animated_properties.insert(property_name);
if (keyframe_offset == 0)
start_properties.insert(property_name);
else if (keyframe_offset == 1)
end_properties.insert(property_name);
}
}
// Compact the vector of keyframes if any keyframes have been merged.
keyframes.EraseAt(0, merged_frame_count);
// Steps 7 and 8 are for adding boundary (neutral) keyframes if needed.
// These steps are deferred and handled in
// KeyframeEffectModelBase::PropertySpecificKeyframeGroup::
// AddSyntheticKeyframeIfRequired
// The rationale for not adding here is as follows:
// 1. Neutral keyframes are also needed for CSS transitions and
// programmatic animations. Avoid duplicating work.
// 2. Keyframe ordering can change due to timeline offsets within keyframes.
// This reordering makes it cumbersome to have to remove and re-inject
// neutral keyframes if explicitly added.
// NOTE: By not adding here, we need to explicitly inject into the set
// generated in effect.getKeyframes().
auto* model = MakeGarbageCollected<CssKeyframeEffectModel>(
keyframes, composite, default_timing_function, has_named_range_keyframes);
if (animation_index > 0 && model->HasSyntheticKeyframes()) {
UseCounter::Count(element.GetDocument(),
WebFeature::kCSSAnimationsStackedNeutralKeyframe);
}
return model;
}
// Returns the start time of an animation given the start delay. A negative
// start delay results in the animation starting with non-zero progress.
AnimationTimeDelta StartTimeFromDelay(AnimationTimeDelta start_delay) {
return start_delay < AnimationTimeDelta() ? -start_delay
: AnimationTimeDelta();
}
// Timing functions for computing elapsed time of an event.
AnimationTimeDelta IntervalStart(const AnimationEffect& effect) {
AnimationTimeDelta start_delay = effect.NormalizedTiming().start_delay;
const AnimationTimeDelta active_duration =
effect.NormalizedTiming().active_duration;
// This fixes a problem where start_delay could be -0
if (!start_delay.is_zero()) {
start_delay = -start_delay;
}
return std::max(std::min(start_delay, active_duration), AnimationTimeDelta());
}
AnimationTimeDelta IntervalEnd(const AnimationEffect& effect) {
const AnimationTimeDelta start_delay = effect.NormalizedTiming().start_delay;
const AnimationTimeDelta end_delay = effect.NormalizedTiming().end_delay;
const AnimationTimeDelta active_duration =
effect.NormalizedTiming().active_duration;
const AnimationTimeDelta target_effect_end =
std::max(start_delay + active_duration + end_delay, AnimationTimeDelta());
return std::max(std::min(target_effect_end - start_delay, active_duration),
AnimationTimeDelta());
}
AnimationTimeDelta IterationElapsedTime(const AnimationEffect& effect,
double previous_iteration) {
const double current_iteration = effect.CurrentIteration().value();
const double iteration_boundary = (previous_iteration > current_iteration)
? current_iteration + 1
: current_iteration;
const double iteration_start = effect.SpecifiedTiming().iteration_start;
const AnimationTimeDelta iteration_duration =
effect.NormalizedTiming().iteration_duration;
return iteration_duration * (iteration_boundary - iteration_start);
}
const CSSAnimationUpdate* GetPendingAnimationUpdate(Node& node) {
Element* element = DynamicTo<Element>(node);
if (!element)
return nullptr;
ElementAnimations* element_animations = element->GetElementAnimations();
if (!element_animations)
return nullptr;
return &element_animations->CssAnimations().PendingUpdate();
}
// SpecifiedTimelines "zips" together name/axis/inset vectors such that
// individual name/axis/inset values can be accessed as a tuple.
//
// SpecifiedTimelines skips over entries with nullptr-names (which
// represents "none"), because such entries should not yield timelines.
class SpecifiedTimelines {
STACK_ALLOCATED();
public:
explicit SpecifiedTimelines(const ScopedCSSNameList* names,
const Vector<TimelineAxis>& axes,
const Vector<TimelineInset>* insets)
: names_(names ? &names->GetNames() : nullptr),
axes_(axes),
insets_(insets) {}
class Iterator {
STACK_ALLOCATED();
public:
Iterator(wtf_size_t index, const SpecifiedTimelines& timelines)
: index_(index), timelines_(timelines) {}
std::tuple<Member<const ScopedCSSName>, TimelineAxis, TimelineInset>
operator*() const {
const HeapVector<Member<const ScopedCSSName>>& names = *timelines_.names_;
const Vector<TimelineAxis>& axes = timelines_.axes_;
const Vector<TimelineInset>* insets = timelines_.insets_;
Member<const ScopedCSSName> name = names[index_];
TimelineAxis axis = axes.empty()
? TimelineAxis::kBlock
: axes[std::min(index_, axes.size() - 1)];
const TimelineInset& inset =
(!insets || insets->empty())
? TimelineInset()
: (*insets)[std::min(index_, insets->size() - 1)];
return std::make_tuple(name, axis, inset);
}
void operator++() { index_ = timelines_.SkipPastNullptr(index_ + 1); }
bool operator==(const Iterator& o) const { return index_ == o.index_; }
bool operator!=(const Iterator& o) const { return index_ != o.index_; }
private:
wtf_size_t index_;
const SpecifiedTimelines& timelines_;
};
Iterator begin() const { return Iterator(SkipPastNullptr(0), *this); }
Iterator end() const { return Iterator(Size(), *this); }
private:
wtf_size_t Size() const { return names_ ? names_->size() : 0; }
wtf_size_t SkipPastNullptr(wtf_size_t start) const {
wtf_size_t size = Size();
wtf_size_t index = start;
DCHECK_LE(index, size);
while (index < size && !(*names_)[index]) {
++index;
}
return index;
}
const HeapVector<Member<const ScopedCSSName>>* names_;
const Vector<TimelineAxis>& axes_;
const Vector<TimelineInset>* insets_;
};
class SpecifiedScrollTimelines : public SpecifiedTimelines {
STACK_ALLOCATED();
public:
explicit SpecifiedScrollTimelines(const ComputedStyleBuilder& style_builder)
: SpecifiedTimelines(style_builder.ScrollTimelineName(),
style_builder.ScrollTimelineAxis(),
/* insets */ nullptr) {}
};
class SpecifiedViewTimelines : public SpecifiedTimelines {
STACK_ALLOCATED();
public:
explicit SpecifiedViewTimelines(const ComputedStyleBuilder& style_builder)
: SpecifiedTimelines(style_builder.ViewTimelineName(),
style_builder.ViewTimelineAxis(),
&style_builder.ViewTimelineInset()) {}
};
// Invokes `callback` for each timeline we would end up with had
// `changed_timelines` been applied to `existing_timelines`.
template <typename TimelineType, typename CallbackFunc>
void ForEachTimeline(const CSSTimelineMap<TimelineType>* existing_timelines,
const CSSTimelineMap<TimelineType>* changed_timelines,
CallbackFunc callback) {
// First, search through existing named timelines.
if (existing_timelines) {
for (auto [name, value] : *existing_timelines) {
// Skip timelines that are changed; they will be handled by the next
// for-loop.
if (changed_timelines && changed_timelines->Contains(name)) {
continue;
}
callback(*name, value.Get());
}
}
// Search through timelines created or modified this CSSAnimationUpdate.
if (changed_timelines) {
for (auto [name, value] : *changed_timelines) {
if (!value) {
// A value of nullptr means that a currently existing timeline
// was removed.
continue;
}
callback(*name, value.Get());
}
}
}
// When calculating timeline updates, we initially assume that all timelines
// are going to be removed, and then erase the nullptr entries for timelines
// where we discover that this doesn't apply.
template <typename MapType>
MapType NullifyExistingTimelines(const MapType* existing_timelines) {
MapType map;
if (existing_timelines) {
for (const auto& key : existing_timelines->Keys()) {
map.Set(key, nullptr);
}
}
return map;
}
template <typename TimelineType>
TimelineType* GetTimeline(const CSSTimelineMap<TimelineType>* timelines,
const ScopedCSSName& name) {
if (!timelines) {
return nullptr;
}
auto i = timelines->find(&name);
return i != timelines->end() ? i->value.Get() : nullptr;
}
DeferredTimeline* GetTimelineAttachment(
const TimelineAttachmentMap* timeline_attachments,
ScrollSnapshotTimeline* timeline) {
if (!timeline_attachments) {
return nullptr;
}
auto i = timeline_attachments->find(timeline);
return i != timeline_attachments->end() ? i->value.Get() : nullptr;
}
Element* ParentElementForTimelineTraversal(Node& node) {
return RuntimeEnabledFeatures::CSSTreeScopedTimelinesEnabled()
? node.ParentOrShadowHostElement()
: LayoutTreeBuilderTraversal::ParentElement(node);
}
Element* ResolveReferenceElement(Document& document,
TimelineScroller scroller,
Element* reference_element) {
switch (scroller) {
case TimelineScroller::kNearest:
case TimelineScroller::kSelf:
return reference_element;
case TimelineScroller::kRoot:
return document.ScrollingElementNoLayout();
}
}
ScrollTimeline::ReferenceType ComputeReferenceType(TimelineScroller scroller) {
switch (scroller) {
case TimelineScroller::kNearest:
return ScrollTimeline::ReferenceType::kNearestAncestor;
case TimelineScroller::kRoot:
case TimelineScroller::kSelf:
return ScrollTimeline::ReferenceType::kSource;
}
}
ScrollTimeline::ScrollAxis ComputeAxis(TimelineAxis axis) {
switch (axis) {
case TimelineAxis::kBlock:
return ScrollTimeline::ScrollAxis::kBlock;
case TimelineAxis::kInline:
return ScrollTimeline::ScrollAxis::kInline;
case TimelineAxis::kX:
return ScrollTimeline::ScrollAxis::kX;
case TimelineAxis::kY:
return ScrollTimeline::ScrollAxis::kY;
}
NOTREACHED();
return ScrollTimeline::ScrollAxis::kBlock;
}
// The CSSScrollTimelineOptions and CSSViewTimelineOptions structs exist
// in order to avoid creating a new Scroll/ViewTimeline when doing so
// would anyway result in exactly the same Scroll/ViewTimeline that we
// already have. (See TimelineMatches functions).
struct CSSScrollTimelineOptions {
STACK_ALLOCATED();
public:
CSSScrollTimelineOptions(Document& document,
TimelineScroller scroller,
Element* reference_element,
TimelineAxis axis)
: reference_type(ComputeReferenceType(scroller)),
reference_element(
ResolveReferenceElement(document, scroller, reference_element)),
axis(ComputeAxis(axis)) {}
ScrollTimeline::ReferenceType reference_type;
Element* reference_element;
ScrollTimeline::ScrollAxis axis;
};
struct CSSViewTimelineOptions {
STACK_ALLOCATED();
public:
CSSViewTimelineOptions(Element* subject,
TimelineAxis axis,
TimelineInset inset)
: subject(subject), axis(ComputeAxis(axis)), inset(inset) {}
Element* subject;
ScrollTimeline::ScrollAxis axis;
TimelineInset inset;
};
bool TimelineMatches(const ScrollTimeline& timeline,
const CSSScrollTimelineOptions& options) {
return timeline.Matches(options.reference_type, options.reference_element,
options.axis);
}
bool TimelineMatches(const ViewTimeline& timeline,
const CSSViewTimelineOptions& options) {
return timeline.Matches(options.subject, options.axis, options.inset);
}
} // namespace
void CSSAnimations::CalculateScrollTimelineUpdate(
CSSAnimationUpdate& update,
Element& animating_element,
const ComputedStyleBuilder& style_builder) {
const CSSAnimations::TimelineData* timeline_data =
GetTimelineData(animating_element);
const CSSScrollTimelineMap* existing_scroll_timelines =
(timeline_data && !timeline_data->GetScrollTimelines().empty())
? &timeline_data->GetScrollTimelines()
: nullptr;
if (style_builder.ScrollTimelineName() || existing_scroll_timelines) {
update.SetChangedScrollTimelines(CalculateChangedScrollTimelines(
animating_element, existing_scroll_timelines, style_builder));
}
}
void CSSAnimations::CalculateViewTimelineUpdate(
CSSAnimationUpdate& update,
Element& animating_element,
const ComputedStyleBuilder& style_builder) {
const CSSAnimations::TimelineData* timeline_data =
GetTimelineData(animating_element);
const CSSViewTimelineMap* existing_view_timelines =
(timeline_data && !timeline_data->GetViewTimelines().empty())
? &timeline_data->GetViewTimelines()
: nullptr;
if (style_builder.ViewTimelineName() || existing_view_timelines) {
update.SetChangedViewTimelines(CalculateChangedViewTimelines(
animating_element, existing_view_timelines, style_builder));
}
}
void CSSAnimations::CalculateDeferredTimelineUpdate(
CSSAnimationUpdate& update,
Element& animating_element,
const ComputedStyleBuilder& style_builder) {
const CSSAnimations::TimelineData* timeline_data =
GetTimelineData(animating_element);
const CSSDeferredTimelineMap* existing_deferred_timelines =
(timeline_data && !timeline_data->GetDeferredTimelines().empty())
? &timeline_data->GetDeferredTimelines()
: nullptr;