Skip to content

Commit b396050

Browse files
feat(mosaic): stack Flow step transitions by default (#10152)
Co-authored-by: Alex Carpenter <alex.carpenter@clerk.dev>
1 parent c781630 commit b396050

14 files changed

Lines changed: 298 additions & 105 deletions
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎.changeset/flow-stack-motion.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
---
2+
---

‎packages/mosaic/src/components/flow/flow.styles.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as stylex from '@stylexjs/stylex';
22

3-
import { durationVars, easingVars } from '../../tokens.stylex';
3+
import { durationVars, easingVars, space, typeScaleVars } from '../../tokens.stylex';
44

55
export const styles = stylex.create({
66
root: {
@@ -15,7 +15,10 @@ export const styles = stylex.create({
1515
':where([data-transitioning])': 'height',
1616
'@media (prefers-reduced-motion: reduce)': 'none',
1717
},
18-
transitionTimingFunction: easingVars['--cl-ease-enter'],
18+
transitionTimingFunction: {
19+
default: easingVars['--cl-ease-enter'],
20+
':where([data-height-change="shrink"])': easingVars['--cl-ease-in-out'],
21+
},
1922
height: 'var(--cl-flow-step-height)',
2023
},
2124
step: {
@@ -29,26 +32,40 @@ export const styles = stylex.create({
2932
default: null,
3033
':where([data-closed])': 0,
3134
},
35+
opacity: {
36+
default: 1,
37+
':where([data-starting-style], [data-ending-style])': 0,
38+
},
3239
position: {
3340
default: 'relative',
3441
':where([data-closed])': 'absolute',
3542
},
3643
transform: {
37-
default: 'translateX(0)',
38-
':where([data-ending-style])': 'translateX(calc(var(--cl-flow-transition-direction, 1) * -100%))',
39-
':where([data-starting-style])': 'translateX(calc(var(--cl-flow-transition-direction, 1) * 100%))',
44+
default: 'scale(1)',
45+
':where([data-starting-style], [data-ending-style])': 'scale(0.96)',
4046
'@media (prefers-reduced-motion: reduce)': {
41-
default: 'translateX(0)',
42-
':where([data-ending-style])': 'translateX(0)',
43-
':where([data-starting-style])': 'translateX(0)',
47+
default: 'scale(1)',
48+
':where([data-starting-style], [data-ending-style])': 'scale(1)',
4449
},
4550
},
46-
transitionDuration: durationVars['--cl-duration-slow'],
51+
transformOrigin: `50% calc(${space['4']} + ${typeScaleVars['--cl-text-base-size']} * ${typeScaleVars['--cl-text-base-leading']} / 2)`,
52+
transitionDelay: {
53+
default: `calc(${durationVars['--cl-duration-base']} / 2)`,
54+
':where([data-ending-style])': durationVars['--cl-duration-instant'],
55+
'@media (prefers-reduced-motion: reduce)': durationVars['--cl-duration-instant'],
56+
},
57+
transitionDuration: {
58+
default: `${durationVars['--cl-duration-base']}, ${durationVars['--cl-duration-slow']}`,
59+
':where([data-ending-style])': durationVars['--cl-duration-base'],
60+
},
4761
transitionProperty: {
48-
default: 'transform',
49-
'@media (prefers-reduced-motion: reduce)': 'none',
62+
default: 'opacity, transform',
63+
'@media (prefers-reduced-motion: reduce)': 'opacity',
64+
},
65+
transitionTimingFunction: {
66+
default: easingVars['--cl-ease-enter'],
67+
':where([data-ending-style])': easingVars['--cl-ease-in-out'],
5068
},
51-
transitionTimingFunction: easingVars['--cl-ease-enter'],
5269
willChange: 'transform',
5370
minWidth: 0,
5471
width: '100%',

‎packages/mosaic/src/primitives/flow/README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,9 @@ The initially active step does not receive `data-starting-style`. An exiting ste
8080

8181
`Flow.Root` carries `data-initial` through the first measured frame. Styled adapters can use it to disable viewport transitions so the initial step never animates.
8282

83-
`Flow.Root` carries `data-transitioning` while any step is exiting. Styled adapters should only transition the viewport height under it, so a resize inside the active step (for example a field message animating open) is tracked as-is instead of being animated a second time.
83+
`Flow.Root` carries `data-transitioning` from a step change until its own `height` transition finishes, independent of how long the steps take to enter or exit. If the height does not transition, it clears at once, and other animations on the root are ignored. Styled adapters should only transition the viewport height under it, so a resize inside the active step (for example a field message animating open) is tracked as-is instead of being animated a second time.
84+
85+
`Flow.Root` carries `data-height-change` set to `grow` or `shrink` after the measured step height changes, so the height transition can use a different curve in each direction.
8486

8587
## CSS variable
8688

‎packages/mosaic/src/primitives/flow/flow-context.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ export interface FlowContextValue {
88
rootRef: RefObject<HTMLDivElement | null>;
99
registerActiveStep: (element: HTMLElement) => void;
1010
unregisterActiveStep: (element: HTMLElement) => void;
11-
registerExitingStep: (element: HTMLElement) => void;
12-
unregisterExitingStep: (element: HTMLElement) => void;
1311
}
1412

1513
export const FlowContext = createContext<FlowContextValue | null>(null);

‎packages/mosaic/src/primitives/flow/flow-root.tsx‎

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@
22

33
import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
44

5+
import { useAnimationsFinished } from '../hooks/use-animations-finished';
56
import { type ComponentProps, mergeProps, useRender } from '../utils';
67
import { autoUpdate, getDimensions } from '../utils/dom';
78
import { FlowContext, type FlowContextValue, type FlowDirection } from './flow-context';
89

10+
function isHeightTransition(animation: Animation): boolean {
11+
return 'transitionProperty' in animation && animation.transitionProperty === 'height';
12+
}
13+
914
export interface FlowRootProps extends ComponentProps<'div'> {
1015
value: string;
1116
direction?: FlowDirection;
@@ -17,42 +22,48 @@ export const FlowRoot = React.forwardRef<HTMLDivElement, FlowRootProps>(function
1722
const [activeStep, setActiveStep] = useState<HTMLElement | null>(null);
1823
const [measured, setMeasured] = useState(false);
1924
const [initial, setInitial] = useState(true);
20-
const [exitingSteps, setExitingSteps] = useState<ReadonlySet<HTMLElement>>(() => new Set());
25+
const [transitioning, setTransitioning] = useState(false);
26+
const lastActiveStepRef = useRef<HTMLElement | null>(null);
27+
const stepHeightRef = useRef<number | null>(null);
28+
const runOnHeightTransitionFinished = useAnimationsFinished(rootRef, false, isHeightTransition);
2129

2230
const registerActiveStep = useCallback((element: HTMLElement) => {
31+
if (lastActiveStepRef.current && lastActiveStepRef.current !== element) {
32+
setTransitioning(true);
33+
}
34+
lastActiveStepRef.current = element;
2335
setActiveStep(element);
2436
}, []);
2537

2638
const unregisterActiveStep = useCallback((element: HTMLElement) => {
2739
setActiveStep(current => (current === element ? null : current));
2840
}, []);
2941

30-
const registerExitingStep = useCallback((element: HTMLElement) => {
31-
setExitingSteps(current => new Set(current).add(element));
32-
}, []);
33-
34-
const unregisterExitingStep = useCallback((element: HTMLElement) => {
35-
setExitingSteps(current => {
36-
if (!current.has(element)) {
37-
return current;
38-
}
39-
const next = new Set(current);
40-
next.delete(element);
41-
return next;
42-
});
43-
}, []);
44-
4542
useLayoutEffect(() => {
4643
if (!activeStep) {
4744
return;
4845
}
4946

5047
return autoUpdate(activeStep, () => {
51-
rootRef.current?.style.setProperty('--cl-flow-step-height', `${getDimensions(activeStep).height}px`);
48+
const root = rootRef.current;
49+
const { height } = getDimensions(activeStep);
50+
if (root && stepHeightRef.current !== null && height !== stepHeightRef.current) {
51+
root.dataset.heightChange = height < stepHeightRef.current ? 'shrink' : 'grow';
52+
}
53+
stepHeightRef.current = height;
54+
root?.style.setProperty('--cl-flow-step-height', `${height}px`);
5255
setMeasured(true);
5356
});
5457
}, [activeStep]);
5558

59+
useLayoutEffect(() => {
60+
if (!transitioning) {
61+
return;
62+
}
63+
64+
return runOnHeightTransitionFinished(() => setTransitioning(false));
65+
}, [transitioning, activeStep, runOnHeightTransitionFinished]);
66+
5667
useLayoutEffect(() => {
5768
if (!measured || !initial) {
5869
return;
@@ -69,10 +80,8 @@ export const FlowRoot = React.forwardRef<HTMLDivElement, FlowRootProps>(function
6980
rootRef,
7081
registerActiveStep,
7182
unregisterActiveStep,
72-
registerExitingStep,
73-
unregisterExitingStep,
7483
}),
75-
[value, direction, registerActiveStep, unregisterActiveStep, registerExitingStep, unregisterExitingStep],
84+
[value, direction, registerActiveStep, unregisterActiveStep],
7685
);
7786

7887
const element = useRender({
@@ -82,7 +91,7 @@ export const FlowRoot = React.forwardRef<HTMLDivElement, FlowRootProps>(function
8291
props: mergeProps<'div'>(
8392
{
8493
'data-initial': initial ? '' : undefined,
85-
'data-transitioning': exitingSteps.size > 0 ? '' : undefined,
94+
'data-transitioning': transitioning ? '' : undefined,
8695
},
8796
otherProps,
8897
),

‎packages/mosaic/src/primitives/flow/flow-step.tsx‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,7 @@ function firstInDocumentOrder(elements: Iterable<HTMLElement>): HTMLElement | nu
3030
export const FlowStep = React.forwardRef<HTMLDivElement, FlowStepProps>(function FlowStep(props, forwardedRef) {
3131
const { render, ids, children, ...otherProps } = props;
3232
const parentActive = useFlowStepActive();
33-
const {
34-
value,
35-
direction,
36-
rootRef,
37-
registerActiveStep,
38-
unregisterActiveStep,
39-
registerExitingStep,
40-
unregisterExitingStep,
41-
} = useFlowContext();
33+
const { value, direction, rootRef, registerActiveStep, unregisterActiveStep } = useFlowContext();
4234
const open = ids.includes(value);
4335
const stepRef = useRef<HTMLDivElement | null>(null);
4436
const activeChildrenRef = useRef(children);
@@ -64,18 +56,6 @@ export const FlowStep = React.forwardRef<HTMLDivElement, FlowStepProps>(function
6456
return () => unregisterActiveStep(element);
6557
}, [open, registerActiveStep, unregisterActiveStep]);
6658

67-
const exiting = mounted && !open;
68-
69-
useLayoutEffect(() => {
70-
const element = stepRef.current;
71-
if (!exiting || !element) {
72-
return;
73-
}
74-
75-
registerExitingStep(element);
76-
return () => unregisterExitingStep(element);
77-
}, [exiting, registerExitingStep, unregisterExitingStep]);
78-
7959
// A layout effect, so focus moves in the commit that makes the leaving step inert: field to field,
8060
// which iOS does without dropping the keyboard. A passive effect would leave a frame with none.
8161
useLayoutEffect(() => {

‎packages/mosaic/src/primitives/flow/flow.test.tsx‎

Lines changed: 80 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -239,40 +239,101 @@ describe('Flow', () => {
239239

240240
expect(root).not.toHaveAttribute('data-initial');
241241

242+
expect(root).not.toHaveAttribute('data-height-change');
243+
242244
rerender(<TestFlow value='otp' />);
243245

244246
expect(root.style.getPropertyValue('--cl-flow-step-height')).toBe('240px');
247+
expect(root).toHaveAttribute('data-height-change', 'grow');
245248
expect(root).not.toHaveAttribute('data-initial');
249+
250+
rerender(<TestFlow value='password' />);
251+
252+
expect(root).toHaveAttribute('data-height-change', 'shrink');
246253
offsetHeight.mockRestore();
247254
});
248-
it('marks the root as transitioning only while a step is exiting', async () => {
249-
let finishAnimation!: () => void;
250-
const animationFinished = new Promise<void>(resolve => {
251-
finishAnimation = resolve;
255+
describe('data-transitioning', () => {
256+
function deferred() {
257+
let resolve!: () => void;
258+
const promise = new Promise<void>(r => {
259+
resolve = r;
260+
});
261+
return { promise, resolve };
262+
}
263+
264+
function mockRootAnimations(root: HTMLElement, animations: Array<Record<string, unknown>>) {
265+
root.getAnimations = vi.fn(() => animations as unknown as Animation[]);
266+
}
267+
268+
it('lasts from a step change until the root height transition finishes', async () => {
269+
const height = deferred();
270+
const { rerender } = render(<TestFlow value='password' />);
271+
const root = screen.getByTestId('flow-root');
272+
mockRootAnimations(root, [{ transitionProperty: 'height', finished: height.promise }]);
273+
274+
rerender(<TestFlow value='password-error' />);
275+
276+
expect(root).not.toHaveAttribute('data-transitioning');
277+
278+
rerender(<TestFlow value='otp' />);
279+
280+
expect(screen.queryByTestId('password-step')).not.toBeInTheDocument();
281+
expect(root).toHaveAttribute('data-transitioning');
282+
283+
mockRootAnimations(root, []);
284+
await act(async () => {
285+
height.resolve();
286+
await height.promise;
287+
});
288+
289+
expect(root).not.toHaveAttribute('data-transitioning');
252290
});
253-
const { rerender } = render(<TestFlow value='password' />);
254-
const root = screen.getByTestId('flow-root');
255-
const outgoingStep = screen.getByTestId('password-step');
256-
outgoingStep.getAnimations = vi.fn(() => [{ finished: animationFinished }] as unknown as Animation[]);
257291

258-
expect(root).not.toHaveAttribute('data-transitioning');
292+
it('clears at once when the root height does not transition', () => {
293+
const { rerender } = render(<TestFlow value='password' />);
294+
const root = screen.getByTestId('flow-root');
295+
mockRootAnimations(root, []);
259296

260-
rerender(<TestFlow value='password-error' />);
297+
rerender(<TestFlow value='otp' />);
261298

262-
expect(root).not.toHaveAttribute('data-transitioning');
299+
expect(root).not.toHaveAttribute('data-transitioning');
300+
});
263301

264-
rerender(<TestFlow value='otp' />);
302+
it('is not held by other animations on the root', () => {
303+
const { rerender } = render(<TestFlow value='password' />);
304+
const root = screen.getByTestId('flow-root');
305+
mockRootAnimations(root, [{ animationName: 'pulse', finished: new Promise<void>(() => {}) }]);
265306

266-
expect(root).toHaveAttribute('data-transitioning');
307+
rerender(<TestFlow value='otp' />);
267308

268-
outgoingStep.getAnimations = vi.fn(() => []);
269-
await act(async () => {
270-
finishAnimation();
271-
await animationFinished;
309+
expect(root).not.toHaveAttribute('data-transitioning');
272310
});
273311

274-
expect(screen.queryByTestId('password-step')).not.toBeInTheDocument();
275-
expect(root).not.toHaveAttribute('data-transitioning');
312+
it('waits for the latest height transition when the step changes again', async () => {
313+
const first = deferred();
314+
const second = deferred();
315+
const { rerender } = render(<TestFlow value='password' />);
316+
const root = screen.getByTestId('flow-root');
317+
mockRootAnimations(root, [{ transitionProperty: 'height', finished: first.promise }]);
318+
319+
rerender(<TestFlow value='otp' />);
320+
mockRootAnimations(root, [{ transitionProperty: 'height', finished: second.promise }]);
321+
rerender(<TestFlow value='password' />);
322+
await act(async () => {
323+
first.resolve();
324+
await first.promise;
325+
});
326+
327+
expect(root).toHaveAttribute('data-transitioning');
328+
329+
mockRootAnimations(root, []);
330+
await act(async () => {
331+
second.resolve();
332+
await second.promise;
333+
});
334+
335+
expect(root).not.toHaveAttribute('data-transitioning');
336+
});
276337
});
277338

278339
describe('useFlowAutoFocus', () => {

0 commit comments

Comments
 (0)