-
-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathcreate-projection-node.ts
2296 lines (1947 loc) · 77.7 KB
/
create-projection-node.ts
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
import {
activeAnimations,
AnimationPlaybackControls,
cancelFrame,
frame,
frameData,
frameSteps,
getValueTransition,
microtask,
statsBuffer,
time,
ValueAnimationOptions,
type Process,
} from "motion-dom"
import { noop, SubscriptionManager } from "motion-utils"
import { animateSingleValue } from "../../animation/animate/single-value"
import { getOptimisedAppearId } from "../../animation/optimized-appear/get-appear-id"
import { MotionStyle } from "../../motion/types"
import { HTMLVisualElement } from "../../projection"
import { isSVGElement } from "../../render/dom/utils/is-svg-element"
import { ResolvedValues } from "../../render/types"
import { FlatTree } from "../../render/utils/flat-tree"
import { VisualElement } from "../../render/VisualElement"
import { Transition } from "../../types"
import { clamp } from "../../utils/clamp"
import { delay } from "../../utils/delay"
import { mixNumber } from "../../utils/mix/number"
import { resolveMotionValue } from "../../value/utils/resolve-motion-value"
import { mixValues } from "../animation/mix-values"
import { copyAxisDeltaInto, copyBoxInto } from "../geometry/copy"
import {
applyBoxDelta,
applyTreeDeltas,
transformBox,
translateAxis,
} from "../geometry/delta-apply"
import {
calcBoxDelta,
calcLength,
calcRelativeBox,
calcRelativePosition,
isNear,
} from "../geometry/delta-calc"
import { removeBoxTransforms } from "../geometry/delta-remove"
import { createBox, createDelta } from "../geometry/models"
import { Axis, AxisDelta, Box, Delta, Point } from "../geometry/types"
import {
aspectRatio,
axisDeltaEquals,
boxEquals,
boxEqualsRounded,
isDeltaZero,
} from "../geometry/utils"
import { NodeStack } from "../shared/stack"
import { scaleCorrectors } from "../styles/scale-correction"
import { buildProjectionTransform } from "../styles/transform"
import { eachAxis } from "../utils/each-axis"
import { has2DTranslate, hasScale, hasTransform } from "../utils/has-transform"
import { globalProjectionState } from "./state"
import {
IProjectionNode,
LayoutEvents,
LayoutUpdateData,
Measurements,
Phase,
ProjectionNodeConfig,
ProjectionNodeOptions,
ScrollMeasurements,
} from "./types"
const metrics = {
nodes: 0,
calculatedTargetDeltas: 0,
calculatedProjections: 0,
}
const transformAxes = ["", "X", "Y", "Z"]
const hiddenVisibility: ResolvedValues = { visibility: "hidden" }
/**
* We use 1000 as the animation target as 0-1000 maps better to pixels than 0-1
* which has a noticeable difference in spring animations
*/
const animationTarget = 1000
let id = 0
function resetDistortingTransform(
key: string,
visualElement: VisualElement,
values: ResolvedValues,
sharedAnimationValues?: ResolvedValues
) {
const { latestValues } = visualElement
// Record the distorting transform and then temporarily set it to 0
if (latestValues[key]) {
values[key] = latestValues[key]
visualElement.setStaticValue(key, 0)
if (sharedAnimationValues) {
sharedAnimationValues[key] = 0
}
}
}
function cancelTreeOptimisedTransformAnimations(
projectionNode: IProjectionNode
) {
projectionNode.hasCheckedOptimisedAppear = true
if (projectionNode.root === projectionNode) return
const { visualElement } = projectionNode.options
if (!visualElement) return
const appearId = getOptimisedAppearId(visualElement)
if (window.MotionHasOptimisedAnimation!(appearId, "transform")) {
const { layout, layoutId } = projectionNode.options
window.MotionCancelOptimisedAnimation!(
appearId,
"transform",
frame,
!(layout || layoutId)
)
}
const { parent } = projectionNode
if (parent && !parent.hasCheckedOptimisedAppear) {
cancelTreeOptimisedTransformAnimations(parent)
}
}
export function createProjectionNode<I>({
attachResizeListener,
defaultParent,
measureScroll,
checkIsScrollRoot,
resetTransform,
}: ProjectionNodeConfig<I>) {
return class ProjectionNode implements IProjectionNode<I> {
/**
* A unique ID generated for every projection node.
*/
id: number = id++
/**
* An id that represents a unique session instigated by startUpdate.
*/
animationId: number = 0
/**
* A reference to the platform-native node (currently this will be a HTMLElement).
*/
instance: I
/**
* A reference to the root projection node. There'll only ever be one tree and one root.
*/
root: IProjectionNode
/**
* A reference to this node's parent.
*/
parent?: IProjectionNode
/**
* A path from this node to the root node. This provides a fast way to iterate
* back up the tree.
*/
path: IProjectionNode[]
/**
* A Set containing all this component's children. This is used to iterate
* through the children.
*
* TODO: This could be faster to iterate as a flat array stored on the root node.
*/
children = new Set<IProjectionNode>()
/**
* Options for the node. We use this to configure what kind of layout animations
* we should perform (if any).
*/
options: ProjectionNodeOptions = {}
/**
* A snapshot of the element's state just before the current update. This is
* hydrated when this node's `willUpdate` method is called and scrubbed at the
* end of the tree's `didUpdate` method.
*/
snapshot: Measurements | undefined
/**
* A box defining the element's layout relative to the page. This will have been
* captured with all parent scrolls and projection transforms unset.
*/
layout: Measurements | undefined
/**
* The layout used to calculate the previous layout animation. We use this to compare
* layouts between renders and decide whether we need to trigger a new layout animation
* or just let the current one play out.
*/
targetLayout?: Box
/**
* A mutable data structure we use to apply all parent transforms currently
* acting on the element's layout. It's from here we can calculate the projectionDelta
* required to get the element from its layout into its calculated target box.
*/
layoutCorrected: Box
/**
* An ideal projection transform we want to apply to the element. This is calculated,
* usually when an element's layout has changed, and we want the element to look as though
* its in its previous layout on the next frame. From there, we animated it down to 0
* to animate the element to its new layout.
*/
targetDelta?: Delta
/**
* A mutable structure representing the visual bounding box on the page where we want
* and element to appear. This can be set directly but is currently derived once a frame
* from apply targetDelta to layout.
*/
target?: Box
/**
* A mutable structure describing a visual bounding box relative to the element's
* projected parent. If defined, target will be derived from this rather than targetDelta.
* If not defined, we'll attempt to calculate on the first layout animation frame
* based on the targets calculated from targetDelta. This will transfer a layout animation
* from viewport-relative to parent-relative.
*/
relativeTarget?: Box
relativeTargetOrigin?: Box
relativeParent?: IProjectionNode
/**
* We use this to detect when its safe to shut down part of a projection tree.
* We have to keep projecting children for scale correction and relative projection
* until all their parents stop performing layout animations.
*/
isTreeAnimating = false
isAnimationBlocked = false
/**
* If true, attempt to resolve relativeTarget.
*/
attemptToResolveRelativeTarget?: boolean
/**
* A mutable structure that represents the target as transformed by the element's
* latest user-set transforms (ie scale, x)
*/
targetWithTransforms?: Box
/**
* The previous projection delta, which we can compare with the newly calculated
* projection delta to see if we need to render.
*/
prevProjectionDelta?: Delta
/**
* A calculated transform that will project an element from its layoutCorrected
* into the target. This will be used by children to calculate their own layoutCorrect boxes.
*/
projectionDelta?: Delta
/**
* A calculated transform that will project an element from its layoutCorrected
* into the targetWithTransforms.
*/
projectionDeltaWithTransform?: Delta
/**
* If we're tracking the scroll of this element, we store it here.
*/
scroll?: ScrollMeasurements
/**
* Flag to true if we think this layout has been changed. We can't always know this,
* currently we set it to true every time a component renders, or if it has a layoutDependency
* if that has changed between renders. Additionally, components can be grouped by LayoutGroup
* and if one node is dirtied, they all are.
*/
isLayoutDirty = false
/**
* Flag to true if we think the projection calculations for this node needs
* recalculating as a result of an updated transform or layout animation.
*/
isProjectionDirty = false
/**
* Flag to true if the layout *or* transform has changed. This then gets propagated
* throughout the projection tree, forcing any element below to recalculate on the next frame.
*/
isSharedProjectionDirty = false
/**
* Flag transform dirty. This gets propagated throughout the whole tree but is only
* respected by shared nodes.
*/
isTransformDirty = false
/**
* Block layout updates for instant layout transitions throughout the tree.
*/
updateManuallyBlocked = false
updateBlockedByResize = false
/**
* Set to true between the start of the first `willUpdate` call and the end of the `didUpdate`
* call.
*/
isUpdating = false
/**
* If this is an SVG element we currently disable projection transforms
*/
isSVG = false
/**
* Flag to true (during promotion) if a node doing an instant layout transition needs to reset
* its projection styles.
*/
needsReset = false
/**
* Flags whether this node should have its transform reset prior to measuring.
*/
shouldResetTransform = false
/**
* Store whether this node has been checked for optimised appear animations. As
* effects fire bottom-up, and we want to look up the tree for appear animations,
* this makes sure we only check each path once, stopping at nodes that
* have already been checked.
*/
hasCheckedOptimisedAppear = false
/**
* An object representing the calculated contextual/accumulated/tree scale.
* This will be used to scale calculcated projection transforms, as these are
* calculated in screen-space but need to be scaled for elements to layoutly
* make it to their calculated destinations.
*
* TODO: Lazy-init
*/
treeScale: Point = { x: 1, y: 1 }
/**
* Is hydrated with a projection node if an element is animating from another.
*/
resumeFrom?: IProjectionNode
/**
* Is hydrated with a projection node if an element is animating from another.
*/
resumingFrom?: IProjectionNode
/**
* A reference to the element's latest animated values. This is a reference shared
* between the element's VisualElement and the ProjectionNode.
*/
latestValues: ResolvedValues
/**
*
*/
eventHandlers = new Map<LayoutEvents, SubscriptionManager<any>>()
nodes?: FlatTree
depth: number
/**
* If transformTemplate generates a different value before/after the
* update, we need to reset the transform.
*/
prevTransformTemplateValue: string | undefined
preserveOpacity?: boolean
hasTreeAnimated = false
constructor(
latestValues: ResolvedValues = {},
parent: IProjectionNode | undefined = defaultParent?.()
) {
this.latestValues = latestValues
this.root = parent ? parent.root || parent : this
this.path = parent ? [...parent.path, parent] : []
this.parent = parent
this.depth = parent ? parent.depth + 1 : 0
for (let i = 0; i < this.path.length; i++) {
this.path[i].shouldResetTransform = true
}
if (this.root === this) this.nodes = new FlatTree()
}
addEventListener(name: LayoutEvents, handler: any) {
if (!this.eventHandlers.has(name)) {
this.eventHandlers.set(name, new SubscriptionManager())
}
return this.eventHandlers.get(name)!.add(handler)
}
notifyListeners(name: LayoutEvents, ...args: any) {
const subscriptionManager = this.eventHandlers.get(name)
subscriptionManager && subscriptionManager.notify(...args)
}
hasListeners(name: LayoutEvents) {
return this.eventHandlers.has(name)
}
/**
* Lifecycles
*/
mount(instance: I, isLayoutDirty = this.root.hasTreeAnimated) {
if (this.instance) return
this.isSVG = isSVGElement(instance)
this.instance = instance
const { layoutId, layout, visualElement } = this.options
if (visualElement && !visualElement.current) {
visualElement.mount(instance)
}
this.root.nodes!.add(this)
this.parent && this.parent.children.add(this)
if (isLayoutDirty && (layout || layoutId)) {
this.isLayoutDirty = true
}
if (attachResizeListener) {
let cancelDelay: VoidFunction
const resizeUnblockUpdate = () =>
(this.root.updateBlockedByResize = false)
attachResizeListener(instance, () => {
this.root.updateBlockedByResize = true
cancelDelay && cancelDelay()
cancelDelay = delay(resizeUnblockUpdate, 250)
if (globalProjectionState.hasAnimatedSinceResize) {
globalProjectionState.hasAnimatedSinceResize = false
this.nodes!.forEach(finishAnimation)
}
})
}
if (layoutId) {
this.root.registerSharedNode(layoutId, this)
}
// Only register the handler if it requires layout animation
if (
this.options.animate !== false &&
visualElement &&
(layoutId || layout)
) {
this.addEventListener(
"didUpdate",
({
delta,
hasLayoutChanged,
hasRelativeLayoutChanged,
layout: newLayout,
}: LayoutUpdateData) => {
if (this.isTreeAnimationBlocked()) {
this.target = undefined
this.relativeTarget = undefined
return
}
// TODO: Check here if an animation exists
const layoutTransition =
this.options.transition ||
visualElement.getDefaultTransition() ||
defaultLayoutTransition
const {
onLayoutAnimationStart,
onLayoutAnimationComplete,
} = visualElement.getProps()
/**
* The target layout of the element might stay the same,
* but its position relative to its parent has changed.
*/
const hasTargetChanged =
!this.targetLayout ||
!boxEqualsRounded(this.targetLayout, newLayout)
/*
* Note: Disabled to fix relative animations always triggering new
* layout animations. If this causes further issues, we can try
* a different approach to detecting relative target changes.
*/
// || hasRelativeLayoutChanged
/**
* If the layout hasn't seemed to have changed, it might be that the
* element is visually in the same place in the document but its position
* relative to its parent has indeed changed. So here we check for that.
*/
const hasOnlyRelativeTargetChanged =
!hasLayoutChanged && hasRelativeLayoutChanged
if (
this.options.layoutRoot ||
this.resumeFrom ||
hasOnlyRelativeTargetChanged ||
(hasLayoutChanged &&
(hasTargetChanged || !this.currentAnimation))
) {
if (this.resumeFrom) {
this.resumingFrom = this.resumeFrom
this.resumingFrom.resumingFrom = undefined
}
this.setAnimationOrigin(
delta,
hasOnlyRelativeTargetChanged
)
const animationOptions = {
...getValueTransition(
layoutTransition,
"layout"
),
onPlay: onLayoutAnimationStart,
onComplete: onLayoutAnimationComplete,
}
if (
visualElement.shouldReduceMotion ||
this.options.layoutRoot
) {
animationOptions.delay = 0
animationOptions.type = false
}
this.startAnimation(animationOptions)
} else {
/**
* If the layout hasn't changed and we have an animation that hasn't started yet,
* finish it immediately. Otherwise it will be animating from a location
* that was probably never commited to screen and look like a jumpy box.
*/
if (!hasLayoutChanged) {
finishAnimation(this)
}
if (this.isLead() && this.options.onExitComplete) {
this.options.onExitComplete()
}
}
this.targetLayout = newLayout
}
)
}
}
unmount() {
this.options.layoutId && this.willUpdate()
this.root.nodes!.remove(this)
const stack = this.getStack()
stack && stack.remove(this)
this.parent && this.parent.children.delete(this)
;(this.instance as any) = undefined
cancelFrame(this.updateProjection)
}
// only on the root
blockUpdate() {
this.updateManuallyBlocked = true
}
unblockUpdate() {
this.updateManuallyBlocked = false
}
isUpdateBlocked() {
return this.updateManuallyBlocked || this.updateBlockedByResize
}
isTreeAnimationBlocked() {
return (
this.isAnimationBlocked ||
(this.parent && this.parent.isTreeAnimationBlocked()) ||
false
)
}
// Note: currently only running on root node
startUpdate() {
if (this.isUpdateBlocked()) return
this.isUpdating = true
this.nodes && this.nodes.forEach(resetSkewAndRotation)
this.animationId++
}
getTransformTemplate() {
const { visualElement } = this.options
return visualElement && visualElement.getProps().transformTemplate
}
willUpdate(shouldNotifyListeners = true) {
this.root.hasTreeAnimated = true
if (this.root.isUpdateBlocked()) {
this.options.onExitComplete && this.options.onExitComplete()
return
}
/**
* If we're running optimised appear animations then these must be
* cancelled before measuring the DOM. This is so we can measure
* the true layout of the element rather than the WAAPI animation
* which will be unaffected by the resetSkewAndRotate step.
*
* Note: This is a DOM write. Worst case scenario is this is sandwiched
* between other snapshot reads which will cause unnecessary style recalculations.
* This has to happen here though, as we don't yet know which nodes will need
* snapshots in startUpdate(), but we only want to cancel optimised animations
* if a layout animation measurement is actually going to be affected by them.
*/
if (
window.MotionCancelOptimisedAnimation &&
!this.hasCheckedOptimisedAppear
) {
cancelTreeOptimisedTransformAnimations(this)
}
!this.root.isUpdating && this.root.startUpdate()
if (this.isLayoutDirty) return
this.isLayoutDirty = true
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i]
node.shouldResetTransform = true
node.updateScroll("snapshot")
if (node.options.layoutRoot) {
node.willUpdate(false)
}
}
const { layoutId, layout } = this.options
if (layoutId === undefined && !layout) return
const transformTemplate = this.getTransformTemplate()
this.prevTransformTemplateValue = transformTemplate
? transformTemplate(this.latestValues, "")
: undefined
this.updateSnapshot()
shouldNotifyListeners && this.notifyListeners("willUpdate")
}
// Note: Currently only running on root node
updateScheduled = false
update() {
this.updateScheduled = false
const updateWasBlocked = this.isUpdateBlocked()
// When doing an instant transition, we skip the layout update,
// but should still clean up the measurements so that the next
// snapshot could be taken correctly.
if (updateWasBlocked) {
this.unblockUpdate()
this.clearAllSnapshots()
this.nodes!.forEach(clearMeasurements)
return
}
if (!this.isUpdating) {
this.nodes!.forEach(clearIsLayoutDirty)
}
this.isUpdating = false
/**
* Write
*/
this.nodes!.forEach(resetTransformStyle)
/**
* Read ==================
*/
// Update layout measurements of updated children
this.nodes!.forEach(updateLayout)
/**
* Write
*/
// Notify listeners that the layout is updated
this.nodes!.forEach(notifyLayoutUpdate)
this.clearAllSnapshots()
/**
* Manually flush any pending updates. Ideally
* we could leave this to the following requestAnimationFrame but this seems
* to leave a flash of incorrectly styled content.
*/
const now = time.now()
frameData.delta = clamp(0, 1000 / 60, now - frameData.timestamp)
frameData.timestamp = now
frameData.isProcessing = true
frameSteps.update.process(frameData)
frameSteps.preRender.process(frameData)
frameSteps.render.process(frameData)
frameData.isProcessing = false
}
scheduleUpdate = () => this.update()
didUpdate() {
if (!this.updateScheduled) {
this.updateScheduled = true
microtask.read(this.scheduleUpdate)
}
}
clearAllSnapshots() {
this.nodes!.forEach(clearSnapshot)
this.sharedNodes.forEach(removeLeadSnapshots)
}
projectionUpdateScheduled = false
scheduleUpdateProjection() {
if (!this.projectionUpdateScheduled) {
this.projectionUpdateScheduled = true
frame.preRender(this.updateProjection, false, true)
}
}
scheduleCheckAfterUnmount() {
/**
* If the unmounting node is in a layoutGroup and did trigger a willUpdate,
* we manually call didUpdate to give a chance to the siblings to animate.
* Otherwise, cleanup all snapshots to prevents future nodes from reusing them.
*/
frame.postRender(() => {
if (this.isLayoutDirty) {
this.root.didUpdate()
} else {
this.root.checkUpdateFailed()
}
})
}
checkUpdateFailed = () => {
if (this.isUpdating) {
this.isUpdating = false
this.clearAllSnapshots()
}
}
/**
* This is a multi-step process as shared nodes might be of different depths. Nodes
* are sorted by depth order, so we need to resolve the entire tree before moving to
* the next step.
*/
updateProjection = () => {
this.projectionUpdateScheduled = false
/**
* Reset debug counts. Manually resetting rather than creating a new
* object each frame.
*/
if (statsBuffer.value) {
metrics.nodes =
metrics.calculatedTargetDeltas =
metrics.calculatedProjections =
0
}
this.nodes!.forEach(propagateDirtyNodes)
this.nodes!.forEach(resolveTargetDelta)
this.nodes!.forEach(calcProjection)
this.nodes!.forEach(cleanDirtyNodes)
if (statsBuffer.addProjectionMetrics) {
statsBuffer.addProjectionMetrics(metrics)
}
}
/**
* Update measurements
*/
updateSnapshot() {
if (this.snapshot || !this.instance) return
this.snapshot = this.measure()
if (
this.snapshot &&
!calcLength(this.snapshot.measuredBox.x) &&
!calcLength(this.snapshot.measuredBox.y)
) {
this.snapshot = undefined
}
}
updateLayout() {
if (!this.instance) return
// TODO: Incorporate into a forwarded scroll offset
this.updateScroll()
if (
!(this.options.alwaysMeasureLayout && this.isLead()) &&
!this.isLayoutDirty
) {
return
}
/**
* When a node is mounted, it simply resumes from the prevLead's
* snapshot instead of taking a new one, but the ancestors scroll
* might have updated while the prevLead is unmounted. We need to
* update the scroll again to make sure the layout we measure is
* up to date.
*/
if (this.resumeFrom && !this.resumeFrom.instance) {
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i]
node.updateScroll()
}
}
const prevLayout = this.layout
this.layout = this.measure(false)
this.layoutCorrected = createBox()
this.isLayoutDirty = false
this.projectionDelta = undefined
this.notifyListeners("measure", this.layout.layoutBox)
const { visualElement } = this.options
visualElement &&
visualElement.notify(
"LayoutMeasure",
this.layout.layoutBox,
prevLayout ? prevLayout.layoutBox : undefined
)
}
updateScroll(phase: Phase = "measure") {
let needsMeasurement = Boolean(
this.options.layoutScroll && this.instance
)
if (
this.scroll &&
this.scroll.animationId === this.root.animationId &&
this.scroll.phase === phase
) {
needsMeasurement = false
}
if (needsMeasurement) {
const isRoot = checkIsScrollRoot(this.instance)
this.scroll = {
animationId: this.root.animationId,
phase,
isRoot,
offset: measureScroll(this.instance),
wasRoot: this.scroll ? this.scroll.isRoot : isRoot,
}
}
}
resetTransform() {
if (!resetTransform) return
const isResetRequested =
this.isLayoutDirty ||
this.shouldResetTransform ||
this.options.alwaysMeasureLayout
const hasProjection =
this.projectionDelta && !isDeltaZero(this.projectionDelta)
const transformTemplate = this.getTransformTemplate()
const transformTemplateValue = transformTemplate
? transformTemplate(this.latestValues, "")
: undefined
const transformTemplateHasChanged =
transformTemplateValue !== this.prevTransformTemplateValue
if (
isResetRequested &&
(hasProjection ||
hasTransform(this.latestValues) ||
transformTemplateHasChanged)
) {
resetTransform(this.instance, transformTemplateValue)
this.shouldResetTransform = false
this.scheduleRender()
}
}
measure(removeTransform = true) {
const pageBox = this.measurePageBox()
let layoutBox = this.removeElementScroll(pageBox)
/**
* Measurements taken during the pre-render stage
* still have transforms applied so we remove them
* via calculation.
*/
if (removeTransform) {
layoutBox = this.removeTransform(layoutBox)
}
roundBox(layoutBox)
return {
animationId: this.root.animationId,
measuredBox: pageBox,
layoutBox,
latestValues: {},
source: this.id,
}
}
measurePageBox() {
const { visualElement } = this.options
if (!visualElement) return createBox()
const box = visualElement.measureViewportBox()
const wasInScrollRoot =
this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot)
if (!wasInScrollRoot) {
// Remove viewport scroll to give page-relative coordinates
const { scroll } = this.root
if (scroll) {
translateAxis(box.x, scroll.offset.x)
translateAxis(box.y, scroll.offset.y)
}
}
return box
}
removeElementScroll(box: Box): Box {
const boxWithoutScroll = createBox()
copyBoxInto(boxWithoutScroll, box)
if (this.scroll?.wasRoot) {
return boxWithoutScroll
}
/**
* Performance TODO: Keep a cumulative scroll offset down the tree
* rather than loop back up the path.
*/
for (let i = 0; i < this.path.length; i++) {
const node = this.path[i]
const { scroll, options } = node
if (node !== this.root && scroll && options.layoutScroll) {
/**
* If this is a new scroll root, we want to remove all previous scrolls
* from the viewport box.
*/
if (scroll.wasRoot) {
copyBoxInto(boxWithoutScroll, box)
}
translateAxis(boxWithoutScroll.x, scroll.offset.x)