An open source design system that's fully customizable and agent ready
TypeScript
perf(Item): load the swipe gesture only when swipeActions is set (#7296)
Christopher Chedeau4398c513a783
diff --git a/.changeset/item-swipe-on-demand.md b/.changeset/item-swipe-on-demand.mdnew file mode 100644index 0000000000..0df4e5adb0--- /dev/null+++ b/.changeset/item-swipe-on-demand.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] An `Item` without `swipeActions` no longer bundles the swipe gesture. The panels and the drag that uncovers them now live in a module `Item` loads on demand the first time a row has swipe actions, so an app whose rows never swipe ships about 2.7 KB (gzip) less on its first load and a row that does swipe keeps its DOM, props and behavior; its gesture becomes live once that module has arrived, which on a first load is a moment after the row paints.++@vjeuxdiff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjsindex 5aaa7f2431..f73d12c6df 100644--- a/packages/core/src/Item/Item.doc.mjs+++ b/packages/core/src/Item/Item.doc.mjs@@ -198,7 +198,7 @@ export const docs = {name: 'swipeActions',type: '{leading?: ItemSwipeAction[]; trailing?: ItemSwipeAction[]}',description:- "Swipe actions for touch: the verbs a sideways drag uncovers on each side, outermost last, each `{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`. `leading` is uncovered by a drag toward the inline end, `trailing` toward the inline start. A mouse never starts the drag and a mostly vertical drag stays the scroller's. The gesture is a touch accelerator and never a row's only path to a verb: a verb reachable only by swipe is unreachable by keyboard and by mouse, so every entry must also be reachable through the row's own content. Served on a row whose role permits interactive descendants (a listitem, a row with no role) and not on an option, a menu item, or a row that is the enlarged target of a native radio. The element containing the rows clips in the inline axis with overflow-inline: clip — List does; any other host does it once. `hasRemoval` only says the row holds out after the action fires instead of springing back.",+ "Swipe actions for touch: the verbs a sideways drag uncovers on each side, outermost last, each `{id?, label, icon?, onActivate, isDisabled?, variant?: 'neutral' | 'accent' | 'destructive', hasRemoval?}`. `leading` is uncovered by a drag toward the inline end, `trailing` toward the inline start. A mouse never starts the drag and a mostly vertical drag stays the scroller's. The gesture is a touch accelerator and never a row's only path to a verb: a verb reachable only by swipe is unreachable by keyboard and by mouse, so every entry must also be reachable through the row's own content. Served on a row whose role permits interactive descendants (a listitem, a row with no role) and not on an option, a menu item, or a row that is the enlarged target of a native radio. The element containing the rows clips in the inline axis with overflow-inline: clip — List does; any other host does it once. `hasRemoval` only says the row holds out after the action fires instead of springing back. The gesture and its panels are loaded on demand the first time a row has swipe actions, so a row without them ships none of it.",},{name: 'swipeBehavior',diff --git a/packages/core/src/Item/Item.source-build.test.mjs b/packages/core/src/Item/Item.source-build.test.mjsnew file mode 100644index 0000000000..f9f6c16da7--- /dev/null+++ b/packages/core/src/Item/Item.source-build.test.mjs@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Item.source-build.test.mjs+ * @input Uses Babel, the core build config, and the Item and ItemSwipeLayer+ * sources+ * @output Verifies the shipped Item module reaches the swipe gesture only+ * through a dynamic import, so a row without swipe actions bundles none of it+ * @position Regression test for the import graph of the shipped Item module+ */++import fs from 'node:fs/promises';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {parseAsync, transformAsync} from '@babel/core';+import {describe, expect, it} from 'vitest';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CORE_ROOT = path.resolve(__dirname, '../..');++/**+ * The relative specifiers a compiled module imports, split into the static+ * ones (loaded with the module) and the dynamic ones (loaded on demand). Type+ * imports are gone by now: this is the graph a consumer's bundler sees.+ */+async function compiledImportsOf(fileName) {+ const file = path.join(__dirname, fileName);+ const source = await fs.readFile(file, 'utf8');+ const result = await transformAsync(source, {+ babelrc: false,+ configFile: path.join(CORE_ROOT, 'babel.config.json'),+ filename: file,+ });+ const ast = await parseAsync(result.code, {+ babelrc: false,+ configFile: false,+ filename: `${file}.js`,+ sourceType: 'module',+ });+ const statics = [];+ const dynamics = [];+ const visit = node => {+ if (node == null || typeof node !== 'object') {+ return;+ }+ if (Array.isArray(node)) {+ node.forEach(visit);+ return;+ }+ if (node.type === 'ImportDeclaration') {+ statics.push(node.source.value);+ } else if (+ node.type === 'ImportExpression' ||+ (node.type === 'CallExpression' && node.callee.type === 'Import')+ ) {+ const argument =+ node.type === 'ImportExpression' ? node.source : node.arguments[0];+ dynamics.push(argument.value);+ }+ for (const key of Object.keys(node)) {+ if (+ key !== 'loc' &&+ key !== 'leadingComments' &&+ key !== 'trailingComments'+ ) {+ visit(node[key]);+ }+ }+ };+ visit(ast.program.body);+ return {statics, dynamics};+}++describe('the shipped Item module and the swipe gesture', () => {+ it('reaches the swipe layer only through a dynamic import, and the gesture not at all', async () => {+ const {statics, dynamics} = await compiledImportsOf('Item.tsx');+ // The gesture and its panels are the layer's: a row without swipe actions+ // never loads them, so this module must not import them statically.+ expect(statics).not.toContainEqual(expect.stringMatching(/useSwipeAction/));+ expect(statics).not.toContainEqual(expect.stringMatching(/ItemSwipeLayer/));+ expect(dynamics).toEqual(['./ItemSwipeLayer.js']);+ });++ it('keeps the gesture inside the swipe layer', async () => {+ const {statics} = await compiledImportsOf('ItemSwipeLayer.tsx');+ expect(statics).toContain('./useSwipeAction.js');+ });+});diff --git a/packages/core/src/Item/Item.swipeLayer.test.tsx b/packages/core/src/Item/Item.swipeLayer.test.tsxnew file mode 100644index 0000000000..9f1ebc0398--- /dev/null+++ b/packages/core/src/Item/Item.swipeLayer.test.tsx@@ -0,0 +1,74 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Item.swipeLayer.test.tsx+ * @input Item with and without swipe actions; the swipe layer module, spied+ * @output Verifies a row without swipe actions never renders the swipe layer,+ * and a row with them renders it into the root once it has loaded+ * @position Companion to Item.test.tsx for the lazily loaded swipe layer+ */++import {createElement, type ReactNode} from 'react';+import {describe, expect, it, vi} from 'vitest';+import {act, render, screen, waitFor} from '@testing-library/react';+import {Item} from './Item';+import type {ItemSwipeLayerProps} from './ItemSwipeLayer';++const {layerRenders} = vi.hoisted(() => ({layerRenders: vi.fn()}));++vi.mock('./ItemSwipeLayer', async importOriginal => {+ const actual = await importOriginal<{+ default: (props: ItemSwipeLayerProps) => ReactNode;+ }>();+ return {+ ...actual,+ default: (props: ItemSwipeLayerProps) => {+ layerRenders();+ return createElement(actual.default, props);+ },+ };+});++describe('Item and the swipe layer', () => {+ it('renders a row without swipe actions with no swipe layer at all', async () => {+ render(+ <ul>+ <Item+ as="li"+ label="Inbox"+ description="12 unread"+ onClick={() => {}}+ />+ <Item as="li" label="Drafts" href="/drafts" data-testid="row" />+ <Item as="li" label="Archive" />+ </ul>,+ );+ // Let anything the first render scheduled — a lazy chunk resolving, an+ // effect — run before looking.+ await act(async () => {});+ expect(layerRenders).not.toHaveBeenCalled();+ expect(document.querySelector('[data-swipe-panel]')).toBeNull();+ expect(screen.getByTestId('row').childElementCount).toBe(1);+ });++ it('renders the swipe layer into the root of a row with swipe actions', async () => {+ render(+ <Item+ label="Inbox"+ data-testid="row"+ swipeActions={{trailing: [{label: 'Archive', onActivate: () => {}}]}}+ />,+ );+ const row = screen.getByTestId('row');+ const panel = await waitFor(() => {+ const found = row.querySelector('[data-swipe-panel="trailing"]');+ expect(found).not.toBeNull();+ return found;+ });+ expect(layerRenders).toHaveBeenCalled();+ // The layer adds nothing but the panel: the root is still the content+ // followed by the out-of-flow panel, with no wrapper for either.+ expect(panel?.parentElement).toBe(row);+ expect(row.childElementCount).toBe(2);+ });+});diff --git a/packages/core/src/Item/Item.test.tsx b/packages/core/src/Item/Item.test.tsxindex 3b46964b6f..6d68c32838 100644--- a/packages/core/src/Item/Item.test.tsx+++ b/packages/core/src/Item/Item.test.tsx@@ -10,8 +10,23 @@*/import {use, useRef} from 'react';-import {afterEach, beforeEach, describe, it, expect, vi} from 'vitest';-import {act, fireEvent, render, screen} from '@testing-library/react';+import {+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ it,+ expect,+ vi,+} from 'vitest';+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react';import {rulesDeclaredFor} from '../__tests__/pressState';import userEvent from '@testing-library/user-event';import {Item} from './Item';@@ -607,6 +622,26 @@ describe('Item', () => {});describe('swipeActions', () => {+ // The panels and the gesture are loaded lazily (React.lazy + Suspense), so+ // the first row with swipe actions renders them a tick after it mounts.+ // Mount one once up front: the resolved module is cached on the lazy+ // component, and every row below renders its panels synchronously.+ beforeAll(async () => {+ render(+ <Item+ label="Warm"+ data-testid="warm"+ swipeActions={{leading: [{label: 'Unread', onActivate: () => {}}]}}+ />,+ );+ await waitFor(() => {+ expect(+ screen.getByTestId('warm').querySelector('[data-swipe-panel]'),+ ).not.toBeNull();+ });+ cleanup();+ });+beforeEach(() => {// The gesture reads the clock for its fling test and its settle timers:// fake both, and space the moves out the way a finger does.diff --git a/packages/core/src/Item/Item.tsx b/packages/core/src/Item/Item.tsxindex 231b9dbbab..bbff0f0385 100644--- a/packages/core/src/Item/Item.tsx+++ b/packages/core/src/Item/Item.tsx@@ -8,19 +8,33 @@* @output Exports Item component, ItemProps type; publishes the shared inline inset* @position Core layout primitive; consumed by index.ts, tested by Item.test.tsx*+ * The swipe actions live in ItemSwipeLayer, reached only through a dynamic+ * import when `swipeActions` is set: this module imports nothing of the+ * gesture, so a row without swipe actions ships none of it. The root here+ * still carries the swipe styles and forwards its events into the bridge the+ * layer fills, so a swipeable row keeps the DOM and the event model it had+ * when the gesture was imported here (Item.source-build.test.mjs pins the+ * import graph).+ ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Item/Item.doc.mjs* - /packages/core/src/Item/Item.test.tsx+ * - /packages/core/src/Item/ItemSwipeLayer.tsx* - /packages/core/src/Item/index.ts* - /apps/storybook/stories/Item.stories.tsx* - /packages/cli/assets/templates/blocks/components/Item/ (showcase blocks)*/-import {useId, useRef, type ReactNode} from 'react';+import {+ lazy,+ Suspense,+ useCallback,+ useId,+ useRef,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import {- fontWeightVars,- typographyVars,colorVars,radiusVars,spacingVars,@@ -39,13 +53,15 @@ import {useDevWarning} from '../hooks/useDevWarning';import {themeProps} from '../utils/themeProps';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';-import {useMediaQuery} from '../hooks/useMediaQuery';import {usePressFeedback} from '../hooks/usePressFeedback';-import {- useSwipeAction,- type SwipeBehavior,- type SwipeSide,-} from './useSwipeAction';+import type {ItemSwipeBridge} from './ItemSwipeLayer';++// The gesture and the panels, loaded only by a row that has swipe actions: a+// row without them never bundles useSwipeAction. While the chunk loads the+// row is already painted and at rest — the panels show nothing at rest, so+// nothing appears or moves when the layer mounts; the gesture simply attaches+// once the chunk is ready, as ProgressBar's and Timestamp's lazy affordances do.+const LazyItemSwipeLayer = lazy(async () => import('./ItemSwipeLayer'));// =============================================================================// Types@@ -102,7 +118,7 @@ export interface ItemSwipeActions {* past the commit point slides the row out and fires the outermost entry;* nothing rests, and the panel is presentational.*/-export type ItemSwipeBehavior = SwipeBehavior;+export type ItemSwipeBehavior = 'reveal' | 'commit';export interface ItemProps extends BaseProps<HTMLElement> {/** Ref forwarded to the root element. */@@ -260,6 +276,10 @@ export interface ItemProps extends BaseProps<HTMLElement> {* them (`option`, `menuitem*`, a row that is the enlarged target of a native* radio). The element containing the rows clips in the inline axis* (`overflow-inline: clip`): `List` does; any other host does it once.+ *+ * The gesture and its panels are loaded on demand, the first time a row has+ * swipe actions, so a row without them ships none of it; a row with them is+ * drawn at once and becomes swipeable as soon as that module has loaded.*/swipeActions?: ItemSwipeActions;@@ -304,12 +324,8 @@ const SWIPE_ROLES = new Set(['listitem']);/** The travel a drag writes on the row root, in physical px (see useSwipeAction). */const SWIPE_TRAVEL = 'var(--_item-swipe-travel, 0px)';-/** +1 when the inline end is to the right, -1 under RTL; written beside the travel. */-const SWIPE_DIR = 'var(--_item-swipe-dir, 1)';/** The settle clock, `0s` while the finger drives the row. */const SWIPE_DURATION = 'var(--_item-swipe-duration, 0s)';-/** The travel measured toward the inline end. */-const SWIPE_LOGICAL_TRAVEL = `calc(${SWIPE_TRAVEL} * ${SWIPE_DIR})`;// =============================================================================// Styles@@ -469,95 +485,6 @@ const styles = stylex.create({transitionDuration: `${durationVars['--duration-fast-min']}, ${SWIPE_DURATION}`,transitionTimingFunction: `${easeVars['--ease-standard']}, ease-out`,},- // A side's panel: an out-of-flow child of the root at the inline start or- // end, counter-translated so it appears fixed in the space the row- // vacates, and exactly as wide as the travel toward its side — a padded box- // at `width: 0` would still paint its padding, so the panel has none; its- // entries carry their own. Not a pixel of it shows at rest.- swipePanel: {- position: 'absolute',- top: 0,- bottom: 0,- width: 0,- display: 'flex',- alignItems: 'stretch',- boxSizing: 'border-box',- overflow: 'hidden',- borderRadius: 'inherit',- transform: `translate3d(calc(-1 * ${SWIPE_TRAVEL}), 0, 0)`,- transitionProperty: 'transform, width',- transitionDuration: `${SWIPE_DURATION}, ${SWIPE_DURATION}`,- transitionTimingFunction: 'ease-out, ease-out',- },- swipePanelLeading: {- insetInlineStart: 0,- justifyContent: 'flex-start',- width: `max(0px, ${SWIPE_LOGICAL_TRAVEL})`,- },- swipePanelTrailing: {- insetInlineEnd: 0,- justifyContent: 'flex-end',- width: `max(0px, calc(-1 * ${SWIPE_LOGICAL_TRAVEL}))`,- },- // The entries at their natural width; the panel clips them to the travel.- // The outermost entry is the last, at the panel's outer edge: on the leading- // side that is the inline start, so the row of entries runs in reverse.- swipeEntries: {- display: 'flex',- flexShrink: 0,- height: '100%',- // The entries sit on the surface, not on the panel's own colour: the- // neutral variant is translucent and would otherwise take the outermost- // entry's colour through it.- backgroundColor: colorVars['--color-background-surface'],- },- swipeEntriesLeading: {- flexDirection: 'row-reverse',- },- swipeEntry: {- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- gap: spacingVars['--spacing-1'],- minWidth: 72,- height: '100%',- paddingInline: spacingVars['--spacing-3'],- boxSizing: 'border-box',- margin: 0,- borderWidth: 0,- borderStyle: 'none',- appearance: 'none',- cursor: {- default: 'pointer',- ':is(:disabled,[aria-disabled="true"])': 'default',- },- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-supporting-size'],- fontWeight: fontWeightVars['--font-weight-medium'],- lineHeight: typeScaleVars['--text-supporting-leading'],- whiteSpace: 'nowrap',- },- swipeEntryDisabled: {- opacity: 0.5,- },-});--// A verb's colour: ordinary, the one you mean, the dangerous one. The panel-// wears its outermost entry's, so a slide-out fills the row with it.-const swipeVariantStyles = stylex.create({- neutral: {- backgroundColor: colorVars['--color-neutral'],- color: colorVars['--color-text-primary'],- },- accent: {- backgroundColor: colorVars['--color-accent'],- color: colorVars['--color-on-accent'],- },- destructive: {- backgroundColor: colorVars['--color-error'],- color: colorVars['--color-on-error'],- },});const dynamicStyles = stylex.create({@@ -686,35 +613,12 @@ export function Item({(leadingSwipe.length > 1 || trailingSwipe.length > 1),);const swipeRootRef = useRef<HTMLElement | null>(null);- const leadingEntriesRef = useRef<HTMLDivElement | null>(null);- const trailingEntriesRef = useRef<HTMLDivElement | null>(null);- const isReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');- const outermost = (side: SwipeSide): ItemSwipeAction | undefined => {- const entries = side === 'leading' ? leadingSwipe : trailingSwipe;- return entries[entries.length - 1];- };- const swipe = useSwipeAction({- isEnabled: hasSwipe,- behavior: swipeBehavior,- sides: {- leading: leadingSwipe.length > 0,- trailing: trailingSwipe.length > 0,- },- measurePanel: side =>- (side === 'leading' ? leadingEntriesRef : trailingEntriesRef).current- ?.offsetWidth ?? 0,- fireOutermost: side => {- const entry = outermost(side);- if (entry == null || entry.isDisabled === true) {- return false;- }- void entry.onActivate();- return entry.hasRemoval === true;- },- isReducedMotion,- rootRef: swipeRootRef,- });- const isSwipeResting = swipe.state.phase === 'resting';+ // Filled by the swipe layer once it has mounted; empty until then and on a+ // row without swipe actions, when the forwarders below do nothing.+ const swipeBridgeRef = useRef<ItemSwipeBridge | null>(null);+ const setSwipeBridge = useCallback((bridge: ItemSwipeBridge | null) => {+ swipeBridgeRef.current = bridge;+ }, []);const linkRootProps = isLinkRoot? {// A disabled row keeps its place in the tree but goes nowhere.@@ -890,104 +794,40 @@ export function Item({const rootOnClick =hasSwipe && primaryOnClick != null? (event: React.MouseEvent<HTMLElement>) => {- if (swipe.shouldSuppressClick()) {+ if (swipeBridgeRef.current?.shouldSuppressClick() === true) {return;}primaryOnClick(event);}: primaryOnClick;- // A side's panel: entries as real buttons under `reveal`, presentational- // blocks under `commit`. Out of the accessibility tree and the tab order- // except while the row rests open, so the row keeps one tab stop and a- // pointer that can hover never meets it.- const renderSwipePanel = (side: SwipeSide, entries: ItemSwipeAction[]) => {- if (entries.length === 0) {- return null;- }- const outer = entries[entries.length - 1];- const isCommit = swipeBehavior === 'commit';- const isLive = isSwipeResting && !isCommit;- return (- <div- key={side}- data-swipe-panel={side}- inert={isLive ? undefined : true}- aria-hidden={isCommit ? true : undefined}- {...mergeProps(- themeProps('item-swipe-panel', {side}),- stylex.props(- styles.swipePanel,- side === 'leading'- ? styles.swipePanelLeading- : styles.swipePanelTrailing,- swipeVariantStyles[outer.variant ?? 'accent'],- ),- )}>- <div- ref={side === 'leading' ? leadingEntriesRef : trailingEntriesRef}- {...stylex.props(- styles.swipeEntries,- side === 'leading' && styles.swipeEntriesLeading,- )}>- {entries.map(entry => {- const variant = entry.variant ?? 'accent';- const content = (- <>- {entry.icon}- <span>{entry.label}</span>- </>- );- const entryStyle = stylex.props(- styles.swipeEntry,- swipeVariantStyles[variant],- entry.isDisabled === true && styles.swipeEntryDisabled,- );- if (isCommit) {- return (- <span- key={entry.id ?? entry.label}- {...mergeProps(- themeProps('item-swipe-action', {variant}),- entryStyle,- )}>- {content}- </span>- );- }- return (- <button- key={entry.id ?? entry.label}- type="button"- disabled={entry.isDisabled === true}- onClick={() =>- swipe.activateEntry(() => {- void entry.onActivate();- return entry.hasRemoval === true;- })- }- {...mergeProps(- themeProps('item-swipe-action', {variant}),- focusOutlineProps.focusVisible(- styles.swipeEntry,- swipeVariantStyles[variant],- entry.isDisabled === true && styles.swipeEntryDisabled,- ),- )}>- {content}- </button>- );- })}- </div>- </div>- );- };+ // The gesture's handlers, forwarded from the root into the bridge the swipe+ // layer fills: the root keeps the event model it had before the split — React's+ // own pointer, click-capture and key events on the row's root — while the+ // gesture itself lives in the lazily loaded layer. Until the layer has+ // mounted the bridge is empty and each forwarder does nothing.+ const swipeHandlers = hasSwipe+ ? {+ onPointerDown: (event: React.PointerEvent) =>+ swipeBridgeRef.current?.handlers.onPointerDown(event),+ onPointerMove: (event: React.PointerEvent) =>+ swipeBridgeRef.current?.handlers.onPointerMove(event),+ onPointerUp: (event: React.PointerEvent) =>+ swipeBridgeRef.current?.handlers.onPointerUp(event),+ onPointerCancel: (event: React.PointerEvent) =>+ swipeBridgeRef.current?.handlers.onPointerCancel(event),+ onClickCapture: (event: React.MouseEvent) =>+ swipeBridgeRef.current?.handlers.onClickCapture(event),+ onKeyDown: (event: React.KeyboardEvent) =>+ swipeBridgeRef.current?.handlers.onKeyDown(event),+ }+ : undefined;return (<Componentref={rootRef as React.Ref<never>}{...restProps}- {...(hasSwipe ? swipe.handlers : undefined)}+ {...swipeHandlers}{...linkRootProps}aria-selected={(allowsAriaSelected && isSelected) || undefined}// aria-selected is invalid on roles that don't permit it (listitem, a@@ -1024,8 +864,20 @@ export function Item({value={hasRenderableDescription ? descriptionID : null}>{innerContent}</ItemDescriptionContext>- {hasSwipe && renderSwipePanel('leading', leadingSwipe)}- {hasSwipe && renderSwipePanel('trailing', trailingSwipe)}+ {hasSwipe && (+ // The panels: out-of-flow children of this root, so the DOM is the one+ // the row had before the split. Suspense and lazy add no element, and+ // the fallback is nothing — at rest a panel shows nothing either.+ <Suspense fallback={null}>+ <LazyItemSwipeLayer+ rootRef={swipeRootRef}+ onBridge={setSwipeBridge}+ leading={leadingSwipe}+ trailing={trailingSwipe}+ behavior={swipeBehavior}+ />+ </Suspense>+ )}</Component>);}diff --git a/packages/core/src/Item/ItemSwipeLayer.tsx b/packages/core/src/Item/ItemSwipeLayer.tsxnew file mode 100644index 0000000000..22a05c0652--- /dev/null+++ b/packages/core/src/Item/ItemSwipeLayer.tsx@@ -0,0 +1,333 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ItemSwipeLayer.tsx+ * @input The row root (by ref), the swipe entries per side, the behavior;+ * useSwipeAction, theme tokens+ * @output Exports ItemSwipeLayer (default) — the panels of a row's swipe+ * actions and the gesture that uncovers them — and the ItemSwipeBridge type+ * through which the root reaches the gesture's handlers+ * @position Internal to Item, reached only through a dynamic import from+ * Item.tsx when `swipeActions` is set, so a row without them never loads+ * the gesture. Tested through Item.test.tsx and Item.source-build.test.mjs.+ *+ * The row's root stays Item's: it carries the swipe root styles and forwards+ * its pointer, click-capture and key events into the bridge this layer fills.+ * This layer renders the two panels as out-of-flow children of that root and+ * runs the gesture against it, so the DOM is the one Item rendered before the+ * split — no element is added for the swipe (spec AST-057, FR2).+ */++import {useEffect, useRef, type RefObject} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ fontWeightVars,+ typographyVars,+ colorVars,+ spacingVars,+ typeScaleVars,+} from '../theme/tokens.stylex';+import {mergeProps} from '../utils';+import {themeProps} from '../utils/themeProps';+import {focusOutlineProps} from '../utils/focusOutline.stylex';+import {useMediaQuery} from '../hooks/useMediaQuery';+import {+ useSwipeAction,+ type SwipeHandlers,+ type SwipeSide,+} from './useSwipeAction';+import type {ItemSwipeAction, ItemSwipeBehavior} from './Item';++// =============================================================================+// Types+// =============================================================================++/**+ * What the root needs from the gesture: the handlers it forwards its events+ * into, and the test for the click the browser synthesizes after a drag. The+ * layer writes it on every render; the root reads it on every event.+ */+export interface ItemSwipeBridge {+ handlers: SwipeHandlers;+ shouldSuppressClick: () => boolean;+}++export interface ItemSwipeLayerProps {+ /** The row root: the gesture's target and the element that translates. */+ rootRef: RefObject<HTMLElement | null>;+ /**+ * Called with the gesture for the root to forward into, after every render+ * of the layer, and with `null` when the layer leaves.+ */+ onBridge: (bridge: ItemSwipeBridge | null) => void;+ leading: ItemSwipeAction[];+ trailing: ItemSwipeAction[];+ behavior: ItemSwipeBehavior;+}++// =============================================================================+// Constants+// =============================================================================++// The custom properties the gesture writes on the root (see useSwipeAction;+// StyleX wants literals here, so the names are spelled out rather than imported).+/** The travel a drag writes on the row root, in physical px. */+const SWIPE_TRAVEL = 'var(--_item-swipe-travel, 0px)';+/** +1 when the inline end is to the right, -1 under RTL; written beside the travel. */+const SWIPE_DIR = 'var(--_item-swipe-dir, 1)';+/** The settle clock, `0s` while the finger drives the row. */+const SWIPE_DURATION = 'var(--_item-swipe-duration, 0s)';+/** The travel measured toward the inline end. */+const SWIPE_LOGICAL_TRAVEL = `calc(${SWIPE_TRAVEL} * ${SWIPE_DIR})`;++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ // A side's panel: an out-of-flow child of the root at the inline start or+ // end, counter-translated so it appears fixed in the space the row+ // vacates, and exactly as wide as the travel toward its side — a padded box+ // at `width: 0` would still paint its padding, so the panel has none; its+ // entries carry their own. Not a pixel of it shows at rest.+ swipePanel: {+ position: 'absolute',+ top: 0,+ bottom: 0,+ width: 0,+ display: 'flex',+ alignItems: 'stretch',+ boxSizing: 'border-box',+ overflow: 'hidden',+ borderRadius: 'inherit',+ transform: `translate3d(calc(-1 * ${SWIPE_TRAVEL}), 0, 0)`,+ transitionProperty: 'transform, width',+ transitionDuration: `${SWIPE_DURATION}, ${SWIPE_DURATION}`,+ transitionTimingFunction: 'ease-out, ease-out',+ },+ swipePanelLeading: {+ insetInlineStart: 0,+ justifyContent: 'flex-start',+ width: `max(0px, ${SWIPE_LOGICAL_TRAVEL})`,+ },+ swipePanelTrailing: {+ insetInlineEnd: 0,+ justifyContent: 'flex-end',+ width: `max(0px, calc(-1 * ${SWIPE_LOGICAL_TRAVEL}))`,+ },+ // The entries at their natural width; the panel clips them to the travel.+ // The outermost entry is the last, at the panel's outer edge: on the leading+ // side that is the inline start, so the row of entries runs in reverse.+ swipeEntries: {+ display: 'flex',+ flexShrink: 0,+ height: '100%',+ // The entries sit on the surface, not on the panel's own colour: the+ // neutral variant is translucent and would otherwise take the outermost+ // entry's colour through it.+ backgroundColor: colorVars['--color-background-surface'],+ },+ swipeEntriesLeading: {+ flexDirection: 'row-reverse',+ },+ swipeEntry: {+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: spacingVars['--spacing-1'],+ minWidth: 72,+ height: '100%',+ paddingInline: spacingVars['--spacing-3'],+ boxSizing: 'border-box',+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ appearance: 'none',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ whiteSpace: 'nowrap',+ },+ swipeEntryDisabled: {+ opacity: 0.5,+ },+});++// A verb's colour: ordinary, the one you mean, the dangerous one. The panel+// wears its outermost entry's, so a slide-out fills the row with it.+const swipeVariantStyles = stylex.create({+ neutral: {+ backgroundColor: colorVars['--color-neutral'],+ color: colorVars['--color-text-primary'],+ },+ accent: {+ backgroundColor: colorVars['--color-accent'],+ color: colorVars['--color-on-accent'],+ },+ destructive: {+ backgroundColor: colorVars['--color-error'],+ color: colorVars['--color-on-error'],+ },+});++// =============================================================================+// Component+// =============================================================================++/**+ * The swipe half of an `Item` with `swipeActions`: both panels, rendered into+ * the root Item owns, and the gesture that drives that root.+ */+export default function ItemSwipeLayer({+ rootRef,+ onBridge,+ leading,+ trailing,+ behavior,+}: ItemSwipeLayerProps) {+ const leadingEntriesRef = useRef<HTMLDivElement | null>(null);+ const trailingEntriesRef = useRef<HTMLDivElement | null>(null);+ const isReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');+ const outermost = (side: SwipeSide): ItemSwipeAction | undefined => {+ const entries = side === 'leading' ? leading : trailing;+ return entries[entries.length - 1];+ };+ const swipe = useSwipeAction({+ isEnabled: true,+ behavior,+ sides: {+ leading: leading.length > 0,+ trailing: trailing.length > 0,+ },+ measurePanel: side =>+ (side === 'leading' ? leadingEntriesRef : trailingEntriesRef).current+ ?.offsetWidth ?? 0,+ fireOutermost: side => {+ const entry = outermost(side);+ if (entry == null || entry.isDisabled === true) {+ return false;+ }+ void entry.onActivate();+ return entry.hasRemoval === true;+ },+ isReducedMotion,+ rootRef,+ });+ // The root forwards its events into what this publishes. Published from an+ // effect, like the gesture's own latest-callback refs: React flushes+ // effects before it delivers a discrete event, so a handler never meets a+ // stale bridge; and withdrawn when the layer leaves.+ useEffect(() => {+ onBridge({+ handlers: swipe.handlers,+ shouldSuppressClick: swipe.shouldSuppressClick,+ });+ return () => {+ onBridge(null);+ };+ });+ const isSwipeResting = swipe.state.phase === 'resting';++ // A side's panel: entries as real buttons under `reveal`, presentational+ // blocks under `commit`. Out of the accessibility tree and the tab order+ // except while the row rests open, so the row keeps one tab stop and a+ // pointer that can hover never meets it.+ const renderSwipePanel = (side: SwipeSide, entries: ItemSwipeAction[]) => {+ if (entries.length === 0) {+ return null;+ }+ const outer = entries[entries.length - 1];+ const isCommit = behavior === 'commit';+ const isLive = isSwipeResting && !isCommit;+ return (+ <div+ key={side}+ data-swipe-panel={side}+ inert={isLive ? undefined : true}+ aria-hidden={isCommit ? true : undefined}+ {...mergeProps(+ themeProps('item-swipe-panel', {side}),+ stylex.props(+ styles.swipePanel,+ side === 'leading'+ ? styles.swipePanelLeading+ : styles.swipePanelTrailing,+ swipeVariantStyles[outer.variant ?? 'accent'],+ ),+ )}>+ <div+ ref={side === 'leading' ? leadingEntriesRef : trailingEntriesRef}+ {...stylex.props(+ styles.swipeEntries,+ side === 'leading' && styles.swipeEntriesLeading,+ )}>+ {entries.map(entry => {+ const variant = entry.variant ?? 'accent';+ const content = (+ <>+ {entry.icon}+ <span>{entry.label}</span>+ </>+ );+ const entryStyle = stylex.props(+ styles.swipeEntry,+ swipeVariantStyles[variant],+ entry.isDisabled === true && styles.swipeEntryDisabled,+ );+ if (isCommit) {+ return (+ <span+ key={entry.id ?? entry.label}+ {...mergeProps(+ themeProps('item-swipe-action', {variant}),+ entryStyle,+ )}>+ {content}+ </span>+ );+ }+ return (+ <button+ key={entry.id ?? entry.label}+ type="button"+ disabled={entry.isDisabled === true}+ onClick={() =>+ swipe.activateEntry(() => {+ void entry.onActivate();+ return entry.hasRemoval === true;+ })+ }+ {...mergeProps(+ themeProps('item-swipe-action', {variant}),+ focusOutlineProps.focusVisible(+ styles.swipeEntry,+ swipeVariantStyles[variant],+ entry.isDisabled === true && styles.swipeEntryDisabled,+ ),+ )}>+ {content}+ </button>+ );+ })}+ </div>+ </div>+ );+ };++ return (+ <>+ {renderSwipePanel('leading', leading)}+ {renderSwipePanel('trailing', trailing)}+ </>+ );+}++ItemSwipeLayer.displayName = 'ItemSwipeLayer';diff --git a/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.ts b/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.tsindex 7c37800458..cf1696734c 100644--- a/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.ts+++ b/packages/core/src/Item/__tests__/ItemSwipeActions.a11y.chromium.spec.ts@@ -249,6 +249,9 @@ test('fires the outermost trailing entry on a fling and the row leaves', async (const rows = page.locator('.astryx-item');const row = rows.first();await expect(row.getByText('Message 1')).toBeVisible();+ // The gesture arrives with the lazily loaded swipe layer; its panel is the+ // sign the row can be dragged.+ await expect(row.locator('[data-swipe-panel="trailing"]')).toBeAttached();const before = await rows.count();const rest = await boxOf(row);const y = rest.y + rest.height / 2;@@ -286,6 +289,8 @@ test('the trailing panel: Delete is outermost and the panel wears its colour', a);const row = page.locator('.astryx-item').first();const panel = row.locator('[data-swipe-panel="trailing"]');+ // The gesture arrives with the lazily loaded swipe layer.+ await expect(panel).toBeAttached();const rest = await boxOf(row);const y = rest.y + rest.height / 2;const startX = rest.x + rest.width - 24;diff --git a/packages/core/src/Item/useSwipeAction.ts b/packages/core/src/Item/useSwipeAction.tsindex bf143fe69c..d8e97ce05e 100644--- a/packages/core/src/Item/useSwipeAction.ts+++ b/packages/core/src/Item/useSwipeAction.ts@@ -6,7 +6,8 @@* @file useSwipeAction.ts* @input Pointer events on a row's root; the root element to translate* @output Exports useSwipeAction — the gesture behind Item's `swipeActions`- * @position Internal to Item; tested through Item.test.tsx+ * @position Internal to Item, through ItemSwipeLayer (the only module that+ * imports it, loaded on demand); tested through Item.test.tsx** A native-list swipe: drag a row sideways and the side's panel is uncovered.* Under `reveal` a release past half the panel leaves the row resting opendiff --git a/packages/core/src/List/List.test.tsx b/packages/core/src/List/List.test.tsxindex 485be80759..57a530f241 100644--- a/packages/core/src/List/List.test.tsx+++ b/packages/core/src/List/List.test.tsx@@ -10,7 +10,7 @@*/import {describe, it, expect, vi} from 'vitest';-import {render, screen} from '@testing-library/react';+import {render, screen, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {rulesDeclaredFor} from '../__tests__/pressState';import {List} from './List';@@ -957,7 +957,7 @@ describe('List and swipe actions', () => {expect(rules.some(r => /overflow[-a-z]*: hidden/.test(r))).toBe(false);});- it('passes swipeActions and swipeBehavior through to the row unchanged', () => {+ it('passes swipeActions and swipeBehavior through to the row unchanged', async () => {render(<List><ListItem@@ -971,8 +971,12 @@ describe('List and swipe actions', () => {const row = screen.getByTestId('row');expect(row.tagName).toBe('LI');expect(row.parentElement).toBe(screen.getByRole('list'));- const panel = row.querySelector('[data-swipe-panel="trailing"]');- expect(panel).not.toBeNull();+ // The panel arrives with the lazily loaded swipe layer.+ const panel = await waitFor(() => {+ const found = row.querySelector('[data-swipe-panel="trailing"]');+ expect(found).not.toBeNull();+ return found;+ });// Commit: presentational.expect(panel).toHaveAttribute('aria-hidden', 'true');});