-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
view_transition_style_tracker.cc
1532 lines (1324 loc) · 57.8 KB
/
view_transition_style_tracker.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 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/view_transition/view_transition_style_tracker.h"
#include <limits>
#include "base/containers/contains.h"
#include "components/viz/common/view_transition_element_resource_id.h"
#include "third_party/blink/public/resources/grit/blink_resources.h"
#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_document_state.h"
#include "third_party/blink/renderer/core/dom/node.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/frame/browser_controls.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/page_animator.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer_entry.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style/shape_clip_path_operation.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_content_element.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_pseudo_element_base.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_style_builder.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_supplement.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_utils.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
#include "third_party/blink/renderer/platform/geometry/layout_size.h"
#include "third_party/blink/renderer/platform/widget/frame_widget.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/transform.h"
namespace blink {
namespace {
const char* kContainmentNotSatisfied =
"Aborting transition. Element must contain paint or layout for "
"view-transition-name : ";
const char* kDuplicateTagBaseError =
"Unexpected duplicate view-transition-name: ";
const String& StaticUAStyles() {
DEFINE_STATIC_LOCAL(
String, kStaticUAStyles,
(UncompressResourceAsASCIIString(IDR_UASTYLE_TRANSITION_CSS)));
return kStaticUAStyles;
}
const String& AnimationUAStyles() {
DEFINE_STATIC_LOCAL(
String, kAnimationUAStyles,
(UncompressResourceAsASCIIString(IDR_UASTYLE_TRANSITION_ANIMATIONS_CSS)));
return kAnimationUAStyles;
}
bool SatisfiesContainment(const LayoutObject& object) {
return object.ShouldApplyPaintContainment() ||
object.ShouldApplyLayoutContainment();
}
absl::optional<String> ComputeInsetDifference(PhysicalRect reference_rect,
const LayoutRect& target_rect,
float device_pixel_ratio) {
if (reference_rect.IsEmpty()) {
DCHECK(target_rect.IsEmpty());
return absl::nullopt;
}
// Reference rect is given to us in layout space, but target_rect is in css
// space. Note that this currently relies on the fact that object-view-box
// scales its parameters from CSS to layout space. However, that's a bug.
// TODO(crbug.com/1324618): Fix this when the object-view-box bug is fixed.
reference_rect.Scale(1.f / device_pixel_ratio);
LayoutRect reference_layout_rect = reference_rect.ToLayoutRect();
if (reference_layout_rect == target_rect)
return absl::nullopt;
float top_offset = (target_rect.Y() - reference_layout_rect.Y()).ToFloat();
float right_offset =
(reference_layout_rect.MaxX() - target_rect.MaxX()).ToFloat();
float bottom_offset =
(reference_layout_rect.MaxY() - target_rect.MaxY()).ToFloat();
float left_offset = (target_rect.X() - reference_layout_rect.X()).ToFloat();
return String::Format("inset(%.3fpx %.3fpx %.3fpx %.3fpx);", top_offset,
right_offset, bottom_offset, left_offset);
}
} // namespace
class ViewTransitionStyleTracker::ImageWrapperPseudoElement
: public ViewTransitionPseudoElementBase {
public:
ImageWrapperPseudoElement(Element* parent,
PseudoId pseudo_id,
const AtomicString& view_transition_name,
const ViewTransitionStyleTracker* style_tracker)
: ViewTransitionPseudoElementBase(parent,
pseudo_id,
view_transition_name,
style_tracker) {}
~ImageWrapperPseudoElement() override = default;
private:
bool CanGeneratePseudoElement(PseudoId pseudo_id) const override {
if (!ViewTransitionPseudoElementBase::CanGeneratePseudoElement(pseudo_id)) {
return false;
}
viz::ViewTransitionElementResourceId snapshot_id;
if (pseudo_id == kPseudoIdViewTransitionOld) {
if (style_tracker_->old_root_data_ &&
style_tracker_->old_root_data_->names.Contains(
view_transition_name())) {
snapshot_id = style_tracker_->old_root_data_->snapshot_id;
DCHECK(snapshot_id.IsValid());
} else if (auto it = style_tracker_->element_data_map_.find(
view_transition_name());
it != style_tracker_->element_data_map_.end()) {
snapshot_id = it->value->old_snapshot_id;
} else {
// If we're being called with a name that isn't an old_root name and
// it's not a transition element, it must mean we have it as a new root
// name.
DCHECK(style_tracker_->new_root_data_);
DCHECK(style_tracker_->new_root_data_->names.Contains(
view_transition_name()));
}
} else {
if (style_tracker_->new_root_data_ &&
style_tracker_->new_root_data_->names.Contains(
view_transition_name())) {
snapshot_id = style_tracker_->new_root_data_->snapshot_id;
DCHECK(snapshot_id.IsValid());
} else if (auto it = style_tracker_->element_data_map_.find(
view_transition_name());
it != style_tracker_->element_data_map_.end()) {
snapshot_id = it->value->new_snapshot_id;
} else {
// If we're being called with a name that isn't a new_root name and it's
// not a transition element, it must mean we have it as an old root
// name.
DCHECK(style_tracker_->old_root_data_);
DCHECK(style_tracker_->old_root_data_->names.Contains(
view_transition_name()));
}
}
return snapshot_id.IsValid();
}
};
ViewTransitionStyleTracker::ViewTransitionStyleTracker(Document& document)
: document_(document) {}
ViewTransitionStyleTracker::ViewTransitionStyleTracker(
Document& document,
ViewTransitionState transition_state)
: document_(document), state_(State::kCaptured), deserialized_(true) {
captured_name_count_ = static_cast<int>(transition_state.elements.size());
VectorOf<AtomicString> transition_names;
transition_names.ReserveInitialCapacity(captured_name_count_);
for (const auto& transition_state_element : transition_state.elements) {
AtomicString name(transition_state_element.tag_name.c_str());
transition_names.push_back(name);
if (transition_state_element.is_root) {
DCHECK(!old_root_data_);
old_root_data_.emplace();
old_root_data_->snapshot_id = transition_state_element.snapshot_id;
old_root_data_->names.push_back(name);
// TODO(khushalsagar): We should keep track of the snapshot viewport rect
// size to handle changes in its bounds.
// https://crbug.com/1404957.
continue;
}
DCHECK(!element_data_map_.Contains(name));
auto* element_data = MakeGarbageCollected<ElementData>();
element_data->container_properties.emplace_back(
LayoutSize(transition_state_element.border_box_size_in_css_space),
transition_state_element.viewport_matrix);
element_data->old_snapshot_id = transition_state_element.snapshot_id;
element_data->element_index = transition_state_element.paint_order;
set_element_sequence_id_ = std::max(set_element_sequence_id_,
transition_state_element.paint_order);
element_data->visual_overflow_rect_in_layout_space =
PhysicalRect::EnclosingRect(
transition_state_element.overflow_rect_in_layout_space);
element_data->CacheGeometryState();
element_data_map_.insert(name, std::move(element_data));
}
}
ViewTransitionStyleTracker::~ViewTransitionStyleTracker() = default;
void ViewTransitionStyleTracker::AddConsoleError(
String message,
Vector<DOMNodeId> related_nodes) {
auto* console_message = MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering,
mojom::blink::ConsoleMessageLevel::kError, std::move(message));
console_message->SetNodes(document_->GetFrame(), std::move(related_nodes));
document_->AddConsoleMessage(console_message);
}
void ViewTransitionStyleTracker::AddTransitionElement(
Element* element,
const AtomicString& name) {
DCHECK(element);
// Insert an empty hash set for the element if it doesn't exist, or get it if
// it does.
auto& value = pending_transition_element_names_
.insert(element, HashSet<std::pair<AtomicString, int>>())
.stored_value->value;
// Find the existing name if one is there. If it is there, do nothing.
if (base::Contains(value, name, &std::pair<AtomicString, int>::first))
return;
// Otherwise, insert a new sequence id with this name. We'll use the sequence
// to sort later.
value.insert(std::make_pair(name, set_element_sequence_id_));
++set_element_sequence_id_;
}
bool ViewTransitionStyleTracker::MatchForOnlyChild(
PseudoId pseudo_id,
const AtomicString& view_transition_name) const {
switch (pseudo_id) {
case kPseudoIdViewTransition:
DCHECK(!view_transition_name);
return false;
case kPseudoIdViewTransitionGroup: {
DCHECK(view_transition_name);
const bool has_root = old_root_data_ || new_root_data_;
if (has_root) {
return element_data_map_.empty();
} else {
DCHECK(!element_data_map_.empty());
return element_data_map_.size() == 1;
}
}
case kPseudoIdViewTransitionImagePair:
DCHECK(view_transition_name);
return true;
case kPseudoIdViewTransitionOld: {
DCHECK(view_transition_name);
if (new_root_data_ &&
new_root_data_->names.Contains(view_transition_name)) {
return false;
}
auto it = element_data_map_.find(view_transition_name);
if (it == element_data_map_.end()) {
DCHECK(old_root_data_ &&
old_root_data_->names.Contains(view_transition_name));
return true;
}
const auto& element_data = it->value;
return !element_data->new_snapshot_id.IsValid();
}
case kPseudoIdViewTransitionNew: {
DCHECK(view_transition_name);
if (old_root_data_ &&
old_root_data_->names.Contains(view_transition_name)) {
return false;
}
auto it = element_data_map_.find(view_transition_name);
if (it == element_data_map_.end()) {
DCHECK(new_root_data_ &&
new_root_data_->names.Contains(view_transition_name));
return true;
}
const auto& element_data = it->value;
return !element_data->old_snapshot_id.IsValid();
}
default:
NOTREACHED();
}
return false;
}
void ViewTransitionStyleTracker::AddTransitionElementsFromCSS() {
DCHECK(document_ && document_->View());
// We need our paint layers, and z-order lists which is done during
// compositing inputs update.
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kCompositingInputsClean);
AddTransitionElementsFromCSSRecursive(
document_->GetLayoutView()->PaintingLayer());
}
void ViewTransitionStyleTracker::AddTransitionElementsFromCSSRecursive(
PaintLayer* root) {
// We want to call AddTransitionElements in the order in which
// PaintLayerPaintOrderIterator would cause us to paint the elements.
// Specifically, parents are added before their children, and lower z-index
// children are added before higher z-index children. Given that, what we
// need to do is to first add `root`'s element, and then recurse using the
// PaintLayerPaintOrderIterator which will return values in the correct
// z-index order.
//
// Note that the order of calls to AddTransitionElement determines the DOM
// order of pseudo-elements constructed to represent the transition elements,
// which by default will also represent the paint order of the pseudo-elements
// (unless changed by something like z-index on the pseudo-elements).
auto& root_object = root->GetLayoutObject();
auto& root_style = root_object.StyleRef();
if (root_style.ViewTransitionName()) {
DCHECK(root_object.GetNode());
DCHECK(root_object.GetNode()->IsElementNode());
AddTransitionElement(DynamicTo<Element>(root_object.GetNode()),
root_style.ViewTransitionName());
}
if (root_object.ChildPaintBlockedByDisplayLock())
return;
PaintLayerPaintOrderIterator child_iterator(root, kAllChildren);
while (auto* child = child_iterator.Next()) {
AddTransitionElementsFromCSSRecursive(child);
}
}
bool ViewTransitionStyleTracker::FlattenAndVerifyElements(
VectorOf<Element>& elements,
VectorOf<AtomicString>& transition_names,
absl::optional<RootData>& root_data) {
for (const auto& element : ViewTransitionSupplement::From(*document_)
->ElementsWithViewTransitionName()) {
DCHECK(element->ComputedStyleRef().ViewTransitionName());
// Ignore elements which are not rendered.
if (!element->GetLayoutObject())
continue;
// Skip the transition if containment is not satisfied.
if (!element->IsDocumentElement() &&
!SatisfiesContainment(*element->GetLayoutObject())) {
StringBuilder message;
message.Append(kContainmentNotSatisfied);
message.Append(element->ComputedStyleRef().ViewTransitionName());
AddConsoleError(message.ReleaseString());
return false;
}
}
// We need to flatten the data first, and sort it by ordering which reflects
// the setElement ordering.
struct FlatData : public GarbageCollected<FlatData> {
FlatData(Element* element, const AtomicString& name, int ordering)
: element(element), name(name), ordering(ordering) {}
Member<Element> element;
AtomicString name;
int ordering;
void Trace(Visitor* visitor) const { visitor->Trace(element); }
};
VectorOf<FlatData> flat_list;
// Flatten it.
for (auto& [element, names] : pending_transition_element_names_) {
DCHECK(element->GetLayoutObject());
const bool is_root = element->IsDocumentElement();
if (is_root && !root_data)
root_data.emplace();
for (auto& name_pair : names) {
if (is_root) {
// The order of the root names doesn't matter, so we don't keep the
// ordering.
root_data->names.push_back(name_pair.first);
} else {
flat_list.push_back(MakeGarbageCollected<FlatData>(
element, name_pair.first, name_pair.second));
}
}
}
// Sort it.
std::sort(flat_list.begin(), flat_list.end(),
[](const FlatData* a, const FlatData* b) {
return a->ordering < b->ordering;
});
DCHECK(!root_data || !root_data->names.empty());
auto have_root_name = [&root_data](const AtomicString& name) {
return root_data && root_data->names.Contains(name);
};
// Verify it.
for (auto& flat_data : flat_list) {
auto& name = flat_data->name;
auto& element = flat_data->element;
if (UNLIKELY(transition_names.Contains(name) || have_root_name(name))) {
StringBuilder message;
message.Append(kDuplicateTagBaseError);
message.Append(name);
AddConsoleError(message.ReleaseString());
return false;
}
transition_names.push_back(name);
elements.push_back(element);
}
return true;
}
bool ViewTransitionStyleTracker::Capture() {
DCHECK_EQ(state_, State::kIdle);
// Flatten `pending_transition_element_names_` into a vector of names and
// elements. This process also verifies that the name-element combinations are
// valid.
VectorOf<AtomicString> transition_names;
VectorOf<Element> elements;
bool success =
FlattenAndVerifyElements(elements, transition_names, old_root_data_);
if (!success)
return false;
// Now we know that we can start a transition. Update the state and populate
// `element_data_map_`.
state_ = State::kCapturing;
InvalidateHitTestingCache();
captured_name_count_ = transition_names.size() + OldRootDataTagSize();
element_data_map_.ReserveCapacityForSize(captured_name_count_);
HeapHashMap<Member<Element>, viz::ViewTransitionElementResourceId>
element_snapshot_ids;
int next_index = OldRootDataTagSize();
for (wtf_size_t i = 0; i < transition_names.size(); ++i) {
const auto& name = transition_names[i];
const auto& element = elements[i];
// Reuse any previously generated snapshot_id for this element. If there was
// none yet, then generate the resource id.
auto& snapshot_id =
element_snapshot_ids
.insert(element, viz::ViewTransitionElementResourceId())
.stored_value->value;
if (!snapshot_id.IsValid()) {
snapshot_id = viz::ViewTransitionElementResourceId::Generate();
capture_resource_ids_.push_back(snapshot_id);
}
auto* element_data = MakeGarbageCollected<ElementData>();
element_data->target_element = element;
element_data->element_index = next_index++;
element_data->old_snapshot_id = snapshot_id;
element_data_map_.insert(name, std::move(element_data));
}
if (old_root_data_) {
old_root_data_->snapshot_id =
viz::ViewTransitionElementResourceId::Generate();
}
for (const auto& root_name : AllRootTags())
transition_names.push_front(root_name);
// This informs the style engine the set of names we have, which will be used
// to create the pseudo element tree.
document_->GetStyleEngine().SetViewTransitionNames(transition_names);
// We need a style invalidation to generate the pseudo element tree.
InvalidateStyle();
set_element_sequence_id_ = 0;
pending_transition_element_names_.clear();
DCHECK(!snapshot_root_size_at_capture_.has_value());
snapshot_root_size_at_capture_ = GetSnapshotRootSize();
return true;
}
void ViewTransitionStyleTracker::CaptureResolved() {
DCHECK_EQ(state_, State::kCapturing);
state_ = State::kCaptured;
// TODO(crbug.com/1347473): We should also suppress hit testing at this point,
// since we're about to start painting the element as a captured snapshot, but
// we still haven't given script chance to modify the DOM to the new state.
InvalidateHitTestingCache();
// Since the elements will be unset, we need to invalidate their style first.
// TODO(vmpstr): We don't have to invalidate the pseudo styles at this point,
// just the transition elements. We can split InvalidateStyle() into two
// functions as an optimization.
InvalidateStyle();
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
element_data->target_element = nullptr;
element_data->effect_node = nullptr;
}
root_effect_node_ = nullptr;
}
VectorOf<Element> ViewTransitionStyleTracker::GetTransitioningElements() const {
// In stable states, we don't have transitioning elements.
if (state_ == State::kIdle || state_ == State::kCaptured)
return {};
VectorOf<Element> result;
for (auto& entry : element_data_map_) {
if (entry.value->target_element)
result.push_back(entry.value->target_element);
}
return result;
}
bool ViewTransitionStyleTracker::Start() {
DCHECK_EQ(state_, State::kCaptured);
// Flatten `pending_transition_element_names_` into a vector of names and
// elements. This process also verifies that the name-element combinations are
// valid.
VectorOf<AtomicString> transition_names;
VectorOf<Element> elements;
bool success =
FlattenAndVerifyElements(elements, transition_names, new_root_data_);
if (!success)
return false;
state_ = State::kStarted;
InvalidateHitTestingCache();
HeapHashMap<Member<Element>, viz::ViewTransitionElementResourceId>
element_snapshot_ids;
bool found_new_names = false;
// If this tracker was created from serialized state, transition tags are
// initialized with the style system in the start phase.
if (deserialized_) {
DCHECK(document_->GetStyleEngine().ViewTransitionTags().empty());
DCHECK_GT(captured_name_count_, 0);
found_new_names = true;
}
int next_index =
element_data_map_.size() + OldRootDataTagSize() + NewRootDataTagSize();
for (wtf_size_t i = 0; i < elements.size(); ++i) {
const auto& name = transition_names[i];
const auto& element = elements[i];
// Insert a new name data if there is no data for this name yet.
if (!element_data_map_.Contains(name)) {
found_new_names = true;
auto* data = MakeGarbageCollected<ElementData>();
data->element_index = next_index++;
element_data_map_.insert(name, data);
}
// Reuse any previously generated snapshot_id for this element. If there was
// none yet, then generate the resource id.
auto& snapshot_id =
element_snapshot_ids
.insert(element, viz::ViewTransitionElementResourceId())
.stored_value->value;
if (!snapshot_id.IsValid())
snapshot_id = viz::ViewTransitionElementResourceId::Generate();
auto& element_data = element_data_map_.find(name)->value;
element_data->target_element = element;
element_data->new_snapshot_id = snapshot_id;
DCHECK_LT(element_data->element_index, next_index);
}
// If the old and new root names have different size that means we likely have
// at least one new name.
found_new_names |= OldRootDataTagSize() != NewRootDataTagSize();
if (!found_new_names && new_root_data_) {
DCHECK(old_root_data_);
for (const auto& new_name : new_root_data_->names) {
// If the new root name is not also an old root name and it isn't a
// transition element name, then we have a new name.
if (!old_root_data_->names.Contains(new_name) &&
!element_data_map_.Contains(new_name)) {
found_new_names = true;
break;
}
}
}
if (new_root_data_) {
new_root_data_->snapshot_id =
viz::ViewTransitionElementResourceId::Generate();
}
if (found_new_names) {
VectorOf<std::pair<AtomicString, int>> new_name_pairs;
int next_name_index = 0;
for (const auto& root_name : AllRootTags())
new_name_pairs.push_back(std::make_pair(root_name, ++next_name_index));
for (auto& [name, data] : element_data_map_)
new_name_pairs.push_back(std::make_pair(name, data->element_index));
std::sort(new_name_pairs.begin(), new_name_pairs.end(),
[](const std::pair<AtomicString, int>& left,
const std::pair<AtomicString, int>& right) {
return left.second < right.second;
});
VectorOf<AtomicString> new_names;
for (auto& [name, index] : new_name_pairs)
new_names.push_back(name);
document_->GetStyleEngine().SetViewTransitionNames(new_names);
}
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
// We need to run post prepaint steps here to ensure that the style would be
// correct if computed by either the main frame or by getComputedStyle call.
// TODO(vmpstr): Rename to something like UpdatePseudoGeometry.
const bool continue_transition = RunPostPrePaintSteps();
DCHECK(continue_transition)
<< "The transition should've been skipped by FlattenAndVerifyElements";
// We need a style invalidation to generate new content pseudo elements for
// new elements in the DOM.
InvalidateStyle();
if (auto* page = document_->GetPage())
page->Animator().SetHasViewTransition(true);
return true;
}
void ViewTransitionStyleTracker::StartFinished() {
DCHECK_EQ(state_, State::kStarted);
EndTransition();
}
void ViewTransitionStyleTracker::Abort() {
EndTransition();
}
void ViewTransitionStyleTracker::EndTransition() {
state_ = State::kFinished;
InvalidateHitTestingCache();
// We need a style invalidation to remove the pseudo element tree. This needs
// to be done before we clear the data, since we need to invalidate the
// transition elements stored in `element_data_map_`.
InvalidateStyle();
element_data_map_.clear();
pending_transition_element_names_.clear();
set_element_sequence_id_ = 0;
old_root_data_.reset();
new_root_data_.reset();
document_->GetStyleEngine().SetViewTransitionNames({});
if (auto* page = document_->GetPage())
page->Animator().SetHasViewTransition(false);
}
void ViewTransitionStyleTracker::UpdateElementIndicesAndSnapshotId(
Element* element,
ViewTransitionElementId& index,
viz::ViewTransitionElementResourceId& resource_id) const {
DCHECK(element);
for (const auto& entry : element_data_map_) {
if (entry.value->target_element == element) {
index.AddIndex(entry.value->element_index);
const auto& snapshot_id = HasLiveNewContent()
? entry.value->new_snapshot_id
: entry.value->old_snapshot_id;
DCHECK(!resource_id.IsValid() || resource_id == snapshot_id);
if (!resource_id.IsValid())
resource_id = snapshot_id;
}
}
DCHECK(resource_id.IsValid());
}
auto ViewTransitionStyleTracker::GetCurrentRootData() const
-> absl::optional<RootData> {
return HasLiveNewContent() ? new_root_data_ : old_root_data_;
}
void ViewTransitionStyleTracker::UpdateRootIndexAndSnapshotId(
ViewTransitionElementId& index,
viz::ViewTransitionElementResourceId& resource_id) const {
if (!IsRootTransitioning())
return;
index.AddIndex(0);
const auto& root_data = GetCurrentRootData();
DCHECK(root_data);
resource_id = root_data->snapshot_id;
DCHECK(resource_id.IsValid());
}
PseudoElement* ViewTransitionStyleTracker::CreatePseudoElement(
Element* parent,
PseudoId pseudo_id,
const AtomicString& view_transition_name) {
DCHECK(IsTransitionPseudoElement(pseudo_id));
DCHECK(pseudo_id == kPseudoIdViewTransition || view_transition_name);
switch (pseudo_id) {
case kPseudoIdViewTransition:
case kPseudoIdViewTransitionGroup:
return MakeGarbageCollected<ViewTransitionPseudoElementBase>(
parent, pseudo_id, view_transition_name, this);
case kPseudoIdViewTransitionImagePair:
return MakeGarbageCollected<ImageWrapperPseudoElement>(
parent, pseudo_id, view_transition_name, this);
case kPseudoIdViewTransitionOld: {
LayoutSize size;
viz::ViewTransitionElementResourceId snapshot_id;
if (old_root_data_ &&
old_root_data_->names.Contains(view_transition_name)) {
size = LayoutSize(GetSnapshotRootSize());
snapshot_id = old_root_data_->snapshot_id;
} else {
DCHECK(view_transition_name);
const auto& element_data =
element_data_map_.find(view_transition_name)->value;
// If live data is tracking new elements then use the cached data for
// the pseudo element displaying snapshot of old element.
bool use_cached_data = HasLiveNewContent();
size = element_data->GetIntrinsicSize(use_cached_data);
snapshot_id = element_data->old_snapshot_id;
}
// Note that we say that this layer is not a live content
// layer, even though it may currently be displaying live contents. The
// reason is that we want to avoid updating this value later, which
// involves propagating the update all the way to cc. However, this means
// that we have to have the save directive come in the same frame as the
// first frame that displays this content. Otherwise, we risk DCHECK. This
// is currently the behavior as specced, but this is subtle.
// TODO(vmpstr): Maybe we should just use HasLiveNewContent() here, and
// update it when the value changes.
auto* pseudo_element = MakeGarbageCollected<ViewTransitionContentElement>(
parent, pseudo_id, view_transition_name, snapshot_id,
/*is_live_content_element=*/false, this);
pseudo_element->SetIntrinsicSize(size);
return pseudo_element;
}
case kPseudoIdViewTransitionNew: {
LayoutSize size;
viz::ViewTransitionElementResourceId snapshot_id;
if (new_root_data_ &&
new_root_data_->names.Contains(view_transition_name)) {
size = LayoutSize(GetSnapshotRootSize());
snapshot_id = new_root_data_->snapshot_id;
} else {
DCHECK(view_transition_name);
const auto& element_data =
element_data_map_.find(view_transition_name)->value;
bool use_cached_data = false;
size = element_data->GetIntrinsicSize(use_cached_data);
snapshot_id = element_data->new_snapshot_id;
}
auto* pseudo_element = MakeGarbageCollected<ViewTransitionContentElement>(
parent, pseudo_id, view_transition_name, snapshot_id,
/*is_live_content_element=*/true, this);
pseudo_element->SetIntrinsicSize(size);
return pseudo_element;
}
default:
NOTREACHED();
}
return nullptr;
}
bool ViewTransitionStyleTracker::RunPostPrePaintSteps() {
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
bool needs_style_invalidation = false;
// Use the document element's effective zoom, since that's what the parent
// effective zoom would be.
float device_pixel_ratio = document_->documentElement()
->GetLayoutObject()
->StyleRef()
.EffectiveZoom();
if (device_pixel_ratio_ != device_pixel_ratio) {
device_pixel_ratio_ = device_pixel_ratio;
needs_style_invalidation = true;
}
if (SnapshotRootDidChangeSize()) {
return false;
}
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
if (!element_data->target_element)
continue;
DCHECK_NE(element_data->target_element, document_->documentElement());
auto* layout_object = element_data->target_element->GetLayoutObject();
if (!layout_object || !SatisfiesContainment(*layout_object)) {
StringBuilder message;
message.Append(kContainmentNotSatisfied);
message.Append(entry.key);
AddConsoleError(message.ReleaseString());
return false;
}
gfx::Transform snapshot_matrix = layout_object->LocalToAbsoluteTransform();
if (document_->GetLayoutView()
->ShouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
// The SnapshotViewportRect offset below takes points from the fixed
// viewport into the snapshot viewport. However, the transform is
// currently into absolute coordinates; when the scrollbar appears on the
// left, the fixed viewport origin is actually at (15, 0) in absolute
// coordinates (assuming 15px scrollbars). Therefore we must first shift
// by the scrollbar width so we're in fixed viewport coordinates.
ScrollableArea& viewport = *document_->View()->LayoutViewport();
snapshot_matrix.PostTranslate(-viewport.VerticalScrollbarWidth(), 0);
}
gfx::Vector2d snapshot_to_fixed_offset = -GetFixedToSnapshotRootOffset();
snapshot_matrix.PostTranslate(snapshot_to_fixed_offset.x(),
snapshot_to_fixed_offset.y());
snapshot_matrix.Zoom(1.0 / device_pixel_ratio_);
// ResizeObserverEntry is created to reuse the logic for parsing object size
// for different types of LayoutObjects.
auto* resize_observer_entry =
MakeGarbageCollected<ResizeObserverEntry>(element_data->target_element);
auto entry_size = resize_observer_entry->borderBoxSize()[0];
LayoutSize border_box_size_in_css_space =
layout_object->IsHorizontalWritingMode()
? LayoutSize(LayoutUnit(entry_size->inlineSize()),
LayoutUnit(entry_size->blockSize()))
: LayoutSize(LayoutUnit(entry_size->blockSize()),
LayoutUnit(entry_size->inlineSize()));
if (float effective_zoom = layout_object->StyleRef().EffectiveZoom();
std::abs(effective_zoom - device_pixel_ratio_) >=
std::numeric_limits<float>::epsilon()) {
border_box_size_in_css_space.Scale(effective_zoom / device_pixel_ratio_);
}
PhysicalRect visual_overflow_rect_in_layout_space;
if (auto* box = DynamicTo<LayoutBox>(layout_object))
visual_overflow_rect_in_layout_space = ComputeVisualOverflowRect(*box);
WritingMode writing_mode = layout_object->StyleRef().GetWritingMode();
ContainerProperties container_properties(border_box_size_in_css_space,
snapshot_matrix);
if (!element_data->container_properties.empty() &&
element_data->container_properties.back() == container_properties &&
visual_overflow_rect_in_layout_space ==
element_data->visual_overflow_rect_in_layout_space &&
writing_mode == element_data->container_writing_mode) {
continue;
}
// Only add a new container properties entry if it differs from the last
// one.
if (element_data->container_properties.empty()) {
element_data->container_properties.push_back(container_properties);
} else if (element_data->container_properties.back() !=
container_properties) {
if (state_ == State::kStarted)
element_data->container_properties.push_back(container_properties);
else
element_data->container_properties.back() = container_properties;
}
element_data->visual_overflow_rect_in_layout_space =
visual_overflow_rect_in_layout_space;
element_data->container_writing_mode = writing_mode;
PseudoId live_content_element = HasLiveNewContent()
? kPseudoIdViewTransitionNew
: kPseudoIdViewTransitionOld;
if (auto* pseudo_element =
document_->documentElement()->GetNestedPseudoElement(
live_content_element, entry.key)) {
// A pseudo element of type |tansition*content| must be created using
// ViewTransitionContentElement.
bool use_cached_data = false;
LayoutSize size = element_data->GetIntrinsicSize(use_cached_data);
static_cast<ViewTransitionContentElement*>(pseudo_element)
->SetIntrinsicSize(size);
}
// Ensure that the cached state stays in sync with the current state while
// we're capturing.
if (state_ == State::kCapturing)
element_data->CacheGeometryState();
needs_style_invalidation = true;
}
if (needs_style_invalidation)
InvalidateStyle();
return true;
}
bool ViewTransitionStyleTracker::HasActiveAnimations() const {
auto pseudo_has_animation = [](PseudoElement* pseudo_element) {
auto* animations = pseudo_element->GetElementAnimations();
if (!animations) {
return false;
}
for (auto& animation_pair : animations->Animations()) {
auto animation_play_state =
animation_pair.key->CalculateAnimationPlayState();
if (animation_play_state == Animation::kRunning ||
animation_play_state == Animation::kPaused) {
return true;
}
}
return false;
};
return !!ViewTransitionUtils::FindPseudoIf(*document_, pseudo_has_animation);
}
PaintPropertyChangeType ViewTransitionStyleTracker::UpdateEffect(
Element* element,
EffectPaintPropertyNode::State state,
const EffectPaintPropertyNodeOrAlias& current_effect) {
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
if (element_data->target_element != element)
continue;
if (!element_data->effect_node) {
element_data->effect_node =
EffectPaintPropertyNode::Create(current_effect, std::move(state));
#if DCHECK_IS_ON()
element_data->effect_node->SetDebugName("ViewTransition");
#endif
return PaintPropertyChangeType::kNodeAddedOrRemoved;
}
return element_data->effect_node->Update(current_effect, std::move(state),
{});
}
NOTREACHED();
return PaintPropertyChangeType::kUnchanged;
}
PaintPropertyChangeType ViewTransitionStyleTracker::UpdateRootEffect(
EffectPaintPropertyNode::State state,
const EffectPaintPropertyNodeOrAlias& current_effect) {
if (!root_effect_node_) {
root_effect_node_ =
EffectPaintPropertyNode::Create(current_effect, std::move(state));
#if DCHECK_IS_ON()
root_effect_node_->SetDebugName("ViewTransition");
#endif
return PaintPropertyChangeType::kNodeAddedOrRemoved;
}
return root_effect_node_->Update(current_effect, std::move(state), {});
}
EffectPaintPropertyNode* ViewTransitionStyleTracker::GetEffect(
Element* element) const {
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
if (element_data->target_element != element)
continue;
DCHECK(element_data->effect_node);
return element_data->effect_node.get();
}