Skip to content

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

TypeScript

chore(hooks): source comments explain only non-obvious reasons (1 of 2) (#9514)

Cindy Zhang3be0fbcf658a
diff --git a/.changeset/hooks-comment-cleanup.md b/.changeset/hooks-comment-cleanup.md
new file mode 100644
index 0000000000..6338ca2848
--- /dev/null
+++ b/.changeset/hooks-comment-cleanup.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[docs] Source comments in the core hooks are shorter and explain only non-obvious reasons. A few hook doc comments are reworded. Nothing a consumer imports or renders changes.
+
+@cixzhang
diff --git a/packages/core/src/hooks/actionGroupTracker.ts b/packages/core/src/hooks/actionGroupTracker.ts
index 37529246ad..04ea432b64 100644
--- a/packages/core/src/hooks/actionGroupTracker.ts
+++ b/packages/core/src/hooks/actionGroupTracker.ts
@@ -2,56 +2,12 @@
/**
* @file actionGroupTracker.ts
- * @input The elements whose actions are tracked, the actions' selector and
- * hit expansion, and the press paint and fade clocks
- * @output Exports createActionGroupTracker, ActionGroupTracker,
- * ActionGroupTrackerOptions and ActionGroupTarget: UIKit's tracking of a
- * held finger across a group of targets, as a plain object any gesture
- * recognizer can drive
- * @position The one tracker for a held finger that slides onto an action,
- * internal to core. Gesture recognizers drive it: an alert's or an action
- * sheet's long press on its group of actions, a menu trigger whose held
- * finger slides into the menu it opened, a menu's list, a segmented
- * control's segments, a page control's dots
- *
- * UIKit tracks a group of actions (an alert's, an action sheet's, a menu's)
- * as one control, not as separate buttons (measured on iOS 26.2):
- *
- * - the action under the finger highlights; sliding off it cuts its highlight
- * and sliding onto another highlights that one; between or outside the
- * actions nothing is highlighted;
- * - lifting runs the action under the finger, and nothing when there is none;
- * the lifted action's highlight fades (PRESS_FADE_MS);
- * - a press the owner calls inert (an alert during its transitions) is taken
- * but paints and runs nothing.
- *
- * Which target a finger is on is the hit test above by default; an owner
- * whose targets are a row of segments or dots resolves it itself
- * (`resolveTarget`: the nearest segment along the axis, the end one past the
- * ends), from the same rects. The finger's raw position reaches `onMove`
- * (a lens that chases it), and an owner that shows the highlight another way
- * (focus, a dimmed title) turns the paint off and follows
- * `onHighlightChange(next, previous)`.
- *
- * Nothing reads layout after a press begins: the actions' rects are read once
- * in `begin`, then hit-tested; `offsetBy` shifts them when the content moves
- * under a still finger (autoscroll). A move costs at most two attribute writes
- * and never a render. The action runs through its own `click()` inside `end`,
- * so the recognizer must call `end` from the lift's event (its touchend): that
- * keeps the user activation and every click handler. `onActivated` learns
- * whether a handler cancelled that click (`preventDefault()` vetoes, and the
- * owner can undo its visual at once). A recognizer that does not claim the
- * touch leaves the browser its own click for it; `swallowsNativeClick` takes
- * that one click, so the action runs exactly once (the swallower listens only
- * from that lift until the click, or the next press or key).
- *
- * This is core's one track-across-items loop. Menus still run their own copy
- * of it in useMenuPress.ts; the change after the in-flight menu press work
- * moves that copy here, and useMenuPress keeps only its menu-only parts (a
- * trigger's press or held finger opening the menu, the settle rule, edge
- * autoscroll, the highlight as DOM focus). Add no third copy meanwhile.
- * Nothing in core drives this tracker yet; its first adopters (the segmented
- * control and the action groups) arrive in their own changes.
+ * @input The tracked elements, the action selector and hit expansion, and the
+ * press paint and fade clocks
+ * @output createActionGroupTracker, ActionGroupTracker,
+ * ActionGroupTrackerOptions, ActionGroupTarget
+ * @position Internal core tracker for a held finger that slides across a
+ * group of actions. Gesture recognizers drive it.
*
* SYNC: When modified, update actionGroupTracker.test.ts
*/
@@ -171,11 +127,11 @@ interface TrackedAction {
}
/**
- * The browser's own click for a touch the lift already acted on: swallowed
- * once, by listeners that exist only from that lift until the click, or the
- * next press or key (whichever comes first). An activation with
- * `detail === 0` (a key, assistive technology) is not that click: it always
- * passes, and the swallower keeps waiting (`spec:AST-094` FR21).
+ * Swallow the browser's own click for a touch that the lift already acted
+ * on. The listeners exist only from that lift until the click, the next
+ * press, or the next key. An activation with `detail === 0` (a key or
+ * assistive technology) always passes, and the swallower keeps waiting
+ * (`AST-094`).
*/
function swallowNextClick(view: Window): void {
const disarm = () => {
@@ -221,6 +177,18 @@ function clickAndReport(element: HTMLElement): boolean {
/**
* Create a tracker. `getOptions` is read on every call, so a hook can pass
* the latest props without recreating it.
+ *
+ * The tracker treats a group of actions as one control, as UIKit does:
+ * - The action under the finger highlights. Between or outside the actions,
+ * nothing highlights.
+ * - The lift runs the action under the finger, and its highlight fades.
+ * - An inert press is taken but paints and runs nothing.
+ *
+ * Layout is read only in `begin`. `offsetBy` shifts the cached rects when
+ * the content moves under a still finger. The action runs through its own
+ * `click()` in `end`, so call `end` from the lift's event to keep the user
+ * activation. useMenuPress.ts has its own copy of this loop. Do not add a
+ * third copy.
*/
export function createActionGroupTracker(
getOptions: () => ActionGroupTrackerOptions,
diff --git a/packages/core/src/hooks/menuPressGesture.ts b/packages/core/src/hooks/menuPressGesture.ts
index d33c49ba22..362cb57961 100644
--- a/packages/core/src/hooks/menuPressGesture.ts
+++ b/packages/core/src/hooks/menuPressGesture.ts
@@ -3,32 +3,10 @@
/**
* @file menuPressGesture.ts
* @input A menu press gesture and one pointer event, both as plain data
- * @output Exports the pure `menuPressStep` state machine, its state, event and
- * effect types, and the settle constant
- * @position Pure module under `useMenuPress`; no DOM, no React, so every
- * transition is unit-testable without a browser
- *
- * The press model shared by every Astryx menu and picker: the row under the
- * pointer when it is RELEASED is the row that acts, and the highlight follows
- * the pointer while it is held. It is the model of macOS and iOS menus.
- *
- * States:
- * - `idle` — no gesture is live.
- * - `triggerPress` — a finger rests on the trigger; the menu is not open yet.
- * A mouse skips this state: a mouse press on the trigger opens at once.
- * - `open` — the menu opened under a held pointer (a mouse press, or a finger
- * held for the long-press delay) and the pointer has not entered it yet.
- * - `tracking` — the pointer is held and the highlight follows it.
- *
- * The settle rule: the release of the gesture that OPENED the menu acts only
- * once the pointer has entered the menu or the press has lasted
- * `MENU_PRESS_SETTLE_MS`; otherwise it acts on nothing and the menu stays
- * open. Without it a menu that opens under the pointer would pick a row
- * nobody chose.
- *
- * Rows are opaque (`T`): the machine never touches the DOM. The hook resolves
- * the enabled row under the pointer and feeds it in; `null` means the pointer
- * is over a divider, a heading, a disabled row, or outside the menu.
+ * @output The pure `menuPressStep` state machine, its state, event and effect
+ * types, and the settle constant
+ * @position Pure module under `useMenuPress`. It has no DOM and no React, so
+ * a unit test can check each transition without a browser.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/menuPressGesture.test.ts
@@ -135,6 +113,23 @@ function release<T>(
/**
* Advance the gesture by one event. Pure: same inputs, same output.
+ *
+ * The row under the pointer at the release acts, and the highlight follows
+ * the held pointer, as in macOS and iOS menus. The states:
+ * - `idle`: no gesture is live.
+ * - `triggerPress`: a finger rests on the trigger, and the menu is not open
+ * yet. A mouse press on the trigger skips this state and opens at once.
+ * - `open`: the menu opened under a held pointer, and the pointer has not
+ * entered it yet.
+ * - `tracking`: the pointer is held, and the highlight follows it.
+ *
+ * The settle rule: the release of the opening gesture acts only after the
+ * pointer entered the menu or the press lasted `MENU_PRESS_SETTLE_MS`. Else a
+ * menu that opens under the pointer would pick a row that nobody chose.
+ *
+ * Rows are opaque (`T`). The hook feeds in the enabled row under the
+ * pointer, or `null` over a divider, a heading, a disabled row, or outside
+ * the menu.
*/
export function menuPressStep<T>(
gesture: MenuPressGesture<T>,
@@ -209,10 +204,10 @@ function stepTriggerPress<T>(
// it must pass, and no gesture is live afterwards.
return idle({type: 'settle', stray: false, dismiss: false});
case 'cancel':
- // The browser took the gesture (an incoming call, a system gesture).
- // Settle rather than going quiet: a held finger has already installed
- // the document's touchmove preventer, and only the end of a gesture
- // takes it back off. No click follows a cancelled pointer.
+ // The browser took the gesture, for example for a system gesture.
+ // Settle and do not go idle: a held finger installed the document's
+ // touchmove preventer, and only the end of a gesture removes it. No
+ // click follows a cancelled pointer.
return idle({type: 'settle', stray: false, dismiss: false});
case 'down':
case 'move':
diff --git a/packages/core/src/hooks/useAnnounce.ts b/packages/core/src/hooks/useAnnounce.ts
index 5c9059fefd..f528e8e441 100644
--- a/packages/core/src/hooks/useAnnounce.ts
+++ b/packages/core/src/hooks/useAnnounce.ts
@@ -4,29 +4,12 @@
/**
* @file useAnnounce.ts
- * @input Uses React context and useCallback; DOM APIs and cancellable
- * animation frames for a singleton live-region pair on the page body and
- * one persistent polite/assertive pair inside each open Astryx modal
- * @output Exports useAnnounce hook (with its `hasReplace` option),
- * AnnouncePoliteness and UseAnnounceOptions types; the internal modal
- * context, the in-dialog region writer the busy-announcement hook uses, and
- * the hook the modal route (`modalAnnounce.ts`, loaded only with an Astryx
- * modal) installs itself through
- * @position Core a11y hook; provides imperative screen-reader announcements.
- * A message follows the nearest open native modal enclosing its caller
- * (`spec:AST-086` FR14): inside an Astryx modal it is written to that
- * dialog's own containers, since the page-body channel is not exposed
- * while a native modal is open; otherwise to the shared page-body pair.
- * Containers are created empty (FR3), carry the two urgencies (FR5), join
- * messages written before the previous is exposed and say an identical
- * same-frame repeat once (FR9), except that a `hasReplace` instance's
- * message withdraws that instance's previous one not yet exposed, and clear
- * shortly after each announcement;
- * the route in `modalAnnounce.ts` hands a message still unexposed when its
- * modal stops being exposed to the channel exposed after it — the modal
- * then on top, or the page body once no modal is open. Each write keeps a
- * receipt per announcer beside the words, which follows them wherever
- * they are moved, so the announcer can take back its own share.
+ * @input React context; DOM live regions; animation frames
+ * @output useAnnounce, AnnouncePoliteness, UseAnnounceOptions; the internal
+ * modal context, in-dialog region writer, and modal route hook
+ * @position Core a11y hook for screen-reader announcements. A message goes to
+ * the nearest open native modal around its caller, else to the shared
+ * page-body regions. `modalAnnounce.ts` holds the modal route.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
@@ -54,13 +37,10 @@ export type AnnounceFn = (
/** Options for `useAnnounce`. */
export interface UseAnnounceOptions {
/**
- * The instance states one current state of its owner, such as a search's
- * result count: each message it writes withdraws the instance's previous
- * message while that one is not yet exposed, whatever their urgencies, and
- * is spoken in the region of its own urgency; a message already exposed has
- * been heard and stays. Messages from other instances, and from instances
- * without `hasReplace`, still join (`spec:AST-086` FR9). Give each state a
- * component reports its own instance.
+ * Each message from this instance withdraws the instance's previous message
+ * if assistive technology has not exposed it yet, whatever its urgency. An
+ * exposed message stays. Messages from other instances still join. Use one
+ * instance for each state that a component reports, such as a result count.
* @default false
*/
hasReplace?: boolean;
@@ -104,8 +84,8 @@ export function handleOf(receipt: AnnounceReceipt): WithdrawAnnouncement {
/**
* Move `waiting` words elsewhere, one delivery per announcer and in order,
* and point each receipt at its delivery, so every announcer can still take
- * back its own share (`spec:AST-086` FR9, FR14). The deliveries join where
- * they land, so the words are spoken once. @internal
+ * back its own share. The deliveries join where they land, so the words are
+ * spoken once. @internal
*/
export function forwardWaiting(
waiting: ReadonlyArray<WaitingWords>,
@@ -120,8 +100,8 @@ export function forwardWaiting(
const CONTAINER_ATTR = 'data-astryx-live-region';
-// Visually-hidden clip block (matches the VisuallyHidden primitive). Applied
-// inline so the regions work without any stylesheet being present.
+// The same clip as VisuallyHidden. It is inline, so the regions work without
+// a stylesheet.
const VISUALLY_HIDDEN_CSS =
'position:absolute;width:1px;height:1px;margin:-1px;padding:0;' +
'overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;' +
@@ -134,10 +114,8 @@ interface LiveRegions {
}
/**
- * How long an announcement stays in its region before being auto-cleared.
- * Long enough for screen readers to pick the message up and finish reading
- * it; clearing afterwards keeps stale status text out of the accessibility
- * tree for users who browse the DOM later. Each announce resets the timer.
+ * Screen readers need this time to read the message. The clear then keeps
+ * stale status text out of the accessibility tree.
*/
const CLEAR_DELAY_MS = 2000;
@@ -156,17 +134,15 @@ function cancelScheduledClear(politeness: AnnouncePoliteness): void {
}
}
-// Messages announced before the region exposes them (written in the same
-// frame) wait here and are exposed together, in order, so none is dropped;
-// an identical repeat is the same message and is kept once (spec:AST-086
-// FR9). One frame per region writes them.
+// Messages written before the region exposes them wait here. One frame
+// exposes them together and in order, so none is dropped. An identical repeat
+// is kept once.
const pendingFrames: Record<AnnouncePoliteness, number | null> = {
polite: null,
assertive: null,
};
-// Each pending message counts the announcers waiting on it, so one of them
-// withdrawing it (a busy start overtaken by its outcome) leaves it in place
-// for the others.
+// Each pending message counts its waiting announcers. When one withdraws it
+// (a busy start overtaken by its outcome), the message stays for the others.
interface PendingMessage {
text: string;
holders: number;
@@ -198,11 +174,9 @@ function scheduleClear(
}, CLEAR_DELAY_MS);
}
-// Singleton: the live regions are created ONCE and stay mounted for the
-// lifetime of the document. This is the crux of reliable announcements — many
-// screen readers will not announce content injected into a live region that is
-// created together with its content ("born with content"). By mounting empty
-// regions up front and only mutating their text later, updates are announced.
+// The live regions are created once and stay mounted. Many screen readers do
+// not announce a live region that is created with its content. They do
+// announce a text change in an empty region that is already mounted.
let regions: LiveRegions | null = null;
function createRegion(politeness: AnnouncePoliteness): HTMLElement {
@@ -221,7 +195,7 @@ function getRegions(): LiveRegions | null {
return null;
}
if (regions) {
- // Re-attach if a region was removed from the DOM (e.g. by a test cleanup).
+ // A test cleanup can remove a region from the DOM. Attach it again.
if (!regions.polite.isConnected) {
document.body.appendChild(regions.polite);
}
@@ -262,11 +236,11 @@ export function announceMessage(
pendingMessages[politeness].push(pending);
lastJoined = pending;
if (pendingFrames[politeness] == null) {
- // Clearing first guarantees the mutation is observed even when the new
- // message equals the current text — some AT deduplicate identical content.
+ // Clear first, so the change is seen when the new text equals the old
+ // text. Some assistive technology ignores identical content.
target.textContent = '';
- // A re-set in the next frame is more reliable across AT than an immediate
- // re-set, which can be coalesced with the clear.
+ // Some assistive technology merges an immediate re-set with the clear. A
+ // re-set in the next frame is more reliable.
pendingFrames[politeness] = requestAnimationFrame(() => {
pendingFrames[politeness] = null;
target.textContent = pendingMessages[politeness]
@@ -275,9 +249,8 @@ export function announceMessage(
pendingMessages[politeness] = [];
});
}
- // Auto-clear so the last message does not linger in the accessibility tree
- // indefinitely. Scheduled per announce, so a newer announcement always
- // resets the countdown (the delay comfortably outlasts the rAF re-set).
+ // The clear keeps the last message out of the accessibility tree. Each
+ // announce restarts the delay, which is much longer than the frame re-set.
scheduleClear(politeness, target);
return () => withdrawPendingAnnouncement(pending, politeness);
}
@@ -313,7 +286,7 @@ export function clearRegion(politeness: AnnouncePoliteness): void {
* An instance created with `hasReplace` states one current state, such as a
* search's result count: each message it writes withdraws its previous one
* while that one is not yet exposed, so typing faster than a frame says only
- * the latest count (`spec:AST-086` FR9).
+ * the latest count.
*
* @param options - `hasReplace` (default false)
* @example
@@ -331,8 +304,8 @@ export function useAnnounce({
hasReplace = false,
}: UseAnnounceOptions = {}): AnnounceFn {
const modal = use(ModalAnnounceContext);
- // A `hasReplace` instance's latest write, which its next message takes back
- // if assistive technology has not had it yet.
+ // The latest write of a `hasReplace` instance. Its next message withdraws
+ // it if assistive technology has not had it yet.
const withdrawPreviousRef = useRef<WithdrawAnnouncement | null>(null);
return useCallback(
(message: string, politeness: AnnouncePoliteness = 'polite') => {
@@ -342,15 +315,13 @@ export function useAnnounce({
withdrawPrevious?.();
}
let written: WithdrawAnnouncement | null;
- // Inside an Astryx modal's provider: the modal route decides, per call,
- // where the caller is heard — `modal` is non-null only where a provider
- // rendered, and rendering one loads the route.
+ // `modal` is non-null only below a provider, and a provider loads the
+ // route. The route decides where the caller is heard.
if (modal != null && modalRoute != null) {
written = modalRoute.announce(modal, message, politeness);
} else if (!message) {
- // An empty message clears any lingering status from the region,
- // including messages joined but not yet exposed — useful when the
- // triggering context ends.
+ // An empty message clears the region, with the messages that are
+ // not yet exposed.
clearRegion(politeness);
written = null;
} else {
@@ -364,20 +335,13 @@ export function useAnnounce({
);
}
-// =============================================================================
-// Inside an Astryx modal (spec:AST-086 FR14)
-// =============================================================================
+// Inside an Astryx modal (AST-086 FR14)
//
-// `useAnnounce` reads the nearest ModalAnnounceProvider's scope. The route a
-// scope implies — exposure, the top-layer order, hand-off and hold on close,
-// the covered rule, deferral while a modal is being presented — lives in
-// `modalAnnounce.ts`, which ModalAnnounceProvider imports and which installs
-// itself here when it loads. A context value is non-null only where a
-// provider rendered, so the route is installed before it is needed, and a
-// component that calls `useAnnounce` but renders no modal never loads it.
-// What stays in this module is what a caller without any Astryx modal still
-// needs: the region writer the busy-announcement hook uses inside a native
-// modal an app renders without Astryx, and the DOM walk that finds it.
+// The modal route lives in `modalAnnounce.ts`. ModalAnnounceProvider imports
+// it, and it installs itself here when it loads. A component that calls
+// `useAnnounce` but renders no modal never loads it. This module keeps what a
+// caller without an Astryx modal needs: the region writer for a native modal
+// that an app renders, and the DOM walk that finds that modal.
const MODAL_REGION_ATTR = 'data-astryx-modal-live-region';
@@ -388,8 +352,8 @@ const MODAL_REGION_ATTR = 'data-astryx-modal-live-region';
*/
export interface ModalAnnounceScope {
dialogRef: RefObject<HTMLDialogElement | null>;
- // The owner's intent: open (or presented) in this render. A dialog meant
- // to be open that is not open yet is being presented in this commit.
+ // The owner's intent: open or presented in this render. A dialog that is
+ // meant to be open but is not open yet is being presented in this commit.
isOpen: boolean;
parent: ModalAnnounceScope | null;
}
@@ -440,7 +404,7 @@ export function isOpenModal(
* The nearest open native modal dialog enclosing `element` in the DOM, Astryx
* or app-rendered. Internal: the busy-announcement hook routes by its owner's
* element so a busy start inside a native modal an app renders without Astryx
- * is still heard inside it (`spec:AST-086` FR14, last sentence).
+ * is still heard inside it.
*/
export function enclosingModalDialog(
element: Element | null | undefined,
@@ -463,8 +427,7 @@ export function enclosingModalDialog(
* written to the dialog while it is open as a modal, else to the shared
* channel. Returns how to take the words back while they wait, wherever they
* move, so a busy start overtaken by its own outcome is never heard ahead of
- * it inside a modal (`spec:AST-086` FR8). Internal: used by the
- * busy-announcement hook.
+ * it inside a modal. Internal: used by the busy-announcement hook.
*/
export function announceInModal(
dialog: HTMLDialogElement,
@@ -487,18 +450,15 @@ export interface ModalWriteGuard {
redirect: (waiting: ReadonlyArray<WaitingWords>) => void;
}
-// Each in-dialog region's pending state: the messages written since its text
-// was last exposed, the frame that will expose them joined, the frame after
-// that (text set in one frame is not yet taken by assistive technology in
-// that same frame, so a message arriving before this frame runs still joins
-// rather than wiping the words), and the timer that clears them afterwards.
+// The pending state of each in-dialog region: the messages written since its
+// text was last exposed, the frame that exposes them, the next frame, and the
+// clear timer. Assistive technology does not take text in the frame that sets
+// it. So a message that arrives before the next frame joins the words.
interface ModalPending {
messages: string[];
- // The announcers waiting on each message, one receipt each: one taking its
- // share back (a busy start overtaken by its outcome, a `hasReplace`
- // instance's next message) leaves the message for the others. A fresh map
- // once the words are exposed, so a receipt never reaches equal words
- // written after its own were exposed.
+ // One receipt for each announcer of a message. When one announcer withdraws
+ // its share, the message stays for the others. The map is new after each
+ // exposure, so a receipt never reaches equal words written later.
receipts: Map<string, AnnounceReceipt[]>;
frame: number | null;
settleFrame: number | null;
@@ -611,8 +571,8 @@ export function writeModalRegion(
if (previous != null) {
cancelPending(previous);
}
- // Clearing first guarantees the mutation is observed even when the new
- // message equals the current text — some AT deduplicate identical content.
+ // Clear first, so the change is seen when the new text equals the old
+ // text. Some assistive technology ignores identical content.
target.textContent = '';
const pending: ModalPending = {
messages,
@@ -624,8 +584,8 @@ export function writeModalRegion(
pending.frame = requestAnimationFrame(() => {
pending.frame = null;
if (guard != null && !guard.isExposed()) {
- // Stopped being exposed between the call and this frame: the words go
- // where they will be heard, their receipts with them.
+ // The region stopped being exposed after the call. Send the words and
+ // their receipts to where they will be heard.
pendingByRegion.delete(target);
guard.redirect(waitingIn(pending));
return;
@@ -646,12 +606,10 @@ export function writeModalRegion(
/**
* Withdraw one announcer's share of `message` from `target` while it is not
- * yet exposed — written but not yet spoken — so a busy start overtaken by its
- * own outcome is never heard ahead of it (`spec:AST-086` FR8), and a
- * `hasReplace` instance's next message replaces its previous one (FR9,
- * FR14). The message stays while another announcer holds it; a receipt not
- * among the waiting words (they were exposed, cleared, or moved) takes back
- * nothing.
+ * yet exposed. Then a busy start overtaken by its outcome is never heard, and
+ * a `hasReplace` instance's next message replaces its previous one. The
+ * message stays while another announcer holds it. A receipt that is not among
+ * the waiting words takes back nothing.
*/
function withdrawFromRegion(
target: HTMLElement,
@@ -720,9 +678,10 @@ export function takeJoinedAnnouncement(): object | null {
return joined;
}
+// A busy start overtaken by its own outcome is never spoken (AST-086 FR8).
/**
* Withdraws one announcer's share of a message still waiting to be exposed, so
- * a busy start overtaken by its own outcome is never spoken (spec:AST-086 FR8).
+ * a busy start overtaken by its own outcome is never spoken.
* The message stays while another announcer still holds it.
*
* @internal
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.ts
index d21cccb6eb..90a920efc9 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.ts
+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts
@@ -4,45 +4,27 @@
/**
* @file useAnnounceRenderedText.ts
- * @input A ref to a rendered element, whether it is showing, and a token that
- * marks a new occasion to speak
- * @output Announces that element's own rendered text through the persistent
- * polite live region, or through the announcer the owner passes
- * @position Core a11y hook; mirrors on-screen content into the shared live
- * region by reading the DOM
- *
- * Some content reaches assistive technology only through a live region: a
- * panel message marked `role="presentation"`, for instance, because
- * `role="listbox"` permits only `option` and `group` children. When that
- * content is a caller-supplied `ReactNode`, the component must announce what
- * it actually rendered — announcing a built-in default over a caller's
- * element tells the screen-reader user something the sighted user is not
- * reading (`spec:AST-056` AR1, FR3).
- *
- * The text is read from the DOM after render, never by inspecting React
- * children. That is the whole point: by the time this runs the browser has
- * rendered the subtree, so text a child component generates inside its own
- * render announces correctly, and there is no tree walk, no depth limit, and
- * no "could not read it" fallback to get wrong.
- *
- * Announcing through the persistent `useAnnounce` region rather than putting
- * `role="status"` on the rendered element is both required here — the element
- * is a listbox child, which may only be `option` or `group` — and the
- * repository's established convention for conditionally rendered messages
- * (see `FieldStatus` and `TimeInput`): a live region that mounts together
- * with its content is not reliably announced.
- *
- * Content hidden with `aria-hidden` or `hidden` is excluded,
- * so a decorative icon stays out of the announcement exactly as it stays out
- * of what a screen reader reads. An `aria-label` renaming a descendant is NOT
- * substituted — the region speaks the rendered text.
- *
- * SYNC: deliberately NOT exported from /packages/core/src/hooks/index.ts —
- * that barrel is re-exported wholesale from the package entry point, so
- * adding it there would ship a new public hook without `spec:AST-002`
- * admission. Import it by path from inside the package.
+ * @input A ref to a rendered element, whether it shows, and a token for each
+ * new occasion to speak
+ * @output Announces the element's rendered text through the polite live
+ * region, or through the owner's announcer
+ * @position Core a11y hook. It is not in hooks/index.ts, because that barrel
+ * is public and a new public hook needs admission (AST-002). Import it by
+ * path.
*/
+// Some content reaches assistive technology only through a live region. For
+// example, a listbox permits only `option` and `group` children, so a panel
+// message in it has `role="presentation"`. When that content is a caller's
+// `ReactNode`, announce what was rendered, not a built-in default (AST-056,
+// AST-086).
+//
+// The text comes from the DOM after render, not from React children, so text
+// that a child component generates is included. A live region that mounts
+// with its content is not reliably announced, so the persistent `useAnnounce`
+// region speaks it. Content with `aria-hidden` or `hidden` is left out. An
+// `aria-label` on a descendant is not used.
+
import {useEffect, useRef, useState, type RefObject} from 'react';
import {
useAnnounce,
@@ -82,23 +64,22 @@ function blockText(element: HTMLElement): string {
export interface AnnounceRenderedTextOptions {
/**
- * Text present or changed while the document loads or hydrates is silent;
- * text that appears or changes later is announced once (`spec:AST-086`
- * FR11). A mounted live container speaks its own content (FR4); each child is
- * a block; a reveal without a re-render is read on the next render (FR13).
+ * Text that is present or changes while the document loads or hydrates is
+ * silent. Text that appears or changes later is announced once. A mounted
+ * live container speaks its own content, and each child is a block. A
+ * reveal without a re-render is read on the next render.
*/
skipFirstRender?: boolean;
/**
- * The channel's urgency: errors and time-critical failures are assertive,
- * every other message polite (`spec:AST-086` FR5). Defaults to polite.
+ * The urgency: assertive for errors and time-critical failures, else
+ * polite. Defaults to polite.
*/
politeness?: AnnouncePoliteness;
/**
- * The owner's announcer to speak through, when the rendered text states
- * the next value of a state that announcer states: a picker's empty-panel
- * message goes through its search's `hasReplace` instance, so the two
- * replace each other while not yet exposed (`spec:AST-086` FR13).
- * Defaults to this hook's own instance.
+ * The owner's announcer, when the rendered text states the next value of
+ * that announcer's state. For example, a picker's empty-panel message goes
+ * through its search's `hasReplace` instance, so the two replace each other
+ * while not yet exposed. Defaults to this hook's own instance.
*/
announce?: AnnounceFn;
}
@@ -154,11 +135,9 @@ export function useAnnounceRenderedText(
);
const isFirstRunRef = useRef(true);
- // Deliberately no dependency array. The text lives in the DOM, so there is
- // no React value to depend on that changes when it does — a caller can
- // change the rendered message without any prop this hook can see. Reading
- // one element's text per render is cheap, and the dedupe below makes every
- // render after the first a no-op.
+ // No dependency array: the text lives in the DOM, and a caller can change it
+ // without a prop that this hook sees. One text read per render is cheap, and
+ // the dedupe below makes later renders no-ops.
useEffect(() => {
const isFirstRun = isFirstRunRef.current;
isFirstRunRef.current = false;
diff --git a/packages/core/src/hooks/useContainerReveal.ts b/packages/core/src/hooks/useContainerReveal.ts
index 6e19b32527..3bfb448ee2 100644
--- a/packages/core/src/hooks/useContainerReveal.ts
+++ b/packages/core/src/hooks/useContainerReveal.ts
@@ -4,42 +4,10 @@
/**
* @file useContainerReveal.ts
- * @input Uses the containerReveal styles
- * @output Exports useContainerReveal — a headless hover/focus reveal primitive
- * @position Core hook. Consumed by any component that reveals (or conceals)
- * content when its container is hovered or focused — e.g. Thumbnail's remove
- * button, TreeList row actions.
- *
- * Gives a container a scoped hover/focus-within trigger that reveals or
- * conceals content inside it, entirely in CSS (no hover state in JS, no
- * re-render on hover). The caller authors NO StyleX: the hook hands out the
- * container style and the matching content styles.
- *
- * Scoping is by inheritance: the container publishes its reveal state as
- * custom properties on itself and the content reads them, so a nested
- * container shadows its ancestor's state for its own subtree. See
- * containerReveal.stylex.ts.
- *
- * Two levers sit on top of the pointer, both still CSS-only. On the container:
- * `hoverDelay` (dwell before the reveal starts — the Tooltip / HoverCard
- * intent gate applied to a reveal) and `forceState` (pin the trigger state a
- * caller owns: a motion gate, a scroll, an open menu). On a single piece of
- * content: `forceVisibility`, which pins how THAT element looks. State belongs
- * to the container because one container feeds children whose looks are
- * opposite; appearance belongs to the element, where it is unambiguous.
- * Neither lever can hide content from a keyboard user — see ACCESSIBILITY.
- *
- * ACCESSIBILITY (WCAG 2.2 by construction):
- * - Revealed content is visually hidden at rest via position + opacity, so it
- * stays in the accessibility tree and tab order — never display:none.
- * - Keyboard: revealed on :focus-within, so tabbing in shows it — with no dwell
- * to wait through, and neither an inactive container nor a forced-hidden
- * element can keep it dark.
- * - Touch: always visible on coarse pointers; never gated behind hover.
- * - Concealed (inverted) content is a mouse-only visual swap: it ignores
- * :focus-within (a keyboard user must never watch content vanish) and stays
- * visible on touch and in the a11y tree.
- * - Motion: honors prefers-reduced-motion.
+ * @input The containerReveal styles
+ * @output useContainerReveal, a headless hover and focus reveal primitive
+ * @position Core hook for content that shows or hides when its container is
+ * hovered or focused, such as Thumbnail's remove button
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts (export)
@@ -138,6 +106,11 @@ const EMPTY = Object.freeze({});
/**
* Scoped, CSS-only hover/focus reveal for content inside a container.
*
+ * Revealed content stays in the accessibility tree and the tab order. It
+ * shows on :focus-within without a delay, and it always shows on touch.
+ * Concealed content hides only for a mouse. Motion honors
+ * prefers-reduced-motion.
+ *
* @example
* ```
* const {getContainerProps, getContentRevealProps} = useContainerReveal({
diff --git a/packages/core/src/hooks/useIndicatorFocusRing.tsx b/packages/core/src/hooks/useIndicatorFocusRing.tsx
index ba70a50f2c..fbc2fb0a3f 100644
--- a/packages/core/src/hooks/useIndicatorFocusRing.tsx
+++ b/packages/core/src/hooks/useIndicatorFocusRing.tsx
@@ -10,43 +10,19 @@
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts (exports)
- *
- * A checkbox or radio focuses a native `<input>` that is `opacity: 0`, so the
- * visible focus indicator has to appear on the picture beside it — and that
- * picture is a themeable indicator, which is what makes "who draws the ring"
- * awkward:
- *
- * - Only the indicator's own element can shape the ring: `outline` follows
- * that element's `border-radius`. Draw it on a wrapper and the owner has to
- * hardcode a guess about whatever indicator it hosts (RadioListItem used to
- * carry `border-radius: 50%` for a circle it did not own).
- * - But an indicator supplied by a theme is third-party code. If drawing the
- * ring is its job, a replacement that simply doesn't ships a control with no
- * visible focus (WCAG 2.4.7) — and that is the DEFAULT outcome: the sample
- * replacement in our own Storybook destructures `{state, size, isDisabled}`
- * and drops the rest, which is what a theme author plausibly writes. Nothing
- * can enforce otherwise; a component ignoring every prop is still assignable
- * to `IndicatorComponent`, and branding the return type does not work either
- * (JSX types every expression as `JSX.Element`).
- *
- * So the owner draws it, on the indicator's own element, imperatively at focus
- * time. No cooperation is required and none can be forgotten.
- *
- * Two details that are load-bearing, both measured rather than assumed:
- *
- * 1. **Inline style, not a class.** React replaces `className` wholesale on
- * re-render, so an injected class disappears the moment the control changes
- * state — pressing Space on a focused checkbox lost the ring. React
- * reconciles `style` per property, so an `outline` set here survives.
- * 2. **`:focus-visible`, not `:focus`.** The CSS this replaces got
- * keyboard-vs-pointer for free; an event handler has to ask. Checking the
- * element keeps the browser's heuristic, including `focus({focusVisible:
- * true})`, which a hand-rolled modality guess would miss.
- *
- * Imperative styling on an interaction event follows `useTableSelection`,
- * which sets row-selection styles the same way.
*/
+// The owner draws the ring on the indicator's own element, at focus time:
+// - Only that element can shape the ring, because `outline` follows its
+// `border-radius`.
+// - A theme can replace the indicator, and a replacement can drop any prop.
+// If the indicator drew the ring, such a replacement would have no visible
+// focus. No type can make it keep the props.
+// - The ring is an inline style, not a class. React replaces `className` on
+// re-render, but it updates `style` per property, so the outline stays.
+// - The handler checks `:focus-visible`, not focus. This keeps the browser's
+// heuristic, including `focus({focusVisible: true})`.
+
import {useCallback, useMemo} from 'react';
import type {FocusEvent, RefObject} from 'react';
import {
@@ -86,9 +62,8 @@ export function useIndicatorFocusRing(
): UseIndicatorFocusRingReturn {
const paint = useCallback(
(on: boolean) => {
- // `firstElementChild`, not a search: the container holds the indicator
- // and nothing else, so there is no ambiguity — and no way for a later
- // sibling to quietly become the target.
+ // The container holds only the indicator, so its first child is the
+ // target. A later sibling can never become the target.
const indicator = containerRef.current?.firstElementChild;
if (indicator instanceof HTMLElement) {
Object.assign(
diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts
index 0e69fa2ea3..c70cfdcbfa 100644
--- a/packages/core/src/hooks/useLongPress.ts
+++ b/packages/core/src/hooks/useLongPress.ts
@@ -11,30 +11,21 @@
* `useMenuPress` for the held-finger menu open
*
* SYNC: When modified, update the hooks barrel /packages/core/src/hooks/index.ts
- *
- * Detects a single-finger long-press: fires `onLongPress` with the press
- * start point after `delayMs`. Cancels if the finger moves past
- * `moveCancelPx` on either axis (treated as a scroll/drag), lifts, or the
- * touch is cancelled. The pending timer is also cleared on unmount. The
- * default duration and tolerance are the long-press recognizer's
- * (motion/uikit/longPress.ts); the recognizer measures its tolerance as a
- * distance, as UIKit does, and this hook on each axis: the released rule
- * that ContextMenu's hold and the menu trigger keep. GUESS (`spec:AST-094`
- * FR2): the context menu's own movement allowance and press thresholds are
- * not measured yet (motion/MEASUREMENTS.md M-CM3, M-CM6).
- *
- * Two ways in, one detector. Spread the touch handlers onto an element, or —
- * when the caller already runs its own pointer-event machine, as
- * `useMenuPress` does — call `start`, `moveTo` and `cancel` from it. Either
- * way the hold duration, the movement tolerance and the timer are this
- * hook's, so a long press cannot come to mean one thing on a context menu
- * and another on a menu trigger.
- *
- * Motivation: iOS Safari never synthesizes a `contextmenu` event on
- * long-press, so long-press is the only touch affordance for opening
- * cursor-positioned surfaces.
*/
+// iOS Safari sends no `contextmenu` event on a long press. So a long press is
+// the only touch way to open a surface at the press point.
+//
+// A caller can spread the touch handlers, or call `start`, `moveTo` and
+// `cancel` from its own pointer events, as `useMenuPress` does. Both ways use
+// this hook's hold time, movement tolerance and timer, so a long press means
+// the same thing on a context menu and on a menu trigger.
+//
+// The defaults come from the long-press recognizer. The recognizer measures
+// its tolerance as a distance, as UIKit does. This hook measures it on each
+// axis. The context menu's own movement allowance is a guess and is not
+// measured yet (AST-094).
+
import {useCallback, useEffect, useRef} from 'react';
import {
LONG_PRESS_ALLOWABLE_MOVEMENT_PX,
@@ -105,8 +96,8 @@ export function useLongPress(
options: UseLongPressOptions,
): UseLongPressHandlers {
const {start, ...handlers} = useLongPressDetector(options);
- // The public start takes the point only: a per-press tolerance stays
- // internal to its core caller (architecture:public-component-api INV12).
+ // The public start takes only the point. A per-press tolerance stays
+ // internal to its core caller.
const startAt = useCallback(
(point: {x: number; y: number}) => start(point),
[start],
@@ -146,8 +137,8 @@ export function useLongPressDetector(
if (disabled) {
return;
}
- // Clear any stale timer first, THEN record the start point — clearing
- // also nulls startRef, so order matters.
+ // Clear a stale timer first, then record the start point. The clear
+ // also sets startRef to null.
clear();
startRef.current = {x: point.x, y: point.y};
pressToleranceRef.current = tolerance ?? null;
@@ -174,7 +165,6 @@ export function useLongPressDetector(
Math.abs(point.x - from.x) > limit ||
Math.abs(point.y - from.y) > limit
) {
- // Treat as a scroll/drag, not a long-press.
clear();
return false;
}
@@ -189,7 +179,6 @@ export function useLongPressDetector(
return;
}
if (e.touches.length !== 1) {
- // Multi-touch cancels any pending long-press.
clear();
return;
}
@@ -205,7 +194,6 @@ export function useLongPressDetector(
return;
}
if (e.touches.length !== 1) {
- // Multi-touch cancels the pending long-press.
clear();
return;
}
@@ -215,7 +203,6 @@ export function useLongPressDetector(
[clear, moveTo],
);
- // Cancel any pending long-press timer on unmount.
useEffect(() => clear, [clear]);
return {
diff --git a/packages/core/src/hooks/useMenuHover.ts b/packages/core/src/hooks/useMenuHover.ts
index 03c293f972..0bdada81b1 100644
--- a/packages/core/src/hooks/useMenuHover.ts
+++ b/packages/core/src/hooks/useMenuHover.ts
@@ -4,38 +4,30 @@
/**
* @file useMenuHover.ts
- * @input Uses React hooks, useListFocus, useMediaQuery
- * @output Exports useMenuHover hook
- * @position Internal hook; used by nav heading components, TopNavMenu,
- * TopNavMegaMenu and DropdownMenuSubMenu
- *
- * Hover as a progressive enhancement over standard popover behavior: click
- * toggles, Escape and outside-click close, arrows navigate; on top of that,
- * mouseenter opens after a delay and mouseleave closes one that hover opened.
- *
- * Three behaviors here are not obvious and are load-bearing:
- *
- * 1. Hover→click guard (#3121). A hover-opened menu is already open under the
- * cursor when the pointer arrives, so the click that naturally follows would
- * toggle it shut. Within `clickGuardMs` a click instead confirms it: the menu
- * pins and behaves like a click-open from then on.
- *
- * 2. Focus moves synchronously. `useLayer.show()` calls `showPopover()` in the
- * same tick and the layer's children are always mounted, so items are
- * focusable the moment `show()` returns — a `requestAnimationFrame` here
- * lands after paint and races anything else moving focus. Hover-opens are the
- * exception: the pointer is driving, so focus stays on the trigger. The hook
- * always passes `skipAutoFocus` and owns focus itself, because the popover's
- * auto-focus targets the first *tabbable* node while a menu wants its first
- * item — under roving tabindex those are different elements.
- *
- * 3. Native light dismiss. A `popover="auto"` is dismissed by the browser on
- * pointer interaction outside the panel, and a trigger outside the panel
- * counts — before React's click handler runs. `popoverId` makes the trigger
- * the panel's invoker, which exempts it. jsdom implements neither light
- * dismiss nor invokers, so that wiring is only verifiable in a browser.
+ * @input React hooks, useListFocus, useMediaQuery
+ * @output useMenuHover hook
+ * @position Internal hook for nav heading components, TopNavMenu,
+ * TopNavMegaMenu and DropdownMenuSubMenu
*/
+// Hover adds to the standard popover behavior. A click toggles, Escape and an
+// outside click close, and arrows navigate. Also, mouseenter opens after a
+// delay, and mouseleave closes a menu that hover opened.
+//
+// - A hover-opened menu is open when the click that follows arrives. Within
+// `clickGuardMs`, that click pins the menu and does not close it.
+// - Focus moves synchronously. `useLayer.show()` shows the popover in the
+// same tick, and the items are always mounted. A frame delay lands after
+// paint and races other focus moves. A hover open keeps focus on the
+// trigger.
+// - The hook passes `skipAutoFocus` and moves focus itself. Popover
+// auto-focus goes to the first tabbable node, but under roving tabindex a
+// menu wants its first item.
+// - The browser light-dismisses a `popover="auto"` on a pointer press
+// outside the panel, also on the trigger. `popoverId` makes the trigger the
+// panel's invoker, which exempts it. jsdom has neither feature, so only a
+// browser can test this.
+
import {useCallback, useEffect, useRef} from 'react';
import {useIsomorphicLayoutEffect} from './useIsomorphicLayoutEffect';
import {useListFocus} from './useListFocus';
@@ -45,13 +37,10 @@ import {focusForLastInput} from '../utils/focusReturn';
const DEFAULT_CLICK_GUARD_MS = 500;
/**
- * How long after a close a mouseenter on the trigger is ignored.
- *
- * A panel positioned over its own trigger puts that trigger back under a
- * stationary pointer when it closes, and the browser fires a fresh mouseenter —
- * which reopened the menu the user had just dismissed. Time-bounded rather than
- * a one-shot flag, so a deliberate re-hover seconds later still opens; a real
- * mouseleave clears it early.
+ * How long after a close a mouseenter on the trigger is ignored. A panel over
+ * its own trigger puts the trigger back under a still pointer when it closes,
+ * and the browser fires a new mouseenter. A time limit, not a one-shot flag,
+ * lets a later re-hover open the menu. A real mouseleave clears it early.
*/
const REOPEN_SUPPRESS_MS = 300;
@@ -251,10 +240,9 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
const wasOpen = prevIsOpenRef.current;
prevIsOpenRef.current = isOpen;
if (wasOpen && !isOpen) {
- // A hover-open scheduled before the close must not fire afterwards and
- // reopen what just closed from elsewhere — e.g. the root menu's light
- // dismiss closing a submenu flyout mid hover-intent (#6893). A fresh
- // mouseenter still opens; only the stale timer is cancelled.
+ // Cancel a hover-open that was scheduled before the close. Otherwise it
+ // reopens a menu that closed from elsewhere, such as a submenu flyout
+ // that the root menu light-dismissed. A new mouseenter still opens.
clearTimeouts();
hoverModeRef.current = false;
hoverOpenedAtRef.current = 0;
@@ -282,8 +270,8 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
hide();
const trigger = triggerElRef.current;
if (menuHadFocus && trigger != null) {
- // A pointer's pick leaves no keyboard ring on the trigger; a keyboard's
- // keeps it (`architecture:interaction-modality` INV1).
+ // A pointer pick leaves no keyboard ring on the trigger. A keyboard pick
+ // keeps it.
focusForLastInput(trigger);
}
}, [hide, menuRef]);
@@ -362,9 +350,10 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
}
clearTimeouts();
- // Enter/Space arrive as a click with detail 0, and always open. A keyboard
- // user reaches the trigger of an open menu only because a hover-open left
- // focus behind; closing there would stranded them outside a visible menu.
+ // Enter and Space arrive as a click with detail 0, and always open. A
+ // keyboard user reaches the trigger of an open menu only when a
+ // hover-open left focus there. A close would leave them outside a
+ // visible menu.
const isKeyboardActivation = event != null && event.detail === 0;
if (isKeyboardActivation) {
closedAtRef.current = 0;
@@ -458,12 +447,9 @@ export function useMenuHover<T extends HTMLElement = HTMLElement>(
clearTimeout(hideTimerRef.current);
}
hideTimerRef.current = setTimeout(() => {
- // A pointer that stopped mid-diagonal, aiming at a row, is still
- // heading for the flyout: pausing is not leaving, and that pause
- // is the exact moment the triangle exists to protect. Re-arm
- // instead of closing underneath it. A pointer parked here holds
- // the flyout open the same way a pointer parked on the row does;
- // the first move outside the triangle ends it.
+ // A pointer that stops mid-diagonal is still heading for the
+ // flyout. Restart the delay, and do not close under it. The first
+ // move outside the triangle ends this.
if (isTracking && lastPoint != null && isInside(lastPoint)) {
scheduleHide();
return;
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index da19dc5342..5caaf73606 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -6,41 +6,10 @@
* @file useMenuPress.ts
* @input The menu root, its trigger, the enabled-row selector, and callbacks
* for opening, highlighting, activating and dismissing
- * @output Exports useMenuPress, the marker attribute, and the module-level
- * activation mark
- * @position Core hook; mounted by DropdownMenu, ContextMenu,
- * DropdownMenuSubMenu, Selector and MenuBottomSheetActionList. The pure
- * transition table lives in menuPressGesture.ts.
- *
- * One press in a menu, from the trigger or from inside, owned end to end:
- *
- * - The pointer is tracked at DOCUMENT level by `pointerId`. A finger's
- * pointer events stay with the element it landed on (implicit capture), so a
- * menu container never sees a finger that slid onto it — the document does.
- * - The highlight follows the pointer (DOM focus with `preventScroll` in a
- * menu, its indicator following the last input; a callback for a picker
- * that highlights by index).
- * - The row under the RELEASE acts, the way its own click would, carrying the
- * release's button and modifier keys.
- * - The browser's stray `click` for a tracked gesture is swallowed at the
- * window in the capture phase, ahead of React's own listener. It arms at a
- * tracked release and disarms at the next pointer press or after a short
- * window; a click with `detail === 0` (a keyboard's or a screen reader's)
- * always passes.
- * - A mouse press on the trigger opens the menu at once; a finger held on the
- * trigger opens it after the long-press delay. The settle rule decides
- * whether the opening gesture's release may act (see menuPressGesture.ts).
- * - `pointercancel`, a second pointer, or the window losing focus end the
- * gesture with nothing acting; the model never re-implements scrolling.
- * - While a press is tracked in an overflowing menu, a pointer resting near
- * the top or bottom edge scrolls the menu toward that edge (the shared
- * timer of utils/edgeAutoscroll.ts).
- *
- * The menu root is marked `data-astryx-menu-press` so a nested flyout (a DOM
- * descendant of its parent menu) can tell which level owns a press, and so a
- * surface can be recognised as carrying this model. A menu the root renders
- * beside itself names the root with `data-astryx-menu-press-surface` and counts
- * as nested in it.
+ * @output useMenuPress, the marker attributes, and the activation mark
+ * @position Core hook for DropdownMenu, ContextMenu, DropdownMenuSubMenu,
+ * Selector and MenuBottomSheetActionList. The transition table lives in
+ * menuPressGesture.ts.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
@@ -103,13 +72,12 @@ export const MENU_PRESS_STRAY_CLICK_MS = CLICK_GUARD_WINDOW_MS;
export const MENU_PRESS_LONG_PRESS_MS = LONG_PRESS_DURATION_MS;
/**
* How far a finger held on a DropdownMenu trigger may move before the open,
- * in CSS px, under every primary pointer: `spec:AST-094` FR29's drift
- * allowance (FR2's table: unmeasured, a 12 pt move still opened; useMenuPress
- * FR9, FR43). ContextMenu keeps the long press's own allowable movement.
+ * in CSS px, under every primary pointer. A native menu still opens after a
+ * 12 pt move. ContextMenu keeps the long press's own allowable movement.
*/
export const MENU_PRESS_TRIGGER_DRIFT_PX = 13;
-/** A finger held on the trigger: FR29's drift allowance, the same under every primary pointer. */
+/** A held finger on the trigger gets the same drift allowance under every primary pointer. */
const TRIGGER_TOLERANCE: LongPressTolerance = {
moveCancelPx: MENU_PRESS_TRIGGER_DRIFT_PX,
};
@@ -122,11 +90,6 @@ const FOCUSABLE_ROW_SELECTOR =
'[tabindex], a[href], button, input, select, textarea, [contenteditable]';
const INNER_CONTROL_SELECTOR = 'a[href], button, [tabindex]';
-// =============================================================================
-// Module state: the activation mark (the stray-click swallower is the
-// shared click guard, utils/clickGuard.ts)
-// =============================================================================
-
let isModelActivation = false;
/**
@@ -144,10 +107,6 @@ export function __resetMenuPressForTest(): void {
__resetClickGuardForTest();
}
-// =============================================================================
-// Options
-// =============================================================================
-
export interface UseMenuPressOptions {
/** The menu (or listbox) root: the surface whose rows the press picks from. */
menuRef: RefObject<HTMLElement | null>;
@@ -220,10 +179,6 @@ export interface UseMenuPressReturn {
cancel: () => void;
}
-// =============================================================================
-// Helpers
-// =============================================================================
-
function normalizePointerType(type: string): MenuPressPointerType | null {
return type === 'mouse' || type === 'touch' || type === 'pen' ? type : null;
}
@@ -280,13 +235,24 @@ interface ResolvedPoint {
isOnTrigger: boolean;
}
-// =============================================================================
-// Hook
-// =============================================================================
-
/**
* The press model for a menu: the row under the release acts, the highlight
- * follows a held pointer, a mouse opens on press. See the file header.
+ * follows a held pointer, and a mouse opens the menu on press.
+ *
+ * - The document tracks the pointer by `pointerId`. A finger's events stay
+ * with the element it landed on, so the menu never sees a finger that slid
+ * onto it.
+ * - The release acts on its row as the row's own click would, with the
+ * release's button and modifier keys.
+ * - The browser's stray `click` after a tracked release is swallowed at the
+ * window, in the capture phase. A click with `detail === 0` always passes.
+ * - A finger held on the trigger opens the menu after the long-press delay.
+ * The settle rule in menuPressGesture.ts decides if that release can act.
+ * - `pointercancel`, a second pointer, or a window blur ends the gesture, and
+ * nothing acts.
+ * - A pointer that rests near the edge of an overflowing menu scrolls it.
+ * - The root carries `data-astryx-menu-press`, so a nested flyout can tell
+ * which level owns a press.
*
* @example
* ```
@@ -314,11 +280,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);
const pointerIdRef = useRef<number | null>(null);
const detachRef = useRef<(() => void) | null>(null);
- // The held finger is detected by `useLongPress`, the same hook ContextMenu
- // uses, so the hold duration and the movement tolerance have one home. The
- // handle is held in a ref because the pointer handlers below are stable
- // callbacks and the hook is created further down, once `fireLongPress`
- // exists.
+ // `useLongPress` detects the held finger, as in ContextMenu, so the hold
+ // time and the movement tolerance have one home. A ref holds the handle,
+ // because the pointer handlers below are stable and the hook is created
+ // after `fireLongPress`.
const longPressApiRef = useRef<LongPressDetectorHandlers | null>(null);
const touchMovePreventerRef = useRef<(() => void) | null>(null);
// The edge autoscroll running now: its scroller, its direction, and the
@@ -342,7 +307,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
running.scroller.scrollTop = before + delta;
const moved = running.scroller.scrollTop - before;
if (moved === 0) {
- // The edge is reached; nothing more to reveal.
+ // The edge is reached. There is nothing more to show.
autoscrollRef.current = null;
return 0;
}
@@ -428,12 +393,11 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
onHighlight(row);
return;
}
- // In a menu the highlight IS focus. A row whose root takes no
- // focus is highlighted through the control inside it; over nothing,
- // the menu root holds focus so no row is lit. The focus follows the
- // last input (`architecture:interaction-modality` INV1): a held press
- // is pointer input, so the row does not match :focus-visible, which a
- // plain focus() would inherit from the focus before it.
+ // In a menu the highlight is focus. A row that takes no focus is
+ // highlighted through its inner control. Over nothing, the menu root
+ // holds focus, so no row is lit. A held press is pointer input, so the
+ // row must not match :focus-visible. A plain focus() would keep the
+ // modality of the earlier focus.
const target =
row == null
? menuRef.current
@@ -458,8 +422,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
return;
}
// The row acts as its own click would. `detail: 0` marks a dispatched
- // activation, as a keyboard's does, so the click guard lets
- // it through; the button and modifiers are the release's.
+ // activation, as a keyboard's does, so the click guard lets it pass.
+ // The button and the modifiers are the release's.
row.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
@@ -518,7 +482,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
case 'act': {
// Detach before acting: the activation usually closes the menu.
endGesture();
- // The one swallower stays installed once armed (PR2).
+ // Once armed, the one swallower stays installed.
armClickGuard(doc, {staysInstalled: true});
if (native != null) {
activate(effect.row, native);
@@ -550,8 +514,6 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
);
stepRef.current = step;
- // --- Edge autoscroll -----------------------------------------------
-
const getScroller = useCallback((): HTMLElement | null => {
const {getScroller: custom, menuRef} = optionsRef.current;
if (custom != null) {
@@ -619,8 +581,6 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
[autoscroll, getScroller, resolvePoint, stopAutoscroll],
);
- // --- Document-level tracking ----------------------------------------------
-
const attach = useCallback(
(pointerId: number) => {
detachRef.current?.();
@@ -635,8 +595,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
lastPointerEventRef.current = event;
const gesture = gestureRef.current;
if (gesture.phase === 'triggerPress') {
- // A finger that travels past FR29's drift allowance is scrolling,
- // not holding.
+ // A finger that moves past the drift allowance is scrolling, not
+ // holding.
const isPending = longPressApiRef.current?.moveTo({
x: event.clientX,
y: event.clientY,
@@ -708,8 +668,6 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
[getDocument, resolvePoint, updateAutoscroll],
);
- // --- The held finger on the trigger ----------------------------
-
const fireLongPress = useCallback(() => {
const gesture = gestureRef.current;
if (gesture.phase !== 'triggerPress') {
@@ -737,20 +695,15 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
step({type: 'opened', time: Date.now()});
}, [getDocument, step]);
- // One long-press detector for the system: the same hook ContextMenu spreads
- // onto its trigger, driven here from the pointer stream this model already
- // observes. Its touch handlers go unused; the hold duration, the movement
- // tolerance and the timer are what matter, and they now have one home.
- // The trigger's press takes FR29's drift allowance under every primary
- // pointer, so no menu, row or trigger reads the pointer query (spec:AST-094
- // FR24, FR43).
+ // The same long-press detector as ContextMenu, driven from the pointer
+ // stream this model already observes. Only its hold time, movement
+ // tolerance and timer are used. The trigger uses one drift allowance under
+ // every primary pointer, so no menu, row or trigger reads the pointer query.
longPressApiRef.current = useLongPressDetector({
onLongPress: fireLongPress,
delayMs: options.longPressDelayMs ?? MENU_PRESS_LONG_PRESS_MS,
});
- // --- Handlers ------------------------------------------------------------
-
const handleMenuPointerDown = useCallback(
(event: React.PointerEvent<HTMLElement>) => {
const {menuRef, isEnabled = true} = optionsRef.current;
@@ -781,10 +734,10 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
return;
}
if (pointerType !== 'mouse') {
- // Cancelling pointerdown suppresses the compatibility mouse events a
- // finger would otherwise fire at the row it LANDED on when it lifts —
- // the mousedown that would light the origin row a second time.
- // Scrolling is governed by touch-action and is unaffected.
+ // Cancelling pointerdown stops the compatibility mouse events that a
+ // finger fires at its landing row when it lifts. That mousedown would
+ // light the origin row again. touch-action controls scrolling, so
+ // scrolling does not change.
event.preventDefault();
}
const native = event.nativeEvent;