From 491c8cd754e984716051cdc7132f6a8358e0dd34 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 5 Nov 2026 01:03:31 -0600 Subject: [PATCH] fix(ui): drive text reveal, copy feedback, menu modality and avatar hover through state machines (#61966) --- .../app/component-tests/focus-ring.spec.ts | 29 +++ .../src/components/text-field-machine.test.ts | 99 +++++++++ .../ui/src/components/text-field-machine.ts | 102 ++++++++++ packages/ui/src/components/text-field.tsx | 102 +++++++--- .../components/text-reveal-machine.test.ts | 157 ++++++++++++++ .../ui/src/components/text-reveal-machine.ts | 184 +++++++++++++++++ packages/ui/src/components/text-reveal.tsx | 191 +++++++++--------- .../project-avatar/animation-machine.test.ts | 134 ++++++++++++ .../project-avatar/animation-machine.ts | 182 +++++++++++++++++ .../data-display/project-avatar/animation.ts | 105 ++++++---- .../ui/src/navigation/menu/machine.test.ts | 85 ++++++++ packages/ui/src/navigation/menu/machine.ts | 109 ++++++++++ .../ui/src/navigation/menu/menu.stories.tsx | 34 ++++ packages/ui/src/navigation/menu/menu.tsx | 136 +++++++++++-- 14 files changed, 1474 insertions(+), 175 deletions(-) create mode 100644 packages/ui/src/components/text-field-machine.test.ts create mode 100644 packages/ui/src/components/text-field-machine.ts create mode 100644 packages/ui/src/components/text-reveal-machine.test.ts create mode 100644 packages/ui/src/components/text-reveal-machine.ts create mode 100644 packages/ui/src/data-display/project-avatar/animation-machine.test.ts create mode 100644 packages/ui/src/data-display/project-avatar/animation-machine.ts create mode 100644 packages/ui/src/navigation/menu/machine.test.ts create mode 100644 packages/ui/src/navigation/menu/machine.ts diff --git a/packages/app/component-tests/focus-ring.spec.ts b/packages/app/component-tests/focus-ring.spec.ts index 4f6cfd3d4e7..f655bd0456d 100644 --- a/packages/app/component-tests/focus-ring.spec.ts +++ b/packages/app/component-tests/focus-ring.spec.ts @@ -24,6 +24,35 @@ story("keeps the ring on a menu trigger after a keyboard open", async ({ mount, await expect(trigger).toHaveCSS("outline-style", "solid") }) +story("keeps the ring on a menu trigger opened from code after a pointer open", async ({ mount, page }) => { + await mount("ui-menu--programmatic-and-non-modal") + const trigger = page.getByRole("button", { name: "Controlled" }) + + await trigger.click() + await expect(page.getByRole("menuitem", { name: "Rename" })).toBeVisible() + await page.keyboard.press("Escape") + await expect(page.getByRole("menuitem", { name: "Rename" })).toHaveCount(0) + await page.getByRole("button", { name: "Open from code" }).click() + await expect(page.getByRole("menuitem", { name: "Rename" })).toBeVisible() + await page.keyboard.press("Escape") + await expect(trigger).toBeFocused() + await expect(trigger).toHaveCSS("outline-style", "solid") +}) + +story("leaves focus where an outside click put it when a non-modal menu closes", async ({ mount, page }) => { + await mount("ui-menu--programmatic-and-non-modal") + const trigger = page.getByRole("button", { name: "Non-modal" }) + + await trigger.click() + await expect(page.getByRole("menuitem", { name: "Pin" })).toBeVisible() + await page.mouse.click(4, 300) + await expect(page.getByRole("menuitem", { name: "Pin" })).toHaveCount(0) + // The close focus restore has run once the story counts it; the click on empty space left focus on the body. + await expect(page.getByLabel("Non-modal focus restores")).toHaveText("1") + expect(await page.evaluate(() => document.activeElement === document.body)).toBe(true) + await expect(trigger).not.toBeFocused() +}) + story("returns focus to a dialog's trigger without a ring after a pointer open", async ({ mount, page }) => { await mount("ui-dialog--opened-from-button") const trigger = page.getByRole("button", { name: "Choose model" }) diff --git a/packages/ui/src/components/text-field-machine.test.ts b/packages/ui/src/components/text-field-machine.test.ts new file mode 100644 index 00000000000..4bfbb89af5d --- /dev/null +++ b/packages/ui/src/components/text-field-machine.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, test } from "bun:test" +import { + INITIAL_TEXT_FIELD_COPY_STATE, + selectTextFieldCopied, + selectTextFieldCopyIcon, + selectTextFieldCopyLabelKey, + TEXT_FIELD_COPIED_MS, + TEXT_FIELD_COPY_TIMEOUT_MS, + transitionTextFieldCopy, + type TextFieldCopyEvent, + type TextFieldCopyState, + type TextFieldCopyTransition, +} from "./text-field-machine" + +function run(state: TextFieldCopyState, ...events: TextFieldCopyEvent[]) { + return events.reduce((result, event) => transitionTextFieldCopy(result.state, event), { + state, + effects: [], + }) +} + +const request: TextFieldCopyEvent = { type: "copy.requested", value: "sk-123", enabled: true } + +describe("transitionTextFieldCopy", () => { + test("claims the copy before the write starts, so a second click waits for it", () => { + const first = transitionTextFieldCopy(INITIAL_TEXT_FIELD_COPY_STATE, request) + + expect(first.state).toEqual({ status: "copying", attempt: 1, keepCopied: false }) + expect(first.effects).toEqual([ + { type: "clipboard.write", attempt: 1, value: "sk-123", timeoutMs: TEXT_FIELD_COPY_TIMEOUT_MS }, + ]) + + const second = transitionTextFieldCopy(first.state, request) + + expect(second.state).toBe(first.state) + expect(second.effects).toEqual([]) + }) + + test("a repeat copy restarts the feedback window instead of ending it early", () => { + const copied = run(INITIAL_TEXT_FIELD_COPY_STATE, request, { type: "copy.succeeded", attempt: 1 }) + + expect(copied.effects).toEqual([ + { type: "timer.clear" }, + { type: "reset.schedule", attempt: 1, delayMs: TEXT_FIELD_COPIED_MS }, + ]) + + const again = transitionTextFieldCopy(copied.state, request) + + expect(again.effects[0]).toEqual({ type: "timer.clear" }) + expect(selectTextFieldCopied(again.state)).toBe(true) + // The first copy's reset timer fires late: the checkmark stays. + expect(run(again.state, { type: "reset.elapsed", attempt: 1 }).state).toBe(again.state) + + const second = run(again.state, { type: "copy.succeeded", attempt: 2 }) + + expect(second.effects).toContainEqual({ type: "reset.schedule", attempt: 2, delayMs: TEXT_FIELD_COPIED_MS }) + expect(run(second.state, { type: "reset.elapsed", attempt: 2 }).state).toEqual({ status: "idle", issued: 2 }) + }) + + test.each(["copy.failed", "copy.timed-out"] as const)("%s returns to idle and ignores the late result", (type) => { + const failed = run(INITIAL_TEXT_FIELD_COPY_STATE, request, { type, attempt: 1 }) + + expect(failed.state).toEqual({ status: "idle", issued: 1 }) + expect(failed.effects).toEqual([{ type: "timer.clear" }]) + expect(run(failed.state, { type: "copy.succeeded", attempt: 1 }).state).toBe(failed.state) + + const repeat = run(INITIAL_TEXT_FIELD_COPY_STATE, request, { type: "copy.succeeded", attempt: 1 }, request, { + type, + attempt: 2, + }) + + expect(selectTextFieldCopied(repeat.state)).toBe(false) + }) + + test("a disabled field does not copy", () => { + const result = transitionTextFieldCopy(INITIAL_TEXT_FIELD_COPY_STATE, { ...request, enabled: false }) + + expect(result.state).toBe(INITIAL_TEXT_FIELD_COPY_STATE) + expect(result.effects).toEqual([]) + }) + + test("disposing clears the timer and ignores later results", () => { + const copying = run(INITIAL_TEXT_FIELD_COPY_STATE, request, { type: "disposed" }) + + expect(copying.state).toEqual({ status: "disposed" }) + expect(copying.effects).toEqual([{ type: "timer.clear" }]) + expect(run(copying.state, { type: "copy.succeeded", attempt: 1 }, request).state).toBe(copying.state) + expect(run(INITIAL_TEXT_FIELD_COPY_STATE, { type: "disposed" }).effects).toEqual([]) + }) + + test("labels and icons follow the copied state", () => { + const copied = run(INITIAL_TEXT_FIELD_COPY_STATE, request, { type: "copy.succeeded", attempt: 1 }).state + + expect(selectTextFieldCopyLabelKey(copied, "link")).toBe("ui.textField.copied") + expect(selectTextFieldCopyIcon(copied, "link")).toBe("check") + expect(selectTextFieldCopyLabelKey(INITIAL_TEXT_FIELD_COPY_STATE, "link")).toBe("ui.textField.copyLink") + expect(selectTextFieldCopyIcon(INITIAL_TEXT_FIELD_COPY_STATE, undefined)).toBe("copy") + }) +}) diff --git a/packages/ui/src/components/text-field-machine.ts b/packages/ui/src/components/text-field-machine.ts new file mode 100644 index 00000000000..f0492071419 --- /dev/null +++ b/packages/ui/src/components/text-field-machine.ts @@ -0,0 +1,102 @@ +export const TEXT_FIELD_COPIED_MS = 2_000 + +/** A clipboard write that never settles gives up, so the button can copy again. */ +export const TEXT_FIELD_COPY_TIMEOUT_MS = 2_000 + +export type TextFieldCopyKind = "clipboard" | "link" + +/** + * The copy button's feedback. `copying` claims the click before the write starts, so a second click waits for it; + * `keepCopied` keeps the checkmark of an earlier copy while a repeat copy settles. `attempt` lets only the latest + * write, its timeout and its own reset timer move the button. + */ +export type TextFieldCopyState = + | { readonly status: "idle"; readonly issued: number } + | { readonly status: "copying"; readonly attempt: number; readonly keepCopied: boolean } + | { readonly status: "copied"; readonly attempt: number } + | { readonly status: "disposed" } + +export type TextFieldCopyEvent = + | { readonly type: "copy.requested"; readonly value: string; readonly enabled: boolean } + | { readonly type: "copy.succeeded"; readonly attempt: number } + | { readonly type: "copy.failed"; readonly attempt: number } + | { readonly type: "copy.timed-out"; readonly attempt: number } + | { readonly type: "reset.elapsed"; readonly attempt: number } + | { readonly type: "disposed" } + +export type TextFieldCopyEffect = + | { readonly type: "clipboard.write"; readonly attempt: number; readonly value: string; readonly timeoutMs: number } + | { readonly type: "reset.schedule"; readonly attempt: number; readonly delayMs: number } + | { readonly type: "timer.clear" } + +export type TextFieldCopyTransition = { + readonly state: TextFieldCopyState + readonly effects: readonly TextFieldCopyEffect[] +} + +export const INITIAL_TEXT_FIELD_COPY_STATE: TextFieldCopyState = Object.freeze({ status: "idle", issued: 0 }) + +const NO_EFFECTS: readonly TextFieldCopyEffect[] = Object.freeze([]) + +const TIMER_CLEAR: TextFieldCopyEffect = Object.freeze({ type: "timer.clear" }) + +const DISPOSED: TextFieldCopyState = Object.freeze({ status: "disposed" }) + +export function transitionTextFieldCopy(state: TextFieldCopyState, event: TextFieldCopyEvent): TextFieldCopyTransition { + if (state.status === "disposed") return { state, effects: NO_EFFECTS } + + if (event.type === "disposed") + return { state: DISPOSED, effects: state.status === "idle" ? NO_EFFECTS : [TIMER_CLEAR] } + + if (event.type === "copy.requested") { + if (!event.enabled || state.status === "copying") return { state, effects: NO_EFFECTS } + const attempt = (state.status === "idle" ? state.issued : state.attempt) + 1 + const timeoutMs = TEXT_FIELD_COPY_TIMEOUT_MS + const write: TextFieldCopyEffect = { type: "clipboard.write", attempt, value: event.value, timeoutMs } + + if (state.status === "copied") { + return { state: { status: "copying", attempt, keepCopied: true }, effects: [TIMER_CLEAR, write] } + } + + return { state: { status: "copying", attempt, keepCopied: false }, effects: [write] } + } + + if (state.status === "idle" || event.attempt !== state.attempt) return { state, effects: NO_EFFECTS } + + if (state.status === "copying" && event.type === "copy.succeeded") { + return { + state: { status: "copied", attempt: state.attempt }, + effects: [TIMER_CLEAR, { type: "reset.schedule", attempt: state.attempt, delayMs: TEXT_FIELD_COPIED_MS }], + } + } + + if (state.status === "copying" && (event.type === "copy.failed" || event.type === "copy.timed-out")) { + return { state: { status: "idle", issued: state.attempt }, effects: [TIMER_CLEAR] } + } + + if (state.status === "copied" && event.type === "reset.elapsed") { + return { state: { status: "idle", issued: state.attempt }, effects: NO_EFFECTS } + } + + return { state, effects: NO_EFFECTS } +} + +export function selectTextFieldCopied(state: TextFieldCopyState) { + return state.status === "copied" || (state.status === "copying" && state.keepCopied) +} + +export function selectTextFieldCopyLabelKey(state: TextFieldCopyState, kind: TextFieldCopyKind | undefined) { + if (selectTextFieldCopied(state)) return "ui.textField.copied" + + if (kind === "link") return "ui.textField.copyLink" + + return "ui.textField.copyToClipboard" +} + +export function selectTextFieldCopyIcon(state: TextFieldCopyState, kind: TextFieldCopyKind | undefined) { + if (selectTextFieldCopied(state)) return "check" + + if (kind === "link") return "link" + + return "copy" +} diff --git a/packages/ui/src/components/text-field.tsx b/packages/ui/src/components/text-field.tsx index dbe6571b4e1..501b378cf81 100644 --- a/packages/ui/src/components/text-field.tsx +++ b/packages/ui/src/components/text-field.tsx @@ -1,10 +1,19 @@ import { TextField as Kobalte } from "@kobalte/core/text-field" -import { createSignal, Show, splitProps } from "solid-js" +import { createSignal, onCleanup, Show, splitProps, untrack } from "solid-js" import type { ComponentProps } from "solid-js" import { useI18n } from "../context/i18n" import { IconButton } from "@opencode/ui/icon-button" import { Icon } from "@opencode/ui/icon" import { Tooltip } from "@opencode/ui/tooltip" +import { + INITIAL_TEXT_FIELD_COPY_STATE, + selectTextFieldCopied, + selectTextFieldCopyIcon, + selectTextFieldCopyLabelKey, + transitionTextFieldCopy, + type TextFieldCopyEffect, + type TextFieldCopyEvent, +} from "./text-field-machine" export interface TextFieldProps extends ComponentProps, @@ -56,34 +65,48 @@ export function TextField(props: TextFieldProps) { "multiline", ]) - const [copied, setCopied] = createSignal(false) + const [copyState, setCopyState] = createSignal(INITIAL_TEXT_FIELD_COPY_STATE) + let timer: ReturnType | undefined - const label = () => { - if (copied()) return i18n.t("ui.textField.copied") + const dispatch = (event: TextFieldCopyEvent) => { + const next = transitionTextFieldCopy(untrack(copyState), event) - if (local.copyKind === "link") return i18n.t("ui.textField.copyLink") - - return i18n.t("ui.textField.copyToClipboard") + if (next.state !== untrack(copyState)) setCopyState(next.state) + next.effects.forEach(run) } - const icon = () => { - if (copied()) return "check" + const run = (effect: TextFieldCopyEffect) => { + if (effect.type === "timer.clear") { + clearTimeout(timer) + timer = undefined - if (local.copyKind === "link") return "link" + return + } - return "copy" + if (effect.type === "reset.schedule") { + timer = setTimeout(() => dispatch({ type: "reset.elapsed", attempt: effect.attempt }), effect.delayMs) + + return + } + + timer = setTimeout(() => dispatch({ type: "copy.timed-out", attempt: effect.attempt }), effect.timeoutMs) + void writeClipboard(effect.value).then( + (written) => dispatch({ type: written ? "copy.succeeded" : "copy.failed", attempt: effect.attempt }), + () => dispatch({ type: "copy.failed", attempt: effect.attempt }), + ) } - async function handleCopy() { - const value = local.value ?? local.defaultValue ?? "" - await navigator.clipboard.writeText(value) - setCopied(true) - setTimeout(() => setCopied(false), 2000) - } + onCleanup(() => dispatch({ type: "disposed" })) - function handleClick() { - if (local.copyable) void handleCopy() - } + const copied = () => selectTextFieldCopied(copyState()) + const label = () => i18n.t(selectTextFieldCopyLabelKey(copyState(), local.copyKind)) + + const requestCopy = () => + dispatch({ + type: "copy.requested", + value: local.value ?? local.defaultValue ?? "", + enabled: !!local.copyable && !local.disabled, + }) return ( } + icon={} variant="ghost" - onClick={handleCopy} + disabled={local.disabled} + onClick={(event) => { + // The field itself copies on click too; one click is one copy. + event.stopPropagation() + requestCopy() + }} tabIndex={-1} data-slot="input-copy-button" aria-label={label()} @@ -140,3 +168,29 @@ export function TextField(props: TextFieldProps) { ) } + +// `navigator.clipboard` exists only in secure contexts, so plain-HTTP LAN origins copy through a selected textarea. +async function writeClipboard(text: string) { + const written = await navigator.clipboard?.writeText(text).then( + () => true, + () => false, + ) + + if (written) return true + const active = document.activeElement instanceof HTMLElement ? document.activeElement : undefined + const textarea = document.createElement("textarea") + textarea.value = text + textarea.setAttribute("readonly", "") + textarea.setAttribute("aria-hidden", "true") + textarea.tabIndex = -1 + textarea.style.position = "fixed" + textarea.style.opacity = "0" + textarea.style.pointerEvents = "none" + document.body.appendChild(textarea) + textarea.select() + const copied = document.execCommand("copy") + textarea.remove() + active?.focus({ preventScroll: true }) + + return copied +} diff --git a/packages/ui/src/components/text-reveal-machine.test.ts b/packages/ui/src/components/text-reveal-machine.test.ts new file mode 100644 index 00000000000..6322acf0821 --- /dev/null +++ b/packages/ui/src/components/text-reveal-machine.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, test } from "bun:test" +import { + createTextRevealState, + selectTextRevealEntering, + selectTextRevealLeaving, + selectTextRevealReady, + selectTextRevealSwapping, + selectTextRevealTrackWidth, + transitionTextReveal, + type TextRevealEvent, + type TextRevealState, + type TextRevealTransition, +} from "./text-reveal-machine" + +function run(state: TextRevealState, ...events: TextRevealEvent[]) { + return events.reduce((result, event) => transitionTextReveal(result.state, event), { + state, + effects: [], + }) +} + +const measured = (widthPx: number, growOnly = true) => ({ widthPx, growOnly }) + +const settled = (text: string) => + run( + createTextRevealState(text), + { type: "fonts.settled", ...measured(40) }, + { type: "ready.settled", ...measured(40) }, + ).state + +describe("transitionTextReveal", () => { + test("mounting with text does not swap", () => { + const state = createTextRevealState("Thinking") + const result = transitionTextReveal(state, { type: "text.changed", text: "Thinking" }) + + expect(result.state).toBe(state) + expect(result.effects).toEqual([]) + }) + + test("waits for fonts and one frame before turning transitions on", () => { + const fonts = run(createTextRevealState("Thinking"), { type: "fonts.settled", ...measured(40) }) + + expect(selectTextRevealReady(fonts.state)).toBe(false) + expect(fonts.effects).toEqual([{ type: "ready.frame" }]) + + const ready = transitionTextReveal(fonts.state, { type: "ready.settled", ...measured(42) }) + + expect(ready.state).toMatchObject({ status: "idle", current: "Thinking", widthPx: 42 }) + expect(selectTextRevealReady(ready.state)).toBe(true) + expect(ready.effects).toEqual([{ type: "cancel.frame" }, { type: "cancel.ready-timer" }]) + }) + + test("a change before the first paint replaces the text without a swap", () => { + const result = transitionTextReveal(createTextRevealState("A"), { type: "text.changed", text: "B" }) + + expect(result.state).toMatchObject({ status: "measuring", current: "B" }) + expect(selectTextRevealSwapping(result.state)).toBe(false) + expect(selectTextRevealLeaving(result.state)).toBe("\u00A0") + expect(result.effects).toEqual([{ type: "measure.entering" }]) + }) + + test("fonts that never settle time out into ready and ignore the late results", () => { + const timedOut = run(createTextRevealState("A"), { type: "ready.timed-out", ...measured(30) }) + + expect(timedOut.state).toMatchObject({ status: "idle", widthPx: 30 }) + expect(run(timedOut.state, { type: "ready.settled", ...measured(50) }).state).toBe(timedOut.state) + }) + + test("fonts that settle after the timeout re-measure the width without a frame", () => { + const timedOut = run(createTextRevealState("A"), { type: "ready.timed-out", ...measured(30) }).state + const late = transitionTextReveal(timedOut, { type: "fonts.settled", ...measured(50) }) + + expect(late.state).toMatchObject({ status: "idle", widthPx: 50 }) + expect(late.effects).toEqual([]) + expect(transitionTextReveal(late.state, { type: "fonts.settled", ...measured(50) }).state).toBe(late.state) + + const swapping = transitionTextReveal(timedOut, { type: "text.changed", text: "B" }).state + + expect(transitionTextReveal(swapping, { type: "fonts.settled", ...measured(60) }).state).toMatchObject({ + status: "swapping", + widthPx: 60, + }) + }) + + test("swaps a replaced text and wipes it out after one frame", () => { + const swap = transitionTextReveal(settled("Alpha"), { type: "text.changed", text: "Beta" }) + + expect(swap.state).toMatchObject({ status: "swapping", attempt: 1, current: "Beta", leaving: "Alpha" }) + expect(swap.effects).toEqual([{ type: "swap.frame", attempt: 1 }]) + + const done = transitionTextReveal(swap.state, { type: "swap.settled", attempt: 1, ...measured(60) }) + + expect(done.state).toMatchObject({ status: "idle", current: "Beta", leaving: "Alpha", widthPx: 60 }) + }) + + test("two changes in one frame wipe out the text that was on screen", () => { + const result = run( + settled("Alpha"), + { type: "text.changed", text: "Beta" }, + { type: "text.changed", text: "Gamma" }, + ) + + expect(result.state).toMatchObject({ status: "swapping", attempt: 2, current: "Gamma", leaving: "Alpha" }) + expect(result.effects).toEqual([{ type: "cancel.frame" }, { type: "swap.frame", attempt: 2 }]) + expect(run(result.state, { type: "swap.settled", attempt: 1, ...measured(80) }).state).toBe(result.state) + expect(selectTextRevealLeaving(result.state)).toBe("Alpha") + }) + + test("changing back within one frame cancels the swap", () => { + const result = run( + settled("Alpha"), + { type: "text.changed", text: "Beta" }, + { type: "text.changed", text: "Alpha" }, + ) + + expect(result.state).toMatchObject({ status: "idle", current: "Alpha", leaving: undefined }) + expect(result.effects).toEqual([{ type: "cancel.frame" }, { type: "measure.entering" }]) + + const next = transitionTextReveal(result.state, { type: "text.changed", text: "Gamma" }) + + expect(next.state).toMatchObject({ status: "swapping", attempt: 2, leaving: "Alpha" }) + }) + + test("extending the text grows it in place", () => { + const result = transitionTextReveal(settled("Plan"), { type: "text.changed", text: "Planning" }) + + expect(result.state).toMatchObject({ status: "idle", current: "Planning" }) + expect(result.effects).toEqual([{ type: "measure.entering" }]) + expect(selectTextRevealEntering(result.state)).toBe("Planning") + }) + + test("grows only when asked, and ignores empty measurements", () => { + const state = settled("Alpha") + + expect(transitionTextReveal(state, { type: "width.measured", ...measured(20) }).state).toBe(state) + expect(transitionTextReveal(state, { type: "width.measured", ...measured(0, false) }).state).toBe(state) + expect(transitionTextReveal(state, { type: "width.measured", ...measured(20, false) }).state).toMatchObject({ + widthPx: 20, + }) + expect(selectTextRevealTrackWidth(state, false)).toBe("40px") + expect(selectTextRevealTrackWidth(state, true)).toBe("100%") + expect(selectTextRevealTrackWidth(createTextRevealState("A"), false)).toBe("auto") + }) + + test("disposing cancels pending work and ignores late results", () => { + const measuring = transitionTextReveal(createTextRevealState("A"), { type: "disposed" }) + + expect(measuring.effects).toEqual([{ type: "cancel.frame" }, { type: "cancel.ready-timer" }]) + expect(run(measuring.state, { type: "ready.timed-out", ...measured(10) }).state).toBe(measuring.state) + + const swapping = run(settled("Alpha"), { type: "text.changed", text: "Beta" }, { type: "disposed" }) + + expect(swapping.state).toEqual({ status: "disposed" }) + expect(swapping.effects).toEqual([{ type: "cancel.frame" }]) + expect(run(swapping.state, { type: "swap.settled", attempt: 1, ...measured(10) }).state).toBe(swapping.state) + }) +}) diff --git a/packages/ui/src/components/text-reveal-machine.ts b/packages/ui/src/components/text-reveal-machine.ts new file mode 100644 index 00000000000..c7b0a59d867 --- /dev/null +++ b/packages/ui/src/components/text-reveal-machine.ts @@ -0,0 +1,184 @@ +/** Fonts that never settle must not keep the reveal from animating. */ +export const TEXT_REVEAL_READY_TIMEOUT_MS = 1_000 + +/** + * `measuring` waits for fonts and one painted frame before transitions turn on, so the first text never animates in. + * It only moves forward, so its results match on the phase. `swapping` holds a replaced text in place for one frame, + * then the wipe runs. `leaving` is always text that was on screen, so text replaced within one frame never wipes out. + */ +export type TextRevealState = + | { readonly status: "measuring"; readonly current: string | undefined; readonly widthPx: number } + | { + readonly status: "idle" + readonly issued: number + readonly current: string | undefined + readonly leaving: string | undefined + readonly widthPx: number + } + | { + readonly status: "swapping" + readonly attempt: number + readonly current: string | undefined + readonly leaving: string | undefined + readonly widthPx: number + } + | { readonly status: "disposed" } + +type Measured = { readonly widthPx: number; readonly growOnly: boolean } + +export type TextRevealEvent = + | { readonly type: "text.changed"; readonly text: string | undefined } + | ({ readonly type: "width.measured" } & Measured) + | ({ readonly type: "fonts.settled" } & Measured) + | ({ readonly type: "ready.settled" } & Measured) + | ({ readonly type: "ready.timed-out" } & Measured) + | ({ readonly type: "swap.settled"; readonly attempt: number } & Measured) + | { readonly type: "disposed" } + +export type TextRevealEffect = + | { readonly type: "measure.entering" } + | { readonly type: "ready.frame" } + | { readonly type: "swap.frame"; readonly attempt: number } + | { readonly type: "cancel.frame" } + | { readonly type: "cancel.ready-timer" } + +export type TextRevealTransition = { + readonly state: TextRevealState + readonly effects: readonly TextRevealEffect[] +} + +const NO_EFFECTS: readonly TextRevealEffect[] = Object.freeze([]) + +const MEASURE: TextRevealEffect = Object.freeze({ type: "measure.entering" }) + +const READY_FRAME: TextRevealEffect = Object.freeze({ type: "ready.frame" }) + +const CANCEL_FRAME: TextRevealEffect = Object.freeze({ type: "cancel.frame" }) + +const CANCEL_READY_TIMER: TextRevealEffect = Object.freeze({ type: "cancel.ready-timer" }) + +const DISPOSED: TextRevealState = Object.freeze({ status: "disposed" }) + +export function createTextRevealState(text: string | undefined): TextRevealState { + return { status: "measuring", current: text, widthPx: 0 } +} + +export function transitionTextReveal(state: TextRevealState, event: TextRevealEvent): TextRevealTransition { + if (state.status === "disposed") return { state, effects: NO_EFFECTS } + + if (event.type === "disposed") { + if (state.status === "measuring") return { state: DISPOSED, effects: [CANCEL_FRAME, CANCEL_READY_TIMER] } + + return { state: DISPOSED, effects: state.status === "swapping" ? [CANCEL_FRAME] : NO_EFFECTS } + } + + if (event.type === "text.changed") return changeText(state, event.text) + + if (state.status === "measuring" && event.type === "fonts.settled") { + return { state: { ...state, widthPx: widen(state.widthPx, event) }, effects: [READY_FRAME] } + } + + // Fonts that settle after the ready timeout still widen the track to the real text. + if (event.type === "width.measured" || event.type === "fonts.settled") { + const widthPx = widen(state.widthPx, event) + + return { state: widthPx === state.widthPx ? state : { ...state, widthPx }, effects: NO_EFFECTS } + } + + if (state.status === "measuring" && (event.type === "ready.settled" || event.type === "ready.timed-out")) { + return { + state: { + status: "idle", + issued: 0, + current: state.current, + leaving: undefined, + widthPx: widen(state.widthPx, event), + }, + effects: [CANCEL_FRAME, CANCEL_READY_TIMER], + } + } + + if (state.status === "swapping" && event.type === "swap.settled" && event.attempt === state.attempt) { + return { + state: { + status: "idle", + issued: state.attempt, + current: state.current, + leaving: state.leaving, + widthPx: widen(state.widthPx, event), + }, + effects: NO_EFFECTS, + } + } + + return { state, effects: NO_EFFECTS } +} + +/** Transitions turn on once the first text has painted. */ +export function selectTextRevealReady(state: TextRevealState) { + return state.status === "idle" || state.status === "swapping" +} + +export function selectTextRevealSwapping(state: TextRevealState) { + return state.status === "swapping" +} + +export function selectTextRevealEntering(state: TextRevealState) { + return (state.status === "disposed" ? undefined : state.current) ?? "\u00A0" +} + +export function selectTextRevealLeaving(state: TextRevealState) { + return (state.status === "idle" || state.status === "swapping" ? state.leaving : undefined) ?? "\u00A0" +} + +export function selectTextRevealTrackWidth(state: TextRevealState, truncate: boolean | undefined) { + if (truncate) return "100%" + + return state.status !== "disposed" && state.widthPx > 0 ? `${state.widthPx}px` : "auto" +} + +function changeText( + state: Exclude, + text: string | undefined, +): TextRevealTransition { + if (text === state.current) return { state, effects: NO_EFFECTS } + + // Before the first paint nothing is on screen to wipe out, so the new text just replaces the old. + if (state.status === "measuring") return { state: { ...state, current: text }, effects: [MEASURE] } + + if (state.status === "idle" && state.current !== undefined && text?.startsWith(state.current)) { + return { state: { ...state, current: text }, effects: [MEASURE] } + } + + // Changing back to the text still on screen cancels the swap that never painted. + if (state.status === "swapping" && text === state.leaving) { + return { + state: { status: "idle", issued: state.attempt, current: text, leaving: undefined, widthPx: state.widthPx }, + effects: [CANCEL_FRAME, MEASURE], + } + } + + if (state.status === "swapping") { + const attempt = state.attempt + 1 + + return { + state: { ...state, attempt, current: text }, + effects: [CANCEL_FRAME, { type: "swap.frame", attempt }], + } + } + + const attempt = state.issued + 1 + + return { + state: { status: "swapping", attempt, current: text, leaving: state.current, widthPx: state.widthPx }, + effects: [{ type: "swap.frame", attempt }], + } +} + +function widen(prev: number, measured: Measured) { + if (measured.widthPx <= 0) return prev + + if (measured.growOnly && prev > 0 && measured.widthPx <= prev) return prev + + return measured.widthPx +} diff --git a/packages/ui/src/components/text-reveal.tsx b/packages/ui/src/components/text-reveal.tsx index 32cc26a6833..2a1b86d701d 100644 --- a/packages/ui/src/components/text-reveal.tsx +++ b/packages/ui/src/components/text-reveal.tsx @@ -1,20 +1,23 @@ -import { createEffect, on, onCleanup, onMount } from "solid-js" -import { createStore } from "solid-js/store" +import { createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js" +import { + createTextRevealState, + selectTextRevealEntering, + selectTextRevealLeaving, + selectTextRevealReady, + selectTextRevealSwapping, + selectTextRevealTrackWidth, + TEXT_REVEAL_READY_TIMEOUT_MS, + transitionTextReveal, + type TextRevealEffect, + type TextRevealEvent, +} from "./text-reveal-machine" -const px = (value: number | string | undefined, fallback: number) => { - if (typeof value === "number") return `${value}px` +// A number gets the unit; a string is already a CSS value. +const css = (value: number | string | undefined, fallback: number, unit: "px" | "ms") => { + if (value === undefined) return `${fallback}${unit}` - if (typeof value === "string") return value - - return `${fallback}px` -} - -const ms = (value: number | string | undefined, fallback: number) => { - if (typeof value === "number") return `${value}ms` - - if (typeof value === "string") return value - - return `${fallback}ms` + // oxlint-disable-next-line anti-slop/no-runtime-typeof -- discriminates this prop's own `number | string` union + return typeof value === "number" ? `${value}${unit}` : value } const pct = (value: number | undefined, fallback: number) => { @@ -36,125 +39,125 @@ export function TextReveal(props: { growOnly?: boolean truncate?: boolean }) { - const [state, setState] = createStore({ - cur: props.text, - old: undefined as string | undefined, - width: "auto", - ready: false, - swapping: false, - }) - - const cur = () => state.cur - const old = () => state.old - const width = () => state.width - const ready = () => state.ready - const swapping = () => state.swapping + const [machine, setMachine] = createSignal(createTextRevealState(props.text)) let inRef: HTMLSpanElement | undefined let outRef: HTMLSpanElement | undefined let rootRef: HTMLSpanElement | undefined let frame: number | undefined + let readyTimer: ReturnType | undefined const win = () => inRef?.scrollWidth ?? 0 const wout = () => outRef?.scrollWidth ?? 0 + const growOnly = () => props.growOnly ?? true + // oxlint-disable-next-line anti-slop/no-runtime-typeof -- probing for a browser global; SSR has no frames + const animates = typeof requestAnimationFrame === "function" - const widen = (next: number) => { - if (next <= 0) return + const dispatch = (event: TextRevealEvent) => { + const next = transitionTextReveal(untrack(machine), event) - if (props.growOnly ?? true) { - const prev = Number.parseFloat(width()) - - if (Number.isFinite(prev) && next <= prev) return - } - - setState("width", `${next}px`) + // Commit first: the effects measure the text nodes this state renders. + if (next.state !== untrack(machine)) setMachine(next.state) + next.effects.forEach(run) } - createEffect( - on( - () => props.text, - (next, prev) => { - if (next === prev) return + const cancelFrame = () => { + if (frame !== undefined) cancelAnimationFrame(frame) + frame = undefined + } - if (typeof next === "string" && typeof prev === "string" && next.startsWith(prev)) { - setState("cur", next) - widen(win()) + const onFrame = (finish: () => void) => { + cancelFrame() - return - } + if (!animates) return finish() + frame = requestAnimationFrame(() => { + frame = undefined + finish() + }) + } - setState("swapping", true) - setState("old", prev) - setState("cur", next) + const run = (effect: TextRevealEffect) => { + if (effect.type === "measure.entering") { + dispatch({ type: "width.measured", widthPx: win(), growOnly: growOnly() }) - if (typeof requestAnimationFrame !== "function") { - widen(Math.max(win(), wout())) - rootRef?.offsetHeight - setState("swapping", false) + return + } - return - } + if (effect.type === "ready.frame") { + onFrame(() => dispatch({ type: "ready.settled", widthPx: win(), growOnly: growOnly() })) - if (frame !== undefined && typeof cancelAnimationFrame === "function") cancelAnimationFrame(frame) - frame = requestAnimationFrame(() => { - widen(Math.max(win(), wout())) - rootRef?.offsetHeight - setState("swapping", false) - frame = undefined - }) - }, - ), - ) + return + } + + if (effect.type === "swap.frame") { + onFrame(() => { + const widthPx = Math.max(win(), wout()) + rootRef?.offsetHeight + dispatch({ type: "swap.settled", attempt: effect.attempt, widthPx, growOnly: growOnly() }) + }) + + return + } + + if (effect.type === "cancel.frame") { + cancelFrame() + + return + } + + clearTimeout(readyTimer) + readyTimer = undefined + } + + createEffect(() => { + const text = props.text + untrack(() => dispatch({ type: "text.changed", text })) + }) onMount(() => { - widen(win()) + dispatch({ type: "width.measured", widthPx: win(), growOnly: growOnly() }) + + if (!animates) { + dispatch({ type: "ready.settled", widthPx: win(), growOnly: growOnly() }) + + return + } + + readyTimer = setTimeout( + () => dispatch({ type: "ready.timed-out", widthPx: win(), growOnly: growOnly() }), + TEXT_REVEAL_READY_TIMEOUT_MS, + ) const fonts = typeof document !== "undefined" ? document.fonts : undefined + const settle = () => dispatch({ type: "fonts.settled", widthPx: win(), growOnly: growOnly() }) - if (typeof requestAnimationFrame !== "function") { - setState("ready", true) - - return - } - - if (!fonts) { - requestAnimationFrame(() => setState("ready", true)) - - return - } - - void fonts.ready.finally(() => { - widen(win()) - requestAnimationFrame(() => setState("ready", true)) - }) + if (!fonts) return settle() + void fonts.ready.finally(settle) }) - onCleanup(() => { - if (frame === undefined || typeof cancelAnimationFrame !== "function") return - cancelAnimationFrame(frame) - }) + onCleanup(() => dispatch({ type: "disposed" })) return ( - + - {cur() ?? "\u00A0"} + {selectTextRevealEntering(machine())} - {old() ?? "\u00A0"} + {selectTextRevealLeaving(machine())} diff --git a/packages/ui/src/data-display/project-avatar/animation-machine.test.ts b/packages/ui/src/data-display/project-avatar/animation-machine.test.ts new file mode 100644 index 00000000000..ccc59f0f489 --- /dev/null +++ b/packages/ui/src/data-display/project-avatar/animation-machine.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, test } from "bun:test" +import { + AVATAR_DISPOSED, + AVATAR_POINTER_LEFT, + AVATAR_REFRESH, + AVATAR_REST_MS, + createAvatarClock, + INITIAL_AVATAR_ANIMATION_STATE, + selectAvatarPaintTime, + selectAvatarRunning, + transitionAvatarAnimation, + type AvatarAnimationEvent, + type AvatarAnimationState, + type AvatarAnimationTransition, + type AvatarClock, +} from "./animation-machine" + +const enter = (now: number, reduced = false): AvatarAnimationEvent => ({ type: "pointer.entered", now, reduced }) + +const frame = (now: number): AvatarAnimationEvent => ({ type: "frame", now }) + +const motion = (reduced: boolean): AvatarAnimationEvent => ({ type: "motion.changed", reduced }) + +function run(clock: AvatarClock, state: AvatarAnimationState, ...events: AvatarAnimationEvent[]) { + return events.reduce( + (result, event) => transitionAvatarAnimation(result.state, clock, event), + { state, effect: "none" }, + ) +} + +const animating = (clock: AvatarClock) => + run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0), frame(AVATAR_REST_MS + 10)).state + +describe("transitionAvatarAnimation", () => { + test("waits out the rest delay, then animates", () => { + const clock = createAvatarClock() + const resting = run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0), frame(80)) + + expect(resting.state.status).toBe("resting") + expect(resting.effect).toBe("none") + expect(selectAvatarRunning(resting.state)).toBe(true) + + const first = run(clock, resting.state, frame(AVATAR_REST_MS + 10)) + + expect(first).toMatchObject({ state: { status: "animating" }, effect: "paint-frame" }) + expect(selectAvatarPaintTime(first.state, clock)).toBeCloseTo(0.08) + }) + + test("passing over a row stops at once without painting", () => { + const clock = createAvatarClock() + const result = run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0), frame(30), AVATAR_POINTER_LEFT) + + expect(result).toMatchObject({ state: INITIAL_AVATAR_ANIMATION_STATE, effect: "none" }) + expect(selectAvatarRunning(result.state)).toBe(false) + expect(clock).toEqual(createAvatarClock()) + }) + + test("a refresh repaints the static frame while resting, not while animating", () => { + const clock = createAvatarClock() + const resting = run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0)).state + + expect(run(clock, INITIAL_AVATAR_ANIMATION_STATE, AVATAR_REFRESH).effect).toBe("paint-static") + expect(run(clock, resting, AVATAR_REFRESH)).toMatchObject({ state: resting, effect: "paint-static" }) + expect(run(clock, animating(clock), AVATAR_REFRESH).effect).toBe("none") + }) + + test("reduced motion blocks the hover and stops a running animation", () => { + const clock = createAvatarClock() + + expect(run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0, true)).state).toBe(INITIAL_AVATAR_ANIMATION_STATE) + + const resting = run(clock, INITIAL_AVATAR_ANIMATION_STATE, enter(0)).state + + expect(run(clock, resting, motion(true))).toMatchObject({ state: INITIAL_AVATAR_ANIMATION_STATE, effect: "none" }) + + const stopped = run(clock, animating(clock), motion(true)) + + expect(stopped).toMatchObject({ state: INITIAL_AVATAR_ANIMATION_STATE, effect: "paint-static" }) + expect(clock).toEqual(createAvatarClock()) + expect(run(clock, animating(clock), motion(false)).state.status).toBe("animating") + }) + + test("eases back after the pointer leaves, resumes without a rest delay, and settles", () => { + const clock = createAvatarClock() + const easing = run(clock, animating(clock), AVATAR_POINTER_LEFT) + + expect(easing).toMatchObject({ state: { status: "easing" }, effect: "none" }) + expect(run(clock, easing.state, enter(170, true)).state).toBe(easing.state) + + const resumed = run(clock, easing.state, enter(170), frame(186)) + + expect(resumed).toMatchObject({ state: { status: "animating" }, effect: "paint-frame" }) + + const eased = run(clock, resumed.state, AVATAR_POINTER_LEFT, frame(286)) + + expect(eased).toMatchObject({ state: { status: "easing" }, effect: "paint-frame" }) + expect(clock.time).toBeLessThan(0.116) + + const settled = run(clock, eased.state, frame(386), frame(486), frame(586)) + + expect(settled).toMatchObject({ state: INITIAL_AVATAR_ANIMATION_STATE, effect: "paint-static" }) + }) + + test("a frame step never runs backwards or past the cap", () => { + const clock = createAvatarClock() + const state = animating(clock) + const time = clock.time + + run(clock, state, frame(0)) + expect(clock.time).toBe(time) + run(clock, state, frame(10_000)) + expect(clock.time).toBeCloseTo(time + 0.1) + }) + + test("frames reuse the same frozen transition", () => { + const clock = createAvatarClock() + const state = animating(clock) + const first = transitionAvatarAnimation(state, clock, frame(200)) + + expect(transitionAvatarAnimation(state, clock, frame(216))).toBe(first) + expect(Object.isFrozen(first)).toBe(true) + }) + + test("disposing ignores later events", () => { + const clock = createAvatarClock() + const disposed = run(clock, animating(clock), AVATAR_DISPOSED).state + + expect(selectAvatarRunning(disposed)).toBe(false) + expect(run(clock, disposed, enter(0), frame(500), AVATAR_REFRESH)).toMatchObject({ + state: disposed, + effect: "none", + }) + }) +}) diff --git a/packages/ui/src/data-display/project-avatar/animation-machine.ts b/packages/ui/src/data-display/project-avatar/animation-machine.ts new file mode 100644 index 00000000000..c274b171197 --- /dev/null +++ b/packages/ui/src/data-display/project-avatar/animation-machine.ts @@ -0,0 +1,182 @@ +/** + * A hovered generated avatar's animation. It runs once per frame, so it never allocates: every state and transition is + * a frozen module singleton, events are reused by the driver, and the continuous time lives in an `AvatarClock` that + * only `transitionAvatarAnimation` writes. + */ + +// The animation starts once the pointer rests on the avatar's row, so passing over a list does no drawing. +export const AVATAR_REST_MS = 150 + +export const AVATAR_MAX_STEP_S = 0.1 + +export const AVATAR_DECAY_BASE = 0.002 + +export const AVATAR_SETTLE_EPSILON = 0.01 + +export type AvatarAnimationState = + | { readonly status: "static" } + /** Hovered, waiting out the rest delay before the first animated frame. */ + | { readonly status: "resting" } + | { readonly status: "animating" } + /** The pointer left; the animation slows back to the static frame. */ + | { readonly status: "easing" } + | { readonly status: "disposed" } + +export type AvatarClock = { + entered: number + last: number + time: number +} + +export type AvatarAnimationEvent = + | { readonly type: "pointer.entered"; now: number; reduced: boolean } + | { readonly type: "pointer.left" } + | { readonly type: "frame"; now: number } + | { readonly type: "motion.changed"; reduced: boolean } + | { readonly type: "refresh" } + | { readonly type: "disposed" } + +export type AvatarAnimationEffect = "none" | "paint-static" | "paint-frame" + +export type AvatarAnimationTransition = { + readonly state: AvatarAnimationState + readonly effect: AvatarAnimationEffect +} + +const STATIC: AvatarAnimationState = Object.freeze({ status: "static" }) + +const RESTING: AvatarAnimationState = Object.freeze({ status: "resting" }) + +const ANIMATING: AvatarAnimationState = Object.freeze({ status: "animating" }) + +const EASING: AvatarAnimationState = Object.freeze({ status: "easing" }) + +const DISPOSED: AvatarAnimationState = Object.freeze({ status: "disposed" }) + +export const INITIAL_AVATAR_ANIMATION_STATE = STATIC + +const EFFECTS: readonly AvatarAnimationEffect[] = ["none", "paint-static", "paint-frame"] + +const TRANSITIONS = new Map( + [STATIC, RESTING, ANIMATING, EASING, DISPOSED].map((state) => [ + state, + new Map(EFFECTS.map((effect) => [effect, Object.freeze({ state, effect })])), + ]), +) + +const to = (state: AvatarAnimationState, effect: AvatarAnimationEffect): AvatarAnimationTransition => + TRANSITIONS.get(state)!.get(effect)! + +export const AVATAR_POINTER_LEFT: AvatarAnimationEvent = Object.freeze({ type: "pointer.left" }) + +export const AVATAR_REFRESH: AvatarAnimationEvent = Object.freeze({ type: "refresh" }) + +export const AVATAR_DISPOSED: AvatarAnimationEvent = Object.freeze({ type: "disposed" }) + +export function createAvatarClock(): AvatarClock { + return { entered: 0, last: 0, time: 0 } +} + +export function transitionAvatarAnimation( + state: AvatarAnimationState, + clock: AvatarClock, + event: AvatarAnimationEvent, +): AvatarAnimationTransition { + if (state === DISPOSED) return to(state, "none") + + if (event.type === "disposed") { + reset(clock) + + return to(DISPOSED, "none") + } + + if (event.type === "motion.changed") { + if (!event.reduced || state === STATIC) return to(state, "none") + reset(clock) + + // A resting avatar still shows its static frame. + return to(STATIC, state === RESTING ? "none" : "paint-static") + } + + if (event.type === "refresh") return to(state, state === STATIC || state === RESTING ? "paint-static" : "none") + + if (state === STATIC) { + if (event.type !== "pointer.entered" || event.reduced) return to(state, "none") + clock.entered = clock.last = event.now + clock.time = 0 + + return to(RESTING, "none") + } + + if (state === RESTING) { + if (event.type === "pointer.left") { + reset(clock) + + return to(STATIC, "none") + } + + if (event.type !== "frame") return to(state, "none") + + if (event.now - clock.entered < AVATAR_REST_MS) { + clock.last = event.now + + return to(state, "none") + } + + clock.time += step(event.now - clock.last) + clock.entered = 0 + clock.last = event.now + + return to(ANIMATING, "paint-frame") + } + + if (state === ANIMATING) { + if (event.type === "pointer.left") return to(EASING, "none") + + if (event.type !== "frame") return to(state, "none") + clock.time += step(event.now - clock.last) + clock.last = event.now + + return to(state, "paint-frame") + } + + if (event.type === "pointer.entered") { + if (event.reduced) return to(state, "none") + clock.last = event.now + + return to(ANIMATING, "none") + } + + if (event.type !== "frame") return to(state, "none") + const time = clock.time * AVATAR_DECAY_BASE ** step(event.now - clock.last) + + if (time < AVATAR_SETTLE_EPSILON) { + reset(clock) + + return to(STATIC, "paint-static") + } + + clock.time = time + clock.last = event.now + + return to(state, "paint-frame") +} + +/** Hovered or easing: the driver runs the frame loop and follows the reduce motion setting. */ +export function selectAvatarRunning(state: AvatarAnimationState) { + return state === RESTING || state === ANIMATING || state === EASING +} + +export function selectAvatarPaintTime(state: AvatarAnimationState, clock: Readonly) { + return state === ANIMATING || state === EASING ? clock.time : 0 +} + +function step(ms: number) { + return Math.max(0, Math.min(ms / 1000, AVATAR_MAX_STEP_S)) +} + +function reset(clock: AvatarClock) { + clock.entered = 0 + clock.last = 0 + clock.time = 0 +} diff --git a/packages/ui/src/data-display/project-avatar/animation.ts b/packages/ui/src/data-display/project-avatar/animation.ts index ac4030c099e..2d24c5e4268 100644 --- a/packages/ui/src/data-display/project-avatar/animation.ts +++ b/packages/ui/src/data-display/project-avatar/animation.ts @@ -1,8 +1,18 @@ +import { observeReducedMotion, prefersReducedMotion } from "../../motion/reduced" +import { + AVATAR_DISPOSED, + AVATAR_POINTER_LEFT, + AVATAR_REFRESH, + createAvatarClock, + INITIAL_AVATAR_ANIMATION_STATE, + selectAvatarPaintTime, + selectAvatarRunning, + transitionAvatarAnimation, + type AvatarAnimationEvent, + type AvatarAnimationState, +} from "./animation-machine" import { drawProjectIcon, type GeneratedProjectIcon } from "./generated" -// The animation starts once the pointer rests on the avatar's row, so passing over a list does no drawing. -const REST_MS = 150 - const HOVER_TARGET = 'a, button, [role="menuitem"], [role="option"], [data-titlebar-tab]' // Paints a generated avatar into `canvas`. The static frame is drawn once per icon and pixel size and copied into every @@ -10,11 +20,14 @@ const HOVER_TARGET = 'a, button, [role="menuitem"], [role="option"], [data-title // row animates only that row's icon even when other rows show the same project. Only a hovered avatar runs an // animation loop, and it stops once the icon has eased back to its static frame. export function attachGeneratedAvatar(canvas: HTMLCanvasElement, icon: () => GeneratedProjectIcon) { + let state: AvatarAnimationState = INITIAL_AVATAR_ANIMATION_STATE + const clock = createAvatarClock() let frame = 0 - let time = 0 - let hovering = false - let last = 0 - let entered = 0 + let stopMotionObserver: (() => void) | undefined + // Reused every frame, so the loop allocates nothing. + const enterEvent = { type: "pointer.entered" as const, now: 0, reduced: false } + const frameEvent = { type: "frame" as const, now: 0 } + const motionEvent = { type: "motion.changed" as const, reduced: false } const paint = (draw: (ctx: CanvasRenderingContext2D, px: number) => void) => { const px = Math.max(1, Math.round((canvas.clientWidth || 16) * (window.devicePixelRatio || 1))) @@ -25,60 +38,76 @@ export function attachGeneratedAvatar(canvas: HTMLCanvasElement, icon: () => Gen if (ctx) draw(ctx, px) } - const paintStatic = () => - paint((ctx, px) => { - ctx.clearRect(0, 0, px, px) - const still = staticFrame(icon(), px) + const drawStatic = (ctx: CanvasRenderingContext2D, px: number) => { + ctx.clearRect(0, 0, px, px) + const still = staticFrame(icon(), px) - if (still) ctx.drawImage(still, 0, 0) - }) + if (still) ctx.drawImage(still, 0, 0) + } - const tick = (now: number) => { - if (hovering && time === 0 && now - entered < REST_MS) { - last = now + const drawAnimated = (ctx: CanvasRenderingContext2D, px: number) => + drawProjectIcon(ctx, px, icon(), selectAvatarPaintTime(state, clock)) + + const dispatch = (event: AvatarAnimationEvent) => { + const prev = state + const next = transitionAvatarAnimation(prev, clock, event) + state = next.state + + if (selectAvatarRunning(prev) !== selectAvatarRunning(state)) reconcile() + + if (next.effect === "paint-static") paint(drawStatic) + + if (next.effect === "paint-frame") paint(drawAnimated) + } + + const reconcile = () => { + if (selectAvatarRunning(state)) { + stopMotionObserver = observeReducedMotion(onMotionChange) frame = requestAnimationFrame(tick) return } - const seconds = Math.min((now - last) / 1000, 0.1) - last = now - time = hovering ? time + seconds : time * Math.pow(0.002, seconds) + cancelAnimationFrame(frame) + frame = 0 + stopMotionObserver?.() + stopMotionObserver = undefined + } - if (!hovering && time < 0.01) { - time = 0 - frame = 0 - paintStatic() + const tick = (now: number) => { + frame = 0 + frameEvent.now = now + dispatch(frameEvent) - return - } - - paint((ctx, px) => drawProjectIcon(ctx, px, icon(), time)) - frame = requestAnimationFrame(tick) + if (selectAvatarRunning(state) && !frame) frame = requestAnimationFrame(tick) } const enter = () => { - if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return - hovering = true - - if (frame) return - entered = last = performance.now() - frame = requestAnimationFrame(tick) + enterEvent.now = performance.now() + enterEvent.reduced = prefersReducedMotion() + dispatch(enterEvent) } - const leave = () => (hovering = false) + const leave = () => dispatch(AVATAR_POINTER_LEFT) + + const onMotionChange = () => { + motionEvent.reduced = prefersReducedMotion() + dispatch(motionEvent) + } const target = - canvas.closest(HOVER_TARGET) ?? canvas.closest('[data-component="project-avatar-v2"]') ?? canvas + canvas.closest(HOVER_TARGET) ?? + canvas.closest('[data-component="project-avatar-v2"]') ?? + canvas target.addEventListener("pointerenter", enter) target.addEventListener("pointerleave", leave) return { /** Repaints the static frame unless the avatar is animating, e.g. after the icon changed. */ - refresh: () => !frame && paintStatic(), + refresh: () => dispatch(AVATAR_REFRESH), dispose: () => { - cancelAnimationFrame(frame) + dispatch(AVATAR_DISPOSED) target.removeEventListener("pointerenter", enter) target.removeEventListener("pointerleave", leave) }, diff --git a/packages/ui/src/navigation/menu/machine.test.ts b/packages/ui/src/navigation/menu/machine.test.ts new file mode 100644 index 00000000000..4a84bcea0d4 --- /dev/null +++ b/packages/ui/src/navigation/menu/machine.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, test } from "bun:test" +import { + createMenuState, + MENU_CLOSE_AUTOFOCUS, + MENU_DISPOSED, + MENU_OUTSIDE_INTERACTED, + openChangedEvent, + selectMenuRestoreTriggerWithoutRing, + transitionMenu, + type MenuEvent, + type MenuState, +} from "./machine" + +const run = (state: MenuState, ...events: MenuEvent[]) => events.reduce(transitionMenu, state) + +const CLOSED = createMenuState(false) + +describe("transitionMenu", () => { + test("a pointer open restores the trigger without a ring until focus returns", () => { + const opened = run(CLOSED, openChangedEvent(true, "pointer")) + + expect(opened).toEqual({ status: "open", modality: "pointer", outsideInteracted: false }) + + const closing = run(opened, openChangedEvent(false, "keyboard")) + + expect(closing.status).toBe("closing") + expect(selectMenuRestoreTriggerWithoutRing(closing)).toBe(true) + + const closed = run(closing, MENU_CLOSE_AUTOFOCUS) + + expect(closed).toBe(CLOSED) + expect(selectMenuRestoreTriggerWithoutRing(closed)).toBe(false) + }) + + test("an open without an input gesture keeps the ring, even after an earlier click", () => { + const programmatic = run(CLOSED, openChangedEvent(true, "none"), openChangedEvent(false, "none")) + + expect(programmatic).toEqual({ status: "closing", modality: "programmatic", outsideInteracted: false }) + expect(selectMenuRestoreTriggerWithoutRing(programmatic)).toBe(false) + expect(selectMenuRestoreTriggerWithoutRing(run(CLOSED, openChangedEvent(true, "keyboard")))).toBe(false) + expect(selectMenuRestoreTriggerWithoutRing(createMenuState(true))).toBe(false) + }) + + test("an outside press keeps focus where it landed", () => { + const state = run( + CLOSED, + openChangedEvent(true, "pointer"), + MENU_OUTSIDE_INTERACTED, + openChangedEvent(false, "pointer"), + ) + + expect(state).toEqual({ status: "closing", modality: "pointer", outsideInteracted: true }) + expect(selectMenuRestoreTriggerWithoutRing(state)).toBe(false) + expect(run(state, MENU_CLOSE_AUTOFOCUS)).toBe(CLOSED) + }) + + test("reopening before focus returns takes the new gesture and forgets the outside press", () => { + const state = run( + CLOSED, + openChangedEvent(true, "pointer"), + MENU_OUTSIDE_INTERACTED, + openChangedEvent(false, "none"), + openChangedEvent(true, "keyboard"), + ) + + expect(state).toEqual({ status: "open", modality: "keyboard", outsideInteracted: false }) + }) + + test("a controlled echo of an open keeps its modality, and no-ops keep the same state", () => { + const opened = run(CLOSED, openChangedEvent(true, "pointer")) + + expect(run(opened, openChangedEvent(true, "none"))).toBe(opened) + expect(run(CLOSED, openChangedEvent(false, "pointer"), MENU_OUTSIDE_INTERACTED, MENU_CLOSE_AUTOFOCUS)).toBe(CLOSED) + expect(run(opened, MENU_CLOSE_AUTOFOCUS)).toBe(opened) + expect(run(opened, MENU_OUTSIDE_INTERACTED, MENU_OUTSIDE_INTERACTED)).toBe(run(opened, MENU_OUTSIDE_INTERACTED)) + expect(Object.isFrozen(opened)).toBe(true) + }) + + test("disposing ignores later events", () => { + const disposed = run(CLOSED, openChangedEvent(true, "pointer"), MENU_DISPOSED) + + expect(disposed).toEqual({ status: "disposed" }) + expect(run(disposed, openChangedEvent(true, "pointer"), MENU_CLOSE_AUTOFOCUS)).toBe(disposed) + }) +}) diff --git a/packages/ui/src/navigation/menu/machine.ts b/packages/ui/src/navigation/menu/machine.ts new file mode 100644 index 00000000000..4dc7fad0f97 --- /dev/null +++ b/packages/ui/src/navigation/menu/machine.ts @@ -0,0 +1,109 @@ +/** + * Every dropdown menu runs this machine, so each reachable state and event is a frozen module singleton, and an event + * that changes nothing returns the state it was given. + */ +export type MenuInputGesture = "pointer" | "keyboard" | "none" + +/** How the menu opened. An open without an input gesture (a shortcut handler, an async action) is `programmatic`. */ +export type MenuOpenModality = "pointer" | "keyboard" | "programmatic" + +export type MenuState = + | { readonly status: "closed" } + | { readonly status: "open"; readonly modality: MenuOpenModality; readonly outsideInteracted: boolean } + /** + * Kobalte reports the close first and restores focus a task later, so the modality outlives the open state until + * that focus restore has run. + */ + | { readonly status: "closing"; readonly modality: MenuOpenModality; readonly outsideInteracted: boolean } + | { readonly status: "disposed" } + +export type MenuEvent = + | { readonly type: "open.changed"; readonly open: boolean; readonly gesture: MenuInputGesture } + /** A press outside a non-modal menu, or a context menu anywhere, dismissed it and keeps focus where it landed. */ + | { readonly type: "outside.interacted" } + | { readonly type: "close.autofocus" } + | { readonly type: "disposed" } + +const MODALITIES: readonly MenuOpenModality[] = ["pointer", "keyboard", "programmatic"] + +const GESTURES: readonly MenuInputGesture[] = ["pointer", "keyboard", "none"] + +const CLOSED: MenuState = Object.freeze({ status: "closed" }) + +const DISPOSED: MenuState = Object.freeze({ status: "disposed" }) + +const OPEN = MODALITIES.flatMap((modality) => + [false, true].map((outsideInteracted): MenuState => Object.freeze({ status: "open", modality, outsideInteracted })), +) + +const CLOSING = MODALITIES.flatMap((modality) => + [false, true].map( + (outsideInteracted): MenuState => Object.freeze({ status: "closing", modality, outsideInteracted }), + ), +) + +const key = (modality: MenuOpenModality, outsideInteracted: boolean) => + MODALITIES.indexOf(modality) * 2 + (outsideInteracted ? 1 : 0) + +const open = (modality: MenuOpenModality, outsideInteracted: boolean) => OPEN[key(modality, outsideInteracted)] + +const closing = (modality: MenuOpenModality, outsideInteracted: boolean) => CLOSING[key(modality, outsideInteracted)] + +const OPEN_CHANGED = [false, true].flatMap((isOpen) => + GESTURES.map((gesture): MenuEvent => Object.freeze({ type: "open.changed", open: isOpen, gesture })), +) + +export const MENU_OUTSIDE_INTERACTED: MenuEvent = Object.freeze({ type: "outside.interacted" }) + +export const MENU_CLOSE_AUTOFOCUS: MenuEvent = Object.freeze({ type: "close.autofocus" }) + +export const MENU_DISPOSED: MenuEvent = Object.freeze({ type: "disposed" }) + +export function openChangedEvent(isOpen: boolean, gesture: MenuInputGesture) { + return OPEN_CHANGED[(isOpen ? GESTURES.length : 0) + GESTURES.indexOf(gesture)] +} + +export function createMenuState(initialOpen: boolean) { + return initialOpen ? open("programmatic", false) : CLOSED +} + +export function transitionMenu(state: MenuState, event: MenuEvent): MenuState { + if (state.status === "disposed") return state + + if (event.type === "disposed") return DISPOSED + + if (event.type === "open.changed") { + if (event.open && state.status !== "open") { + return open( + event.gesture === "pointer" ? "pointer" : event.gesture === "keyboard" ? "keyboard" : "programmatic", + false, + ) + } + + if (!event.open && state.status === "open") return closing(state.modality, state.outsideInteracted) + + return state + } + + if (event.type === "outside.interacted") { + if (state.status === "open" && !state.outsideInteracted) return open(state.modality, true) + + if (state.status === "closing" && !state.outsideInteracted) return closing(state.modality, true) + + return state + } + + if (state.status === "closing") return CLOSED + + return state +} + +/** + * Restore focus to the trigger without a focus ring: Escape counts as keyboard use, so Chromium would ring a trigger + * the pointer opened. After an outside press, focus stays where that press put it. + */ +export function selectMenuRestoreTriggerWithoutRing(state: MenuState) { + return ( + (state.status === "closing" || state.status === "open") && state.modality === "pointer" && !state.outsideInteracted + ) +} diff --git a/packages/ui/src/navigation/menu/menu.stories.tsx b/packages/ui/src/navigation/menu/menu.stories.tsx index ddc2ff9bb85..432aa27986c 100644 --- a/packages/ui/src/navigation/menu/menu.stories.tsx +++ b/packages/ui/src/navigation/menu/menu.stories.tsx @@ -55,6 +55,40 @@ export const Basic = { ), } +export const ProgrammaticAndNonModal = { + render: () => { + const [open, setOpen] = createSignal(false) + const [restores, setRestores] = createSignal(0) + + return ( +
+ {/* Opens a task after the click, like a shortcut handler or an async action. */} + + + Controlled + + + Rename + Duplicate + + + + + Non-modal + + {/* Counts close focus restores, which run a task after the menu closes. */} + setRestores((count) => count + 1)}> + Pin + Archive + + + + {restores()} +
+ ) + }, +} + export const Appearances = { render: () => (
diff --git a/packages/ui/src/navigation/menu/menu.tsx b/packages/ui/src/navigation/menu/menu.tsx index 4aca8f6ed47..966f10ee021 100644 --- a/packages/ui/src/navigation/menu/menu.tsx +++ b/packages/ui/src/navigation/menu/menu.tsx @@ -1,8 +1,10 @@ import { DropdownMenu } from "@kobalte/core/dropdown-menu" import { ContextMenu } from "@kobalte/core/context-menu" -import { makeEventListener } from "@solid-primitives/event-listener" import { + createComputed, createContext, + createSignal, + onCleanup, Show, splitProps, useContext, @@ -12,6 +14,18 @@ import { type JSX, type ParentProps, } from "solid-js" +import { + createMenuState, + MENU_CLOSE_AUTOFOCUS, + MENU_DISPOSED, + MENU_OUTSIDE_INTERACTED, + openChangedEvent, + selectMenuRestoreTriggerWithoutRing, + transitionMenu, + type MenuEvent, + type MenuInputGesture, + type MenuState, +} from "./machine" import "./menu.css" const ChevronRight: Component = () => ( @@ -42,13 +56,70 @@ const CheckMark: Component = () => ( export type MenuAppearance = "standard" | "compact" -const MenuAppearanceContext = createContext<{ +type MenuContextValue = { appearance: Accessor - pointerOpened: () => boolean -}>({ - appearance: (): MenuAppearance => "compact", - pointerOpened: () => false, -}) + state: Accessor + modal: Accessor + onOutsideInteract: () => void + onCloseAutoFocus: () => void +} + +// Context menus restore focus through Kobalte alone, so they never run the dropdown machine. +const UNTRACKED_MENU: MenuContextValue = { + appearance: () => "compact", + state: () => createMenuState(false), + modal: () => true, + onOutsideInteract: () => {}, + onCloseAutoFocus: () => {}, +} + +const MenuAppearanceContext = createContext(UNTRACKED_MENU) + +// One set of window listeners serves every mounted menu. Capture runs before the trigger's own handlers, so while an +// input event dispatches, `gesture` names the input that may open a menu. It clears once that event's task ends, so a +// later open without input counts as programmatic. +let trackers = 0 + +let gesture: MenuInputGesture = "none" + +let gestureReset: ReturnType | undefined + +const trackGesture = (event: Event) => { + if (!event.isTrusted) return + // Keyboard activation fires a click with no press count. + gesture = + event.type === "keydown" || (event instanceof MouseEvent && event.type === "click" && event.detail === 0) + ? "keyboard" + : "pointer" + + // A microtask would run between listeners of this same dispatch, before the trigger's handler reads the gesture. + if (gestureReset !== undefined) return + gestureReset = setTimeout(() => { + gestureReset = undefined + gesture = "none" + }) +} + +const GESTURE_EVENTS = ["pointerdown", "click", "keydown"] as const + +const GESTURE_LISTENER_OPTIONS = { capture: true, passive: true } + +function retainGestureTracker() { + trackers += 1 + + if (trackers === 1) + GESTURE_EVENTS.forEach((type) => window.addEventListener(type, trackGesture, GESTURE_LISTENER_OPTIONS)) +} + +function releaseGestureTracker() { + trackers -= 1 + + if (trackers > 0) return + GESTURE_EVENTS.forEach((type) => window.removeEventListener(type, trackGesture, GESTURE_LISTENER_OPTIONS)) + clearTimeout(gestureReset) + gestureReset = undefined + gesture = "none" +} function useMenuContext() { const ctx = useContext(MenuAppearanceContext) @@ -247,14 +318,23 @@ function MenuSeparator(props: ComponentProps) { function MenuContent(props: ComponentProps) { const ctx = useMenuContext() - const [s, r] = splitProps(props, ["class", "classList", "onCloseAutoFocus"]) + const [s, r] = splitProps(props, ["class", "classList", "onCloseAutoFocus", "onInteractOutside"]) - // A menu returns focus to its trigger when it closes. Closing with Escape counts as keyboard use, so Chromium would - // ring a trigger the pointer opened; restore focus without the ring and keep it for keyboard opens. + // Kobalte's own rule for when an outside press keeps focus where it landed. + const onInteractOutside: NonNullable = (event) => { + s.onInteractOutside?.(event) + + if (!event.defaultPrevented && (!ctx.modal() || event.detail.isContextMenu)) ctx.onOutsideInteract() + } + + // A menu returns focus to its trigger when it closes. Restore it without the ring after a pointer open and keep the + // ring for keyboard and programmatic opens. const onCloseAutoFocus = (event: Event) => { + const restore = selectMenuRestoreTriggerWithoutRing(ctx.state()) + ctx.onCloseAutoFocus() s.onCloseAutoFocus?.(event) - if (event.defaultPrevented || !ctx.pointerOpened()) return + if (event.defaultPrevented || !restore) return event.preventDefault() const active = document.activeElement @@ -269,6 +349,7 @@ function MenuContent(props: ComponentProps) { { function MenuRoot(props: MenuProps) { const [local, rest] = splitProps(props, ["appearance", "children", "onOpenChange"]) const appearance = () => local.appearance ?? "compact" - let pointer = false - let pointerOpened = false + const initialOpen = !!props.open || (props.open === undefined && !!props.defaultOpen) + const [menuState, setMenuState] = createSignal(createMenuState(initialOpen)) + const dispatch = (event: MenuEvent) => setMenuState((state) => transitionMenu(state, event)) - // Capture runs before the trigger's own handlers, so the last input is what opened the menu. - makeEventListener(window, "pointerdown", () => (pointer = true), { capture: true }) - makeEventListener(window, "keydown", () => (pointer = false), { capture: true }) + retainGestureTracker() + onCleanup(() => { + releaseGestureTracker() + dispatch(MENU_DISPOSED) + }) + + // Kobalte does not report a controlled open it did not ask for, so a controlled menu follows `open` itself. + createComputed(() => { + if (props.open === undefined) return + dispatch(openChangedEvent(props.open, gesture)) + }) + + const context = { + appearance, + state: menuState, + modal: () => props.modal ?? true, + onOutsideInteract: () => dispatch(MENU_OUTSIDE_INTERACTED), + onCloseAutoFocus: () => dispatch(MENU_CLOSE_AUTOFOCUS), + } return ( - pointerOpened }}> + { - if (open) pointerOpened = pointer + if (props.open === undefined) dispatch(openChangedEvent(open, gesture)) local.onOpenChange?.(open) }} > @@ -314,7 +412,7 @@ function MenuContextRoot(props: MenuContextProps) { const appearance = () => local.appearance ?? "compact" return ( - false }}> + {local.children} )