Skip to content

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

TypeScript

fix(core): a touch press's release lasts until its fade has played (#9758)

Cindy Zhangb206f6399aa4
diff --git a/.changeset/press-release-ends-with-its-animation.md b/.changeset/press-release-ends-with-its-animation.md
new file mode 100644
index 0000000000..c3aa2cd8d0
--- /dev/null
+++ b/.changeset/press-release-ends-with-its-animation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under a finger, a press's release now lasts until its fade has played. The touch press controller ended the release on a clock started at the lift, so when the page's script delayed the fade's first frame, the release was cut short mid-fade. It now ends when the press's release animation ends, on the surface or on a part inside it that a component draws the release on, or on its clock where no release animation runs (an instant release, a surface without one, or an engine without Web Animations). This applies to every surface the touch press controller drives: buttons, switches, checkboxes, cards, menu rows and list rows.
+
+@vjeux
diff --git a/packages/core/src/utils/interactionOverlay.stylex.ts b/packages/core/src/utils/interactionOverlay.stylex.ts
index 4b3fc3349c..67a619e618 100644
--- a/packages/core/src/utils/interactionOverlay.stylex.ts
+++ b/packages/core/src/utils/interactionOverlay.stylex.ts
@@ -76,8 +76,9 @@ export const pressVars = stylex.defineVars({
*
* `defineConsts`, so the one number is inlined here at build time and is the
* controller's constant at run time (`PRESS_FADE_MS` in pressGesture.ts):
- * the release animation and the timer that removes the attribute after it
- * cannot drift apart.
+ * the release animation and the controller's clock cannot drift apart. When
+ * that clock runs out, the controller waits for a release animation that a
+ * busy main thread started late, then removes the attribute.
*/
export const pressConsts = stylex.defineConsts({
/** How long the release takes, in ms. UIKit's deselect clock. */
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index e63c4fc4e3..d7e1fc70aa 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -656,6 +656,164 @@ describe('the release', () => {
});
});
+/**
+ * A CSS animation as a browser reports it from `getAnimations()` (jsdom runs
+ * none): by default the release the stylesheet starts on the surface's
+ * `::before` at the `fading` write, still waiting for its first frame.
+ * `end()` finishes it; `cancel()` cancels it, as unmounting or restyling the
+ * surface does.
+ */
+function cssAnimation(
+ element: Element,
+ {
+ target = element,
+ playState = 'running',
+ endTime = PRESS_FADE_MS,
+ }: {target?: Element; playState?: string; endTime?: number} = {},
+) {
+ let end: () => void = () => undefined;
+ let cancel: () => void = () => undefined;
+ const finished = new Promise<void>((resolve, reject) => {
+ end = resolve;
+ cancel = () => reject(new DOMException('cancelled', 'AbortError'));
+ });
+ finished.catch(() => undefined);
+ return {
+ animation: {
+ animationName: 'release',
+ playState,
+ finished,
+ effect: {
+ target,
+ pseudoElement: '::before',
+ getComputedTiming: () => ({endTime}),
+ },
+ },
+ end: () => end(),
+ cancel: () => cancel(),
+ };
+}
+
+/** The animations a browser would report running on `element` and its pseudo-elements. */
+function animate(element: Element, animations: ReadonlyArray<object>): void {
+ Object.defineProperty(element, 'getAnimations', {
+ configurable: true,
+ value: () => animations,
+ });
+}
+
+/** Let the callbacks a finished or cancelled animation queued run. */
+async function settled(): Promise<void> {
+ for (let i = 0; i < 4; i += 1) {
+ await Promise.resolve();
+ }
+}
+
+/** A finger's held press on the first row, lifted: the release is written. */
+function liftHeldPress(): void {
+ press(rows[0], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ press(rows[0], 'pointerup', 10, 10);
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+}
+
+describe('the release ends with its animation, not its clock', () => {
+ it('keeps `fading` until the release animation ends, however late a busy main thread let its first frame come', async () => {
+ liftHeldPress();
+ // 150 ms of script held the main thread after the lift: the release
+ // started at the first frame after it, and is still running.
+ const release = cssAnimation(rows[0]);
+ animate(rows[0], [release.animation]);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ await settled();
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ release.end();
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('waits for a release still waiting for its first frame when the clock ran out', async () => {
+ liftHeldPress();
+ const release = cssAnimation(rows[0], {playState: 'pending'});
+ animate(rows[0], [release.animation]);
+ vi.advanceTimersByTime(PRESS_FADE_MS * 3);
+ await settled();
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ release.end();
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('ends when the release animation is cancelled: the surface was unmounted or restyled', async () => {
+ liftHeldPress();
+ const release = cssAnimation(rows[0]);
+ animate(rows[0], [release.animation]);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ release.cancel();
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('ends on its clock where no release animation runs: an instant release, a surface without one, or an engine without Web Animations', async () => {
+ liftHeldPress();
+ animate(rows[0], []);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('waits for a release a component draws inside the surface, on a descendant whose nearest press owner is the surface', async () => {
+ liftHeldPress();
+ // The box wrapper's `::after` plays the release for the row's press,
+ // 50 ms longer than the row's clock.
+ const box = document.createElement('span');
+ rows[0].append(box);
+ const release = cssAnimation(rows[0], {
+ target: box,
+ endTime: PRESS_FADE_MS + 50,
+ });
+ animate(rows[0], [release.animation]);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ await settled();
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('fading');
+ release.end();
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('waits for no animation that is not this press’s running release: a nested press owner’s (on it or inside it), an endless one, or one already finished', async () => {
+ liftHeldPress();
+ // A press owner inside the row: its release is its own press's, never
+ // the row's.
+ const nested = pressable('span');
+ const inside = document.createElement('span');
+ nested.append(inside);
+ rows[0].append(nested);
+ animate(rows[0], [
+ cssAnimation(rows[0], {target: nested}).animation,
+ cssAnimation(rows[0], {target: inside}).animation,
+ cssAnimation(rows[0], {endTime: Infinity}).animation,
+ cssAnimation(rows[0], {playState: 'finished'}).animation,
+ ]);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ await settled();
+ expect(rows[0].hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ });
+
+ it('a new press on the surface owns its paint: the old release ending later does not clear it', async () => {
+ liftHeldPress();
+ const release = cssAnimation(rows[0]);
+ animate(rows[0], [release.animation]);
+ vi.advanceTimersByTime(PRESS_FADE_MS);
+ press(rows[0], 'pointerdown', 10, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ release.end();
+ await settled();
+ expect(rows[0].getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ });
+});
+
describe('two touches in a row', () => {
it('answers the second tap while the first is still fading', () => {
press(rows[0], 'pointerdown', 10, 10);
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index f783785068..d2602d579a 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -109,7 +109,8 @@ interface LiveGesture {
* for a press of the Space key.
*/
pointerId: number | null;
- timer: ReturnType<typeof setTimeout> | null;
+ /** Cancels the clock the current phase owes, or the release it waits for. */
+ timer: (() => void) | null;
}
/**
@@ -165,6 +166,76 @@ export function pressFadeMs(element: Element): number {
return reduced ? Math.min(scaled, PRESS_FADE_MS) : scaled;
}
+/**
+ * The release animations that still run for `element`'s press. Each is a
+ * finite CSS animation that has not finished. It runs on the element, on its
+ * `::before` or `::after`, or on a descendant whose nearest press owner is
+ * the element, because a component can draw its release on a part inside the
+ * surface. A press owner nested inside plays the release of its own press,
+ * so it never extends this one. The list is empty where the engine has no Web
+ * Animations.
+ */
+function releaseAnimationsOf(element: Element): Animation[] {
+ if (typeof element.getAnimations !== 'function') {
+ return [];
+ }
+ return element.getAnimations({subtree: true}).filter(animation => {
+ // The effect of a CSS animation is a KeyframeEffect. Its target is the
+ // element, also when the animation runs on a pseudo-element.
+ const effect = animation.effect as KeyframeEffect | null;
+ const target = effect?.target ?? null;
+ if (
+ effect == null ||
+ target == null ||
+ !('animationName' in animation) ||
+ (target !== element &&
+ target.closest(`[${PRESSABLE_ATTRIBUTE}]`) !== element)
+ ) {
+ return false;
+ }
+ if (!Number.isFinite(Number(effect.getComputedTiming().endTime))) {
+ return false;
+ }
+ return animation.playState !== 'finished';
+ });
+}
+
+/**
+ * Calls `end` when the release on `element` is over. A busy main thread
+ * delays the first frame of the release animation, and with it the end. So a
+ * clock that starts at the `fading` write can cut the release short. When
+ * `clockMs` runs out, the release waits for each release animation that still
+ * runs or still waits for its first frame. It ends when those finish or are
+ * cancelled, as when the surface is unmounted or restyled. With no release
+ * animation (an instant release, a surface without one, an engine without Web
+ * Animations), the release ends at the clock. Returns a cancel.
+ */
+function endAfterRelease(
+ element: Element,
+ clockMs: number,
+ end: () => void,
+): () => void {
+ let waiting = true;
+ const timer = setTimeout(() => {
+ const running = releaseAnimationsOf(element);
+ if (running.length === 0) {
+ end();
+ return;
+ }
+ void Promise.allSettled(
+ running.map(async animation => animation.finished),
+ ).then(() => {
+ if (waiting) {
+ end();
+ }
+ });
+ }, clockMs);
+ return () => {
+ waiting = false;
+ clearTimeout(timer);
+ };
+}
+
const TIMER_EVENT = {
fade: 'fadeEnd',
flash: 'flashEnd',
@@ -181,7 +252,7 @@ function paintElement(element: HTMLElement, paint: PressPaint): void {
function clearTimer(slot: Slot): void {
if (slot.live?.timer != null) {
- clearTimeout(slot.live.timer);
+ slot.live.timer();
slot.live.timer = null;
}
}
@@ -217,25 +288,32 @@ function apply(slot: Slot, step: PressStep): void {
}
if (step.timer != null) {
const kind = step.timer;
- // A TIMER, never `requestAnimationFrame`: iOS throttles frame callbacks
- // while a scroll runs, so a frame-based delay would fire late, after the
- // scroll, and paint a control nobody is pressing any more.
- live.timer = setTimeout(
- () => {
- if (slot.live != null) {
- slot.live.timer = null;
- }
- apply(
- slot,
- pressGestureStep(slot.live?.gesture ?? idlePressGesture(), {
- kind: TIMER_EVENT[kind],
- }),
- );
- },
- // The release fade follows the theme's tempo (AST-108). The onset delay
- // and the tap flash do not.
- kind === 'fade' ? pressFadeMs(live.element) : TIMER_MS[kind],
- );
+ const fire = () => {
+ if (slot.live != null) {
+ slot.live.timer = null;
+ }
+ apply(
+ slot,
+ pressGestureStep(slot.live?.gesture ?? idlePressGesture(), {
+ kind: TIMER_EVENT[kind],
+ }),
+ );
+ };
+ if (kind === 'fade') {
+ // The release fade follows the theme's tempo (AST-108). It ends when
+ // its animation ends, however late a busy main thread let it start.
+ live.timer = endAfterRelease(
+ live.element,
+ pressFadeMs(live.element),
+ fire,
+ );
+ } else {
+ // A TIMER, never `requestAnimationFrame`: iOS throttles frame callbacks
+ // while a scroll runs, so a frame-based delay would fire late, after the
+ // scroll, and paint a control nobody is pressing any more.
+ const timer = setTimeout(fire, TIMER_MS[kind]);
+ live.timer = () => clearTimeout(timer);
+ }
}
}
diff --git a/packages/core/src/utils/pressGesture.ts b/packages/core/src/utils/pressGesture.ts
index f9520b1ae1..ecfb5e979c 100644
--- a/packages/core/src/utils/pressGesture.ts
+++ b/packages/core/src/utils/pressGesture.ts
@@ -62,7 +62,9 @@ export const PRESS_FLASH_MS = 100;
* How long the paint takes to leave after a release: UIKit's deselect
* crossfade. The one number, shared with the stylesheet: the release
* animation in interactionOverlay.stylex.ts runs on the same constant, so the
- * timer that removes the attribute and the fade cannot drift apart.
+ * controller's release clock and the fade cannot drift apart. When the clock
+ * runs out, the controller waits for a release animation that still runs,
+ * then removes the attribute.
*/
export const PRESS_FADE_MS: number = pressConsts.releaseMs;
@@ -119,7 +121,7 @@ export type PressEvent =
| {kind: 'onset'}
/** {@link PRESS_FLASH_MS} elapsed on a too-quick tap. */
| {kind: 'flashEnd'}
- /** {@link PRESS_FADE_MS} elapsed; the paint is gone. */
+ /** The release is over: its animation ended, or its clock ran out with none running. */
| {kind: 'fadeEnd'};
export interface PressStep {