diff --git a/.changeset/internal-touch-press-tracker.md b/.changeset/internal-touch-press-tracker.md new file mode 100644 index 0000000000000..b94b6b90508a1 --- /dev/null +++ b/.changeset/internal-touch-press-tracker.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: the internal touch entry re-exports `usePressTracker` for Lab components, as it re-exports `useActionGroupTracking` for Lab's TabBar. Not exported from the package entry point. + +@vjeux diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 1478ce270b345..02f14f27e1071 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -50,7 +50,13 @@ "/pages/motion-lab/springs/", "/pages/motion-lab/tokens/", "/pages/motion-lab/violations/", + "/pages/motion-start-clock/", "/pages/navigation/", + "/pages/navstack-current-proposed/", + "/pages/navstack-heavy-commit/", + "/pages/navstack-inert-cost/", + "/pages/navstack-kept-layout/", + "/pages/navstack-press/", "/pages/neutral-palette/", "/pages/palette-generator/", "/pages/perf-scenes/", diff --git a/apps/sandbox/src/app/(raw)/navigationStackCells.tsx b/apps/sandbox/src/app/(raw)/navigationStackCells.tsx new file mode 100644 index 0000000000000..48dd52bc17bc7 --- /dev/null +++ b/apps/sandbox/src/app/(raw)/navigationStackCells.tsx @@ -0,0 +1,367 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file navigationStackCells.tsx + * @input Lab's NavigationStack and its opt-in options + * @output What the NavigationStack phone pages share: a busy loop, the x a + * screen's card shows, a watch for a change's first moved frame, a readout + * fixed at the page's bottom, a heavy screen and a windowed list in a + * screen's own scroller + * @position Sandbox; imported by the raw navstack-* pages, which a physical + * phone loads from a pull request's preview + */ + +import { + useCallback, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {useNavigationScroller} from '@astryxdesign/lab'; +import {List, ListItem} from '@astryxdesign/core/List'; + +/** Holds the main thread for `ms`, as a heavy commit or task does. */ +export function busyFor(ms: number): void { + const end = performance.now() + ms; + while (performance.now() < end) { + // Spins: nothing else runs on the main thread meanwhile. + } +} + +/** A number from the query, or `fallback` when it is missing or not one. */ +export function queryNumber( + params: URLSearchParams, + name: string, + fallback: number, +): number { + const value = Number(params.get(name)); + return params.has(name) && Number.isFinite(value) ? value : fallback; +} + +/** + * The card of the screen whose entry has `key` (its `getKey`), or the root's + * card for null. The stack names an entry's card `screen-`. + */ +export function cardOf(key: string | null): HTMLElement | null { + return document.querySelector( + `[data-navigation-screen="${CSS.escape(key == null ? 'root' : `screen-${key}`)}"]`, + ); +} + +/** The x the card of `key` shows now, in px, or null with no card. */ +/** A stack card's key, or the moving element itself. */ +export type MovingTarget = string | HTMLElement; + +function elementOf(target: MovingTarget): HTMLElement | null { + return typeof target === 'string' ? cardOf(target) : target; +} + +export function shownX(target: MovingTarget): number | null { + const card = elementOf(target); + if (card == null) { + return null; + } + const translate = getComputedStyle(card).translate; + return translate === 'none' ? 0 : Number.parseFloat(translate); +} + +/** A change's first moved frame on the page clock. */ +export interface FirstMove { + /** Milliseconds from `since` to the frame's callback time. */ + ms: number; + /** How far the card had travelled at that frame: 0 at rest, 1 at its end. */ + travel: number; + /** The frame's callback time on the page clock. */ + at: number; +} + +/** + * Calls `onMove` at the first animation frame after `since` in which the + * card of `key` shows away from `fromX`, with its travel toward `toX`. + * The page clock counts frame callbacks, which stop while the main thread is + * held, so a film of the screen stays the measure. + */ +export function watchFirstMove( + target: MovingTarget, + since: number, + fromX: (width: number) => number, + toX: (width: number) => number, + onMove: (move: FirstMove) => void, +): () => void { + let frame = 0; + let stopped = false; + const deadline = since + 3000; + const tick = (time: number) => { + if (stopped) { + return; + } + const card = elementOf(target); + const x = shownX(target); + if (card != null && x != null) { + const width = card.parentElement?.clientWidth ?? card.clientWidth; + const from = fromX(width); + const to = toX(width); + if (Math.abs(x - from) > 0.5) { + onMove({ + ms: Math.round((time - since) * 10) / 10, + at: time, + travel: Math.round(((x - from) / (to - from)) * 1000) / 1000, + }); + return; + } + } + if (time < deadline) { + frame = requestAnimationFrame(tick); + } + }; + frame = requestAnimationFrame(tick); + return () => { + stopped = true; + cancelAnimationFrame(frame); + }; +} + +const MARKS = Array.from({length: 11}, (_, index) => index * 10); + +const styles = stylex.create({ + ruler: { + position: 'fixed', + insetInline: 0, + top: 0, + height: 14, + zIndex: 11, + pointerEvents: 'none', + }, + mark: (percent: number) => ({ + position: 'absolute', + top: 0, + insetInlineStart: `${percent}%`, + width: 1, + height: percent % 50 === 0 ? 14 : 8, + backgroundColor: 'rgba(220, 0, 0, 0.8)', + }), + readout: { + position: 'fixed', + insetInline: 0, + bottom: 0, + zIndex: 10, + maxHeight: '30dvh', + overflowY: 'auto', + paddingBlock: 6, + paddingInline: 10, + paddingBottom: 'max(6px, env(safe-area-inset-bottom))', + backgroundColor: 'rgba(0, 0, 0, 0.82)', + color: '#fff', + fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', + fontSize: 12, + lineHeight: 1.35, + }, + line: { + margin: 0, + whiteSpace: 'pre-wrap', + }, + links: { + display: 'flex', + flexWrap: 'wrap', + gap: 10, + marginBottom: 4, + }, + link: { + color: '#9cf', + }, + stage: { + position: 'fixed', + insetInline: 0, + top: 0, + bottom: 'var(--navstack-readout-height, 120px)', + }, + scroller: { + height: '100%', + overflowY: 'auto', + overscrollBehavior: 'contain', + }, + spacer: (height: number) => ({ + height, + }), + inset: (height: number) => ({ + paddingTop: height, + }), +}); + +/** The stage the stack fills: the page above the readout. */ +export function Stage({children}: {children: ReactNode}) { + return
{children}
; +} + +/** + * A readout fixed at the page's bottom: links to the page's other arms, then + * one line per measurement, newest first. It sets the stage's bottom edge. + */ +export function Readout({ + links, + lines, + children, +}: { + links: ReadonlyArray<{label: string; href: string}>; + lines: ReadonlyArray; + children?: ReactNode; +}) { + const ref = useRef(null); + useLayoutEffect(() => { + const element = ref.current; + if (element == null) { + return undefined; + } + const measure = () => + document.documentElement.style.setProperty( + '--navstack-readout-height', + `${element.offsetHeight}px`, + ); + measure(); + const observer = new ResizeObserver(measure); + observer.observe(element); + return () => observer.disconnect(); + }, []); + return ( +
+
+ {links.map(link => ( + + {link.label} + + ))} +
+ {children} + {lines.map((line, index) => ( +

+ {line} +

+ ))} +
+ ); +} + +/** Appends a line to a readout, newest first, keeping the last 12. */ +export function useReadoutLines(): [ + ReadonlyArray, + (line: string) => void, +] { + const [lines, setLines] = useState>([]); + const add = useCallback( + (line: string) => setLines(current => [line, ...current].slice(0, 12)), + [], + ); + return [lines, add]; +} + +/** + * A screen whose mount is heavy: `rows` list rows, and `layoutMs` of work in a + * layout effect when it mounts, as a large screen's measuring code does. + */ +export function HeavyScreen({ + name, + rows, + layoutMs, +}: { + name: string; + rows: number; + layoutMs: number; +}) { + useLayoutEffect(() => { + busyFor(layoutMs); + }, [layoutMs]); + return ( + + {Array.from({length: rows}, (_, index) => ( + + ))} + + ); +} + +/** + * A long list in the screen's own scroller (`scroll="content"`) that renders + * only the rows near the viewport, as a windowed list does. + */ +export function WindowedList({ + count, + renderRow, + overscan = 8, +}: { + count: number; + renderRow: (index: number) => ReactNode; + overscan?: number; +}) { + const scroller = useNavigationScroller(); + const boxRef = useRef(null); + const [rowHeight, setRowHeight] = useState(56); + const [range, setRange] = useState({first: 0, last: 30}); + const update = useCallback(() => { + const box = boxRef.current; + if (box == null) { + return; + } + const first = Math.max(0, Math.floor(box.scrollTop / rowHeight) - overscan); + const last = Math.min( + count, + Math.ceil((box.scrollTop + box.clientHeight) / rowHeight) + overscan, + ); + setRange(current => + current.first === first && current.last === last + ? current + : {first, last}, + ); + }, [count, overscan, rowHeight]); + const attach = useCallback( + (element: HTMLDivElement | null) => { + boxRef.current = element; + scroller.ref(element); + }, + [scroller], + ); + useLayoutEffect(() => { + const row = boxRef.current?.querySelector('[data-row]'); + if (row != null && row.offsetHeight > 0) { + setRowHeight(row.offsetHeight); + } + update(); + }, [update]); + const rows: ReactNode[] = []; + for (let index = range.first; index < range.last; index += 1) { + rows.push( +
+ {renderRow(index)} +
, + ); + } + return ( +
+
+
+ {rows} +
+
+ ); +} + +/** Marks every tenth of the screen's width, for reading a film. */ +export function Ruler() { + return ( +
+ {MARKS.map(percent => ( + + ))} +
+ ); +} diff --git a/apps/sandbox/src/app/(raw)/pages/motion-start-clock/page.tsx b/apps/sandbox/src/app/(raw)/pages/motion-start-clock/page.tsx new file mode 100644 index 0000000000000..394e4ba806ab1 --- /dev/null +++ b/apps/sandbox/src/app/(raw)/pages/motion-start-clock/page.tsx @@ -0,0 +1,343 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file page.tsx + * @input `?start=next-frame|presented|browser` (how a motion from rest takes + * its start; next-frame by default), `?work=` (work the tap's task runs + * after the call, 0 by default), `?hold=` (how long the curve holds its + * first value, 0 by default) and `?compare=` (two cards side by side: + * no hold, and a hold of that length) + * @output A card that a row's tap slides in from the trailing edge and Back + * slides out, on the push spring, as one Web Animation per change. A ruler + * of travel marks sits over it. The readout gives each change's start on + * the document timeline and its first moved frame on the page clock + * @position A raw page for how a tap-started motion from rest takes its + * start, filmed on a physical phone: the first frame that shows the change + * must show it at its start + */ + +import {Suspense, useCallback, useRef} from 'react'; +import {useSearchParams} from 'react-router-dom'; +import * as stylex from '@stylexjs/stylex'; +import {Button} from '@astryxdesign/core/Button'; +import {List, ListItem} from '@astryxdesign/core/List'; +import { + busyFor, + queryNumber, + Readout, + Ruler, + Stage, + useReadoutLines, + watchFirstMove, +} from '../../navigationStackCells'; + +const PAGE = '/sandbox/pages/motion-start-clock/'; +const ITEMS = Array.from({length: 16}, (_, index) => `Item ${index + 1}`); + +// UIKit's push spring (response 0.3 s, critically damped) and the +// programmatic push's starting velocity (8.773 travels per second), as Core +// measures them. A page can't import Core's internal constants. +const OMEGA = (2 * Math.PI) / 0.3; +const START_VELOCITY = 8.773; +const DURATION_MS = 700; +const STEP_MS = 1000 / 120; +const HOLDS = [17, 33, 50]; + +/** + * How a change takes its start. `next-frame`: the animation is made in the + * tap's task, and script sets its start to the clock read in the first frame + * after that task, as NavigationStack starts a tap's change today. + * `presented`: it is made two frames after the tap, once the frame at rest + * has been presented, and the browser dates it. `browser`: it is made in the + * tap's task, and the browser dates it. + */ +type StartMode = 'next-frame' | 'presented' | 'browser'; + +const START_MODES: ReadonlyArray = [ + 'next-frame', + 'presented', + 'browser', +]; + +const styles = stylex.create({ + columns: { + position: 'absolute', + inset: 0, + display: 'flex', + }, + column: { + position: 'relative', + flexGrow: 1, + flexBasis: 0, + overflow: 'hidden', + borderInlineEndWidth: 1, + borderInlineEndStyle: 'solid', + borderInlineEndColor: 'rgba(0, 0, 0, 0.2)', + }, + root: { + position: 'absolute', + inset: 0, + overflowY: 'auto', + paddingTop: 20, + }, + card: { + position: 'absolute', + inset: 0, + overflowY: 'auto', + paddingTop: 20, + backgroundColor: 'Canvas', + boxShadow: '-2px 0 12px rgba(0, 0, 0, 0.2)', + translate: '100% 0', + // Mobile Safari runs an animation whose start script sets on its + // compositor only for an element that already has a compositing layer. + willChange: 'translate', + }, + bar: { + display: 'flex', + alignItems: 'center', + gap: 8, + paddingInline: 12, + paddingBlock: 8, + }, +}); + +/** The share of its travel the push spring has covered `t` seconds in. */ +function springTravel(t: number): number { + return 1 - (1 + (OMEGA - START_VELOCITY) * t) * Math.exp(-OMEGA * t); +} + +/** + * The change's keyframes, from `from` to `to` px, sampled at 120 Hz, after + * `hold` ms at `from`. A hold covers the frames a compositor runs before the + * screen first shows a new animation. + */ +function springKeyframes(from: number, to: number, hold: number): Keyframe[] { + const total = hold + DURATION_MS; + const frames: Keyframe[] = + hold > 0 ? [{offset: 0, translate: `${from}px 0`}] : []; + for (let ms = 0; ms < DURATION_MS; ms += STEP_MS) { + frames.push({ + offset: (hold + ms) / total, + translate: `${from + (to - from) * springTravel(ms / 1000)}px 0`, + }); + } + frames.push({offset: 1, translate: `${to}px 0`}); + return frames; +} + +function parseStart(value: string | null): StartMode { + return START_MODES.find(mode => mode === value) ?? 'next-frame'; +} + +const round = (ms: number) => Math.round(ms * 10) / 10; + +/** The width a card travels: its column's, or the page's. */ +function widthOf(card: HTMLElement): number { + return card.parentElement?.clientWidth ?? card.clientWidth; +} + +interface SlidingCardProps { + start: StartMode; + work: number; + hold: number; + /** Names the card in its readout lines and its rows, when there are two. */ + label?: string; + addLine: (line: string) => void; +} + +/** A list, and a card over it that a row's tap slides in and Back out. */ +function SlidingCard({start, work, hold, label, addLine}: SlidingCardProps) { + const cardRef = useRef(null); + const shownRef = useRef<'root' | 'card'>('root'); + // The card starts at the trailing edge in px, which the page's watch reads + // from the computed translate. + const attachCard = useCallback((card: HTMLDivElement | null) => { + cardRef.current = card; + if (card != null) { + card.style.translate = `${widthOf(card)}px 0`; + } + }, []); + + const change = useCallback( + (kind: 'push' | 'pop') => { + const card = cardRef.current; + if (card == null || (kind === 'push') !== (shownRef.current === 'root')) { + return; + } + shownRef.current = kind === 'push' ? 'card' : 'root'; + const tapped = performance.now(); + const width = widthOf(card); + const from = kind === 'push' ? width : 0; + const to = kind === 'push' ? 0 : width; + let startedMs: number | null = null; + const run = () => { + const animation = card.animate(springKeyframes(from, to, hold), { + duration: hold + DURATION_MS, + fill: 'forwards', + }); + animation.finished.then( + () => { + card.style.translate = `${to}px 0`; + animation.cancel(); + }, + () => {}, + ); + if (start === 'next-frame') { + requestAnimationFrame(() => { + const at = performance.now(); + if ( + animation.startTime == null && + animation.playState === 'running' + ) { + animation.startTime = at; + } + startedMs = round(at - tapped); + }); + } else { + animation.ready.then( + () => { + const time = animation.startTime; + startedMs = + typeof time === 'number' ? round(time - tapped) : null; + }, + () => {}, + ); + } + }; + if (start === 'presented') { + requestAnimationFrame(() => requestAnimationFrame(run)); + } else { + run(); + } + if (work > 0) { + // In the tap's own task, after the call, as a later listener's work. + busyFor(work); + } + watchFirstMove( + card, + tapped, + () => from, + () => to, + move => { + addLine( + `${label == null ? '' : `${label}, `}${kind}: started ${startedMs ?? '?'} ms after the tap (document timeline); first moved frame ${move.ms} ms after the tap, at ${Math.round(move.travel * 100)}% of its travel (page clock)`, + ); + }, + ); + }, + [start, work, hold, label, addLine], + ); + + return ( + <> +
+ + {ITEMS.map(item => ( + change('push')} + /> + ))} + +
+
+
+
+ + {ITEMS.map(item => ( + + ))} + +
+ + ); +} + +function MotionStartClockCell() { + const [params] = useSearchParams(); + const start = parseStart(params.get('start')); + const work = queryNumber(params, 'work', 0); + const hold = queryNumber(params, 'hold', 0); + const compare = queryNumber(params, 'compare', 0); + const [lines, addLine] = useReadoutLines(); + + return ( + <> + {compare > 0 ? null : } + + {compare > 0 ? ( +
+
+ +
+
+ +
+
+ ) : ( + + )} +
+ [ + {label: mode, href: `${PAGE}?start=${mode}`}, + { + label: `${mode} + 300 ms`, + href: `${PAGE}?start=${mode}&work=300`, + }, + ]), + ...HOLDS.map(ms => ({ + label: `next-frame, hold ${ms} ms`, + href: `${PAGE}?start=next-frame&hold=${ms}`, + })), + ...HOLDS.map(ms => ({ + label: `current vs hold ${ms} ms`, + href: `${PAGE}?compare=${ms}`, + })), + ]} + lines={[ + compare > 0 + ? `current vs hold ${compare} ms · start: ${start} · ${work} ms of work in the tap's task · tap a row on either side` + : `start: ${start} · ${work} ms of work in the tap's task · hold ${hold} ms · the first frame must show 0% of the travel`, + ...lines, + ]} + /> + + ); +} + +export default function MotionStartClockPage() { + return ( + + + + ); +} diff --git a/apps/sandbox/src/app/(raw)/pages/navstack-current-proposed/page.tsx b/apps/sandbox/src/app/(raw)/pages/navstack-current-proposed/page.tsx new file mode 100644 index 0000000000000..20e1e2988c381 --- /dev/null +++ b/apps/sandbox/src/app/(raw)/pages/navstack-current-proposed/page.tsx @@ -0,0 +1,285 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file page.tsx + * @input `?mode=current|proposed` (proposed by default) + * @output One chat app on a full-page NavigationStack, twice: with today's + * stack (Current) and with its opt-in options (Proposed). A switch at the + * top changes between them, and a line says what to try + * @position A raw page to try NavigationStack's opt-in options on a phone: a + * reopened chat keeps its draft and scroll, a pressed row renders its chat + * ahead, a chat brings its own scroller with a docked composer, the root + * keeps its own header, and New chat opens at once with the keyboard + */ + +import {Suspense, useState, type ReactNode} from 'react'; +import {flushSync} from 'react-dom'; +import {useSearchParams} from 'react-router-dom'; +import * as stylex from '@stylexjs/stylex'; +import { + NavigationScreen, + NavigationStack, + useNavigationLink, + useNavigationScroller, + useNavigationStack, +} from '@astryxdesign/lab'; +import {Button} from '@astryxdesign/core/Button'; +import {HStack, VStack} from '@astryxdesign/core/Layout'; +import {List, ListItem} from '@astryxdesign/core/List'; +import { + SegmentedControl, + SegmentedControlItem, +} from '@astryxdesign/core/SegmentedControl'; +import {Text} from '@astryxdesign/core/Text'; +import {TextInput} from '@astryxdesign/core/TextInput'; + +type Mode = 'current' | 'proposed'; + +const CHATS = Array.from({length: 24}, (_, index) => `Chat ${index + 1}`); + +const HINTS: Record = { + current: + 'Open a chat, type a draft and scroll it, go back and open it again: it starts over. New chat slides in.', + proposed: + 'Open a chat, type a draft and scroll it, go back and open it again: it is as you left it. New chat opens at once.', +}; + +const styles = stylex.create({ + page: { + position: 'fixed', + inset: 0, + display: 'flex', + flexDirection: 'column', + }, + top: { + paddingTop: 'max(8px, env(safe-area-inset-top))', + paddingInline: 12, + paddingBottom: 8, + }, + stack: { + flex: 1, + minHeight: 0, + position: 'relative', + }, + ownScroller: { + flex: 1, + minHeight: 0, + overflowY: 'auto', + overscrollBehavior: 'contain', + }, + inset: (height: number) => ({ + paddingTop: height, + }), + composer: { + padding: 8, + }, +}); + +/** A chat's draft, its sent messages and its earlier messages. */ +function Chat({chat, ownScroller}: {chat: string; ownScroller: boolean}) { + const [draft, setDraft] = useState(''); + const [sent, setSent] = useState([]); + const messages = ( + + {Array.from({length: 60}, (_, index) => ( + + ))} + {sent.map((message, index) => ( + + ))} + + ); + const composer = ( + + +