An open source design system that's fully customizable and agent ready
TypeScript
feat(hooks): useContainerReveal — composable hover/focus reveal primitive (#4573)
Cindy Zhangfc53ff7ac8ce
diff --git a/.changeset/use-container-reveal.md b/.changeset/use-container-reveal.mdnew file mode 100644index 0000000000..06e7c95c87--- /dev/null+++ b/.changeset/use-container-reveal.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Add `useContainerReveal` — a headless hook for revealing (or concealing) content when its container is hovered or focused. CSS-driven (no hover state in JS, no re-render on hover) and accessible by construction: revealed content stays in the accessibility tree and tab order, reveals on keyboard focus-within, and stays visible on touch. Callers spread `getContainerProps()` on the container and `getContentRevealProps()` on each child; no StyleX authoring required. `Thumbnail`'s `showRemoveOn="hover"` now uses this hook internally (no API change).++@cixzhangdiff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.jsonindex 46ae48d210..d0090e05a7 100644--- a/.github/a11y-baseline.json+++ b/.github/a11y-baseline.json@@ -2,5 +2,8 @@"$comment": "Known axe violations tolerated by the pr-a11y CI gate. Entries are keyed Component::Story::rule-id (see .github/scripts/lib/a11y-baseline.js). Regenerate with `pnpm a11y:baseline` after `pnpm storybook:build` and `npx playwright install chromium`. Remove entries as violations are fixed; anything not listed here fails pr-a11y.","version": 1,"generatedAt": null,- "entries": []+ "entries": [+ "Thumbnail::Media Mode (dark vs light images)::color-contrast",+ "Thumbnail::Remove on hover::color-contrast"+ ]}diff --git a/apps/storybook/stories/UseContainerReveal.stories.tsx b/apps/storybook/stories/UseContainerReveal.stories.tsxnew file mode 100644index 0000000000..38d634a245--- /dev/null+++ b/apps/storybook/stories/UseContainerReveal.stories.tsx@@ -0,0 +1,186 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {useContainerReveal} from '@astryxdesign/core/hooks';+import {Button} from '@astryxdesign/core/Button';+import {mergeProps} from '@astryxdesign/core/utils';+import {TrashIcon, PencilIcon} from '@heroicons/react/24/outline';++const styles = stylex.create({+ stack: {+ display: 'flex',+ flexDirection: 'column',+ gap: 8,+ maxWidth: 360,+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 12,+ padding: '8px 12px',+ borderRadius: 8,+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: 'rgba(0,0,0,0.12)',+ background: {+ default: 'transparent',+ ':hover': 'rgba(0,0,0,0.03)',+ },+ },+ label: {fontSize: 14},+ actions: {display: 'flex', gap: 4},+ hint: {fontSize: 12, color: '#888', marginBottom: 8},+ nested: {+ marginTop: 8,+ marginInlineStart: 24,+ borderInlineStartWidth: 2,+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: 'rgba(0,0,0,0.08)',+ paddingInlineStart: 8,+ },+});++/**+ * A row whose secondary actions are hidden at rest and revealed when the row+ * is hovered or focused. The action stays in the a11y tree and tab order.+ */+function RevealRow({label}: {label: string}) {+ const {getContainerProps, getContentRevealProps} = useContainerReveal();+ return (+ <div {...mergeProps(getContainerProps(), stylex.props(styles.row))}>+ <span {...stylex.props(styles.label)}>{label}</span>+ <span {...mergeProps(getContentRevealProps(), stylex.props(styles.actions))}>+ <Button+ label={`Edit ${label}`}+ variant="ghost"+ isIconOnly+ icon={<PencilIcon style={{width: 16, height: 16}} />}+ />+ <Button+ label={`Delete ${label}`}+ variant="ghost"+ isIconOnly+ icon={<TrashIcon style={{width: 16, height: 16}} />}+ />+ </span>+ </div>+ );+}++const meta: Meta = {+ title: 'Hooks/useContainerReveal',+};+export default meta;+type Story = StoryObj;++/** Hover or tab into a row to reveal its actions. */+export const Reveal: Story = {+ render: () => (+ <div {...stylex.props(styles.stack)}>+ <p {...stylex.props(styles.hint)}>+ Hover a row — or press Tab to focus into it — to reveal its actions.+ On touch devices the actions are always visible.+ </p>+ <RevealRow label="report.pdf" />+ <RevealRow label="budget.xlsx" />+ <RevealRow label="notes.txt" />+ </div>+ ),+};++/**+ * Inverted: content is visible at rest and fades OUT on hover. Mouse-only —+ * it never hides on keyboard focus and stays visible on touch.+ */+export const InvertedConceal: Story = {+ render: () => {+ function ConcealRow({label}: {label: string}) {+ const {getContainerProps, getContentRevealProps} = useContainerReveal();+ return (+ <div {...mergeProps(getContainerProps(), stylex.props(styles.row))}>+ <span {...stylex.props(styles.label)}>{label}</span>+ <span+ {...mergeProps(+ getContentRevealProps({isRevealInverted: true}),+ stylex.props(styles.label),+ )}>+ edited 2h ago+ </span>+ </div>+ );+ }+ return (+ <div {...stylex.props(styles.stack)}>+ <p {...stylex.props(styles.hint)}>+ The timestamp shows at rest and fades out on mouse hover (a visual+ declutter). It stays put for keyboard and touch users.+ </p>+ <ConcealRow label="report.pdf" />+ <ConcealRow label="budget.xlsx" />+ </div>+ );+ },+};++/**+ * Layout-preserved reveal reserves the action's box at rest, so surrounding+ * content does not shift when it appears.+ */+export const PreserveLayout: Story = {+ render: () => {+ function PreserveRow({label}: {label: string}) {+ const {getContainerProps, getContentRevealProps} = useContainerReveal();+ return (+ <div {...mergeProps(getContainerProps(), stylex.props(styles.row))}>+ <span {...stylex.props(styles.label)}>{label}</span>+ <span+ {...mergeProps(+ getContentRevealProps({isLayoutPreserved: true}),+ stylex.props(styles.actions),+ )}>+ <Button+ label={`Delete ${label}`}+ variant="ghost"+ isIconOnly+ icon={<TrashIcon style={{width: 16, height: 16}} />}+ />+ </span>+ </div>+ );+ }+ return (+ <div {...stylex.props(styles.stack)}>+ <p {...stylex.props(styles.hint)}>+ The action's space is reserved even while hidden — no reflow when it+ fades in.+ </p>+ <PreserveRow label="report.pdf" />+ <PreserveRow label="budget.xlsx" />+ </div>+ );+ },+};++/**+ * Nested containers each get their own scoped marker from the pool, so+ * hovering the outer row does NOT reveal the inner row's actions.+ */+export const NestedIsolation: Story = {+ render: () => (+ <div {...stylex.props(styles.stack)}>+ <p {...stylex.props(styles.hint)}>+ Hover the outer row: only its own actions appear. The nested row keeps+ its actions hidden until you hover it directly — proof that the pool+ gives each container an isolated marker.+ </p>+ <div>+ <RevealRow label="Parent folder" />+ <div {...stylex.props(styles.nested)}>+ <RevealRow label="Nested file" />+ </div>+ </div>+ </div>+ ),+};diff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsxindex 70cdc1b7dd..f4dbe5a9c1 100644--- a/packages/core/src/Thumbnail/Thumbnail.tsx+++ b/packages/core/src/Thumbnail/Thumbnail.tsx@@ -39,11 +39,11 @@ import {Skeleton} from '../Skeleton';import {Spinner} from '../Spinner';import {Tooltip} from '../Tooltip/Tooltip';import {useDevWarning} from '../hooks/useDevWarning';+import {useContainerReveal} from '../hooks/useContainerReveal';import type {BaseProps} from '../BaseProps';import {mergeProps} from '../utils';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';-import {thumbnailScope} from './thumbnail.markers.stylex';export interface ThumbnailProps extends BaseProps<HTMLDivElement> {/** Ref forwarded to the root element */@@ -236,28 +236,6 @@ const styles = stylex.create({zIndex: 1,lineHeight: 0,},- // showRemoveOn="hover": the remove button is hidden at rest and revealed- // when the thumbnail is hovered or when focus enters it (keyboard). Only- // opacity is animated — the button stays mounted and focusable so tabbing- // to it triggers the :focus-within reveal. Any touch-capable device (incl.- // hybrid laptops that also report hover) keeps the button visible so the- // remove path is never gated behind an unavailable hover.- removeOnHover: {- opacity: {- default: 0,- [stylex.when.ancestor(':hover', thumbnailScope)]: {- '@media (hover: hover)': 1,- },- [stylex.when.ancestor(':focus-within', thumbnailScope)]: 1,- '@media (any-pointer: coarse)': 1,- },- transitionProperty: 'opacity',- transitionDuration: {- default: durationVars['--duration-fast'],- '@media (prefers-reduced-motion: reduce)': '0s',- },- transitionTimingFunction: easeVars['--ease-standard'],- },});// =============================================================================@@ -326,6 +304,9 @@ export function Thumbnail({const isInteractive = onClick != null && !isDisabled && !isLoading;const hasRemove = onRemove != null && !isDisabled;const isHoverReveal = hasRemove && showRemoveOn === 'hover';+ const {getContainerProps, getContentRevealProps} = useContainerReveal({+ isEnabled: isHoverReveal,+ });const accessibleName =label && alt? `${label} — ${alt}`@@ -377,9 +358,12 @@ export function Thumbnail({const removeButtonEl = hasRemove ? (<div- {...stylex.props(- styles.removeSlot,- isHoverReveal && styles.removeOnHover,+ {...mergeProps(+ stylex.props(styles.removeSlot),+ // The remove button is absolutely positioned in the corner, so it is+ // already out of flow — an opacity-only reveal (layout preserved)+ // matches its overlay placement instead of the clip recipe.+ isHoverReveal ? getContentRevealProps({isLayoutPreserved: true}) : {},)}><Buttonicon={<Icon icon="close" size="xsm" />}@@ -410,12 +394,14 @@ export function Thumbnail({)}{...props}><div- {...stylex.props(- styles.imageContainer,- isHoverReveal && thumbnailScope,- isInteractive && styles.interactive,- isInteractive && styles.overlay,- isInteractive && styles.hoverOnPointer,+ {...mergeProps(+ stylex.props(+ styles.imageContainer,+ isInteractive && styles.interactive,+ isInteractive && styles.overlay,+ isInteractive && styles.hoverOnPointer,+ ),+ isHoverReveal ? getContainerProps() : {},)}>{isInteractive ? (<buttondiff --git a/packages/core/src/Thumbnail/thumbnail.markers.stylex.ts b/packages/core/src/Thumbnail/thumbnail.markers.stylex.tsdeleted file mode 100644index 1232101834..0000000000--- a/packages/core/src/Thumbnail/thumbnail.markers.stylex.ts+++ /dev/null@@ -1,12 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--import * as stylex from '@stylexjs/stylex';--/**- * Scoped marker for Thumbnail ancestor selectors. Applied to the image- * container so the remove button's hover/focus reveal (`showRemoveOn="hover"`)- * responds only to this thumbnail — not to hover/focus state from an outer- * container the thumbnail happens to sit inside.- */-export const thumbnailScope: ReturnType<typeof stylex.defineMarker> =- stylex.defineMarker();diff --git a/packages/core/src/hooks/containerReveal.pool.stylex.ts b/packages/core/src/hooks/containerReveal.pool.stylex.tsnew file mode 100644index 0000000000..70ec1c13b6--- /dev/null+++ b/packages/core/src/hooks/containerReveal.pool.stylex.ts@@ -0,0 +1,464 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file containerReveal.pool.stylex.ts+ * @input Uses StyleX, theme tokens+ * @output A fixed pool of scoped markers, each paired with its reveal style+ * blocks (reveal / conceal, each with a layout-preserved variant) compiled+ * against that marker.+ * @position Internal to useContainerReveal.+ *+ * WHY A POOL OF LITERAL BLOCKS: `stylex.when.ancestor(':hover', marker)` is+ * resolved by the StyleX compiler, which welds the marker's class into the+ * emitted selector (`.marker:hover *`). A marker and the styles referencing it+ * are therefore inseparable at build time — the marker cannot be passed as a+ * runtime argument, so the blocks cannot be produced by a loop or a helper and+ * must be written out literally per marker. A single shared marker would leak+ * hover/focus across NESTED reveal containers (an ancestor container's :hover+ * matches a descendant container's revealed content), so useContainerReveal+ * hands each concurrently mounted container a distinct marker from this pool+ * (see the free-list there).+ *+ * The reveal recipe hides content with `position: absolute` (removed from+ * layout flow, so it reserves no space) plus `opacity: 0`. Both keep the+ * content in the accessibility tree and tab order — unlike display/visibility+ * — so it stays reachable by keyboard and assistive tech while hidden.+ */++import * as stylex from '@stylexjs/stylex';+import {durationVars, easeVars} from '../theme/tokens.stylex';++export const POOL_SIZE = 6;++export const m0 = stylex.defineMarker();+const s0 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m0)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m0)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m0)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m0)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m0)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m0)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m0)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m0)]: {'@media (hover: hover)': 0},+ },+ },+});++export const m1 = stylex.defineMarker();+const s1 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m1)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m1)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m1)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m1)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m1)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m1)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m1)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m1)]: {'@media (hover: hover)': 0},+ },+ },+});++export const m2 = stylex.defineMarker();+const s2 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m2)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m2)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m2)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m2)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m2)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m2)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m2)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m2)]: {'@media (hover: hover)': 0},+ },+ },+});++export const m3 = stylex.defineMarker();+const s3 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m3)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m3)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m3)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m3)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m3)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m3)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m3)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m3)]: {'@media (hover: hover)': 0},+ },+ },+});++export const m4 = stylex.defineMarker();+const s4 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m4)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m4)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m4)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m4)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m4)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m4)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m4)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m4)]: {'@media (hover: hover)': 0},+ },+ },+});++export const m5 = stylex.defineMarker();+const s5 = stylex.create({+ // Hidden at rest via position + opacity (kept in the a11y tree and tab+ // order); on container :hover (fine pointer) or :focus-within it returns to+ // flow and fades in. Always shown on touch.+ reveal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m5)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m5)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ position: {+ default: 'absolute',+ [stylex.when.ancestor(':hover', m5)]: {'@media (hover: hover)': 'static'},+ [stylex.when.ancestor(':focus-within', m5)]: 'static',+ '@media (any-pointer: coarse)': 'static',+ },+ },+ // Opacity-only reveal that keeps the box reserved (no layout shift). Use for+ // content that is already positioned (e.g. an absolute overlay).+ revealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 0,+ [stylex.when.ancestor(':hover', m5)]: {'@media (hover: hover)': 1},+ [stylex.when.ancestor(':focus-within', m5)]: 1,+ '@media (any-pointer: coarse)': 1,+ },+ },+ // Inverted: visible at rest, fades OUT on :hover only. Deliberately ignores+ // :focus-within (a keyboard user must never watch content vanish) and stays+ // visible on touch. Never leaves the a11y tree.+ conceal: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m5)]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', m5)]: {'@media (hover: hover)': 0},+ },+ },+});++// The compiled StyleX objects carry `when.ancestor` conditionals the public+// `StyleXStyles` type does not model, so the slot shape is inferred.+export const POOL = [+ {marker: m0, reveal: s0.reveal, revealLayoutPreserved: s0.revealLayoutPreserved, conceal: s0.conceal, concealLayoutPreserved: s0.concealLayoutPreserved},+ {marker: m1, reveal: s1.reveal, revealLayoutPreserved: s1.revealLayoutPreserved, conceal: s1.conceal, concealLayoutPreserved: s1.concealLayoutPreserved},+ {marker: m2, reveal: s2.reveal, revealLayoutPreserved: s2.revealLayoutPreserved, conceal: s2.conceal, concealLayoutPreserved: s2.concealLayoutPreserved},+ {marker: m3, reveal: s3.reveal, revealLayoutPreserved: s3.revealLayoutPreserved, conceal: s3.conceal, concealLayoutPreserved: s3.concealLayoutPreserved},+ {marker: m4, reveal: s4.reveal, revealLayoutPreserved: s4.revealLayoutPreserved, conceal: s4.conceal, concealLayoutPreserved: s4.concealLayoutPreserved},+ {marker: m5, reveal: s5.reveal, revealLayoutPreserved: s5.revealLayoutPreserved, conceal: s5.conceal, concealLayoutPreserved: s5.concealLayoutPreserved},+] as const;++export type RevealSlot = (typeof POOL)[number];diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex c0665beb4b..69e16d5f6a 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -92,3 +92,10 @@ export {useLongPress} from './useLongPress';export type {UseLongPressOptions, UseLongPressHandlers} from './useLongPress';export {useDevWarning} from './useDevWarning';++export {useContainerReveal} from './useContainerReveal';+export type {+ UseContainerRevealOptions,+ UseContainerRevealReturn,+ ContentRevealOptions,+} from './useContainerReveal';diff --git a/packages/core/src/hooks/useContainerReveal.test.tsx b/packages/core/src/hooks/useContainerReveal.test.tsxnew file mode 100644index 0000000000..7afb92bc7c--- /dev/null+++ b/packages/core/src/hooks/useContainerReveal.test.tsx@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useContainerReveal.test.tsx+ * @input Uses vitest, @testing-library/react, useContainerReveal+ * @output Unit tests for the marker-pool free-list, per-instance scoping, the+ * inert (disabled) path, and the content-option → style-block mapping.+ * @position Testing; validates useContainerReveal.ts and its pool.+ *+ * SYNC: When useContainerReveal.ts changes, update these tests.+ */++import {describe, it, expect} from 'vitest';+import {renderHook, render, act} from '@testing-library/react';+import {useContainerReveal} from './useContainerReveal';+import {POOL_SIZE} from './containerReveal.pool.stylex';++describe('useContainerReveal', () => {+ it('returns spreadable getter props for container and content', () => {+ const {result} = renderHook(() => useContainerReveal());+ const container = result.current.getContainerProps();+ const content = result.current.getContentRevealProps();+ expect(container).toHaveProperty('className');+ expect(content).toHaveProperty('className');+ expect(typeof container.className).toBe('string');+ expect(typeof content.className).toBe('string');+ });++ it('is inert when disabled: no marker class, empty content props', () => {+ const {result} = renderHook(() =>+ useContainerReveal({isEnabled: false}),+ );+ expect(result.current.getContainerProps()).toEqual({});+ expect(result.current.getContentRevealProps()).toEqual({});+ });++ it('gives two concurrently mounted containers DISTINCT marker classes', () => {+ // The core leak-safety property: nested/concurrent containers must never+ // share a marker, or an ancestor container's :hover would reveal a+ // descendant container's content.+ const a = renderHook(() => useContainerReveal());+ const b = renderHook(() => useContainerReveal());+ const classA = a.result.current.getContainerProps().className;+ const classB = b.result.current.getContainerProps().className;+ expect(classA).toBeTruthy();+ expect(classB).toBeTruthy();+ expect(classA).not.toBe(classB);+ a.unmount();+ b.unmount();+ });++ it('recycles a slot after unmount (free-list release)', () => {+ const first = renderHook(() => useContainerReveal());+ const firstClass = first.result.current.getContainerProps().className;+ first.unmount();+ // A fresh mount should be able to reclaim the just-released slot.+ const second = renderHook(() => useContainerReveal());+ const secondClass = second.result.current.getContainerProps().className;+ expect(secondClass).toBe(firstClass);+ second.unmount();+ });++ it('reveal and conceal map to different style blocks', () => {+ const {result} = renderHook(() => useContainerReveal());+ const reveal = result.current.getContentRevealProps().className;+ const conceal = result.current.getContentRevealProps({+ isRevealInverted: true,+ }).className;+ expect(reveal).toBeTruthy();+ expect(conceal).toBeTruthy();+ expect(reveal).not.toBe(conceal);+ });++ it('layout-preserved reveal differs from clipped reveal', () => {+ const {result} = renderHook(() => useContainerReveal());+ const clipped = result.current.getContentRevealProps().className;+ const preserved = result.current.getContentRevealProps({+ isLayoutPreserved: true,+ }).className;+ expect(clipped).not.toBe(preserved);+ });++ it('assigns distinct markers across a full pool of concurrent containers', () => {+ function Probe({onClass}: {onClass: (c: string) => void}) {+ const {getContainerProps} = useContainerReveal();+ onClass(getContainerProps().className ?? '');+ return null;+ }+ const classes: string[] = [];+ const {unmount} = render(+ <>+ {Array.from({length: POOL_SIZE}, (_, i) => (+ <Probe key={i} onClass={(c) => classes.push(c)} />+ ))}+ </>,+ );+ const unique = new Set(classes.filter(Boolean));+ expect(unique.size).toBe(POOL_SIZE);+ unmount();+ });++ it('survives repeated mount/unmount without leaking the pool', () => {+ // Mount and unmount a full pool several times; each cycle must still hand+ // out POOL_SIZE distinct markers, proving slots are released.+ for (let cycle = 0; cycle < 3; cycle++) {+ const hooks = Array.from({length: POOL_SIZE}, () =>+ renderHook(() => useContainerReveal()),+ );+ const classes = hooks.map(+ (h) => h.result.current.getContainerProps().className,+ );+ expect(new Set(classes).size).toBe(POOL_SIZE);+ act(() => hooks.forEach((h) => h.unmount()));+ }+ });+});diff --git a/packages/core/src/hooks/useContainerReveal.ts b/packages/core/src/hooks/useContainerReveal.tsnew file mode 100644index 0000000000..e410448812--- /dev/null+++ b/packages/core/src/hooks/useContainerReveal.ts@@ -0,0 +1,180 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useContainerReveal.ts+ * @input Uses React, the generated marker pool, useDevWarning+ * @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 a+ * marker + matching reveal styles from a pre-compiled pool.+ *+ * ACCESSIBILITY (WCAG 2.2 by construction):+ * - Revealed content is visually hidden at rest via the clip recipe, so it+ * stays in the accessibility tree and tab order — never display:none.+ * - Keyboard: revealed on :focus-within, so tabbing in shows it.+ * - 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.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/hooks/index.ts (export)+ * - containerReveal.pool.stylex.ts (if the slot shape changes)+ */++import {useState, useEffect, type CSSProperties} from 'react';+import * as stylex from '@stylexjs/stylex';+import {POOL, POOL_SIZE, type RevealSlot} from './containerReveal.pool.stylex';+import {useDevWarning} from './useDevWarning';++// Module-level free-list. Each mounted, enabled useContainerReveal claims a+// distinct pool slot so that any two CONCURRENTLY mounted containers — in+// particular a nested container inside another's revealed content — get+// different markers and cannot leak hover/focus into one another. Slots are+// returned on unmount. Sibling containers that would only ever collide when+// the pool is exhausted are harmless (a sibling is never an ancestor), so the+// pool only needs to cover the number of concurrently mounted containers, not+// instances over time.+const claimed: boolean[] = new Array(POOL_SIZE).fill(false);++interface Claim {+ /** Pool index to use. */+ index: number;+ /** True when the pool was full and this claim fell back to a shared slot. */+ isExhausted: boolean;+}++function claimSlot(): Claim {+ for (let i = 0; i < POOL_SIZE; i++) {+ if (!claimed[i]) {+ claimed[i] = true;+ return {index: i, isExhausted: false};+ }+ }+ // Exhausted: fall back to slot 0. Safe for siblings (a sibling is never an+ // ancestor); only nesting deeper than POOL_SIZE could reintroduce a leak.+ // Surfaced via useDevWarning so the pool can be grown.+ return {index: 0, isExhausted: true};+}++function releaseSlot(index: number, isExhausted: boolean): void {+ // A fallback claim never owned the slot exclusively; leave it as-is.+ if (!isExhausted) {+ claimed[index] = false;+ }+}++export interface UseContainerRevealOptions {+ /**+ * When false the hook is inert: no marker is applied and content getters+ * return no styles, so content is always shown. Lets a component gate on its+ * own prop (e.g. `revealOn === 'hover'`).+ * @default true+ */+ isEnabled?: boolean;+}++export interface ContentRevealOptions {+ /**+ * Conceal-on-hover instead of reveal-on-hover: content is visible at rest+ * and fades out while the container is hovered. Mouse-only and visual —+ * stays in the a11y tree, ignores focus-within, stays visible on touch.+ * @default false+ */+ isRevealInverted?: boolean;+ /**+ * Reserve the content's layout box while hidden (opacity-only) instead of+ * collapsing it, to avoid layout shift when it appears.+ * @default false+ */+ isLayoutPreserved?: boolean;+}++export interface UseContainerRevealReturn {+ /** Spread onto the container whose hover/focus-within drives the reveal. */+ getContainerProps: () => {className?: string; style?: CSSProperties};+ /** Spread onto each revealed / concealed child. */+ getContentRevealProps: (+ options?: ContentRevealOptions,+ ) => {className?: string; style?: CSSProperties};+}++const EMPTY = Object.freeze({});++/**+ * Scoped, CSS-only hover/focus reveal for content inside a container.+ *+ * @example+ * ```tsx+ * const {getContainerProps, getContentRevealProps} = useContainerReveal({+ * isEnabled: revealOn === 'hover',+ * });+ *+ * <div {...mergeProps(getContainerProps(), stylex.props(styles.row))}>+ * {label}+ * <span {...mergeProps(getContentRevealProps(), stylex.props(styles.actions))}>+ * {actions}+ * </span>+ * </div>+ * ```+ */+export function useContainerReveal(+ options: UseContainerRevealOptions = {},+): UseContainerRevealReturn {+ const {isEnabled = true} = options;++ // Claim a slot for this container's lifetime. Assigned in the initializer+ // (not the render body) and released on unmount so the free-list stays+ // effect-scoped and StrictMode-safe.+ const [claim] = useState<Claim | null>(() =>+ isEnabled ? claimSlot() : null,+ );++ useEffect(() => {+ if (claim == null) {+ return;+ }+ return () => releaseSlot(claim.index, claim.isExhausted);+ }, [claim]);++ useDevWarning(+ 'useContainerReveal',+ `More than ${POOL_SIZE} reveal containers are mounted at once; nested ` ++ `containers beyond the pool may share a marker. Add markers to ` ++ `containerReveal.pool.stylex.ts and raise POOL_SIZE.`,+ claim?.isExhausted ?? false,+ );++ if (claim == null) {+ return {+ getContainerProps: () => EMPTY,+ getContentRevealProps: () => EMPTY,+ };+ }++ const slot: RevealSlot = POOL[claim.index];++ return {+ getContainerProps: () => stylex.props(slot.marker),+ getContentRevealProps: (contentOptions: ContentRevealOptions = {}) => {+ const {isRevealInverted = false, isLayoutPreserved = false} =+ contentOptions;+ const style = isRevealInverted+ ? isLayoutPreserved+ ? slot.concealLayoutPreserved+ : slot.conceal+ : isLayoutPreserved+ ? slot.revealLayoutPreserved+ : slot.reveal;+ return stylex.props(style);+ },+ };+}diff --git a/scripts/gen-container-reveal-pool.mjs b/scripts/gen-container-reveal-pool.mjsnew file mode 100644index 0000000000..0e66f2f766--- /dev/null+++ b/scripts/gen-container-reveal-pool.mjs@@ -0,0 +1,129 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file gen-container-reveal-pool.mjs+ * @input POOL_SIZE+ * @output packages/core/src/hooks/containerReveal.pool.stylex.ts+ * @position Generator for the useContainerReveal marker pool. `stylex.create`+ * must be static (no runtime loops), and each marker's reveal styles must be+ * compiled against that specific marker, so the N repeated blocks are+ * generated rather than hand-written.+ *+ * Run: node scripts/gen-container-reveal-pool.mjs+ */++import {writeFileSync} from 'node:fs';+import {fileURLToPath} from 'node:url';+import {dirname, join} from 'node:path';++const POOL_SIZE = 8;+const OUT = join(+ dirname(fileURLToPath(import.meta.url)),+ '../packages/core/src/hooks/containerReveal.pool.stylex.ts',+);++const transition = `transitionProperty: 'opacity',+ transitionDuration: {+ default: durationVars['--duration-fast'],+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ transitionTimingFunction: easeVars['--ease-standard'],`;++function toggled(m, hidden, shown) {+ return `{+ default: ${hidden},+ [stylex.when.ancestor(':hover', ${m})]: {'@media (hover: hover)': ${shown}},+ [stylex.when.ancestor(':focus-within', ${m})]: ${shown},+ '@media (any-pointer: coarse)': ${shown},+ }`;+}++function block(i) {+ const m = `m${i}`;+ return `+export const ${m} = stylex.defineMarker();+const s${i} = stylex.create({+ reveal: {+ ${transition}+ opacity: ${toggled(m, '0', '1')},+ position: ${toggled(m, "'absolute'", "'static'")},+ width: ${toggled(m, "'1px'", "'auto'")},+ height: ${toggled(m, "'1px'", "'auto'")},+ margin: ${toggled(m, "'-1px'", "'0'")},+ overflow: ${toggled(m, "'hidden'", "'visible'")},+ clip: ${toggled(m, "'rect(0, 0, 0, 0)'", "'auto'")},+ whiteSpace: ${toggled(m, "'nowrap'", "'normal'")},+ },+ revealLayoutPreserved: {+ ${transition}+ opacity: ${toggled(m, '0', '1')},+ pointerEvents: ${toggled(m, "'none'", "'auto'")},+ },+ conceal: {+ ${transition}+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', ${m})]: {'@media (hover: hover)': 0},+ },+ },+ concealLayoutPreserved: {+ ${transition}+ opacity: {+ default: 1,+ [stylex.when.ancestor(':hover', ${m})]: {'@media (hover: hover)': 0},+ },+ },+});`;+}++const header = `// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file containerReveal.pool.stylex.ts+ * @input Uses StyleX, theme tokens+ * @output A fixed pool of scoped markers, each paired with its reveal style+ * blocks (reveal / conceal, each with a layout-preserved variant) compiled+ * against that marker.+ * @position Internal to useContainerReveal. GENERATED by+ * scripts/gen-container-reveal-pool.mjs — do not edit by hand.+ *+ * WHY A POOL: \`stylex.when.ancestor(':hover', marker)\` welds the marker's+ * class into the compiled selector (\`.marker:hover *\`), so a marker and the+ * styles referencing it are inseparable at compile time. A single shared+ * marker would leak hover/focus across NESTED reveal containers (an ancestor+ * container's \`:hover\` matches a descendant container's revealed content).+ * Pre-declaring N markers lets useContainerReveal hand each concurrently+ * mounted container a distinct marker (free-list in useContainerReveal),+ * isolating nested containers without the caller authoring any StyleX.+ *+ * SYNC: When the block shape changes, edit+ * scripts/gen-container-reveal-pool.mjs and useContainerReveal.ts, then+ * regenerate (node scripts/gen-container-reveal-pool.mjs) and commit.+ */++import * as stylex from '@stylexjs/stylex';+import {durationVars, easeVars} from '../theme/tokens.stylex';++export const POOL_SIZE = ${POOL_SIZE};+`;++const blocks = Array.from({length: POOL_SIZE}, (_, i) => block(i)).join('\n');++const footer = `++// The compiled StyleX style objects carry \`when.ancestor\` conditionals that+// the public \`StyleXStyles\` type does not model, so the slot shape is inferred+// from the generated blocks rather than annotated.+export const POOL = [+${Array.from(+ {length: POOL_SIZE},+ (_, i) =>+ ` {marker: m${i}, reveal: s${i}.reveal, revealLayoutPreserved: s${i}.revealLayoutPreserved, conceal: s${i}.conceal, concealLayoutPreserved: s${i}.concealLayoutPreserved},`,+).join('\n')}+] as const;++export type RevealSlot = (typeof POOL)[number];+`;++writeFileSync(OUT, header + '\n' + blocks + footer);+console.log(`Wrote ${OUT}`);