Skip to content

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

TypeScript

feat(ListInput): reveal row actions with their record and hang the grip beside the first field (#7949)

Ernest31e54e473021
diff --git a/packages/lab/src/ListInput/ListInput.doc.mjs b/packages/lab/src/ListInput/ListInput.doc.mjs
index 35b2843410..187dead0d4 100644
--- a/packages/lab/src/ListInput/ListInput.doc.mjs
+++ b/packages/lab/src/ListInput/ListInput.doc.mjs
@@ -95,7 +95,7 @@ export const docs = {
name: 'isReorderable',
type: 'boolean',
description:
- 'Shows a trailing vertical grip after the Remove action. During pointer reordering, list rows stay stationary while the source row and a free-moving duplicate that follows the pointer on both axes appear at 50% opacity as a temporary drag-only state; full opacity returns immediately on drop or cancel. Vertical pointer position determines the accent insertion line and final list placement. The controlled order commits and affected rows animate with Astryx motion tokens only on release. When the grip is focused, Arrow Up or Arrow Down immediately moves the record one position. Space or Enter starts lift mode for Arrow, Home, or End previewing; Space or Enter drops and Escape cancels. Focus and live announcements are preserved.',
+ 'Shows a vertical grip beside the first field of each record. The grip is a bare six-dot glyph with no button fill. It hangs in the inline-start gutter, outside the fields, so the fields and their labels never move, and it appears while the record is hovered or holds keyboard focus and stays visible on touch screens. Grip and clearance take 16px, so the grip sits inside the standard 16px container padding; give the list that much free inline-start space in a clipping or edge-to-edge container. During pointer reordering, list rows stay stationary while the source row and a free-moving duplicate that follows the pointer on both axes appear at 50% opacity as a temporary drag-only state; full opacity returns immediately on drop or cancel. Vertical pointer position determines the accent insertion line and final list placement. The controlled order commits and affected rows animate with Astryx motion tokens only on release. When the grip is focused, Arrow Up or Arrow Down immediately moves the record one position. Space or Enter starts lift mode for Arrow, Home, or End previewing; Space or Enter drops and Escape cancels. Focus and live announcements are preserved.',
default: 'false',
},
{
@@ -162,7 +162,7 @@ export const docs = {
{
guidance: true,
description:
- 'Forward both status and statusVariant from every column renderer to the rendered Astryx input so field messages use the control\'s native accessible tooltip pattern.',
+ "Forward both status and statusVariant from every column renderer to the rendered Astryx input so field messages use the control's native accessible tooltip pattern.",
},
{
guidance: true,
@@ -201,7 +201,7 @@ export const docs = {
name: 'First-record field labels',
required: true,
description:
- 'ListInput renders primary-tone column labels without separate table chrome and keeps each rendered control\'s own label visually hidden but semantically associated. At wider widths, repeated labels are visually hidden; when fields stack at 640px or narrower, every record shows its field labels.',
+ "ListInput renders primary-tone column labels without separate table chrome and keeps each rendered control's own label visually hidden but semantically associated. At wider widths, repeated labels are visually hidden; when fields stack at 640px or narrower, every record shows its field labels.",
},
{
name: 'Record fields',
@@ -213,13 +213,13 @@ export const docs = {
name: 'Remove action',
required: true,
description:
- 'Removes its record immediately, moves focus to a predictable neighboring control, and animates surviving rows into their new positions when supported. In the stacked layout, it aligns beside the first field at the top of the record.',
+ 'Removes its record immediately, moves focus to a predictable neighboring control, and animates surviving rows into their new positions when supported. It is revealed while the record is hovered or contains keyboard focus and stays visible on touch screens; at rest it is transparent but keeps its column and its place in the tab order, so the fields never shift. In the stacked layout, it aligns beside the first field at the top of the record.',
},
{
name: 'Reorder handle',
required: false,
description:
- 'A trailing vertical grip positioned after Remove, with an accessible label and no hover tooltip. In the stacked layout, both actions align beside the first field at the top of the record. Pointer dragging keeps the list stationary, fades both source and duplicate preview to 50%, lets the duplicate follow freely on both axes, and uses vertical position for the insertion line before committing and animating on release. A focused grip moves one position with Arrow Up or Arrow Down; Space or Enter also enables lift mode with Arrow, Home, End, drop, and Escape controls.',
+ "A bare six-dot grip beside the first field of the record, with an accessible label and no hover tooltip or button fill. Its target is 8px wide and as tall as the field, with 8px of clearance to the field, which keeps it within WCAG 2.5.8 through the spacing exception; the glyph uses the primary icon color and shows the standard focus ring. It hangs in the inline-start gutter, outside the fields, so the fields and their labels keep their positions, and grip plus clearance fit the standard 16px container padding. It is revealed while the record is hovered or contains keyboard focus and stays visible on touch screens. At rest it is transparent but stays in the tab order. While a record is being reordered its grip stays visible, and a pointer drag keeps the other records' grips hidden. In the stacked layout, the grip hangs beside the first field and Remove sits on the other side of that field at the top of the record. Pointer dragging keeps the list stationary, fades both source and duplicate preview to 50%, lets the duplicate follow freely on both axes, and uses vertical position for the insertion line before committing and animating on release. A focused grip moves one position with Arrow Up or Arrow Down; Space or Enter also enables lift mode with Arrow, Home, End, drop, and Escape controls.",
},
{
name: 'Empty state',
@@ -237,7 +237,7 @@ export const docs = {
name: 'Validation messages',
required: false,
description:
- 'Explain field-, item-, or list-level errors, warnings, and success states. Field messages use each input\'s native tooltip status affordance and do not change row height. Item messages align to the record fields without extending under reorder or remove controls.',
+ "Explain field-, item-, or list-level errors, warnings, and success states. Field messages use each input's native tooltip status affordance and do not change row height. Item messages align to the record fields without extending under the remove control.",
},
],
},
@@ -338,7 +338,7 @@ export const docsDense = {
getFieldStatus:
'Per-field resolver; complete status plus tooltip variant are forwarded to the rendered input.',
isReorderable:
- 'Adds a trailing grip without a tooltip. During the temporary drag state, source and free-moving preview use 50% opacity while the list stays stationary; full opacity returns on drop/cancel and tokenized motion animates the committed order. Vertical position controls insertion. Focused Arrow Up/Down moves immediately, and keyboard lift/move/drop/cancel is also supported.',
+ 'Adds a bare six-dot grip that hangs in the inline-start gutter beside the first field (fields never move; grip plus clearance take 16px, inside standard container padding), revealed on record hover or focus and always shown on touch, without a tooltip. During the temporary drag state, source and free-moving preview use 50% opacity while the list stays stationary; full opacity returns on drop/cancel and tokenized motion animates the committed order. Vertical position controls insertion. Focused Arrow Up/Down moves immediately, and keyboard lift/move/drop/cancel is also supported.',
isDisabled: 'Disables collection, actions, and rendered inputs.',
isLoading: 'Marks busy and prevents changes.',
maxItems: 'Makes Add unavailable at the limit.',
diff --git a/packages/lab/src/ListInput/ListInput.test.tsx b/packages/lab/src/ListInput/ListInput.test.tsx
index e4df0c6731..c3f915e3b5 100644
--- a/packages/lab/src/ListInput/ListInput.test.tsx
+++ b/packages/lab/src/ListInput/ListInput.test.tsx
@@ -3,7 +3,7 @@
/**
* @file ListInput.test.tsx
* @input Uses Vitest, Testing Library, and the controlled ListInput API
- * @output Behavioral coverage for list editing, pointer-stable adding, tokenized mutation motion, validation, focus, and free-floating stationary-list reordering
+ * @output Behavioral coverage for list editing, pointer-stable adding, tokenized mutation motion, validation, focus, the hover-revealed reorder grip that hangs beside the first field, and free-floating stationary-list reordering
* @position Lab tests; validates ListInput.tsx
*
* SYNC: When ListInput.tsx behavior changes, update these tests.
@@ -14,10 +14,12 @@ import {useState} from 'react';
import {
fireEvent,
render,
+ renderHook,
screen,
waitFor,
within,
} from '@testing-library/react';
+import {useContainerReveal} from '@astryxdesign/core/hooks';
import {TextInput} from '@astryxdesign/core/TextInput';
import {
ListInput,
@@ -114,6 +116,39 @@ function renderListInput(overrides: Partial<ListInputProps<Guest>> = {}) {
return render(<ListInput<Guest> {...props} />);
}
+function classTokens(element: Element | null): string[] {
+ return element?.getAttribute('class')?.split(/\s+/).filter(Boolean) ?? [];
+}
+
+// The reveal is CSS-only, so jsdom can only prove the wiring: each element
+// carries the classes the hook hands out for its role. The browser proves the
+// pixels (Storybook).
+function revealClasses() {
+ const {result} = renderHook(() => useContainerReveal());
+ const reveal = result.current;
+ const tokensOf = (props: {className?: string}) =>
+ props.className?.split(/\s+/).filter(Boolean) ?? [];
+ const container = tokensOf(reveal.getContainerProps());
+ const grip = tokensOf(
+ reveal.getContentRevealProps({isLayoutPreserved: true}),
+ );
+ const containerInactive = tokensOf(
+ reveal.getContainerProps({forceState: 'inactive'}),
+ );
+ const gripShown = tokensOf(
+ reveal.getContentRevealProps({
+ isLayoutPreserved: true,
+ forceVisibility: 'shown',
+ }),
+ );
+ return {
+ container,
+ grip,
+ onlyInactive: containerInactive.filter(token => !container.includes(token)),
+ onlyShown: gripShown.filter(token => !grip.includes(token)),
+ };
+}
+
const originalAnimateDescriptor = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
'animate',
@@ -695,6 +730,151 @@ describe('ListInput', () => {
).not.toBeInTheDocument();
});
+ it('hangs the grip beside the first field and reveals it on hover or focus', () => {
+ const reveal = revealClasses();
+ const {container} = renderListInput({isReorderable: true});
+ const row = container.querySelector<HTMLElement>('[data-list-input-row]');
+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});
+ const remove = screen.getByRole('button', {name: 'Remove guest 1'});
+ const [firstField] = within(row!).getAllByRole('textbox');
+
+ // The grip is the record's first control in reading and tab order. It sits
+ // in the first field's cell but hangs in the inline-start gutter, out of the
+ // flow, so the fields keep their columns.
+ expect(within(row!).getAllByRole('button')).toEqual([handle, remove]);
+ expect(row!.querySelector('[data-list-input-cell="0"]')).toContainElement(
+ handle,
+ );
+ expect(
+ handle.compareDocumentPosition(firstField) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+
+ // The row is the reveal container; the grip fades with opacity alone, so
+ // at rest it stays mounted, named, and focusable.
+ expect(reveal.container.length).toBeGreaterThan(0);
+ expect(classTokens(row)).toEqual(expect.arrayContaining(reveal.container));
+ expect(classTokens(handle.parentElement)).toEqual(
+ expect.arrayContaining(reveal.grip),
+ );
+ expect(handle).toBeEnabled();
+ expect(handle).not.toHaveAttribute('tabindex', '-1');
+ });
+
+ it('reveals Remove on hover or focus, with or without reordering', () => {
+ const reveal = revealClasses();
+ for (const isReorderable of [false, true]) {
+ const {container, unmount} = renderListInput({isReorderable});
+ const rows = container.querySelectorAll<HTMLElement>(
+ '[data-list-input-row]',
+ );
+ rows.forEach((row, index) => {
+ const remove = within(row).getByRole('button', {
+ name: `Remove guest ${index + 1}`,
+ });
+ // The row's direct child holding Remove is its control cell. It fades
+ // with opacity alone, so the button keeps its column, stays mounted,
+ // and stays in the tab order.
+ const removeCell = [...row.children].find(child =>
+ child.contains(remove),
+ );
+ expect(classTokens(row)).toEqual(
+ expect.arrayContaining(reveal.container),
+ );
+ expect(classTokens(removeCell ?? null)).toEqual(
+ expect.arrayContaining(reveal.grip),
+ );
+ expect(remove).toBeEnabled();
+ expect(remove).not.toHaveAttribute('tabindex', '-1');
+ });
+ unmount();
+ }
+ });
+
+ it('keeps the moving grip shown and quiets other rows during a pointer drag', () => {
+ const reveal = revealClasses();
+ expect(reveal.onlyShown.length).toBeGreaterThan(0);
+ expect(reveal.onlyInactive.length).toBeGreaterThan(0);
+ const {container} = renderListInput({isReorderable: true});
+ const rows = container.querySelectorAll<HTMLElement>(
+ '[data-list-input-row]',
+ );
+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});
+ const hasAll = (element: Element | null, tokens: string[]) =>
+ tokens.every(token => classTokens(element).includes(token));
+ const hasAny = (element: Element | null, tokens: string[]) =>
+ tokens.some(token => classTokens(element).includes(token));
+
+ fireEvent.pointerDown(handle, {
+ button: 0,
+ pointerId: 4,
+ clientX: 10,
+ clientY: 10,
+ });
+
+ expect(hasAll(handle.parentElement, reveal.onlyShown)).toBe(true);
+ expect(hasAny(rows[0], reveal.onlyInactive)).toBe(false);
+ expect(hasAll(rows[1], reveal.onlyInactive)).toBe(true);
+ // The duplicate under the pointer shows its grip too.
+ const previewGrip = document.querySelector(
+ '[data-list-input-drag-preview] [data-list-input-cell="0"] button',
+ );
+ expect(hasAll(previewGrip?.parentElement ?? null, reveal.onlyShown)).toBe(
+ true,
+ );
+
+ fireEvent.pointerUp(handle, {pointerId: 4, clientX: 10, clientY: 10});
+
+ expect(hasAny(handle.parentElement, reveal.onlyShown)).toBe(false);
+ expect(hasAny(rows[1], reveal.onlyInactive)).toBe(false);
+ });
+
+ it('keeps a lifted grip shown without quieting rows during keyboard reorder', () => {
+ const reveal = revealClasses();
+ const {container} = renderListInput({isReorderable: true});
+ const handle = screen.getByRole('button', {name: 'Reorder guest 1'});
+ const otherRow = container.querySelectorAll('[data-list-input-row]')[1];
+
+ handle.focus();
+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});
+ expect(classTokens(handle.parentElement)).toEqual(
+ expect.arrayContaining(reveal.onlyShown),
+ );
+ expect(
+ classTokens(otherRow).some(token => reveal.onlyInactive.includes(token)),
+ ).toBe(false);
+
+ fireEvent.keyDown(handle, {key: 'Escape'});
+ expect(
+ classTokens(handle.parentElement).some(token =>
+ reveal.onlyShown.includes(token),
+ ),
+ ).toBe(false);
+ });
+
+ it('focuses the first field of an added record, not its grip', () => {
+ function ReorderableList() {
+ const [value, setValue] = useState(guests);
+ return (
+ <ListInput<Guest>
+ label="Guests"
+ itemName="guest"
+ value={value}
+ onChange={setValue}
+ getItemKey={guest => guest.id}
+ createItem={() => createdGuest}
+ columns={columns}
+ isReorderable
+ />
+ );
+ }
+
+ render(<ReorderableList />);
+ fireEvent.click(screen.getByRole('button', {name: 'Add guest'}));
+
+ expect(screen.getByDisplayValue('Linus')).toHaveFocus();
+ });
+
it('supports consumer-owned validation that appears after blur', () => {
function BlurValidatedList() {
const [value, setValue] = useState<Guest[]>([guests[0]]);
@@ -819,7 +999,7 @@ describe('ListInput', () => {
render(<ArrowReorderList />);
const handle = screen.getByRole('button', {name: 'Reorder guest 1'});
- expect(handle).toHaveAttribute('data-size', 'md');
+ expect(handle).toHaveAttribute('type', 'button');
expect(
screen
.queryAllByRole('tooltip', {hidden: true})
@@ -931,7 +1111,7 @@ describe('ListInput', () => {
});
const remove = screen.getByRole('button', {name: 'Remove guest 2'});
const handle = screen.getByRole('button', {name: 'Reorder guest 2'});
- expect(within(rows[1]).getAllByRole('button')).toEqual([remove, handle]);
+ expect(within(rows[1]).getAllByRole('button')).toEqual([handle, remove]);
fireEvent.pointerDown(handle, {
button: 0,
diff --git a/packages/lab/src/ListInput/ListInput.tsx b/packages/lab/src/ListInput/ListInput.tsx
index 72522245aa..80f1cdbd5a 100644
--- a/packages/lab/src/ListInput/ListInput.tsx
+++ b/packages/lab/src/ListInput/ListInput.tsx
@@ -4,7 +4,7 @@
/**
* @file ListInput.tsx
- * @input React, StyleX, Astryx field/list/button/icon/layer/empty-state primitives, compact size context, browser scroll geometry, programmatic theme tokens, and shared Lab reorder styles
+ * @input React, StyleX, Astryx field/list/button/icon/layer/empty-state primitives, the container-reveal hook, compact size context, browser scroll geometry, programmatic theme tokens, and shared Lab reorder styles
* @output Exports ListInput and its controlled data, column, renderer, and change types
* @position Lab experiment (RFC facebook/astryx#4531) for editing compact repeated records
*
@@ -34,7 +34,11 @@ import {EmptyState} from '@astryxdesign/core/EmptyState';
import {Field, type InputStatus} from '@astryxdesign/core/Field';
import {FieldStatus} from '@astryxdesign/core/FieldStatus';
import {Icon} from '@astryxdesign/core/Icon';
-import {useAnnounce, useMediaQuery} from '@astryxdesign/core/hooks';
+import {
+ useAnnounce,
+ useContainerReveal,
+ useMediaQuery,
+} from '@astryxdesign/core/hooks';
import {IconButton} from '@astryxdesign/core/IconButton';
import {useTranslator} from '@astryxdesign/core/i18n';
import {useLayer} from '@astryxdesign/core/Layer';
@@ -49,7 +53,11 @@ import {
spacingVars,
typeScaleVars,
} from '@astryxdesign/core/theme/tokens.stylex';
-import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+import {
+ focusOutlineStyles,
+ mergeProps,
+ themeProps,
+} from '@astryxdesign/core/utils';
import {reorderStyles} from '../reorderStyles';
export type ListInputChange<T> =
@@ -231,15 +239,9 @@ const styles = stylex.create({
rowFieldsOnly: {
gridTemplateColumns: 'minmax(0, 1fr)',
},
- rowWithReorder: {
- gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']}`,
- },
rowWithRemove: {
gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']}`,
},
- rowWithBothControls: {
- gridTemplateColumns: `minmax(0, 1fr) ${sizeVars['--size-element-md']} ${sizeVars['--size-element-md']}`,
- },
fields: {
display: {
default: 'grid',
@@ -260,7 +262,6 @@ const styles = stylex.create({
},
contentOnly: {gridColumn: '1 / -1'},
contentBeforeOneControl: {gridColumn: '1 / -2'},
- contentBeforeBothControls: {gridColumn: '1 / -3'},
itemStatus: {
gridRow: {
default: '2',
@@ -299,6 +300,10 @@ const styles = stylex.create({
},
},
cellContent: {minWidth: 0},
+ // The first field's cell anchors the hanging reorder grip.
+ handleAnchor: {
+ position: 'relative',
+ },
controlCell: {
display: 'flex',
alignItems: 'center',
@@ -316,16 +321,45 @@ const styles = stylex.create({
'@container list-input (max-width: 640px)': '1',
},
},
- reorderControlCell: {
- gridColumn: {
- default: 'auto',
- '@container list-input (max-width: 640px)': '3',
- },
- gridRow: {
- default: 'auto',
- '@container list-input (max-width: 640px)': '1',
+ // The grip hangs in the inline-start gutter beside the first field's control,
+ // so it never takes width from the fields. Grip plus clearance is 16px, so it
+ // sits inside a container's standard padding. The padding bridges the gap to
+ // the field, so the row stays hovered while the pointer crosses to the grip.
+ reorderHandleHanger: {
+ position: 'absolute',
+ insetBlockStart: 0,
+ insetBlockEnd: 0,
+ insetInlineEnd: '100%',
+ display: 'flex',
+ alignItems: 'stretch',
+ paddingInlineEnd: spacingVars['--spacing-2'],
+ },
+ // A bare glyph rather than a filled button: an 8px-wide target the height of
+ // the field. It meets WCAG 2.5.8 through the spacing exception: the 8px
+ // clearance keeps a 24px circle centered on it clear of the field.
+ reorderGrip: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: spacingVars['--spacing-2'],
+ padding: 0,
+ margin: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: {
+ default: colorVars['--color-icon-primary'],
+ ':disabled': colorVars['--color-icon-disabled'],
},
},
+ reorderGripReveal: {
+ display: 'flex',
+ },
+ reorderGripGlyph: {
+ display: 'block',
+ flexShrink: 0,
+ width: spacingVars['--spacing-1-5'],
+ aspectRatio: '3 / 5',
+ },
emptyItem: {
width: '100%',
},
@@ -350,15 +384,17 @@ const dynamicStyles = stylex.create({
rowTransition: (name: string) => ({viewTransitionName: name}),
});
+// The six-dot grip drawn at its own size, so the narrow reorder target needs no
+// square icon box around it.
function GripVerticalIcon(props: SVGProps<SVGSVGElement>) {
return (
- <svg viewBox="0 0 24 24" fill="none" {...props}>
- <circle cx="9" cy="6" r="1.5" fill="currentColor" />
- <circle cx="15" cy="6" r="1.5" fill="currentColor" />
- <circle cx="9" cy="12" r="1.5" fill="currentColor" />
- <circle cx="15" cy="12" r="1.5" fill="currentColor" />
- <circle cx="9" cy="18" r="1.5" fill="currentColor" />
- <circle cx="15" cy="18" r="1.5" fill="currentColor" />
+ <svg viewBox="0 0 6 10" fill="none" aria-hidden="true" {...props}>
+ <circle cx="1" cy="1" r="1" fill="currentColor" />
+ <circle cx="5" cy="1" r="1" fill="currentColor" />
+ <circle cx="1" cy="5" r="1" fill="currentColor" />
+ <circle cx="5" cy="5" r="1" fill="currentColor" />
+ <circle cx="1" cy="9" r="1" fill="currentColor" />
+ <circle cx="5" cy="9" r="1" fill="currentColor" />
</svg>
);
}
@@ -387,8 +423,9 @@ function joinIDs(...ids: Array<string | undefined>): string | undefined {
return resolved.length > 0 ? resolved.join(' ') : undefined;
}
+// The reorder grip shares the first field's cell but is not a field.
const focusableFieldSelector =
- '[data-list-input-cell] input, [data-list-input-cell] select, [data-list-input-cell] textarea, [data-list-input-cell] button, [data-list-input-cell] [tabindex]:not([tabindex="-1"])';
+ '[data-list-input-cell] input, [data-list-input-cell] select, [data-list-input-cell] textarea, [data-list-input-cell] button:not([data-list-input-reorder]), [data-list-input-cell] [tabindex]:not([tabindex="-1"]):not([data-list-input-reorder])';
function getScrollableAncestors(element: HTMLElement): HTMLElement[] {
const scrollRoots: HTMLElement[] = [];
@@ -679,6 +716,9 @@ export function ListInput<T>({
show: showDragPreviewLayer,
hide: hideDragPreviewLayer,
} = useLayer({mode: 'fixed'});
+ // Each record row reveals its row actions (Remove and, when reorderable, the
+ // grip) on hover or keyboard focus; touch keeps them visible.
+ const {getContainerProps, getContentRevealProps} = useContainerReveal();
const setReorderState = (nextState: ReorderState<T> | null) => {
reorderStateRef.current = nextState;
@@ -698,7 +738,7 @@ export function ListInput<T>({
reorderState.toIndex,
);
}, [reorderState, value]);
- const showReorderColumn = isReorderable;
+ const showReorderHandle = isReorderable;
const showRemoveColumn = true;
const fieldGridTemplate = useMemo(
() => columns.map(column => resolveColumnTrack(column.width)).join(' '),
@@ -733,6 +773,7 @@ export function ListInput<T>({
}, [getItemKey, reorderState]);
const previewCloneKey =
reorderState?.mode === 'pointer' ? String(reorderState.itemKey) : null;
+ const isPointerReorderActive = previewCloneKey != null;
useEffect(() => {
if (process.env.NODE_ENV === 'production') {
@@ -1431,18 +1472,12 @@ export function ListInput<T>({
}
};
- const rowLayoutStyle = showReorderColumn
- ? showRemoveColumn
- ? styles.rowWithBothControls
- : styles.rowWithReorder
- : showRemoveColumn
- ? styles.rowWithRemove
- : styles.rowFieldsOnly;
- const contentGridStyle = showReorderColumn
- ? styles.contentBeforeBothControls
- : showRemoveColumn
- ? styles.contentBeforeOneControl
- : styles.contentOnly;
+ const rowLayoutStyle = showRemoveColumn
+ ? styles.rowWithRemove
+ : styles.rowFieldsOnly;
+ const contentGridStyle = showRemoveColumn
+ ? styles.contentBeforeOneControl
+ : styles.contentOnly;
const dragPreviewPosition =
reorderState?.mode === 'pointer' &&
reorderState.pointerClientX != null &&
@@ -1527,6 +1562,130 @@ export function ListInput<T>({
const itemStatusID = itemStatus?.message
? `${groupID}-item-${index}-status`
: undefined;
+ const reorderHandle = showReorderHandle ? (
+ <div {...stylex.props(styles.reorderHandleHanger)}>
+ <div
+ {...mergeProps(
+ getContentRevealProps({
+ isLayoutPreserved: true,
+ // The grip owns an active reorder, so it stays
+ // visible however the pointer moves.
+ forceVisibility: isActiveReorder
+ ? 'shown'
+ : undefined,
+ }),
+ // A flex row, so the grip stretches to the field's height.
+ stylex.props(styles.reorderGripReveal),
+ )}>
+ <button
+ type="button"
+ aria-label={t('@astryx.listInput.reorderItem', {
+ itemName,
+ position: index + 1,
+ })}
+ disabled={isDisabled || isLoading}
+ aria-describedby={reorderInstructionsID}
+ aria-pressed={isActiveReorder || undefined}
+ data-list-input-reorder=""
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.reorderGrip,
+ reorderStyles.handle,
+ isActiveReorder && reorderStyles.handleActive,
+ )}
+ onKeyDown={event =>
+ handleReorderKeyDown(event, item, index)
+ }
+ onBlur={() => {
+ const activeState = reorderStateRef.current;
+ if (
+ activeState?.mode === 'keyboard' &&
+ String(activeState.itemKey) === itemKeyString
+ ) {
+ cancelReorder();
+ }
+ }}
+ onPointerDown={event => {
+ if (event.button !== 0 || isDisabled || isLoading) {
+ return;
+ }
+ const sourceRow = rowRefs.current.get(itemKeyString);
+ if (sourceRow == null) {
+ return;
+ }
+ const bounds = sourceRow.getBoundingClientRect();
+ event.currentTarget.setPointerCapture?.(
+ event.pointerId,
+ );
+ startReorder(
+ item,
+ index,
+ 'pointer',
+ event.pointerId,
+ {
+ pointerStartX: event.clientX,
+ pointerStartY: event.clientY,
+ pointerOffsetX: event.clientX - bounds.left,
+ pointerOffsetY: event.clientY - bounds.top,
+ pointerClientX: event.clientX,
+ pointerClientY: event.clientY,
+ previewWidth: bounds.width,
+ },
+ );
+ }}
+ onPointerMove={handlePointerMove}
+ onPointerUp={event => {
+ const activeState = reorderStateRef.current;
+ if (
+ activeState?.mode === 'pointer' &&
+ activeState.pointerId === event.pointerId
+ ) {
+ commitReorder();
+ if (
+ event.currentTarget.hasPointerCapture?.(
+ event.pointerId,
+ )
+ ) {
+ event.currentTarget.releasePointerCapture?.(
+ event.pointerId,
+ );
+ }
+ }
+ }}
+ onPointerCancel={event => {
+ const activeState = reorderStateRef.current;
+ if (
+ activeState?.mode === 'pointer' &&
+ activeState.pointerId === event.pointerId
+ ) {
+ cancelReorder();
+ if (
+ event.currentTarget.hasPointerCapture?.(
+ event.pointerId,
+ )
+ ) {
+ event.currentTarget.releasePointerCapture?.(
+ event.pointerId,
+ );
+ }
+ }
+ }}
+ onLostPointerCapture={event => {
+ const activeState = reorderStateRef.current;
+ if (
+ activeState?.mode === 'pointer' &&
+ activeState.pointerId === event.pointerId
+ ) {
+ cancelReorder();
+ }
+ }}>
+ <GripVerticalIcon
+ {...stylex.props(styles.reorderGripGlyph)}
+ />
+ </button>
+ </div>
+ </div>
+ ) : null;
return (
<li
key={itemKey}
@@ -1553,13 +1712,23 @@ export function ListInput<T>({
}
}}
data-list-input-row={itemKeyString}
- {...stylex.props(
- styles.row,
- rowLayoutStyle,
- dynamicStyles.rowTransition(
- transitionName(groupID, itemKey),
+ {...mergeProps(
+ getContainerProps({
+ // A pointer drag owns the list: rows the pointer
+ // crosses stay quiet instead of lighting their grips.
+ forceState:
+ isPointerReorderActive && !isActiveReorder
+ ? 'inactive'
+ : undefined,
+ }),
+ stylex.props(
+ styles.row,
+ rowLayoutStyle,
+ dynamicStyles.rowTransition(
+ transitionName(groupID, itemKey),
+ ),
+ isPointerReorderSource && reorderStyles.source,
),
- isPointerReorderSource && reorderStyles.source,
)}>
<div
{...stylex.props(
@@ -1620,7 +1789,14 @@ export function ListInput<T>({
)}>
{column.header}
</span>
- <div {...stylex.props(styles.cellContent)}>
+ <div
+ {...stylex.props(
+ styles.cellContent,
+ columnIndex === 0 &&
+ showReorderHandle &&
+ styles.handleAnchor,
+ )}>
+ {columnIndex === 0 ? reorderHandle : null}
{content}
</div>
</div>
@@ -1629,9 +1805,14 @@ export function ListInput<T>({
</div>
{showRemoveColumn ? (
<div
- {...stylex.props(
- styles.controlCell,
- styles.removeControlCell,
+ {...mergeProps(
+ // Opacity only: Remove keeps its column, so the
+ // fields never shift when it appears.
+ getContentRevealProps({isLayoutPreserved: true}),
+ stylex.props(
+ styles.controlCell,
+ styles.removeControlCell,
+ ),
)}>
<IconButton
label={t('@astryx.listInput.removeItem', {
@@ -1657,122 +1838,6 @@ export function ListInput<T>({
/>
</div>
) : null}
- {showReorderColumn ? (
- <div
- {...stylex.props(
- styles.controlCell,
- styles.reorderControlCell,
- )}>
- <IconButton
- label={t('@astryx.listInput.reorderItem', {
- itemName,
- position: index + 1,
- })}
- icon={<Icon icon={GripVerticalIcon} size="sm" />}
- variant="ghost"
- size="md"
- isDisabled={isDisabled || isLoading}
- aria-describedby={reorderInstructionsID}
- aria-pressed={isActiveReorder || undefined}
- data-list-input-reorder=""
- xstyle={[
- reorderStyles.handle,
- isActiveReorder && reorderStyles.handleActive,
- ]}
- onKeyDown={event =>
- handleReorderKeyDown(event, item, index)
- }
- onBlur={() => {
- const activeState = reorderStateRef.current;
- if (
- activeState?.mode === 'keyboard' &&
- String(activeState.itemKey) === itemKeyString
- ) {
- cancelReorder();
- }
- }}
- onPointerDown={event => {
- if (
- event.button !== 0 ||
- isDisabled ||
- isLoading
- ) {
- return;
- }
- const sourceRow =
- rowRefs.current.get(itemKeyString);
- if (sourceRow == null) {
- return;
- }
- const bounds = sourceRow.getBoundingClientRect();
- event.currentTarget.setPointerCapture?.(
- event.pointerId,
- );
- startReorder(
- item,
- index,
- 'pointer',
- event.pointerId,
- {
- pointerStartX: event.clientX,
- pointerStartY: event.clientY,
- pointerOffsetX: event.clientX - bounds.left,
- pointerOffsetY: event.clientY - bounds.top,
- pointerClientX: event.clientX,
- pointerClientY: event.clientY,
- previewWidth: bounds.width,
- },
- );
- }}
- onPointerMove={handlePointerMove}
- onPointerUp={event => {
- const activeState = reorderStateRef.current;
- if (
- activeState?.mode === 'pointer' &&
- activeState.pointerId === event.pointerId
- ) {
- commitReorder();
- if (
- event.currentTarget.hasPointerCapture?.(
- event.pointerId,
- )
- ) {
- event.currentTarget.releasePointerCapture?.(
- event.pointerId,
- );
- }
- }
- }}
- onPointerCancel={event => {
- const activeState = reorderStateRef.current;
- if (
- activeState?.mode === 'pointer' &&
- activeState.pointerId === event.pointerId
- ) {
- cancelReorder();
- if (
- event.currentTarget.hasPointerCapture?.(
- event.pointerId,
- )
- ) {
- event.currentTarget.releasePointerCapture?.(
- event.pointerId,
- );
- }
- }
- }}
- onLostPointerCapture={event => {
- const activeState = reorderStateRef.current;
- if (
- activeState?.mode === 'pointer' &&
- activeState.pointerId === event.pointerId
- ) {
- cancelReorder();
- }
- }}
- />
- </div>
- ) : null}
{itemStatus?.message ? (
<FieldStatus
id={itemStatusID}
@@ -1812,7 +1877,7 @@ export function ListInput<T>({
/>
</div>
</div>
- {showReorderColumn ? (
+ {showReorderHandle ? (
<VisuallyHidden as="div" id={reorderInstructionsID}>
{t('@astryx.listInput.reorderInstructions')}
</VisuallyHidden>