Skip to content

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

TypeScript

refactor(motion): one release policy, resolveSnapPoint, on selectSnapPoint (#8663)

Cindy Zhang6aea9bda01e5
diff --git a/.changeset/resolve-snap-point.md b/.changeset/resolve-snap-point.md
new file mode 100644
index 0000000000..c051e8fb34
--- /dev/null
+++ b/.changeset/resolve-snap-point.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the motion foundation has one release policy, `motion/resolveSnapPoint.ts` (where a release lands: a flick goes at least to the next snap point, a release moving back toward its start cancels to it), on the `selectSnapPoint` primitive; paging moves to `motion/selectPage.ts` on top of it. No behavior change.
+
+@cixzhang
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index aa3f609c00..f21c4d8aa0 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -24,7 +24,9 @@ so each keeps its measured value; no shipped component reads the roles yet.
| `decay.ts` | UIScrollView's momentum coast. |
| `coast.ts` | A release's momentum curves for `animator.decay`: the coast, the edge spring, a release past an edge. |
| `rubberBand.ts` | UIScrollView's resistance past an edge, and its inverse. |
-| `projection.ts` | Release targets: the rest point nearest the projected coast; paging. |
+| `projection.ts` | Release targets: the rest point nearest the projected coast. |
+| `resolveSnapPoint.ts` | Release policy: the snap point a release lands on (flick, back-out cancel, step limit), on `selectSnapPoint`. Internal. |
+| `selectPage.ts` | Paging: at most one page per release, on `resolveSnapPoint`. |
| `bezier.ts` | Cubic-bézier timing functions (Core Animation's named curves). |
| `animator.ts` | Compositor animator: springs, coasts and any closed-form curve compiled to Web Animations, read back analytically. |
| `reducedMotionPlan.ts` | The animator's Reduce Motion planner: what one call becomes, a cross-fade whose travel lands while transparent or at once. |
diff --git a/packages/core/src/motion/projection.test.ts b/packages/core/src/motion/projection.test.ts
index 21bdae9f96..c15cc8106f 100644
--- a/packages/core/src/motion/projection.test.ts
+++ b/packages/core/src/motion/projection.test.ts
@@ -4,17 +4,12 @@
* @file projection.test.ts
* @input vitest, the projection functions
* @output Checks WWDC18's projection verbatim and the release-target rules
- * (nearest projected rest, step limits, paging)
+ * (nearest projected rest, step limits)
* @position Testing; validates projection.ts without a browser
*/
import {describe, expect, it} from 'vitest';
-import {
- project,
- projectDistance,
- selectPage,
- selectSnapPoint,
-} from './projection';
+import {project, projectDistance, selectSnapPoint} from './projection';
import {scroll} from './uikit/scroll';
describe('projectDistance', () => {
@@ -110,30 +105,3 @@ describe('selectSnapPoint', () => {
);
});
});
-
-describe('selectPage', () => {
- it('lands on a real page when the current page is past the end', () => {
- const result = selectPage({
- position: 400,
- velocity: 0,
- pageSize: 100,
- pageCount: 3,
- currentPage: 4,
- });
- expect(result.value).toBeDefined();
- expect(result.index).toBeGreaterThanOrEqual(0);
- expect(result.index).toBeLessThanOrEqual(2);
- });
-
- it('moves at most one page per release', () => {
- const page = (position: number, velocity: number, currentPage: number) =>
- selectPage({position, velocity, pageSize: 390, pageCount: 6, currentPage})
- .index;
- expect(page(390, 0, 1)).toBe(1);
- expect(page(430, 8000, 1)).toBe(2);
- expect(page(350, -8000, 1)).toBe(0);
- // A slow drag past half a page settles on the next page.
- expect(page(600, 0, 1)).toBe(2);
- expect(page(1950, 9000, 5)).toBe(5);
- });
-});
diff --git a/packages/core/src/motion/projection.ts b/packages/core/src/motion/projection.ts
index 8f0d0c8b92..f3ff310d2f 100644
--- a/packages/core/src/motion/projection.ts
+++ b/packages/core/src/motion/projection.ts
@@ -4,8 +4,7 @@
* @file projection.ts
* @input A release position and velocity, candidate rest points
* @output Exports `projectDistance` / `project` (WWDC18's momentum
- * projection), `selectSnapPoint` (the release target UIKit-style) and
- * `selectPage` (paging: at most one page per release)
+ * projection) and `selectSnapPoint` (the release target UIKit-style)
* @position Pure math; no DOM, no React
*
* WWDC18 "Designing Fluid Interfaces" (session 803): a thrown object goes to
@@ -58,7 +57,10 @@ export interface SnapSelection {
/**
* The rest point a release goes to: the one nearest the projected rest
- * position. `fromIndex` + `maxSteps` limit how many points away from the
+ * position. This is the math primitive (projection + nearest); the release
+ * policy on top of it (a flick advances at least one detent, a release moving
+ * back toward its start cancels) is `resolveSnapPoint` (resolveSnapPoint.ts), so a
+ * component's release rule calls that rather than adding its own. `fromIndex` + `maxSteps` limit how many points away from the
* starting one a single release may travel (by index order; pass points
* sorted along the axis). Ties go to the point in the direction of travel.
*
@@ -112,37 +114,3 @@ export function selectSnapPoint(
}
return {index: best, value: points[best], projected};
}
-
-/**
- * UIScrollView paging (`isPagingEnabled`): the page a release settles on, at
- * most one page from `currentPage`, chosen by projecting the release with
- * the paging projection rate (uikit/scroll.ts; a GUESS until measured).
- * Pages are `pageSize` apart starting at 0.
- */
-export function selectPage({
- position,
- velocity,
- pageSize,
- pageCount,
- currentPage,
- rate = scroll.paging.projectionRate,
-}: {
- position: number;
- velocity: number;
- pageSize: number;
- pageCount: number;
- currentPage: number;
- rate?: number;
-}): SnapSelection {
- const points = Array.from(
- {length: Math.max(1, pageCount)},
- (_, i) => i * pageSize,
- );
- return selectSnapPoint(points, {
- position,
- velocity,
- rate,
- fromIndex: currentPage,
- maxSteps: 1,
- });
-}
diff --git a/packages/core/src/motion/resolveSnapPoint.test.ts b/packages/core/src/motion/resolveSnapPoint.test.ts
new file mode 100644
index 0000000000..742291cee1
--- /dev/null
+++ b/packages/core/src/motion/resolveSnapPoint.test.ts
@@ -0,0 +1,189 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import * as core from '../index';
+import {resolveSnapPoint} from './resolveSnapPoint';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+
+const SHEET = {
+ flickThreshold: 1008,
+ tolerance: 1,
+ projection: {seconds: 0.1, minSpeed: 250},
+} as const;
+
+describe('resolveSnapPoint', () => {
+ it('lands a slow release on the snap point nearest where it was let go', () => {
+ expect(
+ resolveSnapPoint({
+ points: [0, 300, 640],
+ position: 140,
+ velocity: 0,
+ flickThreshold: 48,
+ }),
+ ).toEqual({index: 0, projected: 140});
+ expect(
+ resolveSnapPoint({
+ points: [0, 300, 640],
+ position: 160,
+ velocity: 20,
+ flickThreshold: 48,
+ }).index,
+ ).toBe(1);
+ });
+
+ it('projects nothing below the projection speed, and judges a faster slow release where it coasts to', () => {
+ // 240 px/s is below 250: judged at 140, nearer 0.
+ expect(
+ resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 140,
+ velocity: 240,
+ }),
+ ).toEqual({index: 0, projected: 140});
+ // 600 px/s projects 0.1 s ahead: 140 + 60 = 200, nearer 300.
+ const projected = resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 140,
+ velocity: 600,
+ });
+ expect(projected.index).toBe(1);
+ expect(projected.projected).toBeCloseTo(200, 6);
+ });
+
+ it('takes a flick at least to the next snap point beyond, or to its projection if that is farther', () => {
+ // At 300 moving 1200 px/s: projected 420 (nearer 300), but a flick goes on.
+ const flick = resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 300,
+ velocity: 1200,
+ });
+ expect(flick.index).toBe(2);
+ expect(flick.projected).toBeCloseTo(420, 6);
+ // Without projection, from just past the first snap point.
+ expect(
+ resolveSnapPoint({
+ points: [0, 300],
+ position: 2,
+ velocity: 60,
+ flickThreshold: 48,
+ }).index,
+ ).toBe(1);
+ // Moving down the axis, to the next snap point below.
+ expect(
+ resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 620,
+ velocity: -1100,
+ }).index,
+ ).toBe(1);
+ });
+
+ it('counts a snap point within the tolerance as reached, so a flick goes on to the one after it', () => {
+ expect(
+ resolveSnapPoint({
+ points: [0, 300, 640],
+ position: 300.5,
+ velocity: 2000,
+ flickThreshold: 1008,
+ tolerance: 1,
+ }).index,
+ ).toBe(2);
+ // Past the last snap point there is nothing beyond: the nearest stays.
+ expect(
+ resolveSnapPoint({
+ points: [0, 300],
+ position: 310,
+ velocity: 2000,
+ flickThreshold: 1008,
+ tolerance: 1,
+ }).index,
+ ).toBe(1);
+ });
+
+ it('cancels a release moving back toward where the drag began, whatever its travel or speed', () => {
+ // Dragged from 0 to 280, released slowly moving back up: back to 0.
+ expect(
+ resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 280,
+ velocity: -10,
+ start: 0,
+ }).index,
+ ).toBe(0);
+ // A flick back toward the start cancels too.
+ expect(
+ resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 500,
+ velocity: -1500,
+ start: 300,
+ }).index,
+ ).toBe(1);
+ // Moving away from the start does not cancel.
+ expect(
+ resolveSnapPoint({
+ ...SHEET,
+ points: [0, 300, 640],
+ position: 280,
+ velocity: 10,
+ start: 0,
+ }).index,
+ ).toBe(1);
+ });
+
+ it('sends a tie the way a projected release moves, and otherwise to the earlier snap point', () => {
+ const at = (velocity: number, projection?: typeof SHEET.projection) =>
+ resolveSnapPoint({
+ points: [0, 300],
+ // Released where its projection lands on the midpoint.
+ position: 150 - velocity * 0.1 * (projection == null ? 0 : 1),
+ velocity,
+ flickThreshold: 1008,
+ projection,
+ }).index;
+ expect(at(0)).toBe(0);
+ expect(at(10)).toBe(0);
+ expect(at(-10)).toBe(0);
+ expect(at(400, SHEET.projection)).toBe(1);
+ expect(at(-400, SHEET.projection)).toBe(0);
+ });
+
+ it('needs at least one snap point', () => {
+ expect(() =>
+ resolveSnapPoint({
+ points: [],
+ position: 0,
+ velocity: 0,
+ flickThreshold: 1,
+ }),
+ ).toThrow(RangeError);
+ });
+
+ it('stays internal: not exported from the package or any barrel', () => {
+ expect(core).not.toHaveProperty('resolveSnapPoint');
+ const pkg = JSON.parse(
+ fs.readFileSync(path.join(here, '../../package.json'), 'utf8'),
+ ) as {exports: Record<string, unknown>};
+ expect(
+ Object.keys(pkg.exports).filter(key => key.includes('motion')),
+ ).toEqual([]);
+ const barrels = fs
+ .readdirSync(here)
+ .filter(name => /^index\.(ts|tsx|js|mjs)$/.test(name));
+ for (const barrel of barrels) {
+ expect(fs.readFileSync(path.join(here, barrel), 'utf8')).not.toMatch(
+ /resolveSnapPoint/,
+ );
+ }
+ });
+});
diff --git a/packages/core/src/motion/resolveSnapPoint.ts b/packages/core/src/motion/resolveSnapPoint.ts
new file mode 100644
index 0000000000..b23f5bdbd1
--- /dev/null
+++ b/packages/core/src/motion/resolveSnapPoint.ts
@@ -0,0 +1,169 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file resolveSnapPoint.ts
+ * @input A release (position and velocity on one axis), the points it can
+ * land on, and the release policy's thresholds
+ * @output Exports resolveSnapPoint: the index of the snap point a release lands on,
+ * and the projected rest position it was judged from
+ * @position The release policy of the motion foundation, on
+ * `selectSnapPoint` (projection.ts), which stays the math primitive
+ * (projection + nearest). Pure: no DOM, no React. Internal to core: not
+ * exported from the package or any barrel (resolveSnapPoint.test.ts locks
+ * that). A component's release rule calls it with its own points and
+ * thresholds; this is the one "where does a release land" helper, so a
+ * second one should not be added beside it.
+ *
+ * - A slow release lands on the snap point nearest where it would come to rest:
+ * its position, or, with `projection`, its position plus the distance it
+ * would coast at its velocity (projection.ts). Below
+ * `projection.minSpeed` nothing is projected, so it lands on the snap point
+ * nearest where it was let go. A tie goes the way a projected release
+ * moves, and otherwise to the earlier snap point (`selectSnapPoint`).
+ * - A flick (`flickThreshold` or faster) lands at least on the next snap point
+ * beyond its position in the direction it moves, or on the nearest
+ * snap point to its projection if that is farther. A snap point within
+ * `tolerance` of the position counts as reached, so the flick goes on to
+ * the one after it.
+ * - With `start` (where the drag began), a release moving back toward it
+ * cancels to the snap point nearest `start`, whatever its travel so far or its
+ * speed.
+ * - With `fromIndex` and `maxSteps`, a release lands at most `maxSteps`
+ * points away from the one at `fromIndex` (a pager's one page per
+ * release).
+ *
+ * Snap points are ascending positions on the axis; velocities are in the same
+ * units per second, positive toward larger positions.
+ *
+ * SYNC: When modified, update resolveSnapPoint.test.ts.
+ */
+
+import {selectSnapPoint} from './projection';
+
+/** Where a release lands. */
+export interface SnapPointRelease {
+ /** Index into the points passed in. */
+ readonly index: number;
+ /** The rest position the choice was judged from (the position without a projection). */
+ readonly projected: number;
+}
+
+/** A release's projection: how far ahead it is judged, and from what speed. */
+export interface SnapPointProjection {
+ /** Seconds of the release velocity the projection reaches. */
+ readonly seconds: number;
+ /** Below this speed (units/s), nothing is projected (default 0). */
+ readonly minSpeed?: number;
+}
+
+/** The deceleration rate whose projection reaches `seconds` of the velocity. */
+function rateForProjection(seconds: number): number {
+ // WWDC18's projection coasts (v / 1000) · r / (1 − r): r / (1 − r) = 1000·τ.
+ const ms = seconds * 1000;
+ return ms / (1 + ms);
+}
+
+/** The index of the snap point nearest `position` (the first on a tie). */
+function nearestIndex(points: ReadonlyArray<number>, position: number): number {
+ let best = 0;
+ for (let i = 1; i < points.length; i += 1) {
+ if (Math.abs(points[i] - position) < Math.abs(points[best] - position)) {
+ best = i;
+ }
+ }
+ return best;
+}
+
+/**
+ * The snap point a release lands on.
+ *
+ * @example
+ * ```
+ * // Snap points at 0, 300 and 640 px. Released at 300 px moving toward 640 at
+ * // 1200 px/s, a flick: on to 640, although its projection (420 px) is
+ * // nearer 300.
+ * resolveSnapPoint({
+ * points: [0, 300, 640],
+ * position: 300,
+ * velocity: 1200,
+ * flickThreshold: 1008,
+ * tolerance: 1,
+ * projection: {seconds: 0.1, minSpeed: 250},
+ * start: 0,
+ * }); // {index: 2, projected: 420}
+ * ```
+ */
+export function resolveSnapPoint({
+ points,
+ position,
+ velocity,
+ flickThreshold,
+ tolerance = 0,
+ projection,
+ start,
+ fromIndex,
+ maxSteps,
+}: {
+ /** Snap point positions, ascending. */
+ points: ReadonlyArray<number>;
+ position: number;
+ velocity: number;
+ /** From this speed (units/s) on, a release is a flick. */
+ flickThreshold: number;
+ /** A snap point this close to the position counts as reached by a flick. */
+ tolerance?: number;
+ /** Judge a slow release where it would coast to; absent, where it was let go. */
+ projection?: SnapPointProjection;
+ /** Where the drag began: a release moving back toward it cancels to it. */
+ start?: number;
+ /** The snap point the release starts from, for `maxSteps`. */
+ fromIndex?: number;
+ /** At most this many points away from `fromIndex`. */
+ maxSteps?: number;
+}): SnapPointRelease {
+ if (points.length === 0) {
+ throw new RangeError('resolveSnapPoint needs at least one snap point');
+ }
+ const projectedVelocity =
+ projection == null || Math.abs(velocity) < (projection.minSpeed ?? 0)
+ ? 0
+ : velocity;
+ const choice = selectSnapPoint(points, {
+ position,
+ velocity: projectedVelocity,
+ rate:
+ projection == null ? undefined : rateForProjection(projection.seconds),
+ fromIndex,
+ maxSteps,
+ });
+ let index = choice.index;
+ if (Math.abs(velocity) >= flickThreshold) {
+ // A flick goes at least to the next snap point beyond where it is.
+ let next = -1;
+ if (velocity > 0) {
+ next = points.findIndex(d => d > position + tolerance);
+ } else {
+ for (let i = points.length - 1; i >= 0 && next === -1; i -= 1) {
+ if (points[i] < position - tolerance) {
+ next = i;
+ }
+ }
+ }
+ if (next !== -1 && (velocity > 0 ? next > index : next < index)) {
+ index = next;
+ }
+ }
+ if (
+ start != null &&
+ velocity !== 0 &&
+ Math.sign(velocity) === Math.sign(start - position)
+ ) {
+ index = nearestIndex(points, start);
+ }
+ if (fromIndex != null && maxSteps != null) {
+ // A stale index past either end counts from the nearest real snap point.
+ const from = Math.min(Math.max(fromIndex, 0), points.length - 1);
+ index = Math.min(Math.max(index, from - maxSteps), from + maxSteps);
+ }
+ return {index, projected: choice.projected};
+}
diff --git a/packages/core/src/motion/selectPage.test.ts b/packages/core/src/motion/selectPage.test.ts
new file mode 100644
index 0000000000..39d8785d2d
--- /dev/null
+++ b/packages/core/src/motion/selectPage.test.ts
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {selectPage} from './selectPage';
+
+describe('selectPage', () => {
+ it('lands on a real page when the current page is past the end', () => {
+ const result = selectPage({
+ position: 400,
+ velocity: 0,
+ pageSize: 100,
+ pageCount: 3,
+ currentPage: 4,
+ });
+ expect(result.value).toBeDefined();
+ expect(result.index).toBeGreaterThanOrEqual(0);
+ expect(result.index).toBeLessThanOrEqual(2);
+ });
+
+ it('moves at most one page per release', () => {
+ const page = (position: number, velocity: number, currentPage: number) =>
+ selectPage({position, velocity, pageSize: 390, pageCount: 6, currentPage})
+ .index;
+ expect(page(390, 0, 1)).toBe(1);
+ expect(page(430, 8000, 1)).toBe(2);
+ expect(page(350, -8000, 1)).toBe(0);
+ // A slow drag past half a page settles on the next page.
+ expect(page(600, 0, 1)).toBe(2);
+ expect(page(1950, 9000, 5)).toBe(5);
+ });
+});
diff --git a/packages/core/src/motion/selectPage.ts b/packages/core/src/motion/selectPage.ts
new file mode 100644
index 0000000000..26f76cb0fe
--- /dev/null
+++ b/packages/core/src/motion/selectPage.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file selectPage.ts
+ * @input A release (position, velocity), the page size and count, the
+ * current page
+ * @output Exports `selectPage`: the page a paging release settles on
+ * @position UIScrollView paging (`isPagingEnabled`) on the release policy
+ * (resolveSnapPoint.ts). Pure: no DOM, no React
+ *
+ * SYNC: When modified, update selectPage.test.ts.
+ */
+
+import type {SnapSelection} from './projection';
+import {resolveSnapPoint} from './resolveSnapPoint';
+import {scroll} from './uikit/scroll';
+
+/**
+ * UIScrollView paging (`isPagingEnabled`): the page a release settles on, at
+ * most one page from `currentPage`, chosen by projecting the release with
+ * the paging projection rate (uikit/scroll.ts; a GUESS until measured).
+ * Pages are `pageSize` apart starting at 0.
+ */
+export function selectPage({
+ position,
+ velocity,
+ pageSize,
+ pageCount,
+ currentPage,
+ rate = scroll.paging.projectionRate,
+}: {
+ position: number;
+ velocity: number;
+ pageSize: number;
+ pageCount: number;
+ currentPage: number;
+ rate?: number;
+}): SnapSelection {
+ const points = Array.from(
+ {length: Math.max(1, pageCount)},
+ (_, i) => i * pageSize,
+ );
+ // The release policy (resolveSnapPoint.ts), with the paging rate as the
+ // seconds of velocity it projects, no flick and one page per release.
+ const {index, projected} = resolveSnapPoint({
+ points,
+ position,
+ velocity,
+ flickThreshold: Infinity,
+ projection: {seconds: rate / (1 - rate) / 1000},
+ fromIndex: currentPage,
+ maxSteps: 1,
+ });
+ return {index, value: points[index], projected};
+}