Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): a rebase toward the new rest shifts the curve whole (#10369)

Christopher Chedeau39d5abc763e8
diff --git a/.changeset/animator-rebase-toward-rest.md b/.changeset/animator-rebase-toward-rest.md
new file mode 100644
index 0000000000..3e60df76f6
--- /dev/null
+++ b/.changeset/animator-rebase-toward-rest.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Motion: a Switch's value change mid-travel keeps the thumb's running speed. A rebase toward the new rest shifts the curve whole.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 37101d4860..5e58898af6 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -265,9 +265,11 @@ a measured, sourced difference exists.
velocity to the settle. The floor is a guess inside the measured bracket
(UIKit zeroes steady releases at 175 and 200 pt/s and keeps 249 pt/s, iOS
26.2 simulator, 2026-10-23) until a measurement replaces it (FR2). A page
- change during a drag starts from rest (DEC-25). On a starved page, a
- retarget may skip ahead by up to the browser's commit delay
- (start-at-call).
+ change during a drag starts from rest (DEC-25). A rebase toward the new
+ rest shifts a spring heading there whole: its curve and target move by the
+ rest's change, and it keeps its start time and velocity. On a starved page,
+ the Switch's value change then shows no step in its frame proofs; any other
+ retarget may still skip ahead by up to the browser's commit delay.
- **FR7 — Exits keep the native counterpart's look.** A touch presentation MUST
play an exit with the look of its UIKit counterpart's exit, on every touch
platform: a menu shrinks into its trigger, and an alert fades. In a component
@@ -1039,7 +1041,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li
| FR5 glide | Browser proof: the animated-layout glide keeps moving through a 700 ms main-thread block, on every frame a compositor control moves | the content after a Collapsible, a TreeList branch and a Table row; verified in Chromium; WebKit by an iOS Simulator spot-check (38/39 frames), not an automated run (evidence gap) | a glide stepped from the main thread freezes |
| FR6 | Unit and browser tests catching an animation mid-flight and retargeting it | catch at peak velocity; retarget with a new spring; a retarget before the browser reports the call's start | a layout read, a jump, or a lost velocity fails |
| FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, a catch that loses the on-screen velocity, or a programmatic page change mid-settle that starts from rest fails; a page change during a drag starts from rest |
-| FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); a unit test of a retarget on a settle tail | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still | a jump out of a thumb that is still fails; a mid-travel step within the browser's commit delay is the known limit |
+| FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); unit tests of a retarget on a settle tail and a rebase toward a new rest | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still; a value change mid-slide, whose rebase moves the travel whole | a jump out of a thumb that is still fails; a value change mid-slide shows no step; another retarget's step within the browser's commit delay is the known limit |
| FR7, FR8 | Component browser tests and storyboards with and without Reduce Motion | entrance, exit, move; a drag and its lift under Reduce Motion; a tap-, key- and program-started close of a sheet and the Lightbox | a missing exit, any travel, scale or spring under Reduce Motion other than a coast after a throw and its settle at an edge (`design:reduced-motion` DR2), an opacity fade over 200 ms, or a tap-, key- or program-started close of a gesture component on the exit curve instead of its spring, fails |
| FR45 | Browser tests with a mouse, a pen, a trackpad and a finger at each `tempo` bound and each `character`, and with Reduce Motion | a tap, a click, a key and a programmatic change on a Switch, a menu, an alert, a sheet and a ProgressBar under a fine and a coarse pointer; a drag release, a flick and a pinch on a Switch, a Slider, a sheet, a pager and a Lightbox photo under each pointer; a tap that continues as a drag | a tap, click, key or programmatic change in a tap-classified component that plays a measured role or a spring instead of the theme's duration and easing tokens, a touch tap-started move in a gesture or gesture-capable component on a curve instead of its spring, a click, a key or a value change on Switch or SegmentedControl without a touch presentation that leaves the theme's curve, a velocity-carrying release that settles from rest or on a curve, a gesture's spring that ignores `character` or `tempo`, or a part that follows one pointer and not another, fails; the pager's measured settle, which does not yet follow `tempo` or `character`, is a recorded implementation gap |
| FR45 | Component source and token tests for a tap component's motion whose record names no step, with a platform measurement | a small anchored surface (a popover, a menu, a toggle, a row) and a full-screen surface (a Dialog, an AlertDialog), each with its own measurement; a tap component's overlay exit | a token cited as nearest to the measurement in the Storybook theme passes, and a tap component's overlay exit on `--duration-exit` passes; a token chosen by role alone, or nearest at Core's unthemed defaults, fails |
diff --git a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
index ca548953fa..aa602f7cc2 100644
--- a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
+++ b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
@@ -29,6 +29,7 @@ import {
busyWindowProof,
compareCurve,
cubicBezier,
+ controlClock,
countBetween,
advanceFrozenPage,
drag,
@@ -42,6 +43,7 @@ import {
releaseAnimations,
seekAnimations,
springStep,
+ startBusyControl,
startScreencast,
tap,
thawPage,
@@ -50,6 +52,7 @@ import {
touchDriver,
touchStoryboard,
traceRendering,
+ trackControl,
trackMarker,
waitForRest,
watchAnimations,
@@ -57,6 +60,7 @@ import {
writeEvidence,
type CastFrame,
type TouchDriver,
+ CONTROL_SIDE,
} from '@astryxdesign/interaction-harness';
import {BROWSER_CLICK_WAIT_MS} from '../../utils/browserClickWait';
import {CLICK_GUARD_WINDOW_MS} from '../../utils/clickGuard';
@@ -313,10 +317,16 @@ async function openSwitch(
{
direction = 'ltr',
globals = [],
+ belowControls = false,
}: {
direction?: 'ltr' | 'rtl';
/** More Storybook globals, e.g. `theme:probe`. */
globals?: string[];
+ /**
+ * Moves the switch below the busy controls' strips (the top
+ * `2 * CONTROL_SIDE + 4` px), so a control never crosses its marker.
+ */
+ belowControls?: boolean;
} = {},
): Promise<OpenSwitch> {
const allGlobals = [
@@ -342,6 +352,17 @@ async function openSwitch(
);
});
}
+ if (belowControls) {
+ await page.addStyleTag({
+ content: `#storybook-root { padding-top: ${2 * CONTROL_SIDE + 16}px !important; }`,
+ });
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+ }
const driver = await touchDriver(page);
const root = page.locator('#storybook-root');
const input = root.getByRole('switch').first();
@@ -2025,6 +2046,122 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
expectCaughtWithoutAJump(samples.filter((_, index) => index % 3 === 0));
});
+ /** The side of the marker on the thumb, px (`markElement`). */
+ const MARKER_PX = 6;
+
+ /** The inset that centres the marker on the off thumb (16 px). */
+ const MARKER_CENTRE_PX = (THUMB_OFF - MARKER_PX) / 2;
+
+ /**
+ * The narrowest box a whole marker can show, px. When the value changes,
+ * the thumb's scale carries its old size, down to `THUMB_OFF / THUMB_ON`.
+ * At a subpixel offset, the pixel at each edge is only partly covered. A
+ * narrower box is a torn frame: the cast caught the marker half drawn.
+ */
+ const WHOLE_MARKER_PX = Math.ceil((MARKER_PX * THUMB_OFF) / THUMB_ON) - 2;
+
+ /** How long each busy-window control takes to cross and come back, ms. */
+ const CONTROL_CYCLE_MS = 800;
+
+ /** One 60 Hz frame, ms. */
+ const FRAME_60_MS = 1000 / 60;
+
+ /**
+ * Starts the two busy-window controls, half a leg apart. It resolves with
+ * each one's start on the page clock, epoch ms.
+ */
+ async function startControls(page: Page): Promise<[number, number]> {
+ const first = await startBusyControl(page);
+ const ahead = await startBusyControl(page, {ahead: true});
+ return [first.start, ahead.start];
+ }
+
+ /**
+ * The thumb's center in each presented frame, on the page clock, `[ms,
+ * px]`. The two controls time each frame by the compositor's own
+ * progress, so a late or bunched cast stamp moves nothing. Only frames
+ * with a whole marker count, and the run logs how many it drops.
+ */
+ /**
+ * A frame on the page clock: its time, the marker's x, and how many torn
+ * frames were dropped just before it.
+ */
+ type ClockedFrame = [ms: number, px: number, dropsBefore: number];
+
+ async function thumbOnControlClock(
+ page: Page,
+ castFrames: Parameters<typeof trackMarker>[1],
+ starts: [number, number],
+ ): Promise<ClockedFrame[]> {
+ const readers = [
+ {
+ clock: controlClock(await trackControl(page, castFrames)),
+ origin: starts[0],
+ },
+ {
+ clock: controlClock(
+ await trackControl(page, castFrames, {ahead: true}),
+ ),
+ origin: starts[1],
+ },
+ ];
+ const pageTime = (stamp: number): number | null => {
+ for (const {clock, origin} of readers) {
+ const ms = clock.get(stamp);
+ if (ms != null) {
+ // The stamp only picks the control's cycle.
+ const cycles = Math.round((stamp - origin - ms) / CONTROL_CYCLE_MS);
+ return origin + ms + cycles * CONTROL_CYCLE_MS;
+ }
+ }
+ return null;
+ };
+ const tracked = await trackMarker(page, castFrames);
+ const shown = tracked.filter(
+ (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
+ f.box != null && f.box.width > 0 && f.box.height > 0,
+ );
+ // Cast frames come in the order the compositor presented them.
+ const clocked: ClockedFrame[] = [];
+ let dropped = 0;
+ let dropsBefore = 0;
+ for (const f of [...shown].sort((a, b) => a.t - b.t)) {
+ if (f.box.width < WHOLE_MARKER_PX || f.box.height < WHOLE_MARKER_PX) {
+ dropped += 1;
+ dropsBefore += 1;
+ continue;
+ }
+ const at = pageTime(f.t);
+ if (at != null) {
+ clocked.push([at, f.box.x + f.box.width / 2, dropsBefore]);
+ dropsBefore = 0;
+ }
+ }
+ clocked.sort((a, b) => a[0] - b[0]);
+ const gaps = clocked.slice(1).map(([at], i) => at - clocked[i][0]);
+ test.info().annotations.push({
+ type: 'torn marker frames',
+ description: `${dropped} of ${shown.length} frames show a marker box under ${WHOLE_MARKER_PX} px; ${clocked.filter(([, , drops]) => drops > 0).length} steps span one; the longest gap is ${(Math.max(0, ...gaps) / FRAME_60_MS).toFixed(1)} frames`,
+ });
+ return clocked;
+ }
+
+ /**
+ * Each presented frame's step from the one before, in px per 60 Hz frame. A
+ * frame that comes late spans more time, so its step counts per frame. A
+ * step across dropped frames counts as the whole move over them, since a
+ * skip inside them would show only in part.
+ */
+ function frameSteps(samples: ReadonlyArray<ClockedFrame>): number[] {
+ return samples
+ .slice(1)
+ .map(
+ ([time, x, drops], i) =>
+ ((drops + 1) * Math.abs(x - samples[i][1]) * FRAME_60_MS) /
+ Math.max(time - samples[i][0], FRAME_60_MS),
+ );
+ }
+
test('P14 · a second tap whose lift the page handles late (its main thread busy for 100 ms) catches the thumb where the screen shows it, without a jump (spec:AST-094 FR6)', async ({
page,
browserName,
@@ -2033,8 +2170,12 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
browserName !== 'chromium',
'screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',
);
- const {driver, input, thumb, center} = await openSwitch(page);
- await markElement(thumb, {size: 6, inset: 2});
+ const {driver, input, thumb, center} = await openSwitch(page, undefined, {
+ belowControls: true,
+ });
+ // The marker sits at the thumb's centre, so the thumb's scale does not
+ // move it.
+ await markElement(thumb, {size: MARKER_PX, inset: MARKER_CENTRE_PX});
// The page blocks at the second touch's start, so that touch's lift waits
// for the block. The switch handles the lift about 70 ms after it
// happened, while the compositor keeps the first travel moving.
@@ -2060,6 +2201,7 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
{capture: true, passive: true},
);
});
+ const controls = await startControls(page);
const cast = await startScreencast(page);
// The travel has to keep moving through the block, so this second tap is
// not frozen.
@@ -2072,33 +2214,23 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
(window as unknown as {__block?: {from: number; to: number}}).__block,
);
expect(block, 'the page was busy when the lift came').toBeDefined();
- const tracked = await trackMarker(page, castFrames);
- // Present and painted first: the marked thumb in the frames, with a box.
- const shown = tracked.filter(
- (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
- f.box != null && f.box.width > 0 && f.box.height > 0,
- );
- expect(shown.length).toBeGreaterThan(10);
- const samples = shown.map(
- f => [f.t, f.box.x + f.box.width / 2] as [number, number],
- );
- const xs = samples.map(([, x]) => x);
- const farthest = Math.max(...xs) - xs[0];
- // It turned around mid-travel, short of the on end...
+ const samples = await thumbOnControlClock(page, castFrames, controls);
+ expect(samples.length).toBeGreaterThan(10);
+ // No presented frame moves it more than a few px from the one before, on
+ // the compositor's clock.
+ expect(
+ Math.max(...frameSteps(samples)),
+ JSON.stringify(samples),
+ ).toBeLessThan(4);
+ // It turned around mid-travel, short of the on end. A loaded page can
+ // handle the late lift once the travel has ended. That fails here, by
+ // name.
+ const farthest = Math.max(...samples.map(([, x]) => x)) - samples[0][1];
expect(farthest).toBeGreaterThan(1);
- expect(farthest).toBeLessThan(TRAVEL_PX - 1);
- // ...from the place the screen showed when the late lift was handled. No
- // presented frame moves it more than a few px from the one before,
- // measured against the time the two frames span.
- const FRAME_MS = 1000 / 60;
- const perFrame = samples
- .slice(1)
- .map(
- ([time, x], i) =>
- (Math.abs(x - samples[i][1]) * FRAME_MS) /
- Math.max(time - samples[i][0], FRAME_MS),
- );
- expect(Math.max(...perFrame), JSON.stringify(samples)).toBeLessThan(4);
+ expect(
+ farthest,
+ `the late lift came after the travel ended on screen (it reached ${farthest} px)`,
+ ).toBeLessThan(TRAVEL_PX - 1);
});
test('a tap whose first frame the page commits late (its main thread busy for 100 ms after the lift) starts the travel from rest on that frame, not partway into its curve', async ({
@@ -2109,8 +2241,12 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
browserName !== 'chromium',
'screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',
);
- const {driver, input, thumb, center} = await openSwitch(page);
- await markElement(thumb, {size: 6, inset: 2});
+ const {driver, input, thumb, center} = await openSwitch(page, undefined, {
+ belowControls: true,
+ });
+ // The marker sits at the thumb's centre, so the thumb's scale does not
+ // move it.
+ await markElement(thumb, {size: MARKER_PX, inset: MARKER_CENTRE_PX});
// The page blocks in the lift's own dispatch, after the switch's
// listeners have started the travel. The frame that first shows the
// travel comes about 100 ms after the switch asked for it. As Core
@@ -2139,6 +2275,7 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
const restLeft = async () =>
thumb.evaluate(element => element.getBoundingClientRect().left);
const offLeft = await restLeft();
+ const controls = await startControls(page);
const cast = await startScreencast(page);
await driver.play(tap(center, {holdMs: 40}));
await expect(input).toBeChecked();
@@ -2150,31 +2287,18 @@ test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger',
(window as unknown as {__block?: {from: number; to: number}}).__block,
);
expect(block, 'the page was busy after the lift').toBeDefined();
- const tracked = await trackMarker(page, castFrames);
- // Present and painted first: the marked thumb in the frames, with a box.
- const shown = tracked.filter(
- (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
- f.box != null && f.box.width > 0 && f.box.height > 0,
- );
- expect(shown.length).toBeGreaterThan(10);
- const samples = shown.map(
- f => [f.t, f.box.x + f.box.width / 2] as [number, number],
- );
+ const samples = await thumbOnControlClock(page, castFrames, controls);
+ expect(samples.length).toBeGreaterThan(10);
const xs = samples.map(([, x]) => x);
// It travelled from the off rest to the on rest (the frames place the
// marker to the whole px)...
expect(Math.abs(xs.at(-1)! - xs[0] - (onLeft - offLeft))).toBeLessThan(1.5);
// ...from rest: no presented frame moves it more than a few px from the
- // one before, measured against the time the two frames span.
- const FRAME_MS = 1000 / 60;
- const perFrame = samples
- .slice(1)
- .map(
- ([time, x], i) =>
- (Math.abs(x - samples[i][1]) * FRAME_MS) /
- Math.max(time - samples[i][0], FRAME_MS),
- );
- expect(Math.max(...perFrame), JSON.stringify(samples)).toBeLessThan(4);
+ // one before, on the compositor's clock.
+ expect(
+ Math.max(...frameSteps(samples)),
+ JSON.stringify(samples),
+ ).toBeLessThan(4);
});
test('a disabled or busy switch stays inert under a finger', async ({
diff --git a/packages/core/src/Switch/useSwitchTouch.test.ts b/packages/core/src/Switch/useSwitchTouch.test.ts
index e278e35be4..5e632f547e 100644
--- a/packages/core/src/Switch/useSwitchTouch.test.ts
+++ b/packages/core/src/Switch/useSwitchTouch.test.ts
@@ -239,6 +239,30 @@ describe('the colour layer when the value changes', () => {
});
});
+describe('the thumb when the value changes', () => {
+ it('rebases toward the new rest, so a spring already heading there moves whole, then sends it there', () => {
+ const {controller, track} = mount();
+ const element = track.firstElementChild;
+ const thumb = animators.find(
+ animator =>
+ animator.element === element && animator.pseudoElement == null,
+ );
+ if (thumb == null) {
+ throw new Error('no thumb animator');
+ }
+ thumb.calls.length = 0;
+ render(controller, track, true);
+ // The CSS rest moved by the travel. The shift names the rest the spring
+ // heads for after it. The animator moves a spring whole only when its
+ // target lands there, and otherwise rebases as before.
+ const travel = switchTouchGeometry(40, 24).travel;
+ const rebase = thumb.calls.find(call => call.name === 'rebase');
+ expect(rebase?.args).toEqual([{x: -travel}, {towards: {x: 0}}]);
+ const animates = thumb.calls.filter(call => call.name === 'animate');
+ expect(animates.at(-1)?.args[0]).toEqual({x: 0});
+ });
+});
+
describe("the press's lift and settle at the theme's tempo", () => {
/** The release curve's length when the thumb's theme plays at `tempo`. */
function settleSeconds(tempo: number): number {
diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.ts
index b7bda6c98e..fcdbf2cff5 100644
--- a/packages/core/src/Switch/useSwitchTouch.ts
+++ b/packages/core/src/Switch/useSwitchTouch.ts
@@ -435,12 +435,14 @@ export class SwitchTouchController {
const time = now();
// The thumb's CSS rest moved with the value: shift it back by as much,
// so nothing moves on screen. A spring keeps its target through the shift
- // and is sent to the new rest below. A reduced-motion dip shifts whole,
- // its end included, and keeps going.
+ // and is sent to the new rest below. A spring already heading for the new
+ // rest moves whole instead, keeping its start time and velocity. A
+ // reduced-motion dip shifts whole, its end included, and keeps going.
const springs = thumb.reducedMotion() === 'off';
- thumb.rebase({
- x: this.direction * (this.rest(previous) - this.rest(isOn)),
- });
+ thumb.rebase(
+ {x: this.direction * (this.rest(previous) - this.rest(isOn))},
+ springs ? {towards: {x: this.toX(this.rest(isOn))}} : {},
+ );
// Each state has its own thumb size, the circle a mouse sees. The box the
// CSS now renders is the new value's. Its scale takes the old size over
// and grows or shrinks it from there.
diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.ts
index db1282048f..e03b4defe8 100644
--- a/packages/core/src/motion/animator.test.ts
+++ b/packages/core/src/motion/animator.test.ts
@@ -4484,3 +4484,106 @@ describe("a theme's reduced-motion mark", () => {
theme.remove();
});
});
+
+describe('rebase towards a new rest', () => {
+ const curve = solveSpring(toSpring(springs.settle), {from: 0, to: 300});
+
+ /** A spring to 300 whose first frame came late, its start still unread. */
+ async function lateStart() {
+ const ready = setup();
+ const handle = ready.animator.animate({x: 300}, {spring: springs.settle});
+ const [animation] = live('translate');
+ clock = 1070;
+ await commitFrame(1070, {startUnread: true});
+ clock = 1170;
+ return {...ready, handle, animation};
+ }
+
+ it('before its first frame, a spring heading for the new rest keeps its own velocity', () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ clock = 1033;
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ // The curve has not started, so it keeps its own course. 33 ms in, it has
+ // its own velocity, not that of a new spring dated from the call.
+ expect(animator.get('x')).toBeCloseTo(-300, 6);
+ expect(animator.getVelocity('x')).toBeCloseTo(curve.velocity(0.033), 3);
+ });
+
+ it('while its start is unread, a spring heading for the new rest moves whole in the model only', async () => {
+ const {element, animator, animation} = await lateStart();
+ const keyframes = animation.keyframes;
+ const under = inlineX(element);
+ const shown = animator.get('x');
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ // Within the task, the animation on screen keeps its keyframes, its
+ // inline value and the compositor's start; the model reads the shift.
+ expect(live('translate')).toEqual([animation]);
+ expect(animation.keyframes).toBe(keyframes);
+ expect(animation.startTime).toBeNull();
+ expect(inlineX(element)).toBe(under);
+ expect(animator.get('x')).toBeCloseTo(shown - 300, 6);
+ });
+
+ it('a call in the same task rebuilds the channel from the shifted curve, and nothing rebuilds it again', async () => {
+ const {animator, animation} = await lateStart();
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ const shown = animator.get('x');
+ animator.animate({x: 0}, {spring: springs.settle});
+ const rebuilt = live('translate').at(-1) as Recorded;
+ expect(rebuilt).not.toBe(animation);
+ expect(parse(rebuilt.keyframes[0].translate)[0]).toBeCloseTo(shown, 1);
+ expect(parse(rebuilt.keyframes.at(-1)?.translate)[0]).toBeCloseTo(0, 1);
+ await Promise.resolve();
+ expect(live('translate')).toEqual([rebuilt]);
+ });
+
+ it('with no call after it, the end of the task rebuilds the channel from the shifted curve', async () => {
+ const {animator, animation} = await lateStart();
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ const shown = animator.get('x');
+ await Promise.resolve();
+ const [healed] = live('translate');
+ expect(healed).not.toBe(animation);
+ expect(animation.cancelled).toBe(true);
+ expect(parse(healed.keyframes[0].translate)[0]).toBeCloseTo(shown, 1);
+ expect(parse(healed.keyframes.at(-1)?.translate)[0]).toBeCloseTo(0, 1);
+ });
+
+ it('a dispose in the same task leaves nothing for the end of the task to rebuild', async () => {
+ const {animator, animation} = await lateStart();
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ animator.dispose();
+ await Promise.resolve();
+ expect(animation.cancelled).toBe(true);
+ expect(live('translate')).toEqual([]);
+ });
+
+ it('a spring with a known start moves whole on its own course', async () => {
+ const {animator} = setup();
+ animator.animate({x: 300}, {spring: springs.settle});
+ clock = 1016;
+ await commitFrame(1016);
+ clock = 1116;
+ animator.rebase({x: -300}, {towards: {x: 0}});
+ const rebuilt = live('translate').at(-1) as Recorded;
+ clock = 1216;
+ expect(animator.get('x')).toBeCloseTo(curve.value(0.2) - 300, 6);
+ expect(sampleAt(rebuilt, 'translate', 1216)[0]).toBeCloseTo(
+ curve.value(0.2) - 300,
+ 0,
+ );
+ });
+
+ it('a target the shift does not bring to `towards` rebases as without it', async () => {
+ const plain = await lateStart();
+ plain.animator.rebase({x: -16});
+ const plainX = plain.animator.get('x');
+ recorded = [];
+ clock = 1000;
+ const toward = await lateStart();
+ toward.animator.rebase({x: -16}, {towards: {x: 0}});
+ expect(toward.animator.get('x')).toBe(plainX);
+ expect(live('translate')).not.toContain(toward.animation);
+ });
+});
diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.ts
index 0843f545a6..b363d7fee7 100644
--- a/packages/core/src/motion/animator.ts
+++ b/packages/core/src/motion/animator.ts
@@ -223,6 +223,23 @@ export interface SpringTransition {
velocity?: MotionValues;
}
+/** What `Animator.rebase` takes besides the amounts. */
+export interface RebaseOptions {
+ /** Time of the shift on the document timeline (ms). Defaults to now. */
+ at?: number;
+ /**
+ * Per property, the value its spring heads for after the shift. A spring
+ * whose target plus its amount lands there moves whole, before its first
+ * frame and once its start is known. Its curve and target move by the
+ * amount. It keeps its start time and velocity, as when the element's
+ * resting place moves under a curve that keeps going. If its first frame
+ * has run while its start is unread, only the model moves. The next call
+ * on the channel in the same task rebuilds its animation, or else the end
+ * of the task does.
+ */
+ towards?: MotionValues;
+}
+
/**
* Options of `animate` and `play`: the spring, a release velocity, the Reduced
* Motion handling.
@@ -452,9 +469,10 @@ export interface Animator {
* moves the element under them: a property moving on a spring keeps its
* spring, velocity and target (the curve restarts from the shifted value);
* any other moving curve shifts whole, its end included; a resting
- * property takes the offset and stays.
+ * property takes the offset and stays. `towards` moves some springs whole
+ * instead (RebaseOptions).
*/
- rebase(deltas: MotionValues, options?: Pick<AnimateOptions, 'at'>): void;
+ rebase(deltas: MotionValues, options?: RebaseOptions): void;
/** Freezes properties (all by default) at their presentation values. */
stop(properties?: ReadonlyArray<MotionProperty | 'scale'>): void;
/**
@@ -676,6 +694,13 @@ const REST_FRAMES_PER_SECOND = 60;
/** A curve that has not settled by then (an undamped spring) snaps. */
const MAX_DURATION_MS = 30_000;
+/**
+ * How close a spring's target and a value must be to count as the same, in
+ * the property's own units. Only float rounding separates two ways of
+ * computing one value, far below anything the screen shows.
+ */
+const SAME_VALUE = 1e-6;
+
/**
* The task calls from rest are made in, shared by every call made in it
* (every animator's), so one motion's parts that are separate calls start
@@ -1371,7 +1396,43 @@ export function createMotionEngine(
running.set(channel, animation);
};
+ const replaceIn = (group: StartGroup, segment: Segment, next: Segment) => {
+ const index = group.segments.indexOf(segment);
+ if (index >= 0) {
+ group.segments[index] = next;
+ } else {
+ group.segments.push(next);
+ }
+ };
+
+ /**
+ * Channels whose model a rebase moved while their animation still shows
+ * the old curve. Any rebuild clears its channel; the end of the task
+ * rebuilds the rest, so a frame never shows the old curve at the new rest.
+ */
+ const stale = new Set<Channel>();
+ let healQueued = false;
+
+ const markStale = (channel: Channel) => {
+ stale.add(channel);
+ if (!healQueued) {
+ healQueued = true;
+ queueMicrotask(healStale);
+ }
+ };
+
+ const healStale = () => {
+ healQueued = false;
+ if (stale.size === 0) {
+ return;
+ }
+ const properties = [...stale].flatMap(channel => CHANNELS[channel]);
+ stale.clear();
+ commit(properties, now());
+ };
+
const rebuild = (channel: Channel, time: number) => {
+ stale.delete(channel);
const previous = running.get(channel);
running.delete(channel);
clearTimeout(retireTimers.get(channel));
@@ -3869,6 +3930,7 @@ export function createMotionEngine(
syncPending();
flushDeferred();
const time = rebaseOptions.at ?? now();
+ const towards = expand(rebaseOptions.towards ?? {});
const changed: MotionProperty[] = [];
const owners = new Set<HandleState>();
for (const [property, delta] of Object.entries(expand(deltas)) as [
@@ -3878,9 +3940,9 @@ export function createMotionEngine(
if (delta === 0) {
continue;
}
- changed.push(property);
const segment = segmentAt(property, time);
if (segment == null) {
+ changed.push(property);
resting[property] = valueAt(property, time) + delta;
segments.delete(property);
continue;
@@ -3896,15 +3958,40 @@ export function createMotionEngine(
: undefined;
const replace = (next: Segment) => {
if (group != null) {
- const index = group.segments.indexOf(segment);
- if (index >= 0) {
- group.segments[index] = next;
- } else {
- group.segments.push(next);
- }
+ replaceIn(group, segment, next);
}
segments.set(property, next);
};
+ const heading = towards[property];
+ if (
+ segment.spring != null &&
+ heading != null &&
+ Math.abs(segment.target + delta - heading) <= SAME_VALUE
+ ) {
+ // The spring keeps its course to the shifted target from its own
+ // start.
+ const whole: Segment = {
+ ...segment,
+ target: heading,
+ at: t => segment.at(t) + delta,
+ };
+ if (latest == null) {
+ changed.push(property);
+ replace(whole);
+ continue;
+ }
+ // While the browser has not told the start, only the model moves.
+ // The call that follows rebuilds the channel from it, or else the
+ // end of the task does.
+ const waiting = segment.group;
+ if (waiting != null && !waiting.resolved) {
+ replaceIn(waiting, segment, whole);
+ segments.set(property, whole);
+ markStale(CHANNEL_OF[property]);
+ continue;
+ }
+ }
+ changed.push(property);
if (segment.spring != null) {
const from = valueAt(property, time) + delta;
const velocity = velocityAt(property, time);
@@ -4023,6 +4110,7 @@ export function createMotionEngine(
animation.cancel();
}
running.clear();
+ stale.clear();
for (const timer of retireTimers.values()) {
clearTimeout(timer);
}