An open source design system that's fully customizable and agent ready
TypeScript
refactor(core): a shared edge autoscroll timer, used by the menu press model (#8334)
Christopher Chedeaua4261e95a9f4
diff --git a/.changeset/edge-autoscroll.md b/.changeset/edge-autoscroll.mdnew file mode 100644index 0000000000..8b092e9eab--- /dev/null+++ b/.changeset/edge-autoscroll.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: a menu's edge autoscroll runs on a shared edge-autoscroll timer (utils/edgeAutoscroll.ts), with the same zone, step and interval as before. No behavior change.++@vjeuxdiff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.tsindex dd06ef3ad1..8313a32ade 100644--- a/packages/core/src/hooks/useMenuPress.ts+++ b/packages/core/src/hooks/useMenuPress.ts@@ -33,7 +33,8 @@* - `pointercancel`, a second pointer, or the window losing focus end the* gesture with nothing acting; the model never re-implements scrolling.* - While a press is tracked in an overflowing menu, a pointer resting near- * the top or bottom edge scrolls the menu toward that edge.+ * the top or bottom edge scrolls the menu toward that edge (the shared+ * timer of utils/edgeAutoscroll.ts).** The menu root is marked `data-astryx-menu-press` so a nested flyout (a DOM* descendant of its parent menu) can tell which level owns a press, and so a@@ -48,7 +49,14 @@* - /packages/core/src/hooks/menuPressGesture.ts*/-import {useCallback, useEffect, useMemo, useRef, type RefObject} from 'react';+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ type RefObject,+} from 'react';import {currentGesture} from '../Layer/gestureCounter';import {IDLE_MENU_PRESS,@@ -59,6 +67,7 @@ import {type MenuPressPointerType,} from './menuPressGesture';import {useLongPress, type UseLongPressHandlers} from './useLongPress';+import {edgeAutoscroll} from '../utils/edgeAutoscroll';import {focusForLastInput} from '../utils/focusReturn';import {useInteractionModalityTracking} from '../utils/interactionModality';@@ -344,10 +353,36 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {// exists.const longPressApiRef = useRef<UseLongPressHandlers | null>(null);const touchMovePreventerRef = useRef<(() => void) | null>(null);+ // The edge autoscroll running now: its scroller, its direction, and the+ // re-read of the row under the resting pointer after each step.const autoscrollRef = useRef<{- timer: ReturnType<typeof setInterval>;+ scroller: HTMLElement;direction: 1 | -1;+ reread: () => void;} | null>(null);+ const [autoscroll] = useState(() =>+ edgeAutoscroll({+ intervalMs: AUTOSCROLL_INTERVAL_MS,+ immediate: true,+ step: () => (autoscrollRef.current?.direction ?? 0) * AUTOSCROLL_STEP_PX,+ apply: delta => {+ const running = autoscrollRef.current;+ if (running == null) {+ return 0;+ }+ const before = running.scroller.scrollTop;+ running.scroller.scrollTop = before + delta;+ const moved = running.scroller.scrollTop - before;+ if (moved === 0) {+ // The edge is reached; nothing more to reveal.+ autoscrollRef.current = null;+ return 0;+ }+ running.reread();+ return moved;+ },+ }),+ );const lastPointerEventRef = useRef<PointerEvent | null>(null);const triggerGestureRef = useRef<number | null>(null);// The second pointer that ended a gesture must not start the next one.@@ -402,11 +437,9 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {);const stopAutoscroll = useCallback(() => {- if (autoscrollRef.current != null) {- clearInterval(autoscrollRef.current.timer);- autoscrollRef.current = null;- }- }, []);+ autoscroll.stop();+ autoscrollRef.current = null;+ }, [autoscroll]);const endGesture = useCallback(() => {longPressApiRef.current?.cancel();@@ -589,36 +622,29 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {return;}stopAutoscroll();- const tick = () => {- const before = scroller.scrollTop;- scroller.scrollTop = before + direction * AUTOSCROLL_STEP_PX;- if (scroller.scrollTop === before) {- // The edge is reached; nothing more to reveal.- stopAutoscroll();- return;- }- // The rows moved under the resting pointer: re-read the row under it.- const last = lastPointerEventRef.current;- if (last != null) {- const point = resolvePoint(last);- stepRef.current(- {- type: 'move',- row: point.row,- isInMenu: point.isInMenu,- time: Date.now(),- },- last,- );- }- };autoscrollRef.current = {+ scroller,direction,- timer: setInterval(tick, AUTOSCROLL_INTERVAL_MS),+ // The rows moved under the resting pointer: re-read the row under it.+ reread: () => {+ const last = lastPointerEventRef.current;+ if (last != null) {+ const point = resolvePoint(last);+ stepRef.current(+ {+ type: 'move',+ row: point.row,+ isInMenu: point.isInMenu,+ time: Date.now(),+ },+ last,+ );+ }+ },};- tick();+ autoscroll.update();},- [getScroller, resolvePoint, stopAutoscroll],+ [autoscroll, getScroller, resolvePoint, stopAutoscroll],);// --- Document-level tracking ----------------------------------------------diff --git a/packages/core/src/utils/edgeAutoscroll.test.ts b/packages/core/src/utils/edgeAutoscroll.test.tsnew file mode 100644index 0000000000..7d22825a34--- /dev/null+++ b/packages/core/src/utils/edgeAutoscroll.test.ts@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file edgeAutoscroll.test.ts+ * @input edgeAutoscroll with fake timers and a fake clock+ * @output The timer's rules: idle until a step, an immediate first tick when+ * asked, one step per tick, stopping when the step is 0 or an edge stops+ * the content, restarting on the next update with no latch, no restart+ * while running, and the interval's clock kept when asked (a late timer+ * catches up one tick, a stall is skipped)+ * @position Tests for utils/edgeAutoscroll.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {edgeAutoscroll} from './edgeAutoscroll';++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ vi.useRealTimers();+});++/** A scroller from 0 to `max` that records each step it is asked for. */+function scroller(max = 1000) {+ const state = {position: 0, steps: [] as number[]};+ const apply = (delta: number) => {+ state.steps.push(delta);+ const next = Math.min(max, Math.max(0, state.position + delta));+ const moved = next - state.position;+ state.position = next;+ return moved;+ };+ return {state, apply};+}++describe('edgeAutoscroll', () => {+ it('stays idle until update finds a step, then steps once per interval', () => {+ let step = 0;+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 20,+ step: () => step,+ apply,+ });+ autoscroll.update();+ vi.advanceTimersByTime(100);+ expect(autoscroll.isRunning).toBe(false);+ expect(state.steps).toEqual([]);+ step = 3;+ autoscroll.update();+ expect(state.steps).toEqual([]);+ vi.advanceTimersByTime(60);+ expect(state.steps).toEqual([3, 3, 3]);+ expect(state.position).toBe(9);+ });++ it('ticks at once when asked to', () => {+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 16,+ immediate: true,+ step: () => 6,+ apply,+ });+ autoscroll.update();+ expect(state.steps).toEqual([6]);+ vi.advanceTimersByTime(16);+ expect(state.steps).toEqual([6, 6]);+ });++ it('reads the step at every tick and stops when it turns 0', () => {+ let step = 2;+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 20,+ step: () => step,+ apply,+ });+ autoscroll.update();+ vi.advanceTimersByTime(20);+ step = -4;+ vi.advanceTimersByTime(20);+ step = 0;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, -4]);+ expect(autoscroll.isRunning).toBe(false);+ });++ it('stops at an edge, and starts again on the next update, the other way too', () => {+ let step = 6;+ const {state, apply} = scroller(10);+ const autoscroll = edgeAutoscroll({+ intervalMs: 16,+ step: () => step,+ apply,+ });+ autoscroll.update();+ vi.advanceTimersByTime(16 * 3);+ // 6, then 4 to the end, then nothing moved: stopped.+ expect(state.steps).toEqual([6, 6, 6]);+ expect(state.position).toBe(10);+ expect(autoscroll.isRunning).toBe(false);+ vi.advanceTimersByTime(100);+ expect(state.steps).toHaveLength(3);+ step = -6;+ autoscroll.update();+ vi.advanceTimersByTime(16);+ expect(state.position).toBe(4);+ expect(autoscroll.isRunning).toBe(true);+ });++ it('keeps its timer through an update while it runs', () => {+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 20,+ immediate: true,+ step: () => 1,+ apply,+ });+ autoscroll.update();+ vi.advanceTimersByTime(10);+ autoscroll.update();+ autoscroll.update();+ expect(state.steps).toEqual([1]);+ vi.advanceTimersByTime(10);+ expect(state.steps).toEqual([1, 1]);+ });++ it('keeps to its clock when asked: a late timer catches up one tick, a stall is skipped', () => {+ let clock = 0;+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 20,+ catchUp: true,+ now: () => clock,+ step: () => 2,+ apply,+ });+ autoscroll.update();+ // On time.+ clock = 20;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2]);+ // The next fire comes 25 ms late: two ticks were due by then.+ clock = 65;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, 4]);+ // A 200 ms stall: at most one tick of catch-up, the rest skipped.+ clock = 265;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, 4, 4]);+ clock = 280;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, 4, 4, 2]);+ });++ it('catches up on the same clock when it also ticked at once', () => {+ let clock = 0;+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({+ intervalMs: 20,+ immediate: true,+ catchUp: true,+ now: () => clock,+ step: () => 2,+ apply,+ });+ autoscroll.update();+ // The tick at once is not one of the interval's ticks.+ expect(state.steps).toEqual([2]);+ clock = 20;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, 2]);+ // The next fire comes 25 ms late: two ticks were due by then.+ clock = 65;+ vi.advanceTimersByTime(20);+ expect(state.steps).toEqual([2, 2, 4]);+ });++ it('stops on stop()', () => {+ const {state, apply} = scroller();+ const autoscroll = edgeAutoscroll({intervalMs: 20, step: () => 1, apply});+ autoscroll.update();+ vi.advanceTimersByTime(20);+ autoscroll.stop();+ vi.advanceTimersByTime(100);+ expect(state.steps).toEqual([1]);+ expect(autoscroll.isRunning).toBe(false);+ });+});diff --git a/packages/core/src/utils/edgeAutoscroll.ts b/packages/core/src/utils/edgeAutoscroll.tsnew file mode 100644index 0000000000..f4d86beea8--- /dev/null+++ b/packages/core/src/utils/edgeAutoscroll.ts@@ -0,0 +1,111 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file edgeAutoscroll.ts+ * @input How far to scroll on the next tick, and a way to scroll that far+ * @output `edgeAutoscroll`: the timer behind an edge autoscroll. While a+ * pointer rests near a scroll edge, the content scrolls toward it one step+ * per tick, until the step is 0 or an edge stops it+ * @position Shared by the menu press model (hooks/useMenuPress.ts, its edge+ * autoscroll) and anything else that scrolls under a held pointer+ *+ * The caller owns the geometry: `step` reads where the pointer is and+ * answers how far to scroll (0 when it is out of the edge zone), and+ * `apply` scrolls and answers how far the content actually moved, so the+ * caller can re-read what is under the pointer by exactly that much. An edge+ * stops the timer (`apply` answers 0); nothing latches, so the next `update`+ * starts it again whenever `step` is not 0.+ */++/** Options of `edgeAutoscroll`. */+export interface EdgeAutoscrollOptions {+ /** Milliseconds between ticks. */+ readonly intervalMs: number;+ /**+ * The signed distance to scroll on the next tick (positive toward the end),+ * read at every tick and by `update`; 0 stops the timer.+ */+ readonly step: () => number;+ /**+ * Scrolls by `delta` and returns how far the content actually moved; 0 (an+ * edge) stops the timer.+ */+ readonly apply: (delta: number) => number;+ /** Ticks once as the timer starts, rather than one interval later. @default false */+ readonly immediate?: boolean;+ /**+ * Keeps to the interval's clock: a late timer catches up by one tick, a+ * longer stall is skipped, as a run loop's missed timer fires are.+ * @default false+ */+ readonly catchUp?: boolean;+ /** The clock, in milliseconds. @default performance.now */+ readonly now?: () => number;+}++/** A running or idle edge autoscroll. */+export interface EdgeAutoscroll {+ /** Starts the timer when `step` is not 0, and stops it when it is. */+ update(): void;+ /** Stops the timer. */+ stop(): void;+ /** Whether the timer runs. */+ readonly isRunning: boolean;+}++/** An edge autoscroll; idle until `update` finds a step. */+export function edgeAutoscroll(options: EdgeAutoscrollOptions): EdgeAutoscroll {+ const {intervalMs, immediate = false, catchUp = false} = options;+ const now = options.now ?? (() => performance.now());+ let timer: ReturnType<typeof setInterval> | null = null;+ let base = 0;+ let ticks = 0;++ const stop = () => {+ if (timer != null) {+ clearInterval(timer);+ timer = null;+ }+ };++ // `onClock` is false for the tick `immediate` adds as the timer starts: it+ // is not one of the interval's ticks, so it leaves the catch-up count alone.+ const tick = (onClock: boolean) => {+ const step = options.step();+ if (step === 0) {+ stop();+ return;+ }+ let count = 1;+ if (catchUp && onClock) {+ const due = Math.floor((now() - base) / intervalMs);+ count = Math.max(1, Math.min(2, due - ticks));+ ticks = Math.max(ticks + count, due);+ }+ if (options.apply(step * count) === 0) {+ stop();+ }+ };++ return {+ update() {+ if (options.step() === 0) {+ stop();+ return;+ }+ if (timer != null) {+ return;+ }+ base = now();+ ticks = 0;+ timer = setInterval(() => tick(true), intervalMs);+ if (immediate) {+ tick(false);+ }+ },+ stop,+ get isRunning() {+ return timer != null;+ },+ };+}