Skip to content

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

TypeScript

feat(lab): TransferList reorders through core's createReorderable (#8143)

Christopher Chedeau36b8f6ebc00a
diff --git a/.changeset/core-internal-reorder-lab-transferlist.md b/.changeset/core-internal-reorder-lab-transferlist.md
new file mode 100644
index 0000000000..02a31ad2e6
--- /dev/null
+++ b/.changeset/core-internal-reorder-lab-transferlist.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: the undocumented `@astryxdesign/core/internal/reorder` entry lets Lab's `TransferList` and `TransferListSelector` reorder through a `createReorderable` object: `adaptReorderable` runs the owner's engine with the collection's own moves, and the owner's `start(key)` still finds the collection's list. Existing `List` callers are unchanged. Internal entries are outside the public API and its compatibility promise.
+
+@vjeux
diff --git a/apps/storybook/stories/TransferList.stories.tsx b/apps/storybook/stories/TransferList.stories.tsx
index abbd549b54..f0275018e6 100644
--- a/apps/storybook/stories/TransferList.stories.tsx
+++ b/apps/storybook/stories/TransferList.stories.tsx
@@ -16,7 +16,7 @@
* docs, and tests.
*/
-import {useEffect, useRef, useState, type SVGProps} from 'react';
+import {useEffect, useMemo, useRef, useState, type SVGProps} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {TransferList} from '@astryxdesign/lab';
@@ -24,6 +24,7 @@ import type {TransferListOption} from '@astryxdesign/lab';
import {Theme} from '@astryxdesign/core';
import {Button} from '@astryxdesign/core/Button';
import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';
+import {createReorderable} from '@astryxdesign/core';
import {Divider} from '@astryxdesign/core/Divider';
import {Heading} from '@astryxdesign/core/Heading';
import {Icon} from '@astryxdesign/core/Icon';
@@ -169,12 +170,33 @@ const BASIC_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
{value: 'created', label: 'Created', description: 'Original creation time'},
];
+/** The owner's reorder: each move lands in `setValue`'s value where reported. */
+function useMoveReorderable<T extends string>(
+ setValue: (update: (value: readonly T[]) => readonly T[]) => void,
+ isReorderable?: (value: T) => boolean,
+) {
+ return useMemo(
+ () =>
+ createReorderable<T>({
+ onReorder: ({key, to}) =>
+ setValue(current => {
+ const next = current.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+ }),
+ isReorderable,
+ }),
+ [setValue, isReorderable],
+ );
+}
+
function DefaultExample() {
const [value, setValue] = useState<readonly string[]>([
'name',
'owner',
'status',
]);
+ const reorderable = useMoveReorderable(setValue);
return (
<TransferList
label="Visible fields"
@@ -182,6 +204,7 @@ function DefaultExample() {
options={BASIC_OPTIONS}
value={value}
onChange={setValue}
+ reorderable={reorderable}
selectedLabel="Visible fields"
availableLabel="Available fields"
hasSelectAll
@@ -202,7 +225,6 @@ const LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
description: 'Required identity field',
group: 'Identity',
isTransferDisabled: true,
- isReorderDisabled: true,
disabledMessage: 'Name is required and fixed in position.',
},
{
@@ -219,9 +241,6 @@ const LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
label: 'Status',
description: 'Current workflow state',
group: 'Planning',
- isReorderDisabled: true,
- disabledMessage:
- 'Status can be hidden but its current position is fixed while selected.',
},
{
value: 'priority',
@@ -237,6 +256,9 @@ const LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
},
];
+/** The fields that keep their place in the selected list. */
+const FIXED_FIELDS = new Set(['name', 'status']);
+
function LockedExample() {
const [value, setValue] = useState<readonly string[]>([
'name',
@@ -244,13 +266,29 @@ function LockedExample() {
'status',
'updated',
]);
+ // The owner's reorder: Name and Status keep their place, and each move
+ // lands where TransferList reports it.
+ const reorderable = useMemo(
+ () =>
+ createReorderable<string>({
+ onReorder: ({key, to}) =>
+ setValue(current => {
+ const next = current.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+ }),
+ isReorderable: key => !FIXED_FIELDS.has(key),
+ }),
+ [],
+ );
return (
<TransferList
label="Record fields"
- description="Transfer and reorder are constrained per option, so a field can be locked in place without being locked in the list."
+ description="Transfer and reorder are constrained independently, so a field can be locked in place without being locked in the list."
options={LOCKED_OPTIONS}
value={value}
onChange={setValue}
+ reorderable={reorderable}
selectedLabel="Shown"
availableLabel="Hidden"
hasSelectAll
@@ -261,8 +299,10 @@ function LockedExample() {
/**
* TransferList has no component-wide disabled state. Availability is decided
- * per option, and the two constraints are independent: `isTransferDisabled`
- * pins an option to its panel, `isReorderDisabled` pins it to its position.
+ * per option, and the two constraints are independent. `isTransferDisabled`
+ * pins an option to its panel. The reorderable object's `isReorderable` takes
+ * away its reorder handle, and at either end of the selected list it also
+ * bounds the others.
*/
export const Locked: Story = {
render: () => <LockedExample />,
@@ -283,14 +323,13 @@ function UnorderedExample() {
onChange={setValue}
selectedLabel="Included"
availableLabel="Not included"
- isReorderable={false}
hasSelectAll
hasClear
/>
);
}
-/** `isReorderable={false}` for selections where order carries no meaning. */
+/** No `reorderable` for selections where order carries no meaning. */
export const Unordered: Story = {
render: () => <UnorderedExample />,
};
@@ -310,6 +349,7 @@ function SearchableExample() {
const [value, setValue] = useState<readonly string[]>(
LARGE_POOL_OPTIONS.slice(0, 12).map(option => option.value),
);
+ const reorderable = useMoveReorderable(setValue);
return (
<TransferList
label="Report fields"
@@ -317,6 +357,7 @@ function SearchableExample() {
options={LARGE_POOL_OPTIONS}
value={value}
onChange={setValue}
+ reorderable={reorderable}
selectedLabel="In report"
availableLabel="Available"
hasSearch
@@ -626,6 +667,12 @@ function TableColumnSettingsExample() {
setDraftColumns(nextColumns);
setActiveSavedView(findSavedViewValue(nextColumns));
};
+ // The draft is the order being edited, so a reorder moves the draft.
+ const draftColumnsRef = useRef(draftColumns);
+ draftColumnsRef.current = draftColumns;
+ const draftReorderable = useMoveReorderable<ProjectColumnKey>(update =>
+ changeDraftColumns(update(draftColumnsRef.current)),
+ );
const saveCurrentColumnsAsView = () => {
const nextNumber = nextSavedViewNumberRef.current;
@@ -704,6 +751,7 @@ function TableColumnSettingsExample() {
options={PROJECT_TRANSFER_OPTIONS}
value={draftColumns}
onChange={changeDraftColumns}
+ reorderable={draftReorderable}
selectedLabel="Visible fields"
availableLabel="Available fields"
hasSearch
diff --git a/apps/storybook/stories/TransferListA11y.stories.tsx b/apps/storybook/stories/TransferListA11y.stories.tsx
new file mode 100644
index 0000000000..e3503c2670
--- /dev/null
+++ b/apps/storybook/stories/TransferListA11y.stories.tsx
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferListA11y.stories.tsx
+ * @input TransferList with reordering, and a switch that disables the list
+ * @output A fixture for the Chromium check that a disabled list keeps each
+ * reorder handle focusable and disabled, with the focus where it was. It is
+ * excluded from the visual matrix
+ * @position Browser fixture for TransferList's disabled state
+ */
+
+import {useMemo, useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {TransferList} from '@astryxdesign/lab';
+import type {TransferListOption} from '@astryxdesign/lab';
+import {createReorderable} from '@astryxdesign/core';
+import {Switch} from '@astryxdesign/core/Switch';
+
+const meta: Meta = {
+ title: 'A11y/TransferList',
+ tags: ['no-visual'],
+};
+
+export default meta;
+
+const OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ {value: 'name', label: 'Name'},
+ {value: 'owner', label: 'Owner'},
+ {value: 'status', label: 'Status'},
+ {value: 'priority', label: 'Priority'},
+];
+
+export const Disabled: StoryObj = {
+ render: function DisabledStory() {
+ const [value, setValue] = useState<readonly string[]>([
+ 'name',
+ 'owner',
+ 'status',
+ ]);
+ const [isDisabled, setIsDisabled] = useState(false);
+ const reorderable = useMemo(
+ () =>
+ createReorderable<string>({
+ onReorder: ({key, to}) =>
+ setValue(current => {
+ const next = current.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+ }),
+ }),
+ [],
+ );
+ return (
+ <>
+ <Switch
+ label="Disable the list"
+ value={isDisabled}
+ onChange={checked => setIsDisabled(checked)}
+ />
+ <TransferList
+ label="Visible fields"
+ options={OPTIONS}
+ value={value}
+ onChange={setValue}
+ reorderable={reorderable}
+ isDisabled={isDisabled}
+ />
+ </>
+ );
+ },
+};
diff --git a/apps/storybook/stories/TransferListSelector.stories.tsx b/apps/storybook/stories/TransferListSelector.stories.tsx
index 568827d6a8..c57742bda2 100644
--- a/apps/storybook/stories/TransferListSelector.stories.tsx
+++ b/apps/storybook/stories/TransferListSelector.stories.tsx
@@ -14,8 +14,9 @@
* SYNC: When selector commit behavior changes, update source, docs, and tests.
*/
-import {useState} from 'react';
+import {useMemo, useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
+import {createReorderable} from '@astryxdesign/core';
import {TransferListSelector} from '@astryxdesign/lab';
import type {TransferListOption, TransferListProps} from '@astryxdesign/lab';
@@ -92,15 +93,37 @@ const BASIC_TRANSFER_LIST_PROPS = {
hasClear: true,
} satisfies Omit<TransferListProps<string>, 'value' | 'onChange'>;
+/** The owner's reorder: each move lands in `setValue`'s value where reported. */
+function useMoveReorderable<T extends string>(
+ setValue: (update: (value: readonly T[]) => readonly T[]) => void,
+ isReorderable?: (value: T) => boolean,
+) {
+ return useMemo(
+ () =>
+ createReorderable<T>({
+ onReorder: ({key, to}) =>
+ setValue(current => {
+ const next = current.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+ }),
+ isReorderable,
+ }),
+ [setValue, isReorderable],
+ );
+}
+
function DefaultExample() {
const defaults = ['name', 'owner', 'status'];
const [value, setValue] = useState<readonly string[]>(defaults);
+ const reorderable = useMoveReorderable(setValue);
return (
<TransferListSelector
{...BASIC_TRANSFER_LIST_PROPS}
description={BASIC_DESCRIPTION}
value={value}
onChange={setValue}
+ reorderable={reorderable}
triggerLabel={`${value.length} visible fields`}
/>
);
@@ -113,12 +136,15 @@ export const Default: Story = {
function StagedChangesExample() {
const defaults = ['name', 'owner', 'status'];
const [value, setValue] = useState<readonly string[]>(defaults);
+ // Staged: the selector moves its draft, and Apply commits it.
+ const stagedReorderable = useMoveReorderable(setValue);
return (
<TransferListSelector
{...BASIC_TRANSFER_LIST_PROPS}
description="Review the complete field selection before applying it."
value={value}
onChange={setValue}
+ reorderable={stagedReorderable}
commitBehavior="staged"
triggerLabel={`${value.length} visible fields`}
/>
@@ -136,7 +162,6 @@ const GROUPED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
description: 'Required identity field',
group: 'Identity',
isTransferDisabled: true,
- isReorderDisabled: true,
disabledMessage: 'Name is required and fixed in position.',
},
{
@@ -158,9 +183,6 @@ const GROUPED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
label: 'Status',
description: 'Current workflow state',
group: 'Planning',
- isReorderDisabled: true,
- disabledMessage:
- 'Status can be hidden but its current position is fixed while selected.',
},
{
value: 'priority',
@@ -188,9 +210,13 @@ const GROUPED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
},
];
+const isMovableField = (field: string) =>
+ field !== 'name' && field !== 'status';
+
function GroupedAndLockedExample() {
const defaults = ['name', 'owner', 'status', 'updated'];
const [value, setValue] = useState<readonly string[]>(defaults);
+ const reorderable = useMoveReorderable(setValue, isMovableField);
return (
<TransferListSelector
@@ -199,6 +225,8 @@ function GroupedAndLockedExample() {
options={GROUPED_OPTIONS}
value={value}
onChange={setValue}
+ // Name and Status keep their place.
+ reorderable={reorderable}
selectedLabel="Shown"
availableLabel="Hidden"
hasSelectAll
@@ -228,7 +256,6 @@ function UnorderedExample() {
onChange={setValue}
selectedLabel="Included"
availableLabel="Not included"
- isReorderable={false}
hasSelectAll
hasClear
triggerLabel={`${value.length} included filters`}
@@ -258,7 +285,6 @@ function NarrowContainerExample() {
placement="below"
selectedLabel="Visible"
availableLabel="Available"
- isReorderable={false}
hasSelectAll
hasClear
/>
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index 50fa9a1cc9..7b1444605a 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -298,7 +298,10 @@ those contracts.
(`spec:AST-094` FR4, `spec:AST-108` FR3), a closed-form curve played with
retargets, a companion on its clock and a chosen start (`spec:AST-094` FR5,
FR6), and the Reduce Motion substitution for a move, an entrance or an exit
- (`design:reduced-motion` DR1–DR3); and the touch hit-area expansion.
+ (`design:reduced-motion` DR1–DR3); the touch hit-area expansion; and List's
+ reorder session, for a collection that adapts the reorderable object to its
+ own values or whose rows are not `ListItem`s (`createReorderable`'s
+ plain-element `attach`, `spec:AST-103` FR4b, is not built).
Components import
them statically, and the bundler
keeps one copy per page however many components use them. A touch
diff --git a/packages/core/package.json b/packages/core/package.json
index 01bac0aa56..9ae0551908 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -834,6 +834,11 @@
"types": "./dist/internal/indicatorPress.stylex.d.ts",
"default": "./dist/internal/indicatorPress.stylex.js"
},
+ "./internal/reorder": {
+ "source": "./src/internal/reorder.ts",
+ "types": "./dist/internal/reorder.d.ts",
+ "default": "./dist/internal/reorder.js"
+ },
"./internal/touchHitArea.stylex": {
"source": "./src/internal/touchHitArea.stylex.ts",
"types": "./dist/internal/touchHitArea.stylex.d.ts",
diff --git a/packages/core/src/List/listReorderContext.ts b/packages/core/src/List/listReorderContext.ts
index 5a971e2aa6..64195d8e55 100644
--- a/packages/core/src/List/listReorderContext.ts
+++ b/packages/core/src/List/listReorderContext.ts
@@ -36,6 +36,12 @@ export interface ListReorderOptions {
readonly onReorder: (move: {key: Key; to: number}) => void;
/** Whether the item with `key` moves; every item does without it. */
readonly isReorderable?: (key: Key) => boolean;
+ /**
+ * An adapted object's (internal/reorder `adaptReorderable`): the owner's
+ * options, which the owner's `start` finds this list by, while the moves go
+ * through these.
+ */
+ readonly startedBy?: ListReorderOptions;
}
/** The handle a reorderable row ends with (List/ListReorderHandle.tsx). */
diff --git a/packages/core/src/List/listReorderEngine.tsx b/packages/core/src/List/listReorderEngine.tsx
index 50e675cb83..41f10bdc56 100644
--- a/packages/core/src/List/listReorderEngine.tsx
+++ b/packages/core/src/List/listReorderEngine.tsx
@@ -2144,10 +2144,14 @@ function ListReorderHost({reorder}: {reorder: ListReorderContextValue}) {
});
// The list's own pointer listeners, on its DOM element.
useIsomorphicLayoutEffect(() => controller.attachMouse(), [controller]);
- // Where the object's `start` finds this list.
+ // The owner's options, for an object a Lab collection adapted from the
+ // owner's.
+ const startedBy = options.startedBy ?? options;
+ // Registers this list in the sessions the object's `start` searches, a
+ // registry outside React.
useIsomorphicLayoutEffect(
- () => mountSession(options, controller),
- [options, controller],
+ () => mountSession(startedBy, controller),
+ [startedBy, controller],
);
// The List stopped reordering, or unmounted: a drag goes home.
useIsomorphicLayoutEffect(() => () => controller.dispose(), [controller]);
diff --git a/packages/core/src/internal/reorder.ts b/packages/core/src/internal/reorder.ts
new file mode 100644
index 0000000000..72725fc387
--- /dev/null
+++ b/packages/core/src/internal/reorder.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file reorder.ts
+ * @input A reorderable object made by createReorderable
+ * @output `reorderableOptions`: the options a reorderable object was made
+ * with. `adaptReorderable`: an object that runs the owner's engine with
+ * other options. A Lab collection uses it to adapt the owner's moves, such
+ * as a staged selector that aims them at its draft. The owner's `start`
+ * still finds its list. Neither loads the reorder engine: it comes with the
+ * owner's object
+ * @position `@astryxdesign/core/internal/reorder`: an internal entry reserved
+ * for Core and Lab. It is undocumented, outside the public API and its
+ * compatibility promise, and versioned in lockstep with Core.
+ */
+
+import {
+ REORDER_ENGINE,
+ type ListReorderOptions,
+ type ReorderableInternals,
+} from '../List/listReorderContext';
+import type {
+ Reorderable,
+ ReorderableOptions,
+} from '../reorderable/createReorderable';
+
+/** The options `reorderable` was made with by `createReorderable`. */
+export function reorderableOptions<TKey extends string | number, TTo>(
+ reorderable: Reorderable<TKey, TTo>,
+): ReorderableOptions<TKey, TTo> {
+ return (reorderable as unknown as ReorderableInternals)
+ .options as unknown as ReorderableOptions<TKey, TTo>;
+}
+
+/**
+ * An object that reorders with `reorderable`'s engine but `options`' moves
+ * and `isReorderable`: a Lab collection's adapter of the owner's object. The
+ * owner's `start(key)` still finds the collection's list,
+ * and its own `start` is the owner's.
+ */
+export function adaptReorderable<TKey extends string | number, TTo>(
+ reorderable: Reorderable<TKey, TTo>,
+ options: ReorderableOptions<TKey, TTo>,
+): Reorderable<TKey, TTo> {
+ const source = reorderable as unknown as ReorderableInternals;
+ const adapted: ReorderableInternals = {
+ options: {
+ ...(options as unknown as ListReorderOptions),
+ startedBy: source.options.startedBy ?? source.options,
+ },
+ [REORDER_ENGINE]: source[REORDER_ENGINE],
+ start: key => source.start(key),
+ };
+ return adapted as unknown as Reorderable<TKey, TTo>;
+}
diff --git a/packages/lab/src/TransferList/TransferList.composition.test.tsx b/packages/lab/src/TransferList/TransferList.composition.test.tsx
index 28d8865da0..54e8b1fd23 100644
--- a/packages/lab/src/TransferList/TransferList.composition.test.tsx
+++ b/packages/lab/src/TransferList/TransferList.composition.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When the ComplexSelector + TransferList staged contract changes, update this test.
*/
-import {useEffect, useRef, useState} from 'react';
+import {useEffect, useMemo, useRef, useState} from 'react';
import {describe, expect, it, vi} from 'vitest';
import {
fireEvent,
@@ -20,6 +20,7 @@ import {
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';
+import {createReorderable} from '@astryxdesign/core';
import {TransferList, type TransferListOption} from './TransferList';
type Column = 'name' | 'owner' | 'status' | 'updated';
@@ -68,6 +69,18 @@ function StagedColumnSelector({
const [appliedValue, setAppliedValue] =
useState<readonly Column[]>(initialValue);
const [draftValue, setDraftValue] = useState<readonly Column[]>(initialValue);
+ // The composition owns the draft, so its reorderable moves the draft.
+ const reorderable = useMemo(
+ () =>
+ createReorderable<Column>({
+ onReorder: ({key, to}) =>
+ setDraftValue(draft => {
+ const rest = draft.filter(item => item !== key);
+ return [...rest.slice(0, to), key, ...rest.slice(to)];
+ }),
+ }),
+ [],
+ );
return (
<>
@@ -105,6 +118,7 @@ function StagedColumnSelector({
options={OPTIONS}
value={draftValue}
onChange={setDraftValue}
+ reorderable={reorderable}
/>
<button type="button" onClick={close}>
Close
@@ -251,7 +265,7 @@ describe('ComplexSelector + TransferList composition', () => {
).toEqual(['Owner', 'Name']);
});
- it('lets Escape cancel an active reorder without closing the selector', async () => {
+ it('lets Escape end reorder mode without closing the selector', async () => {
const user = userEvent.setup();
const onCommit = vi.fn();
render(<StagedColumnSelector onCommit={onCommit} />);
@@ -272,15 +286,18 @@ describe('ComplexSelector + TransferList composition', () => {
...hidden,
});
reorder.focus();
+ // In reorder mode, a move changes the draft at once.
await user.keyboard('{Enter}{ArrowDown}');
expect(screen.getByTestId('draft-value')).toHaveTextContent(
'["status","name"]',
);
+ expect(reorder).toHaveAttribute('aria-pressed', 'true');
+ // Escape ends the mode, keeping the move, and leaves the selector open.
await user.keyboard('{Escape}');
-
+ expect(reorder).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByTestId('draft-value')).toHaveTextContent(
- '["name","status"]',
+ '["status","name"]',
);
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(onCommit).not.toHaveBeenCalled();
diff --git a/packages/lab/src/TransferList/TransferList.doc.mjs b/packages/lab/src/TransferList/TransferList.doc.mjs
index e5b099c6be..5b45910392 100644
--- a/packages/lab/src/TransferList/TransferList.doc.mjs
+++ b/packages/lab/src/TransferList/TransferList.doc.mjs
@@ -45,7 +45,7 @@ export const docs = {
name: 'options',
type: 'readonly TransferListOption<T>[]',
description:
- 'Complete option pool. Each option has value and label, with optional searchable description metadata, group, independent isTransferDisabled and isReorderDisabled constraints, and disabledMessage.',
+ "Complete option pool. Each option has value and label, with optional searchable description metadata, group, an isTransferDisabled constraint, and disabledMessage. Which options keep their place is the reorderable object's isReorderable.",
required: true,
},
{
@@ -119,11 +119,10 @@ export const docs = {
default: "'Search...'",
},
{
- name: 'isReorderable',
- type: 'boolean',
+ name: 'reorderable',
+ type: 'Reorderable<T>',
description:
- 'Shows a left-side grip for every selected option. Per-option isReorderDisabled keeps its grip visible but disabled and makes it a fixed-order barrier.',
- default: 'true',
+ "Makes the selected options reorderable: pass the object createReorderable makes. Each selected row ends with a reorder handle: on a touch screen hold the handle for a moment, then drag; a mouse drags at once; a tap, a click, Space or Enter on a handle turns on reorder mode for its row, in which each arrow key (or each move in the hint below the handle) moves it a place, and Escape, Done or another activation ends the mode, keeping the moves. The object's isReorderable(value) says which values move: one it rejects has no handle, and at either end of the selected list it also keeps the others from moving past it. In immediate behavior each move goes to the object's onReorder({key, to}); in staged behavior the selector moves its draft instead, so Cancel drops the move with the draft and Apply commits it through onChange. Reordering pauses while a search filters the panel. Without it, the selected options keep their order.",
},
{
name: 'hasSelectAll',
@@ -303,7 +302,7 @@ export const docs = {
name: 'onChange',
type: '(nextValue: readonly T[]) => void',
description:
- 'Called immediately after a permitted option is added, removed, bulk changed, or reordered.',
+ "Called immediately after a permitted option is added, removed, or bulk changed. Moves go to the reorderable object's onReorder instead.",
required: true,
},
{
@@ -344,11 +343,10 @@ export const docs = {
default: "'Search...'",
},
{
- name: 'isReorderable',
- type: 'boolean',
+ name: 'reorderable',
+ type: 'Reorderable<T>',
description:
- 'Enables pointer and keyboard ordering. Per-option isReorderDisabled keeps a visible disabled grip and fixed-order barrier.',
- default: 'true',
+ 'Makes the selected options reorderable through a handle at the end of each row: pass the object createReorderable makes. Its isReorderable(value) decides which options move (one it rejects at either end of the list also keeps the others from moving past it), and each move goes to its onReorder({key, to}), to being the index of the value in value after the move. Without it, the selected options keep their order.',
},
{
name: 'hasSelectAll',
@@ -402,7 +400,7 @@ export const docs = {
{
guidance: true,
description:
- 'Start with immediate behavior. Add, remove, bulk, and reorder changes call onChange as they occur, and closing or dismissing the popover keeps those committed changes.',
+ "Start with immediate behavior. Add, remove, and bulk changes call onChange as they occur and moves call the reorderable object's onReorder, and closing or dismissing the popover keeps those committed changes.",
},
{
guidance: true,
@@ -417,7 +415,12 @@ export const docs = {
{
guidance: true,
description:
- 'Use isTransferDisabled and isReorderDisabled independently. Provide disabledMessage whenever either action is unavailable so the constraint is discoverable.',
+ "Use isTransferDisabled and the reorderable object's isReorderable independently: isTransferDisabled pins an option to its panel, and isReorderable keeps an option in its place. Provide disabledMessage when a transfer is unavailable so the constraint is discoverable; a row that keeps its place shows no reorder handle, so say why in its content when it matters.",
+ },
+ {
+ guidance: true,
+ description:
+ "With no `reorderable`, TransferList no longer reorders; pass `reorderable={createReorderable(…)}`. Migrating from isReorderable: pass reorderable={createReorderable({onReorder, isReorderable})} instead. The isReorderable prop and each option's isReorderDisabled are gone; return false from the object's isReorderable(value) for an option that stays put.",
},
{
guidance: true,
@@ -427,7 +430,7 @@ export const docs = {
{
guidance: true,
description:
- 'Commit add, remove, bulk, and keyboard reorder changes immediately. During pointer reordering, keep rows stationary, lock the translucent preview to its source-column position, use vertical pointer movement to determine insertion, and commit once on release. Keep the preview in the nearest popover or dialog top layer.',
+ "Commit add, remove, and bulk changes immediately. A drag leaves the rows still: the row dims in place, a copy of it follows the finger or pointer, and an insertion line marks where it would land; the reorderable object's onReorder runs once on release.",
},
{
guidance: false,
@@ -469,7 +472,13 @@ export const docs = {
name: 'Row actions',
required: true,
description:
- 'Uses a direction-neutral X to remove and plus to add. Selected rows retain a start-aligned grip when reordering is enabled; constraints disable each control independently.',
+ 'Uses a direction-neutral X to remove and plus to add. Selected rows end with a reorder handle when reordering is enabled; a row that keeps its place has none, and transfer constraints disable the remove action.',
+ },
+ {
+ name: 'Reorder hint',
+ required: false,
+ description:
+ 'While a selected row is in reorder mode: the hint below its handle, whose Move up, Move down and Done are buttons.',
},
{
name: 'Bulk actions',
@@ -510,7 +519,7 @@ export const docs = {
},
{
className: 'astryx-transfer-list-item',
- visualProps: ['side', 'state'],
+ visualProps: ['side', 'state', 'reorder'],
},
],
},
@@ -555,7 +564,17 @@ export const docs = {
},
{
label: 'Independent transfer and reorder constraints',
- code: `<TransferListSelector
+ code: `const reorderable = useMemo(
+ () =>
+ createReorderable<string>({
+ onReorder: ({key, to}) => setFields(fields => moveTo(fields, key, to)),
+ // Status keeps its place, but can be removed.
+ isReorderable: value => value !== 'status',
+ }),
+ [],
+);
+
+<TransferListSelector
label="Visible fields"
options={[
{
@@ -564,17 +583,40 @@ export const docs = {
isTransferDisabled: true,
disabledMessage: 'Name must remain visible.',
},
- {
- value: 'status',
- label: 'Status',
- isReorderDisabled: true,
- disabledMessage: 'Status is fixed in position but can be removed.',
- },
+ {value: 'status', label: 'Status'},
{value: 'owner', label: 'Owner'},
]}
+ reorderable={reorderable}
value={fields}
onChange={setFields}
/>`,
+ },
+ {
+ label: 'Migrating from isReorderable to reorderable',
+ code: `// BEFORE: isReorderable turned reordering on, and an option opted out.
+<TransferList
+ options={[{value: 'name', label: 'Name', isReorderDisabled: true}, ...rest]}
+ isReorderable
+ value={fields}
+ onChange={setFields}
+/>;
+
+// AFTER: reordering is opt-in through the object createReorderable makes.
+const reorderable = useMemo(
+ () =>
+ createReorderable<string>({
+ onReorder: ({key, to}) => setFields(fields => moveTo(fields, key, to)),
+ isReorderable: value => value !== 'name',
+ }),
+ [],
+);
+
+<TransferList
+ options={[{value: 'name', label: 'Name'}, ...rest]}
+ reorderable={reorderable}
+ value={fields}
+ onChange={setFields}
+/>;`,
},
{
label: 'Saved views in a custom ComplexSelector',
@@ -678,7 +720,7 @@ export const docsDense = {
{
guidance: true,
description:
- 'Set transfer and reorder constraints independently and explain either with disabledMessage.',
+ 'Set transfer and reorder constraints independently and explain a locked transfer with disabledMessage.',
},
{
guidance: true,
@@ -699,7 +741,7 @@ export const docsDense = {
propDescriptions: {
label: 'External field label and accessible name.',
options:
- 'Full pool: value, label, description?, group?, isTransferDisabled?, isReorderDisabled?, disabledMessage?.',
+ 'Full pool: value, label, description?, group?, isTransferDisabled?, disabledMessage?.',
value: 'Committed selected values in display order.',
onChange:
'Called per edit in immediate behavior or from changed Apply in staged behavior.',
@@ -713,8 +755,8 @@ export const docsDense = {
hasSearch: 'Shared list filter; default false.',
searchLabel: 'Accessible search label.',
searchPlaceholder: 'Search placeholder.',
- isReorderable:
- 'Enable grip-based pointer and keyboard ordering; default true.',
+ reorderable:
+ 'createReorderable object for a trailing reorder handle (touch hold, mouse drag, keys); its isReorderable says which values move; staged moves change the draft; paused while searching.',
hasSelectAll: 'Add all transfer-enabled available options.',
hasClear: 'Remove all transfer-enabled selected options.',
renderOption: 'Custom row content.',
@@ -751,10 +793,10 @@ export const docsDense = {
label: 'Accessible control label.',
isLabelHidden: 'Hide control label visually, preserving its name.',
description: 'Supporting control guidance.',
- options:
- 'Full pool with metadata, groups, transfer constraints, and reorder constraints.',
+ options: 'Full pool with metadata, groups, and transfer constraints.',
value: 'Selected values in display order.',
- onChange: 'Called after each add/remove/bulk/reorder change.',
+ onChange:
+ 'Called after each add/remove/bulk change; moves go to onReorder.',
selectedLabel: 'Selected-list heading and name.',
availableLabel: 'Available-list heading and name.',
hasSearch: 'Shared list filter; default false.',
@@ -762,7 +804,8 @@ export const docsDense = {
'Disable every control; rows and search stay focusable; default false.',
searchLabel: 'Accessible search label.',
searchPlaceholder: 'Search placeholder.',
- isReorderable: 'Enable pointer and keyboard ordering; default true.',
+ reorderable:
+ 'createReorderable object (its isReorderable says which values move; its onReorder gets {key, to} in value terms); paused while searching.',
hasSelectAll: 'Add all transfer-enabled options.',
hasClear: 'Remove all transfer-enabled selected options.',
renderOption: 'Custom row content.',
diff --git a/packages/lab/src/TransferList/TransferList.test.tsx b/packages/lab/src/TransferList/TransferList.test.tsx
index 2bd40a6718..d5ccadf0b4 100644
--- a/packages/lab/src/TransferList/TransferList.test.tsx
+++ b/packages/lab/src/TransferList/TransferList.test.tsx
@@ -3,17 +3,29 @@
/**
* @file TransferList.test.tsx
* @input Uses Vitest, Testing Library, and the data-driven TransferList API
- * @output Behavioral coverage for immediate transfers, filtering, and vertically constrained pointer/keyboard reordering
+ * @output Behavioral coverage for immediate transfers, filtering, and
+ * reordering through core List's reorder handles, with keys here. The touch
+ * and mouse drags in a real browser are in the a11y Chromium specs
* @position Lab tests; validates TransferList.tsx
*
* SYNC: When TransferList.tsx behavior changes, update these tests.
*/
-import {useState} from 'react';
+import {useMemo, useState} from 'react';
import {afterEach, describe, expect, it, vi} from 'vitest';
-import {fireEvent, render, screen, within} from '@testing-library/react';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ within,
+ waitFor,
+} from '@testing-library/react';
+import fs from 'node:fs';
+import path from 'node:path';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
+import {createReorderable} from '@astryxdesign/core';
import {
TransferList,
type TransferListOption,
@@ -39,7 +51,6 @@ const LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
label: 'Owner',
group: 'Identity',
isTransferDisabled: true,
- isReorderDisabled: true,
disabledMessage: 'Owner is required and fixed in position.',
},
OPTIONS[2],
@@ -59,18 +70,16 @@ const TRANSFER_LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
OPTIONS[3],
];
-const REORDER_LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
- OPTIONS[0],
- {
- value: 'owner',
- label: 'Owner',
- group: 'Identity',
- isReorderDisabled: true,
- disabledMessage: 'Owner has a fixed position.',
- },
- OPTIONS[2],
- OPTIONS[3],
-];
+/** Moves `key` to index `to` of `value`: how an owner applies a move. */
+function moveValue(
+ value: readonly string[],
+ key: string,
+ to: number,
+): readonly string[] {
+ const next = value.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+}
type ControlledTransferListProps = Omit<
TransferListProps<string>,
@@ -79,15 +88,40 @@ type ControlledTransferListProps = Omit<
initialValue?: readonly string[];
onValueChange?: (value: readonly string[]) => void;
options?: ReadonlyArray<TransferListOption<string>>;
+ /**
+ * Values that keep their place: the helper's reorderable object rejects
+ * them in `isReorderable`. Its `onReorder` applies each move to its value.
+ */
+ fixed?: readonly string[];
+ /** Pass no reorderable object, so the selected options keep their order. */
+ isUnordered?: boolean;
};
function ControlledTransferList({
initialValue = [],
onValueChange,
options = OPTIONS,
+ fixed,
+ isUnordered = false,
...props
}: ControlledTransferListProps) {
const [value, setValue] = useState<readonly string[]>(initialValue);
+ const reorderable = useMemo(
+ () =>
+ isUnordered
+ ? undefined
+ : createReorderable<string>({
+ onReorder: ({key, to}) =>
+ setValue(current => {
+ const next = moveValue(current, key, to);
+ onValueChange?.(next);
+ return next;
+ }),
+ isReorderable:
+ fixed == null ? undefined : key => !fixed.includes(key),
+ }),
+ [fixed, isUnordered, onValueChange],
+ );
return (
<TransferList
@@ -100,32 +134,18 @@ function ControlledTransferList({
onValueChange?.(nextValue);
setValue(nextValue);
}}
+ {...(reorderable == null ? null : {reorderable})}
{...props}
/>
);
}
+const FIXED_OWNER: readonly string[] = ['owner'];
+
const testStyles = stylex.create({
root: (opacity: number) => ({opacity}),
});
-function mockRowBounds(rows: ReadonlyArray<HTMLElement>): void {
- rows.forEach((row, index) => {
- const top = index * 40;
- vi.spyOn(row, 'getBoundingClientRect').mockReturnValue({
- x: 0,
- y: top,
- top,
- right: 400,
- bottom: top + 40,
- left: 0,
- width: 400,
- height: 40,
- toJSON: () => {},
- });
- });
-}
-
afterEach(() => {
vi.restoreAllMocks();
});
@@ -234,9 +254,10 @@ describe('TransferList', () => {
const rowButtons = within(nameRow as HTMLLIElement).getAllByRole(
'button',
);
- expect(rowButtons[0]).toHaveAccessibleName('Reorder Name');
- expect(rowButtons[0].querySelector('.astryx-icon')).toBeInTheDocument();
- expect(rowButtons[1]).toHaveAccessibleName('Remove Name');
+ // The row's action, then List's reorder handle at the row's end.
+ expect(rowButtons[0]).toHaveAccessibleName('Remove Name');
+ expect(rowButtons[1]).toHaveAccessibleName('Reorder Name');
+ expect(rowButtons[1]).toHaveAttribute('data-astryx-list-reorder');
});
it('keeps support metadata out of rows while retaining search and groups', async () => {
@@ -272,6 +293,28 @@ describe('TransferList', () => {
expect(screen.getByTestId('custom-status')).toHaveTextContent(
'Custom Status',
);
+ // The handle is named after the row's text, not its place.
+ expect(
+ screen.getByRole('button', {name: 'Reorder Custom Name'}),
+ ).toBeInTheDocument();
+ });
+
+ it('names a reorder handle after its option when renderOption returns a component (spec:AST-103 FR4)', async () => {
+ function OptionLabel({label}: {label: string}) {
+ return <span>{label}</span>;
+ }
+ render(
+ <ControlledTransferList
+ initialValue={['name', 'status']}
+ renderOption={option => <OptionLabel label={option.label} />}
+ />,
+ );
+ expect(
+ await screen.findByRole('button', {name: 'Reorder Name'}),
+ ).toBeInTheDocument();
+ expect(
+ await screen.findByRole('button', {name: 'Reorder Status'}),
+ ).toBeInTheDocument();
});
it('renders custom empty-state copy for both panels', () => {
@@ -347,7 +390,7 @@ describe('TransferList', () => {
);
});
- it('disables search and enables reordering by default', () => {
+ it('disables search by default, and shows a reorder handle with reorderable', () => {
render(<ControlledTransferList initialValue={['name']} />);
expect(screen.queryByRole('searchbox')).not.toBeInTheDocument();
@@ -361,7 +404,7 @@ describe('TransferList', () => {
<ControlledTransferList
initialValue={['name']}
hasSearch
- isReorderable={false}
+ isUnordered
/>,
);
@@ -377,6 +420,7 @@ describe('TransferList', () => {
render(
<ControlledTransferList
options={LOCKED_OPTIONS}
+ fixed={['owner']}
initialValue={['owner', 'status']}
/>,
);
@@ -384,9 +428,11 @@ describe('TransferList', () => {
expect(
screen.getByRole('button', {name: 'Remove Owner'}),
).toHaveAttribute('aria-disabled', 'true');
+ // A row that keeps its place has no handle.
+ expect(screen.queryByRole('button', {name: 'Reorder Owner'})).toBeNull();
expect(
- screen.getByRole('button', {name: 'Reorder Owner'}),
- ).toHaveAttribute('aria-disabled', 'true');
+ screen.getByRole('button', {name: 'Reorder Status'}),
+ ).toBeInTheDocument();
});
it('applies transfer and reorder constraints independently', async () => {
@@ -398,15 +444,12 @@ describe('TransferList', () => {
isTransferDisabled: true,
disabledMessage: 'Owner is required.',
},
- {
- ...OPTIONS[2],
- isReorderDisabled: true,
- disabledMessage: 'Status has a fixed position.',
- },
+ OPTIONS[2],
];
render(
<ControlledTransferList
options={constrainedOptions}
+ fixed={['status']}
initialValue={['owner', 'status']}
onValueChange={onValueChange}
/>,
@@ -421,9 +464,7 @@ describe('TransferList', () => {
expect(
screen.getByRole('button', {name: 'Remove Status'}),
).not.toHaveAttribute('aria-disabled');
- expect(
- screen.getByRole('button', {name: 'Reorder Status'}),
- ).toHaveAttribute('aria-disabled', 'true');
+ expect(screen.queryByRole('button', {name: 'Reorder Status'})).toBeNull();
await user.click(screen.getByRole('button', {name: 'Remove Status'}));
expect(onValueChange).toHaveBeenCalledWith(['owner']);
@@ -529,346 +570,203 @@ describe('TransferList', () => {
});
});
- describe('pointer reordering', () => {
- it('promotes the drag preview to the top layer from inside a popover host', () => {
- const {container} = render(
- <div data-testid="popover-host" popover="auto">
- <ControlledTransferList initialValue={['name', 'owner', 'status']} />
- </div>,
- );
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
-
- const handle = container.querySelector<HTMLButtonElement>(
- '[aria-label="Reorder Owner"]',
- );
- expect(handle).not.toBeNull();
- fireEvent.pointerDown(handle as HTMLButtonElement, {
- button: 0,
- pointerId: 7,
- clientX: 300,
- clientY: 50,
+ describe('reordering through List', () => {
+ it("reports each move to an owner's reorderable object in value terms, never through onChange", async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const onReorder = vi.fn();
+ const reorderable = createReorderable<string>({
+ onReorder,
+ isReorderable: key => key !== 'owner',
});
-
- const preview = document.querySelector<HTMLElement>(
- '[data-transfer-list-drag-preview]',
- );
- // The ghost reaches the top layer through its host's popover attribute
- // rather than by being relocated into an ancestor. That keeps it painted
- // above this popover host while it still inherits the host's theme
- // variables, which a portal to document.body would have dropped.
- const layer = preview?.parentElement ?? null;
- expect(layer).toHaveAttribute('popover');
- expect(screen.getByTestId('popover-host')).toContainElement(layer);
- });
-
- it('cancels a pointer reorder when a second pointer lands, as a pinch does', () => {
- const onValueChange = vi.fn();
- const {container} = render(
- <ControlledTransferList
- initialValue={['name', 'owner', 'status']}
- onValueChange={onValueChange}
+ // `legacy` has no option: it keeps a place in the value, unshown.
+ render(
+ <TransferList
+ label="Columns"
+ options={OPTIONS}
+ value={['name', 'legacy', 'status', 'owner']}
+ onChange={onChange}
+ reorderable={reorderable}
/>,
);
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
- const handle = screen.getByRole('button', {name: 'Reorder Name'});
-
- fireEvent.pointerDown(handle, {
- button: 0,
- pointerId: 7,
- clientX: 300,
- clientY: 10,
- });
- fireEvent.pointerMove(handle, {pointerId: 7, clientX: 300, clientY: 34});
- expect(
- container.querySelector('[data-transfer-list-reorder-source]'),
- ).toBeInTheDocument();
-
- // The second finger of a pinch lands elsewhere on the page.
- fireEvent.pointerDown(document.body, {pointerId: 8, clientX: 600});
- expect(
- container.querySelector('[data-transfer-list-reorder-source]'),
- ).not.toBeInTheDocument();
-
- fireEvent.pointerMove(handle, {pointerId: 7, clientX: 300, clientY: 140});
- fireEvent.pointerUp(handle, {pointerId: 7, clientX: 300, clientY: 140});
- expect(onValueChange).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', {name: 'Reorder Owner'})).toBeNull();
+ screen.getByRole('button', {name: 'Reorder Name'}).focus();
+ await user.keyboard('{Enter}{ArrowDown}{Escape}');
+ // Name now follows Status: index 2 of the value, `legacy` counted.
+ expect(onReorder).toHaveBeenCalledOnce();
+ expect(onReorder).toHaveBeenCalledWith({key: 'name', to: 2});
+ expect(onChange).not.toHaveBeenCalled();
});
- it('keeps rows stationary, locks X, follows pointer Y, and commits once', () => {
+ it("applies an owner object's moves the way it reports them, a value without an option keeping its place among the hidden", async () => {
+ const user = userEvent.setup();
const onValueChange = vi.fn();
- const {container} = render(
+ render(
<ControlledTransferList
- initialValue={['name', 'owner', 'status']}
+ fixed={[]}
+ initialValue={['legacy', 'name', 'status', 'updated']}
onValueChange={onValueChange}
/>,
);
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
- const selectedList = screen.getByRole('list', {
- name: 'Selected columns',
- });
- const handle = screen.getByRole('button', {name: 'Reorder Owner'});
-
- fireEvent.pointerDown(handle, {
- button: 0,
- pointerId: 7,
- clientX: 300,
- clientY: 50,
- });
-
- const source = container.querySelector<HTMLElement>(
- '[data-transfer-list-reorder-source]',
- );
- const preview = document.querySelector<HTMLElement>(
- '[data-transfer-list-drag-preview]',
- );
- expect(source).toBe(rows[1]);
- expect(getComputedStyle(source!).opacity).toBe('0.5');
- expect(preview).toBeInTheDocument();
- expect(getComputedStyle(preview!).opacity).toBe('0.5');
- expect(preview).toHaveAttribute('aria-hidden', 'true');
- expect(preview).toHaveTextContent('Owner');
- // Placement lives on the layer as fixed insets. The coordinates come
- // from getBoundingClientRect, so reading them as viewport insets is what
- // keeps the ghost under the pointer once the page has been scrolled.
- expect(preview!.parentElement).toHaveStyle({top: '40px', left: '0px'});
- expect(
- container.querySelector('[data-transfer-list-drop-target]'),
- ).not.toBeInTheDocument();
-
- fireEvent.pointerMove(handle, {
- pointerId: 7,
- clientX: 345,
- clientY: 5,
- });
-
- expect(preview!.parentElement).toHaveStyle({top: '-5px', left: '0px'});
- expect([
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ]).toEqual(rows);
- expect(
- within(selectedList)
- .getAllByRole('listitem')
- .map(row => row.textContent?.trim()),
- ).toEqual(['Name', 'Owner', 'Status']);
- expect(onValueChange).not.toHaveBeenCalled();
- expect(rows[0]).toHaveAttribute(
- 'data-transfer-list-drop-target',
- 'before',
- );
-
- fireEvent.pointerMove(handle, {
- pointerId: 7,
- clientX: 245,
- clientY: 115,
- });
-
- expect(preview!.parentElement).toHaveStyle({top: '105px', left: '0px'});
- expect(rows[0]).not.toHaveAttribute('data-transfer-list-drop-target');
- expect(rows[2]).toHaveAttribute(
- 'data-transfer-list-drop-target',
- 'after',
- );
- expect(onValueChange).not.toHaveBeenCalled();
-
- fireEvent.pointerUp(handle, {
- pointerId: 7,
- clientX: 245,
- clientY: 115,
- });
-
- expect(onValueChange).toHaveBeenCalledOnce();
- expect(onValueChange).toHaveBeenCalledWith(['name', 'status', 'owner']);
- expect(
- document.querySelector('[data-transfer-list-drop-target]'),
- ).not.toBeInTheDocument();
- expect(
- document.querySelector('[data-transfer-list-drag-preview]'),
- ).not.toBeInTheDocument();
+ screen.getByRole('button', {name: 'Reorder Updated'}).focus();
+ await user.keyboard('{Enter}{ArrowUp}{ArrowUp}{Escape}');
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'legacy',
+ 'updated',
+ 'name',
+ 'status',
+ ]);
});
- it('ignores a horizontal-only gesture without changing the value', () => {
+ it('takes no change from a drag that drops after the list became disabled', () => {
const onValueChange = vi.fn();
- const {container} = render(
+ const {rerender} = render(
<ControlledTransferList
- initialValue={['name', 'owner']}
+ initialValue={['name', 'owner', 'status']}
onValueChange={onValueChange}
/>,
);
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
const handle = screen.getByRole('button', {name: 'Reorder Name'});
-
- fireEvent.pointerDown(handle, {
+ const list = handle.closest('ul');
+ if (list == null) {
+ throw new Error('no selected list');
+ }
+ // jsdom lays nothing out: 44 px rows from 300 px down the viewport.
+ const place = (row: Element) => Array.from(list.children).indexOf(row);
+ for (const row of Array.from(list.children)) {
+ Object.defineProperty(row, 'offsetParent', {
+ configurable: true,
+ get: () => list,
+ });
+ Object.defineProperty(row, 'offsetTop', {
+ configurable: true,
+ get: () => place(row) * 44,
+ });
+ Object.defineProperty(row, 'offsetHeight', {
+ configurable: true,
+ value: 44,
+ });
+ row.getBoundingClientRect = () =>
+ DOMRect.fromRect({
+ x: 0,
+ y: 300 + place(row) * 44,
+ width: 300,
+ height: 44,
+ });
+ }
+ const mouse = {
+ pointerType: 'mouse',
+ pointerId: 1,
button: 0,
- pointerId: 8,
- clientX: 10,
- clientY: 10,
- });
- expect(
- fireEvent.pointerMove(handle, {
- pointerId: 8,
- clientX: 210,
- clientY: 10,
- }),
- ).toBe(true);
- expect(
- container.querySelector('[data-transfer-list-reorder-source]'),
- ).toBeInTheDocument();
- expect(
- document.querySelector('[data-transfer-list-drag-preview]'),
- ).toBeInTheDocument();
- // A horizontal-only gesture must not move the ghost off the row it came
- // from: the drag is locked to the Y axis.
- expect(
- document.querySelector<HTMLElement>('[data-transfer-list-drag-preview]')
- ?.parentElement,
- ).toHaveStyle({top: '0px', left: '0px'});
- expect(
- container.querySelector('[data-transfer-list-drop-target]'),
- ).not.toBeInTheDocument();
+ clientX: 280,
+ };
+ fireEvent.pointerDown(handle, {...mouse, clientY: 322});
+ fireEvent.pointerMove(handle, {...mouse, clientY: 330});
+ fireEvent.pointerMove(handle, {...mouse, clientY: 392});
- fireEvent.pointerUp(handle, {
- pointerId: 8,
- clientX: 210,
- clientY: 10,
- });
-
- expect(onValueChange).not.toHaveBeenCalled();
- expect(
- container.querySelector('[data-transfer-list-reorder-source]'),
- ).not.toBeInTheDocument();
- expect(
- document.querySelector('[data-transfer-list-drag-preview]'),
- ).not.toBeInTheDocument();
- });
-
- it('cancels on pointer cancellation and does not suppress the next activation', () => {
- const onValueChange = vi.fn();
- const {container} = render(
+ rerender(
<ControlledTransferList
initialValue={['name', 'owner', 'status']}
onValueChange={onValueChange}
+ isDisabled
/>,
);
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
- const handle = screen.getByRole('button', {name: 'Reorder Owner'});
-
- fireEvent.pointerDown(handle, {
- button: 0,
- pointerId: 9,
- clientX: 300,
- clientY: 50,
- });
- fireEvent.pointerMove(handle, {
- pointerId: 9,
- clientX: 300,
- clientY: 5,
+ act(() => {
+ fireEvent.pointerUp(list, {...mouse, clientY: 392});
});
- fireEvent.pointerCancel(handle, {pointerId: 9});
-
expect(onValueChange).not.toHaveBeenCalled();
+ });
+
+ it('gives each selected row a List reorder handle and none to available rows', () => {
+ render(<ControlledTransferList initialValue={['name', 'status']} />);
+ const selected = screen.getByRole('list', {name: 'Selected columns'});
+ const available = screen.getByRole('list', {name: 'Available columns'});
expect(
- document.querySelector('[data-transfer-list-drag-preview]'),
- ).not.toBeInTheDocument();
+ within(selected).getAllByRole('button', {name: /^Reorder /}),
+ ).toHaveLength(2);
expect(
- container.querySelector('[data-transfer-list-reorder-source]'),
- ).not.toBeInTheDocument();
-
- fireEvent.click(handle);
- expect(handle).toHaveAttribute('aria-pressed', 'true');
- expect(onValueChange).not.toHaveBeenCalled();
+ within(available).queryAllByRole('button', {name: /^Reorder /}),
+ ).toHaveLength(0);
+ expect(
+ selected.querySelectorAll('[data-astryx-list-reorder]'),
+ ).toHaveLength(2);
});
- it('keeps reorder-disabled selected options as pointer-order barriers', () => {
- const onValueChange = vi.fn();
- const {container} = render(
+ it('turns reordering off while a search filters the panel', async () => {
+ const user = userEvent.setup();
+ render(
<ControlledTransferList
- options={REORDER_LOCKED_OPTIONS}
- initialValue={['name', 'owner', 'status', 'updated']}
- onValueChange={onValueChange}
+ initialValue={['name', 'owner', 'status']}
+ hasSearch
/>,
);
- const rows = [
- ...container.querySelectorAll<HTMLElement>('[data-transfer-list-row]'),
- ];
- mockRowBounds(rows);
- const handle = screen.getByRole('button', {name: 'Reorder Updated'});
-
- fireEvent.pointerDown(handle, {
- button: 0,
- pointerId: 10,
- clientX: 300,
- clientY: 130,
- });
- fireEvent.pointerMove(handle, {
- pointerId: 10,
- clientX: 300,
- clientY: 5,
- });
-
- expect(rows[2]).toHaveAttribute(
- 'data-transfer-list-drop-target',
- 'before',
- );
- fireEvent.pointerUp(handle, {
- pointerId: 10,
- clientX: 300,
- clientY: 5,
- });
-
- expect(onValueChange).toHaveBeenCalledOnce();
- expect(onValueChange).toHaveBeenCalledWith([
- 'name',
- 'owner',
- 'updated',
- 'status',
- ]);
+ expect(screen.getByRole('button', {name: 'Reorder Name'})).toBeVisible();
+ await user.type(screen.getByRole('searchbox'), 'n');
+ expect(screen.queryByRole('button', {name: 'Reorder Name'})).toBeNull();
+ await user.clear(screen.getByRole('searchbox'));
+ expect(screen.getByRole('button', {name: 'Reorder Name'})).toBeVisible();
});
- });
- describe('keyboard reordering', () => {
- it('moves immediately, keeps handle focus, and drops without another change', async () => {
+ it('reports each move so the owner keeps the shown rows in the order the list shows, around a value without an option', async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
render(
<ControlledTransferList
- initialValue={['name', 'owner', 'status']}
+ initialValue={['name', 'retired', 'owner', 'status']}
onValueChange={onValueChange}
/>,
);
-
- const handle = screen.getByRole('button', {name: 'Reorder Owner'});
- handle.focus();
- await user.keyboard('{Enter}{ArrowUp}');
-
- expect(onValueChange).toHaveBeenCalledTimes(1);
- expect(onValueChange).toHaveBeenLastCalledWith([
- 'owner',
- 'name',
- 'status',
- ]);
- expect(handle).toHaveFocus();
-
- await user.keyboard('{Enter}');
- expect(onValueChange).toHaveBeenCalledTimes(1);
- expect(handle).toHaveFocus();
+ // The rows the list shows: every value with an option, in value order.
+ const shown = () =>
+ (onValueChange.mock.lastCall?.[0] as readonly string[]).filter(
+ value => value !== 'retired',
+ );
+ screen.getByRole('button', {name: 'Reorder Owner'}).focus();
+ await user.keyboard(' {ArrowDown}');
+ expect(shown()).toEqual(['name', 'status', 'owner']);
+ await user.keyboard('{ArrowUp}{ArrowUp}{Escape}');
+ expect(shown()).toEqual(['owner', 'name', 'status']);
+ // The value without an option stays in the value, wherever the owner
+ // places it.
+ expect(onValueChange.mock.lastCall?.[0]).toContain('retired');
+ screen.getByRole('button', {name: 'Reorder Name'}).focus();
+ await user.keyboard(' {ArrowDown}{Escape}');
+ expect(shown()).toEqual(['owner', 'status', 'name']);
});
+ });
- it('supports Home and End while a value is grabbed', async () => {
+ describe('keyboard reordering', () => {
+ it.each([
+ ['Enter', '{Enter}'],
+ ['Space', ' '],
+ ])(
+ 'turns on reorder mode with %s: each arrow changes the value once, keeping handle focus',
+ async (_, press) => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status']}
+ onValueChange={onValueChange}
+ />,
+ );
+
+ const handle = screen.getByRole('button', {name: 'Reorder Owner'});
+ handle.focus();
+ await user.keyboard(press);
+ expect(handle).toHaveAttribute('aria-pressed', 'true');
+ await user.keyboard('{ArrowUp}');
+ expect(onValueChange).toHaveBeenCalledTimes(1);
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'owner',
+ 'name',
+ 'status',
+ ]);
+ expect(handle).toHaveFocus();
+ },
+ );
+
+ it('changes the value once per move', async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
render(
@@ -880,25 +778,25 @@ describe('TransferList', () => {
const handle = screen.getByRole('button', {name: 'Reorder Owner'});
handle.focus();
- await user.keyboard(' {End}{Home} ');
+ await user.keyboard(' {ArrowDown}{ArrowDown}');
expect(onValueChange).toHaveBeenNthCalledWith(1, [
'name',
'status',
- 'updated',
'owner',
+ 'updated',
]);
expect(onValueChange).toHaveBeenNthCalledWith(2, [
- 'owner',
'name',
'status',
'updated',
+ 'owner',
]);
expect(onValueChange).toHaveBeenCalledTimes(2);
expect(handle).toHaveFocus();
});
- it('restores the original order when a grabbed move is cancelled', async () => {
+ it('keeps the moves when Escape ends reorder mode', async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
render(
@@ -912,16 +810,13 @@ describe('TransferList', () => {
handle.focus();
await user.keyboard('{Enter}{ArrowDown}{Escape}');
- expect(onValueChange).toHaveBeenNthCalledWith(1, [
+ expect(handle).toHaveAttribute('aria-pressed', 'false');
+ expect(onValueChange).toHaveBeenCalledTimes(1);
+ expect(onValueChange).toHaveBeenLastCalledWith([
'name',
'status',
'owner',
]);
- expect(onValueChange).toHaveBeenNthCalledWith(2, [
- 'name',
- 'owner',
- 'status',
- ]);
expect(handle).toHaveFocus();
});
@@ -952,38 +847,173 @@ describe('TransferList', () => {
expect(onValueChange).toHaveBeenCalledTimes(1);
});
- it('does not allow a value to cross a reorder-disabled value', async () => {
+ it('keeps a focused handle focused, in the tab order and disabled when the list becomes disabled', async () => {
+ const {rerender} = render(
+ <ControlledTransferList initialValue={['name', 'owner', 'status']} />,
+ );
+ const handle = screen.getByRole('button', {name: 'Reorder Owner'});
+ handle.focus();
+
+ rerender(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status']}
+ isDisabled
+ />,
+ );
+ expect(handle).toHaveFocus();
+ expect(handle.tabIndex).toBe(0);
+ expect(handle).not.toHaveAttribute('disabled');
+ for (const each of screen.getAllByRole('button', {name: /^Reorder /})) {
+ expect(each).toHaveAttribute('aria-disabled', 'true');
+ }
+ // The handle's description says why the row does not move.
+ await waitFor(() =>
+ expect(handle).toHaveAccessibleDescription(/Owner cannot be reordered/),
+ );
+ });
+
+ it('describes the reorder handle, not a toggle that renderOption puts in the row, when the list is disabled', async () => {
+ render(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status']}
+ isDisabled
+ renderOption={option => (
+ <span>
+ {option.label}
+ <button type="button" aria-pressed="false">
+ {`Pin ${option.label}`}
+ </button>
+ </span>
+ )}
+ />,
+ );
+ const handle = screen.getByRole('button', {name: /^Reorder Owner/});
+ await waitFor(() =>
+ expect(handle).toHaveAccessibleDescription(/Owner cannot be reordered/),
+ );
+ expect(
+ screen.getByRole('button', {name: 'Pin Owner'}),
+ ).not.toHaveAccessibleDescription(/cannot be reordered/);
+ });
+
+ it('keeps values from passing a reorder-disabled value at an end, and lets them pass one in the middle', async () => {
const user = userEvent.setup();
const onValueChange = vi.fn();
- render(
+ const {unmount} = render(
<ControlledTransferList
- options={REORDER_LOCKED_OPTIONS}
- initialValue={['name', 'owner', 'status', 'updated']}
+ fixed={FIXED_OWNER}
+ initialValue={['owner', 'name', 'status', 'updated']}
onValueChange={onValueChange}
/>,
);
- const beforeBarrier = screen.getByRole('button', {
- name: 'Reorder Name',
- });
- beforeBarrier.focus();
- await user.keyboard('{Enter}{ArrowDown}{Enter}');
+ // Owner leads the list: nothing goes before it.
+ const name = screen.getByRole('button', {name: 'Reorder Name'});
+ name.focus();
+ await user.keyboard('{Enter}{ArrowUp}{Escape}');
expect(onValueChange).not.toHaveBeenCalled();
- const afterBarrier = screen.getByRole('button', {
- name: 'Reorder Updated',
- });
- afterBarrier.focus();
- await user.keyboard('{Enter}{Home}');
+ const updated = screen.getByRole('button', {name: 'Reorder Updated'});
+ updated.focus();
+ await user.keyboard('{Enter}{ArrowUp}{ArrowUp}{ArrowUp}{Escape}');
+ expect(onValueChange).toHaveBeenCalledTimes(2);
expect(onValueChange).toHaveBeenLastCalledWith([
- 'name',
'owner',
'updated',
+ 'name',
'status',
]);
- await user.keyboard('{ArrowUp}{Enter}');
- expect(onValueChange).toHaveBeenCalledTimes(1);
- expect(afterBarrier).toHaveFocus();
+ expect(updated).toHaveFocus();
+ unmount();
+
+ // In the middle, Owner is passed like any other row.
+ onValueChange.mockClear();
+ render(
+ <ControlledTransferList
+ fixed={FIXED_OWNER}
+ initialValue={['name', 'owner', 'status', 'updated']}
+ onValueChange={onValueChange}
+ />,
+ );
+ screen.getByRole('button', {name: 'Reorder Name'}).focus();
+ await user.keyboard('{Enter}{ArrowDown}{Escape}');
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'owner',
+ 'name',
+ 'status',
+ 'updated',
+ ]);
});
});
});
+
+describe("the owner's reorderable object", () => {
+ it("its start(key) turns on reorder mode for that row in TransferList's list (spec:AST-103 FR4a)", () => {
+ let start: ((key: string) => void) | undefined;
+ function Owned() {
+ const [value, setValue] = useState<readonly string[]>(['name', 'status']);
+ const reorderable = useMemo(
+ () =>
+ createReorderable<string>({
+ onReorder: ({key, to}) =>
+ setValue(current => moveValue(current, key, to)),
+ }),
+ [],
+ );
+ start = key => reorderable.start(key);
+ return (
+ <TransferList
+ label="Columns"
+ selectedLabel="Selected columns"
+ availableLabel="Available columns"
+ options={OPTIONS}
+ value={value}
+ onChange={setValue}
+ reorderable={reorderable}
+ />
+ );
+ }
+ render(<Owned />);
+ const handle = screen.getByRole('button', {name: 'Reorder Status'});
+ expect(handle).not.toHaveAttribute('aria-pressed', 'true');
+ act(() => start?.('status'));
+ expect(handle).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ it('loads no reorder code of its own: the engine comes with the owner\u2019s object (spec:AST-103 FR2)', () => {
+ for (const file of ['TransferList.tsx', 'TransferListSelector.tsx']) {
+ const source = fs.readFileSync(
+ path.join(import.meta.dirname, file),
+ 'utf8',
+ );
+ const valueImports = [
+ ...source.matchAll(
+ /^import\s+(?!type\b)\{([^}]*)\}\s+from\s+'([^']+)';/gm,
+ ),
+ ];
+ for (const [, names, from] of valueImports) {
+ const values = names
+ .split(',')
+ .map(name => name.trim())
+ .filter(name => name !== '' && !name.startsWith('type '));
+ expect(values, `${file}: ${from}`).not.toContain('createReorderable');
+ }
+ }
+ });
+
+ it('reflects a kept row as reorder fixed on its own target, apart from its transfer state (theming-surface INV6)', () => {
+ const {container} = render(
+ <ControlledTransferList
+ initialValue={['name', 'status']}
+ fixed={['name']}
+ />,
+ );
+ const rowOf = (value: string) =>
+ container.querySelector<HTMLElement>(
+ `[data-transfer-list-row="${value}"]`,
+ );
+ expect(rowOf('name')).toHaveAttribute('data-reorder', 'fixed');
+ expect(rowOf('name')).toHaveAttribute('data-state', 'enabled');
+ expect(rowOf('status')).toHaveAttribute('data-reorder', 'movable');
+ });
+});
diff --git a/packages/lab/src/TransferList/TransferList.tsx b/packages/lab/src/TransferList/TransferList.tsx
index 49aafa88e0..74373083a1 100644
--- a/packages/lab/src/TransferList/TransferList.tsx
+++ b/packages/lab/src/TransferList/TransferList.tsx
@@ -4,7 +4,10 @@
/**
* @file TransferList.tsx
- * @input Controlled option data, React DOM portals, local action glyphs, shared Lab reorder styles, and the core i18n catalog
+ * @input Controlled option data, local action glyphs, core's reorder (List
+ * `reorderable` and ListItem `itemKey`) and the core i18n catalog. The
+ * owner's createReorderable object is adapted through Core's internal
+ * reorder entry, which loads no reorder code of its own
* @output Exports TransferList with immediate transfers, vertical reordering, and responsive scroll ownership
* @position Lab collection input; consumed by index.ts, TransferListSelector, docs, and tests
*
@@ -17,28 +20,29 @@
import {
Fragment,
useCallback,
- useEffect,
useId,
- useLayoutEffect,
useMemo,
useRef,
useState,
- type KeyboardEvent as ReactKeyboardEvent,
- type PointerEvent as ReactPointerEvent,
type ReactNode,
+ type RefObject,
type SVGProps,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {flushSync} from 'react-dom';
import type {BaseProps} from '@astryxdesign/core';
import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {IconButton} from '@astryxdesign/core/IconButton';
import {Item} from '@astryxdesign/core/Item';
-import {useLayer} from '@astryxdesign/core/Layer';
-import {List} from '@astryxdesign/core/List';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {type Reorderable, type ReorderMove} from '@astryxdesign/core';
+import {
+ adaptReorderable,
+ reorderableOptions,
+} from '@astryxdesign/core/internal/reorder';
import {Text} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
+import {Tooltip} from '@astryxdesign/core/Tooltip';
import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {useAnnounce} from '@astryxdesign/core/hooks';
import {useTranslator} from '@astryxdesign/core/i18n';
@@ -55,11 +59,10 @@ import {
mergeRefs,
themeProps,
} from '@astryxdesign/core/utils';
-import {reorderStyles} from '../reorderStyles';
import {transferListVars} from './tokens.stylex';
-// Lucide glyphs the shared icon registry does not carry (there is no `add` or
-// `grip` semantic name). Typed as icon components and rendered through `Icon`
+// A Lucide glyph the shared icon registry does not carry (there is no `add`
+// semantic name). Typed as icon components and rendered through `Icon`
// so sizing, colour and a11y come from the icon pipeline rather than a raw
// inline `<svg>`. Removal reuses the registry `close` glyph instead.
function PlusIcon(props: SVGProps<SVGSVGElement>) {
@@ -78,26 +81,6 @@ function PlusIcon(props: SVGProps<SVGSVGElement>) {
);
}
-function GripVerticalIcon(props: SVGProps<SVGSVGElement>) {
- return (
- <svg
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.5}
- strokeLinecap="round"
- strokeLinejoin="round"
- {...props}>
- <circle cx="9" cy="5" r="1" />
- <circle cx="9" cy="12" r="1" />
- <circle cx="9" cy="19" r="1" />
- <circle cx="15" cy="5" r="1" />
- <circle cx="15" cy="12" r="1" />
- <circle cx="15" cy="19" r="1" />
- </svg>
- );
-}
-
export interface TransferListOption<T extends string = string> {
/** Stable value written to the controlled value array. */
value: T;
@@ -109,9 +92,7 @@ export interface TransferListOption<T extends string = string> {
group?: string;
/** Prevents moving the option between the selected and available lists. */
isTransferDisabled?: boolean;
- /** Prevents reordering the selected option and keeps its position fixed. */
- isReorderDisabled?: boolean;
- /** Explains why a transfer or reorder action is unavailable. */
+ /** Explains why a transfer is unavailable. */
disabledMessage?: string;
}
@@ -148,8 +129,17 @@ export interface TransferListProps<T extends string = string> extends Omit<
searchLabel?: string;
/** Search input placeholder. @default 'Search…' */
searchPlaceholder?: string;
- /** Enables pointer and keyboard ordering on selected options. @default true */
- isReorderable?: boolean;
+ /**
+ * Makes the selected options reorderable through core List's reorder
+ * handle (touch hold, mouse drag, keys, reorder mode): pass the object
+ * `createReorderable` makes. Its `isReorderable(value)` decides which
+ * options move. One it rejects at either end of the list also keeps the
+ * others from moving past it. Each move goes to its `onReorder({key, to})`,
+ * `to` being the value's index in `value` after the move. Paused while a
+ * search filters the panel. Without it, the selected options keep their
+ * order.
+ */
+ reorderable?: Reorderable<T>;
/** Shows an Add all action. @default false */
hasSelectAll?: boolean;
/** Shows a Clear action. Transfer-disabled selected options are retained. */
@@ -164,35 +154,14 @@ export interface TransferListProps<T extends string = string> extends Omit<
noResultsText?: string;
}
-interface ReorderSession<T extends string> {
- value: T;
- label: string;
- mode: 'keyboard' | 'pointer';
- originalValue: readonly T[];
- fromIndex: number;
- toIndex: number;
- pointerId?: number;
- pointerStartY?: number;
- pointerOffsetY?: number;
- pointerClientY?: number;
- previewX?: number;
- previewWidth?: number;
- hasPointerMoved?: boolean;
-}
-
-type PointerGeometry = Required<
- Pick<
- ReorderSession<string>,
- | 'pointerId'
- | 'pointerStartY'
- | 'pointerOffsetY'
- | 'pointerClientY'
- | 'previewX'
- | 'previewWidth'
- >
->;
-
const styles = stylex.create({
+ // Core List's reorder handle is a small control, 28 px for every pointer,
+ // overlapping the row's end padding by 8 px. A finger's 44 px target is its
+ // invisible hit layer. A row without one keeps its end content clear of
+ // it, so every Remove sits in one column.
+ clearsHandle: {
+ marginInlineEnd: 20,
+ },
root: {
display: 'flex',
flexDirection: 'column',
@@ -227,7 +196,13 @@ const styles = stylex.create({
display: 'flex',
flexDirection: 'column',
minWidth: 0,
- overflow: 'hidden',
+ // In the phone layout the body does not scroll, so the panel does not
+ // clip. On iOS, that clip around the list's own clip draws the row at its
+ // edge one point off while rows glide.
+ overflow: {
+ default: 'hidden',
+ '@container (max-width: 40rem)': 'visible',
+ },
// Inset, not the shared offset: the panel's own edge is the container
// boundary, so an outset ring would fall outside the component.
outlineOffset: {default: '0', ':focus-visible': -2},
@@ -317,15 +292,20 @@ const styles = stylex.create({
':first-child': 0,
},
},
+ // A disabled row still takes the pointer, so its disabled controls show
+ // their tooltips on hover.
+ disabledItem: {
+ pointerEvents: 'auto',
+ },
+ // A disabled row already dims its end content, Remove included. Remove's
+ // own disabled dim would make it fainter than the list's other controls.
+ removeInDisabledRow: {
+ opacity: 1,
+ },
item: {
minWidth: 0,
paddingInline: spacingVars['--spacing-3'],
},
- reorderHandle: {
- marginInlineStart: `calc(-1 * ${spacingVars['--spacing-1-5']})`,
- },
- draggingItem: {backgroundColor: colorVars['--color-accent-muted']},
- dragPreviewContainer: {listStyleType: 'none'},
empty: {
display: 'flex',
alignItems: 'center',
@@ -339,24 +319,6 @@ const styles = stylex.create({
},
});
-const dynamicStyles = stylex.create({
- // Only the width is dynamic here. The layer owns the placement: it reads the
- // same viewport coordinates as `position: fixed` insets, which is what
- // getBoundingClientRect gives us.
- dragPreview: (width: number) => ({width}),
-});
-
-function moveItem<T>(
- value: readonly T[],
- fromIndex: number,
- toIndex: number,
-): T[] {
- const nextValue = [...value];
- const [item] = nextValue.splice(fromIndex, 1);
- nextValue.splice(toIndex, 0, item);
- return nextValue;
-}
-
// Case folding is locale-independent here, matching Selector, MultiSelector,
// and CommandPalette. Locale-sensitive folding would mean raw Intl access,
// which the shipped packages route through the provider instead.
@@ -374,6 +336,39 @@ function matchesQuery<T extends string>(
);
}
+interface DisabledHandleTooltipProps {
+ rootRef: RefObject<HTMLElement | null>;
+ value: string;
+ content: string;
+}
+
+/**
+ * The tooltip and description of a disabled list's reorder handle, which say
+ * why the row does not move. Core List renders the handle. So the tooltip
+ * finds it in its row when it attaches. It takes the row's last toggle
+ * button: the handle comes after the row's own content.
+ */
+function DisabledHandleTooltip({
+ rootRef,
+ value,
+ content,
+}: DisabledHandleTooltipProps) {
+ const anchorRef = useMemo(
+ () => ({
+ get current() {
+ const toggles = rootRef.current?.querySelectorAll<HTMLElement>(
+ `[data-transfer-list-row="${CSS.escape(value)}"] button[aria-pressed]`,
+ );
+ return toggles == null || toggles.length === 0
+ ? null
+ : toggles[toggles.length - 1];
+ },
+ }),
+ [rootRef, value],
+ );
+ return <Tooltip anchorRef={anchorRef} content={content} />;
+}
+
/**
* A controlled dual-panel collection input for choosing and ordering values.
* Selection, ordering, drafts, persistence, and saved views stay explicit in
@@ -403,7 +398,7 @@ export function TransferList<T extends string = string>({
hasSearch = false,
searchLabel,
searchPlaceholder: searchPlaceholderFromProps,
- isReorderable = true,
+ reorderable: reorderableProp,
hasSelectAll = false,
hasClear = false,
renderOption,
@@ -436,36 +431,16 @@ export function TransferList<T extends string = string>({
const descriptionId = useId();
const selectedHeadingId = useId();
const availableHeadingId = useId();
- const reorderInstructionsId = useId();
const rootRef = useRef<HTMLDivElement | null>(null);
const searchRef = useRef<HTMLInputElement | null>(null);
const selectedPanelRef = useRef<HTMLDivElement | null>(null);
const availablePanelRef = useRef<HTMLDivElement | null>(null);
- const selectedRowRefs = useRef(new Map<T, HTMLElement>());
- const dragPreviewRef = useRef<HTMLDivElement | null>(null);
- // The ghost that follows the pointer is a layer, not a portal into body.
- // Its coordinates come from getBoundingClientRect, so they are viewport
- // relative; the top layer is the only host that reads them that way from
- // any scroll position and still paints above a Popover or open dialog.
- const dragPreviewLayer = useLayer({mode: 'fixed'});
const currentValueRef = useRef<readonly T[]>(value);
- const reorderSessionRef = useRef<ReorderSession<T> | null>(null);
- const suppressClickRef = useRef(false);
const [query, setQuery] = useState('');
- const [reorderSession, setReorderSessionState] =
- useState<ReorderSession<T> | null>(null);
const announce = useAnnounce();
currentValueRef.current = value;
- const setReorderSession = useCallback(
- (nextSession: ReorderSession<T> | null) => {
- reorderSessionRef.current = nextSession;
- setReorderSessionState(nextSession);
- },
- [],
- );
-
// An option's own message names its own constraint.
// It does not apply to a disabled list.
const options = useMemo(
@@ -474,7 +449,6 @@ export function TransferList<T extends string = string>({
? optionsFromProps.map(option => ({
...option,
isTransferDisabled: true,
- isReorderDisabled: true,
disabledMessage: undefined,
}))
: optionsFromProps,
@@ -521,63 +495,6 @@ export function TransferList<T extends string = string>({
return Array.from(groups.entries());
}, [availableOptions]);
- const pointerPlacement = useMemo(() => {
- if (
- reorderSession?.mode !== 'pointer' ||
- !reorderSession.hasPointerMoved ||
- reorderSession.toIndex === reorderSession.fromIndex
- ) {
- return null;
- }
- const remainingValues = reorderSession.originalValue.filter(
- optionValue => optionValue !== reorderSession.value,
- );
- const beforeValue = remainingValues[reorderSession.toIndex];
- if (beforeValue != null) {
- return {value: beforeValue, position: 'before' as const};
- }
- const afterValue = remainingValues.at(-1);
- return afterValue == null
- ? null
- : {value: afterValue, position: 'after' as const};
- }, [reorderSession]);
-
- const previewCloneValue =
- reorderSession?.mode === 'pointer' ? reorderSession.value : null;
-
- useLayoutEffect(() => {
- const previewHost = dragPreviewRef.current;
- if (previewHost == null || previewCloneValue == null) {
- return;
- }
- const sourceRow = selectedRowRefs.current.get(previewCloneValue);
- if (sourceRow == null) {
- return;
- }
- const clone = sourceRow.cloneNode(true) as HTMLElement;
- previewHost.style.direction = getComputedStyle(sourceRow).direction;
- clone.style.opacity = '1';
- clone.setAttribute('aria-hidden', 'true');
- const clonedElements = [clone, ...clone.querySelectorAll<HTMLElement>('*')];
- for (const element of clonedElements) {
- element.removeAttribute('id');
- element.removeAttribute('aria-describedby');
- element.removeAttribute('aria-labelledby');
- element.removeAttribute('name');
- for (const attribute of Array.from(element.attributes)) {
- if (attribute.name.startsWith('data-transfer-list-')) {
- element.removeAttribute(attribute.name);
- }
- }
- element.setAttribute('tabindex', '-1');
- }
- previewHost.replaceChildren(clone);
- return () => {
- previewHost.replaceChildren();
- previewHost.style.removeProperty('direction');
- };
- }, [previewCloneValue]);
-
const commit = useCallback(
(nextValue: readonly T[]) => {
currentValueRef.current = nextValue;
@@ -684,367 +601,56 @@ export function TransferList<T extends string = string>({
}
}, [announce, commit, optionByValue, t]);
- const movableRange = useCallback(
- (optionValue: T, orderedValue: readonly T[]) => {
- const index = orderedValue.indexOf(optionValue);
- let start = 0;
- let end = orderedValue.length - 1;
- for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
- const option = optionByValue.get(orderedValue[cursor] as T);
- if (option == null || option.isReorderDisabled) {
- start = cursor + 1;
- break;
- }
- }
- for (let cursor = index + 1; cursor < orderedValue.length; cursor += 1) {
- const option = optionByValue.get(orderedValue[cursor] as T);
- if (option == null || option.isReorderDisabled) {
- end = cursor - 1;
- break;
- }
- }
- return {index, start, end};
- },
- [optionByValue],
- );
-
- const moveOption = useCallback(
- (optionValue: T, requestedIndex: number) => {
- const nextValue = [...currentValueRef.current];
- const {index, start, end} = movableRange(optionValue, nextValue);
- if (index < 0) {
- return false;
- }
- const target = Math.max(start, Math.min(end, requestedIndex));
- if (target === index) {
- return false;
- }
- nextValue.splice(index, 1);
- nextValue.splice(target, 0, optionValue);
- commit(nextValue);
- return true;
- },
- [commit, movableRange],
+ // Reordering is off while a search filters the panel. A hidden row could
+ // otherwise move past the shown rows.
+ const isOrdering = reorderableProp != null && normalizedQuery === '';
+ // The owner's object decides which values move and takes each move.
+ const owner =
+ reorderableProp == null ? undefined : reorderableOptions(reorderableProp);
+ const canMove = useCallback(
+ (optionValue: T) => owner?.isReorderable?.(optionValue) ?? true,
+ [owner],
);
-
- const beginReorder = useCallback(
- (
- option: TransferListOption<T>,
- mode: 'keyboard' | 'pointer',
- pointerGeometry?: PointerGeometry,
- ) => {
- if (option.isReorderDisabled || !isReorderable) {
+ const reorderSelected = useCallback(
+ ({key, to: toIndex}: ReorderMove) => {
+ const shown = selectedOptions.map(option => option.value);
+ const fromIndex = shown.indexOf(key as T);
+ if (fromIndex < 0 || fromIndex === toIndex || shown[toIndex] == null) {
return;
}
- const index = currentValueRef.current.indexOf(option.value);
- if (index < 0 || (mode === 'pointer' && pointerGeometry == null)) {
- return;
- }
- setReorderSession({
- value: option.value,
- label: option.label,
- mode,
- originalValue: [...currentValueRef.current],
- fromIndex: index,
- toIndex: index,
- ...pointerGeometry,
- hasPointerMoved: false,
- });
- if (mode === 'keyboard') {
- announce(
- t('@astryx.transferList.announceGrabbed', {
- label: option.label,
- position: index + 1,
- total: currentValueRef.current.length,
- }),
- );
- }
- },
- [announce, isReorderable, setReorderSession, t],
- );
-
- const finishReorder = useCallback(
- (cancelled: boolean) => {
- const session = reorderSessionRef.current;
- if (!session) {
- return;
- }
- // A list disabled mid-reorder takes no change from it, not even the
- // cancel that restores the order from before the grab.
- if (isDisabled) {
- setReorderSession(null);
- return;
- }
- if (session.mode === 'pointer') {
- if (cancelled || !session.hasPointerMoved) {
- setReorderSession(null);
- if (cancelled) {
- announce(
- t('@astryx.transferList.announceMoveCancelled', {
- label: session.label,
- }),
- );
- }
- return;
- }
- const hasChanged = session.fromIndex !== session.toIndex;
- const nextValue = moveItem(
- session.originalValue,
- session.fromIndex,
- session.toIndex,
- );
- flushSync(() => setReorderSession(null));
- if (hasChanged) {
- commit(nextValue);
- announce(
- t('@astryx.transferList.announceDropped', {
- label: session.label,
- position: session.toIndex + 1,
- total: session.originalValue.length,
- }),
- );
- } else {
- announce(
- t('@astryx.transferList.announceReturned', {
- label: session.label,
- position: session.fromIndex + 1,
- }),
- );
- }
- return;
- }
- if (cancelled) {
- commit(session.originalValue);
- announce(
- t('@astryx.transferList.announceMoveCancelled', {
- label: session.label,
- }),
- );
- } else {
- const index = currentValueRef.current.indexOf(session.value);
- announce(
- t('@astryx.transferList.announceDropped', {
- label: session.label,
- position: index + 1,
- total: currentValueRef.current.length,
- }),
- );
- }
- setReorderSession(null);
- },
- [announce, commit, isDisabled, setReorderSession, t],
- );
-
- const handleReorderClick = useCallback(
- (option: TransferListOption<T>) => {
- if (suppressClickRef.current) {
- suppressClickRef.current = false;
- return;
- }
- if (reorderSessionRef.current?.value === option.value) {
- finishReorder(false);
- } else {
- beginReorder(option, 'keyboard');
- }
- },
- [beginReorder, finishReorder],
- );
-
- const handleReorderKeyDown = useCallback(
- (
- event: ReactKeyboardEvent<HTMLButtonElement>,
- option: TransferListOption<T>,
- ) => {
- const session = reorderSessionRef.current;
- if (session?.value !== option.value || session.mode !== 'keyboard') {
- return;
- }
- if (event.key === 'Escape') {
- event.preventDefault();
- finishReorder(true);
- return;
- }
- if (event.key === ' ' || event.key === 'Enter') {
- event.preventDefault();
- finishReorder(false);
- return;
- }
- const {index, start, end} = movableRange(
- option.value,
- currentValueRef.current,
+ const order = [...shown];
+ const [moved] = order.splice(fromIndex, 1);
+ order.splice(toIndex, 0, moved);
+ // The shown rows' new order goes back into the places the shown values
+ // held. So a value without an option keeps its place in this order.
+ const isShown = new Set(shown);
+ let next = 0;
+ const nextValue = currentValueRef.current.map(item =>
+ isShown.has(item) ? order[next++] : item,
);
- const targets: Record<string, number> = {
- ArrowUp: index - 1,
- ArrowDown: index + 1,
- Home: start,
- End: end,
- };
- const target = targets[event.key];
- if (target == null) {
+ if (owner == null) {
return;
}
- event.preventDefault();
- if (moveOption(option.value, target)) {
- const nextIndex = currentValueRef.current.indexOf(option.value);
- announce(
- t('@astryx.transferList.announceMovedToPosition', {
- label: option.label,
- position: nextIndex + 1,
- total: currentValueRef.current.length,
- }),
- );
- }
- },
- [announce, finishReorder, movableRange, moveOption, t],
- );
-
- const handlePointerDown = useCallback(
- (
- event: ReactPointerEvent<HTMLButtonElement>,
- option: TransferListOption<T>,
- ) => {
- if (event.button !== 0 || option.isReorderDisabled) {
- return;
- }
- const sourceRow = selectedRowRefs.current.get(option.value);
- if (sourceRow == null) {
- return;
- }
- const bounds = sourceRow.getBoundingClientRect();
- suppressClickRef.current = true;
- event.currentTarget.setPointerCapture?.(event.pointerId);
- beginReorder(option, 'pointer', {
- pointerId: event.pointerId,
- pointerStartY: event.clientY,
- pointerOffsetY: event.clientY - bounds.top,
- pointerClientY: event.clientY,
- previewX: bounds.left,
- previewWidth: bounds.width,
- });
- },
- [beginReorder],
- );
-
- const handlePointerMove = useCallback(
- (
- event: ReactPointerEvent<HTMLButtonElement>,
- option: TransferListOption<T>,
- ) => {
- const session = reorderSessionRef.current;
- if (
- session?.value !== option.value ||
- session.mode !== 'pointer' ||
- session.pointerId !== event.pointerId
- ) {
- return;
- }
- const verticalDistance =
- event.clientY - (session.pointerStartY ?? event.clientY);
- const hasCrossedThreshold =
- session.hasPointerMoved || Math.abs(verticalDistance) >= 5;
- let targetIndex = session.fromIndex;
- if (hasCrossedThreshold) {
- event.preventDefault();
- const {start, end} = movableRange(session.value, session.originalValue);
- const remainingValues = session.originalValue.filter(
- optionValue => optionValue !== session.value,
- );
- const candidates = session.originalValue
- .map((optionValue, originalIndex) => ({optionValue, originalIndex}))
- .filter(
- candidate =>
- candidate.optionValue !== session.value &&
- candidate.originalIndex >= start &&
- candidate.originalIndex <= end,
- )
- .map(candidate => ({
- row: selectedRowRefs.current.get(candidate.optionValue),
- targetIndex: remainingValues.indexOf(candidate.optionValue),
- }))
- .filter(
- (candidate): candidate is {row: HTMLElement; targetIndex: number} =>
- candidate.row != null,
- );
- if (candidates.length > 0) {
- targetIndex = candidates[candidates.length - 1].targetIndex + 1;
- for (const candidate of candidates) {
- const bounds = candidate.row.getBoundingClientRect();
- if (event.clientY < bounds.top + bounds.height / 2) {
- targetIndex = candidate.targetIndex;
- break;
- }
- }
- targetIndex = Math.max(start, Math.min(end, targetIndex));
- }
- }
- const nextSession = {
- ...session,
- pointerClientY: event.clientY,
- hasPointerMoved: hasCrossedThreshold,
- toIndex: targetIndex,
- };
- setReorderSession(nextSession);
- if (hasCrossedThreshold && session.toIndex !== targetIndex) {
- announce(
- t('@astryx.transferList.announceMovedToPosition', {
- label: option.label,
- position: targetIndex + 1,
- total: session.originalValue.length,
- }),
- );
- }
+ // In the value's terms: where the moved value lands. The owner moving
+ // it there keeps the shown rows in this order.
+ owner.onReorder({key: key as T, to: nextValue.indexOf(key as T)});
},
- [announce, movableRange, setReorderSession, t],
+ [owner, selectedOptions],
);
-
- const handlePointerEnd = useCallback(
- (event: ReactPointerEvent<HTMLButtonElement>, cancelled: boolean) => {
- const session = reorderSessionRef.current;
- if (
- session?.mode !== 'pointer' ||
- session.pointerId !== event.pointerId
- ) {
- return;
- }
- if (cancelled) {
- suppressClickRef.current = false;
- } else {
- setTimeout(() => {
- suppressClickRef.current = false;
- }, 0);
- }
- finishReorder(cancelled);
- if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
- event.currentTarget.releasePointerCapture?.(event.pointerId);
- }
- },
- [finishReorder],
+ // The owner's object, adapted so List's moves among the shown rows reach
+ // the owner in the value's terms. Its engine is the owner's, so nothing
+ // here loads the reorder, and the owner's `start(key)` finds this list.
+ const reorderable = useMemo(
+ () =>
+ isOrdering && reorderableProp != null
+ ? adaptReorderable<string, number>(reorderableProp, {
+ onReorder: reorderSelected,
+ isReorderable: key => canMove(key as T),
+ })
+ : undefined,
+ [canMove, isOrdering, reorderSelected, reorderableProp],
);
- // A second pointer that lands anywhere during a pointer reorder (the second
- // finger of a pinch) cancels the reorder. A pinch whose first finger slid
- // first zooms without a pointercancel, so the drag would otherwise commit on
- // release and drop the row at the end of the list.
- const isPointerReorderActive = previewCloneValue != null;
- useEffect(() => {
- if (!isPointerReorderActive) {
- return;
- }
- const onPointerDown = (event: PointerEvent) => {
- const session = reorderSessionRef.current;
- if (
- session?.mode === 'pointer' &&
- session.pointerId !== event.pointerId
- ) {
- suppressClickRef.current = false;
- finishReorder(true);
- }
- };
- document.addEventListener('pointerdown', onPointerDown, true);
- return () =>
- document.removeEventListener('pointerdown', onPointerDown, true);
- }, [isPointerReorderActive, finishReorder]);
-
const handleSearch = useCallback(
(nextQuery: string) => {
setQuery(nextQuery);
@@ -1084,7 +690,7 @@ export function TransferList<T extends string = string>({
/>
);
}
- return (
+ const remove = (
<IconButton
label={t('@astryx.transferList.removeOption', {label: option.label})}
icon={<Icon icon="close" size="sm" />}
@@ -1094,73 +700,28 @@ export function TransferList<T extends string = string>({
tooltip={isTransferDisabled ? disabledReason : undefined}
data-transfer-list-action="selected"
onClick={() => removeOption(option, index)}
+ // A row that keeps its place has no handle: its Remove keeps the
+ // movable rows' column, clear of where their handles sit.
+ xstyle={[
+ isOrdering && !canMove(option.value) && styles.clearsHandle,
+ isDisabled && styles.removeInDisabledRow,
+ ]}
/>
);
- };
-
- const dragPreviewPosition =
- reorderSession?.mode === 'pointer' &&
- reorderSession.pointerClientY != null &&
- reorderSession.pointerOffsetY != null &&
- reorderSession.previewX != null &&
- reorderSession.previewWidth != null
- ? {
- x: reorderSession.previewX,
- y: reorderSession.pointerClientY - reorderSession.pointerOffsetY,
- width: reorderSession.previewWidth,
- }
- : null;
- const isDraggingPreview = dragPreviewPosition != null;
- const {show: showDragPreview, hide: hideDragPreview} = dragPreviewLayer;
- useEffect(() => {
- if (!isDraggingPreview) {
- return undefined;
+ if (!isDisabled || !isOrdering || !canMove(option.value)) {
+ return remove;
}
- showDragPreview();
- return hideDragPreview;
- }, [isDraggingPreview, showDragPreview, hideDragPreview]);
-
- const reorderControl = (option: TransferListOption<T>) => {
- if (!isReorderable) {
- return undefined;
- }
- const active = reorderSession?.value === option.value;
- const isReorderDisabled = option.isReorderDisabled === true;
- const disabledReason =
- option.disabledMessage ??
- t('@astryx.transferList.reorderDisabled', {label: option.label});
return (
- <IconButton
- label={t('@astryx.transferList.reorderOption', {label: option.label})}
- aria-describedby={reorderInstructionsId}
- aria-pressed={active && !isDisabled}
- icon={<Icon icon={GripVerticalIcon} size="sm" />}
- size="sm"
- variant="ghost"
- isDisabled={isReorderDisabled}
- tooltip={isReorderDisabled ? disabledReason : undefined}
- xstyle={[
- styles.reorderHandle,
- reorderStyles.handle,
- active && reorderStyles.handleActive,
- ]}
- onClick={() => handleReorderClick(option)}
- onKeyDown={event => handleReorderKeyDown(event, option)}
- onPointerDown={event => handlePointerDown(event, option)}
- onPointerMove={event => handlePointerMove(event, option)}
- onPointerUp={event => handlePointerEnd(event, false)}
- onPointerCancel={event => handlePointerEnd(event, true)}
- onLostPointerCapture={event => {
- const session = reorderSessionRef.current;
- if (
- session?.mode === 'pointer' &&
- session.pointerId === event.pointerId
- ) {
- suppressClickRef.current = false;
- finishReorder(true);
- }
- }}
- />
+ <>
+ {remove}
+ <DisabledHandleTooltip
+ rootRef={rootRef}
+ value={option.value}
+ content={t('@astryx.transferList.reorderDisabled', {
+ label: option.label,
+ })}
+ />
+ </>
);
};
@@ -1169,53 +730,46 @@ export function TransferList<T extends string = string>({
side: 'selected' | 'available',
index: number,
) => {
- const active = reorderSession?.value === option.value;
- const isPointerSource = active && reorderSession?.mode === 'pointer';
- const dropPosition =
- pointerPlacement?.value === option.value
- ? pointerPlacement.position
- : null;
- const orderedIndex = currentValueRef.current.indexOf(option.value);
+ // Transfer and reorder are separate states of the row's own target. A
+ // row the owner keeps in place is `fixed`.
+ const theme = themeProps('transfer-list-item', {
+ side,
+ state: option.isTransferDisabled ? 'disabled' : 'enabled',
+ reorder:
+ side === 'selected' && isOrdering
+ ? canMove(option.value)
+ ? 'movable'
+ : 'fixed'
+ : undefined,
+ });
+ if (side === 'selected') {
+ return (
+ <ListItem
+ key={option.value}
+ itemKey={option.value}
+ label={renderOption?.(option) ?? option.label}
+ endContent={optionActions(option, side, index)}
+ // A disabled list keeps each handle as a focusable disabled
+ // control. Core List ends its reorder mode and sends a drag home.
+ isDisabled={isDisabled}
+ xstyle={[styles.item, isDisabled && styles.disabledItem]}
+ data-transfer-list-row={option.value}
+ data-transfer-list-index={String(
+ currentValueRef.current.indexOf(option.value),
+ )}
+ {...theme}
+ />
+ );
+ }
return (
<Item
key={option.value}
as="li"
- ref={node => {
- if (side !== 'selected') {
- return;
- }
- if (node == null) {
- selectedRowRefs.current.delete(option.value);
- } else {
- selectedRowRefs.current.set(option.value, node);
- }
- }}
density="compact"
- startContent={side === 'selected' ? reorderControl(option) : undefined}
label={renderOption?.(option) ?? option.label}
endContent={optionActions(option, side, index)}
- xstyle={[
- styles.item,
- active && reorderSession?.mode === 'keyboard' && styles.draggingItem,
- isPointerSource && reorderStyles.source,
- dropPosition === 'before' && reorderStyles.dropBefore,
- dropPosition === 'after' && reorderStyles.dropAfter,
- ]}
- data-transfer-list-row={side === 'selected' ? option.value : undefined}
- data-transfer-list-reorder-source={isPointerSource || undefined}
- data-transfer-list-drop-target={dropPosition ?? undefined}
- data-transfer-list-index={
- side === 'selected' ? String(orderedIndex) : undefined
- }
- {...themeProps('transfer-list-item', {
- side,
- state:
- option.isTransferDisabled || option.isReorderDisabled
- ? 'disabled'
- : active
- ? 'reordering'
- : 'enabled',
- })}
+ xstyle={styles.item}
+ {...theme}
/>
);
};
@@ -1274,10 +828,6 @@ export function TransferList<T extends string = string>({
</div>
)}
- <VisuallyHidden id={reorderInstructionsId}>
- {t('@astryx.transferList.reorderInstructions')}
- </VisuallyHidden>
-
<div
{...mergeProps(
themeProps('transfer-list-collection'),
@@ -1319,7 +869,8 @@ export function TransferList<T extends string = string>({
{selectedOptions.length > 0 ? (
<List
density="compact"
- header={<VisuallyHidden>{selectedLabel}</VisuallyHidden>}>
+ header={<VisuallyHidden>{selectedLabel}</VisuallyHidden>}
+ reorderable={reorderable}>
{selectedOptions.map((option, index) =>
transferItem(option, 'selected', index),
)}
@@ -1411,21 +962,6 @@ export function TransferList<T extends string = string>({
</div>
</div>
</div>
- {dragPreviewPosition != null
- ? dragPreviewLayer.render(
- <div
- ref={dragPreviewRef}
- aria-hidden="true"
- data-transfer-list-drag-preview=""
- {...stylex.props(
- reorderStyles.preview,
- styles.dragPreviewContainer,
- dynamicStyles.dragPreview(dragPreviewPosition.width),
- )}
- />,
- {x: dragPreviewPosition.x, y: dragPreviewPosition.y},
- )
- : null}
</div>
);
}
diff --git a/packages/lab/src/TransferList/TransferListSelector.test.tsx b/packages/lab/src/TransferList/TransferListSelector.test.tsx
index 5eaccff7f4..6fa3c805e2 100644
--- a/packages/lab/src/TransferList/TransferListSelector.test.tsx
+++ b/packages/lab/src/TransferList/TransferListSelector.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When TransferListSelector.tsx behavior changes, update this test.
*/
-import {Profiler, useState} from 'react';
+import {Profiler, useMemo, useRef, useState} from 'react';
import {afterAll, beforeEach, describe, expect, it, vi} from 'vitest';
import {
fireEvent,
@@ -24,6 +24,7 @@ import {
type TransferListSelectorProps,
} from './TransferListSelector';
import type {TransferListOption} from './TransferList';
+import {createReorderable} from '@astryxdesign/core';
type Column = 'name' | 'owner' | 'status' | 'updated';
@@ -71,6 +72,8 @@ afterAll(() => {
type HarnessProps = {
initialValue?: readonly Column[];
onCommit: (value: readonly Column[]) => void;
+ /** The owner's reorderable object's `isReorderable`. */
+ isMovable?: (value: Column) => boolean;
selectorProps?: Partial<
Omit<
TransferListSelectorProps<Column>,
@@ -83,8 +86,25 @@ function Harness({
initialValue = ['name', 'status'],
onCommit,
selectorProps,
+ isMovable,
}: HarnessProps) {
const [value, setValue] = useState<readonly Column[]>(initialValue);
+ const valueRef = useRef(value);
+ valueRef.current = value;
+ // The owner's reorder: each move it is handed applies to its value.
+ const reorderable = useMemo(
+ () =>
+ createReorderable<Column>({
+ onReorder: ({key, to}) => {
+ const rest = valueRef.current.filter(item => item !== key);
+ const next = [...rest.slice(0, to), key, ...rest.slice(to)];
+ onCommit(next);
+ setValue(next);
+ },
+ isReorderable: isMovable,
+ }),
+ [isMovable, onCommit],
+ );
return (
<>
@@ -97,6 +117,7 @@ function Harness({
onCommit(nextValue);
setValue(nextValue);
}}
+ reorderable={reorderable}
{...selectorProps}
/>
</>
@@ -116,6 +137,14 @@ async function openSelector(
return trigger;
}
+/** The selector moves the focus into its panel once open; wait for it. */
+async function waitForPanelFocus(trigger: HTMLElement): Promise<void> {
+ await waitFor(() => {
+ expect(document.activeElement).not.toBe(document.body);
+ expect(document.activeElement).not.toBe(trigger);
+ });
+}
+
describe('TransferListSelector', () => {
it('commits each edit immediately by default and renders no footer', async () => {
const user = userEvent.setup();
@@ -265,6 +294,55 @@ describe('TransferListSelector', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'false');
});
+ it('reorders a staged draft through its own reorder object: Cancel drops the move with the draft, Apply commits it', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <Harness
+ initialValue={['name', 'status', 'updated']}
+ onCommit={onCommit}
+ selectorProps={{commitBehavior: 'staged'}}
+ />,
+ );
+ await waitForPanelFocus(await openSelector());
+ screen.getByRole('button', {name: 'Reorder Name', ...hidden}).focus();
+ await user.keyboard('{Enter}{ArrowDown}{Escape}');
+ expect(onCommit).not.toHaveBeenCalled();
+ await user.click(screen.getByRole('button', {name: 'Cancel', ...hidden}));
+ expect(onCommit).not.toHaveBeenCalled();
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status","updated"]',
+ );
+
+ await waitForPanelFocus(await openSelector());
+ screen.getByRole('button', {name: 'Reorder Name', ...hidden}).focus();
+ await user.keyboard('{Enter}{ArrowDown}{Escape}');
+ await user.click(screen.getByRole('button', {name: 'Apply', ...hidden}));
+ expect(onCommit).toHaveBeenCalledOnce();
+ expect(onCommit).toHaveBeenCalledWith(['status', 'name', 'updated']);
+ });
+
+ it('keeps in place the values the owner\u2019s isReorderable rejects, and hands immediate moves to the owner at once', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <Harness
+ initialValue={['owner', 'name', 'status']}
+ onCommit={onCommit}
+ isMovable={value => value !== 'owner'}
+ />,
+ );
+ await waitForPanelFocus(await openSelector());
+ expect(
+ screen.queryByRole('button', {name: 'Reorder Owner', ...hidden}),
+ ).toBeNull();
+ screen.getByRole('button', {name: 'Reorder Status', ...hidden}).focus();
+ await user.keyboard('{Enter}{ArrowUp}{ArrowUp}{Escape}');
+ // Owner leads the list, so Status stops below it.
+ expect(onCommit).toHaveBeenCalledOnce();
+ expect(onCommit).toHaveBeenCalledWith(['owner', 'status', 'name']);
+ });
+
it('closes unchanged Apply without calling onChange or changeAction', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
@@ -574,7 +652,6 @@ describe('TransferListSelector', () => {
availableLabel="Hidden"
hasSearch
searchPlaceholder="Find a column"
- isReorderable={false}
hasSelectAll
hasClear
commitBehavior="staged"
diff --git a/packages/lab/src/TransferList/TransferListSelector.tsx b/packages/lab/src/TransferList/TransferListSelector.tsx
index fa106bd054..914cebf95b 100644
--- a/packages/lab/src/TransferList/TransferListSelector.tsx
+++ b/packages/lab/src/TransferList/TransferListSelector.tsx
@@ -4,7 +4,10 @@
/**
* @file TransferListSelector.tsx
- * @input Controlled option data, uncontrolled ComplexSelector state, TransferList, action controls, and the core i18n catalog
+ * @input Controlled option data, uncontrolled ComplexSelector state, action
+ * controls and the core i18n catalog. Also TransferList with the owner's
+ * reorderable object, adapted through Core's internal reorder entry and
+ * aimed at the draft when staged
* @output Exports the immediate-or-staged TransferListSelector composition with draft cleanup after dismissal
* @position Lab collection input shell; consumed by the TransferList entry point, docs, and tests
*
@@ -24,6 +27,11 @@ import {
import {useTranslator} from '@astryxdesign/core/i18n';
import {HStack} from '@astryxdesign/core/Stack';
import {borderVars, colorVars} from '@astryxdesign/core/theme/tokens.stylex';
+import type {Reorderable} from '@astryxdesign/core';
+import {
+ adaptReorderable,
+ reorderableOptions,
+} from '@astryxdesign/core/internal/reorder';
import {TransferList, type TransferListProps} from './TransferList';
const DEFAULT_SELECTOR_WIDTH = 'min(41rem, calc(100vw - 32px))';
@@ -105,7 +113,6 @@ type TransferListContentProp =
| 'hasSearch'
| 'searchLabel'
| 'searchPlaceholder'
- | 'isReorderable'
| 'hasSelectAll'
| 'hasClear'
| 'renderOption'
@@ -135,8 +142,24 @@ export type TransferListSelectorProps<T extends string = string> = Pick<
applyLabel?: string;
/** Label for the staged discard action. Only used in staged behavior. @default 'Cancel' */
cancelLabel?: string;
+ /**
+ * Makes the selected options reorderable: pass the object
+ * `createReorderable` makes. Its `isReorderable(value)` says which values
+ * move. An immediate selector hands each move to its `onReorder`. A
+ * staged one moves its draft instead, so Cancel drops the move with the
+ * draft, and Apply commits it through `onChange`. Without it, the
+ * selected options keep their order.
+ */
+ reorderable?: Reorderable<T>;
};
+/** `value` with `key` moved to index `to`. */
+function moveValue<T>(value: readonly T[], key: T, to: number): readonly T[] {
+ const next = value.filter(item => item !== key);
+ next.splice(to, 0, key);
+ return next;
+}
+
function areOrderedValuesEqual<T>(
first: readonly T[],
second: readonly T[],
@@ -202,7 +225,7 @@ export function TransferListSelector<T extends string = string>({
hasSearch,
searchLabel,
searchPlaceholder,
- isReorderable,
+ reorderable: ownerReorderable,
hasSelectAll,
hasClear,
renderOption,
@@ -260,6 +283,34 @@ export function TransferListSelector<T extends string = string>({
{(appliedValue, commit, close, state) => {
const isStaged = commitBehavior === 'staged';
const transferListValue = isStaged ? draftValue : appliedValue;
+ // The owner's reorder, aimed at the draft when staged and handed to
+ // the owner when immediate, with the owner's `isReorderable`. Made
+ // each render, so a move reads this render's value (the object may
+ // be made anew).
+ const owner =
+ ownerReorderable == null
+ ? undefined
+ : reorderableOptions(ownerReorderable);
+ // Adapted, so the engine is the owner's: nothing here loads the
+ // reorder, and the owner's `start` finds the list.
+ const reorderable =
+ owner == null || ownerReorderable == null
+ ? undefined
+ : adaptReorderable(ownerReorderable, {
+ onReorder: move => {
+ if (state.isBusy) {
+ return;
+ }
+ if (isStaged) {
+ setDraftValue(current =>
+ moveValue(current, move.key, move.to),
+ );
+ } else {
+ owner.onReorder(move);
+ }
+ },
+ isReorderable: owner.isReorderable,
+ });
return (
<div
@@ -304,7 +355,7 @@ export function TransferListSelector<T extends string = string>({
hasSearch={hasSearch}
searchLabel={searchLabel}
searchPlaceholder={searchPlaceholder}
- isReorderable={isReorderable}
+ reorderable={reorderable}
hasSelectAll={hasSelectAll}
hasClear={hasClear}
renderOption={renderOption}
diff --git a/packages/lab/src/TransferList/__tests__/TransferListReorder.a11y.chromium.spec.ts b/packages/lab/src/TransferList/__tests__/TransferListReorder.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..56262d8bcb
--- /dev/null
+++ b/packages/lab/src/TransferList/__tests__/TransferListReorder.a11y.chromium.spec.ts
@@ -0,0 +1,369 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferListReorder.a11y.chromium.spec.ts
+ * @input The checked-in Lab/TransferList › Default story, a built Storybook and
+ * real Chromium touch input (CDP) on a phone viewport. The A11y/TransferList
+ * › Disabled fixture, with a mouse and keys
+ * @output Browser evidence that a selected row dragged past the end of its
+ * list stays inside that list, its bottom on the list's end. It never slides
+ * under the next panel's header, and it lands last on release. In the phone
+ * layout the panels do not clip; at a desktop width they do. A disabled
+ * list keeps each handle focusable and disabled, with the focus where it was
+ * @position Chromium proof for TransferList's selected panel, which reorders
+ * through core's createReorderable on its List (List/listReorderEngine.tsx
+ * clamps the row)
+ */
+
+import {
+ expect,
+ test,
+ type CDPSession,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+test.use({
+ hasTouch: true,
+ isMobile: true,
+ viewport: {width: 390, height: 844},
+ deviceScaleFactor: 3,
+});
+
+const sleep = async (ms: number) =>
+ new Promise(resolve => setTimeout(resolve, ms));
+
+type Point = {x: number; y: number};
+
+async function touch(
+ cdp: CDPSession,
+ type: 'touchStart' | 'touchMove' | 'touchEnd',
+ points: Point[],
+) {
+ await cdp.send('Input.dispatchTouchEvent', {
+ type,
+ touchPoints: points.map((point, index) => ({...point, id: index + 1})),
+ });
+}
+
+const GRIP = '[data-transfer-list-row] button[data-astryx-list-reorder]';
+// Core List's handle claims a still finger after 150 ms.
+const HOLD_MS = 250;
+
+test('a row dragged past the end of its list stays inside it, clear of the next panel', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-transferlist--default&viewMode=story`,
+ );
+ const grip = page.locator(GRIP).first();
+ await expect(grip).toBeVisible();
+ const order = async () =>
+ page.evaluate(
+ selector =>
+ Array.from(document.querySelectorAll(selector)).map(
+ element =>
+ element
+ .closest('[data-transfer-list-row]')
+ ?.getAttribute('data-transfer-list-row') ?? '',
+ ),
+ GRIP,
+ );
+ const before = await order();
+ // The dragged row as it shows: during a drag its preview, which follows
+ // the finger while the row itself stays dimmed in place.
+ const geometry = async () =>
+ grip.evaluate(element => {
+ const row = element.closest('li') as HTMLElement;
+ const list = row.parentElement as HTMLElement;
+ const shown =
+ list.querySelector<HTMLElement>(
+ ':scope > [data-astryx-reorder-preview]',
+ ) ?? row;
+ const rowBox = shown.getBoundingClientRect();
+ const listBox = list.getBoundingClientRect();
+ return {
+ rowTop: rowBox.top,
+ rowBottom: rowBox.bottom,
+ listBottom: listBox.bottom,
+ };
+ });
+ const start = await geometry();
+ const box = (await grip.boundingBox()) as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ const from = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const to = {x: from.x, y: start.listBottom + 200};
+ const cdp = await page.context().newCDPSession(page);
+ await touch(cdp, 'touchStart', [from]);
+ await sleep(HOLD_MS);
+ for (let i = 1; i <= 24; i++) {
+ await sleep(16);
+ await touch(cdp, 'touchMove', [
+ {x: from.x, y: from.y + ((to.y - from.y) * i) / 24},
+ ]);
+ }
+ await sleep(150);
+ const held = await geometry();
+ // The finger is 200 px past the list's end. The preview stopped with its
+ // bottom on that end, so none of it hangs under the next panel.
+ expect(held.rowTop).toBeGreaterThan(start.rowTop + 40);
+ expect(held.rowBottom).toBeLessThanOrEqual(held.listBottom + 0.5);
+ expect(held.rowBottom).toBeGreaterThan(held.listBottom - 1);
+ await touch(cdp, 'touchEnd', []);
+ await sleep(700);
+ const after = await order();
+ expect(after[after.length - 1]).toBe(before[0]);
+});
+
+test('the panels clip nothing in the phone layout, and clip at a desktop width', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-transferlist--default&viewMode=story`,
+ );
+ await expect(page.locator(GRIP).first()).toBeVisible();
+ const overflows = async () =>
+ page
+ .locator('[role="group"][data-side]')
+ .evaluateAll(panels =>
+ panels.map(panel => getComputedStyle(panel).overflow),
+ );
+ expect(await overflows()).toEqual(['visible', 'visible']);
+ await page.setViewportSize({width: 1024, height: 768});
+ await expect.poll(overflows).toEqual(['hidden', 'hidden']);
+});
+
+test('selected rows keep one height and one Remove column, fixed rows included', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-transferlist--locked&viewMode=story`,
+ );
+ await expect(page.locator(GRIP).first()).toBeVisible();
+ const rows = await page.evaluate(() =>
+ Array.from(document.querySelectorAll('[data-transfer-list-row]'))
+ .map(row => row.closest('li') as HTMLElement)
+ .filter(row =>
+ row.closest('ul')?.querySelector('[data-astryx-list-reorder]'),
+ )
+ .map(row => {
+ const remove = Array.from(row.querySelectorAll('button')).find(
+ button => !button.hasAttribute('data-astryx-list-reorder'),
+ );
+ const box = row.getBoundingClientRect();
+ const removeBox = remove?.getBoundingClientRect();
+ return {
+ label: row.textContent?.trim() ?? '',
+ height: box.height,
+ removeRight: removeBox == null ? null : box.right - removeBox.right,
+ removeMiddle:
+ removeBox == null
+ ? null
+ : removeBox.top +
+ removeBox.height / 2 -
+ (box.top + box.height / 2),
+ hasHandle: row.querySelector('[data-astryx-list-reorder]') != null,
+ };
+ }),
+ );
+ // Both kinds of row are here: movable ones with a handle, fixed ones without.
+ expect(rows.some(row => row.hasHandle)).toBe(true);
+ expect(rows.some(row => !row.hasHandle)).toBe(true);
+ const [first] = rows;
+ for (const row of rows) {
+ expect(row.height, row.label).toBeCloseTo(first.height, 0);
+ expect(row.removeRight, row.label).toBeCloseTo(first.removeRight ?? 0, 0);
+ expect(Math.abs(row.removeMiddle ?? 0), row.label).toBeLessThan(1);
+ }
+});
+
+test.describe('with a mouse', () => {
+ test.use({
+ hasTouch: false,
+ isMobile: false,
+ viewport: {width: 1024, height: 768},
+ });
+
+ test('a mouse drags a handle at once and the row lands where it is dropped', async ({
+ page,
+ }) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-transferlist--default&viewMode=story`,
+ );
+ // This context's primary pointer is fine: the case is a mouse's.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const grip = page.locator(GRIP).first();
+ await expect(grip).toBeVisible();
+ const order = async () =>
+ page.evaluate(
+ selector =>
+ Array.from(document.querySelectorAll(selector)).map(
+ element =>
+ element
+ .closest('[data-transfer-list-row]')
+ ?.getAttribute('data-transfer-list-row') ?? '',
+ ),
+ GRIP,
+ );
+ const before = await order();
+ const box = (await grip.boundingBox()) as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ const pitch = await page.evaluate(selector => {
+ const [a, b] = Array.from(document.querySelectorAll(selector)).map(
+ element =>
+ (element.closest('li') as HTMLElement).getBoundingClientRect().top,
+ );
+ return b - a;
+ }, GRIP);
+ const from = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ for (let i = 1; i <= 12; i++) {
+ await page.mouse.move(from.x, from.y + (1.2 * pitch * i) / 12);
+ }
+ await page.mouse.up();
+ await sleep(300);
+ const after = await order();
+ // Past the next row's boundary, not the one after: one place down.
+ expect(after[1]).toBe(before[0]);
+ expect(after[0]).toBe(before[1]);
+ });
+});
+
+test.describe('a disabled list', () => {
+ test.use({
+ hasTouch: false,
+ isMobile: false,
+ viewport: {width: 1024, height: 768},
+ deviceScaleFactor: 1,
+ });
+
+ test('dims a disabled row once: its label, Remove and handle at half opacity', async ({
+ page,
+ }) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-transferlist--disabled&viewMode=story`,
+ );
+ await page.getByRole('switch', {name: 'Disable the list'}).click();
+ const row = page.locator('[data-transfer-list-row="owner"]');
+ const handle = 'button[data-astryx-list-reorder]';
+ await expect(row.locator(handle)).toHaveAttribute('aria-disabled', 'true');
+ // The opacity a reader sees: the product of the element's own and its
+ // ancestors' opacity, up to the row.
+ const seen = async (selector: string) =>
+ row
+ .locator(selector)
+ .first()
+ .evaluate(element => {
+ let opacity = 1;
+ for (
+ let node: Element | null = element;
+ node != null && !node.matches('[data-transfer-list-row]');
+ node = node.parentElement
+ ) {
+ opacity *= Number(getComputedStyle(node).opacity);
+ }
+ return Math.round(opacity * 100) / 100;
+ });
+ await expect.poll(() => seen('text=Owner')).toBe(0.5);
+ await expect
+ .poll(() => seen('[data-transfer-list-action="selected"]'))
+ .toBe(0.5);
+ await expect.poll(() => seen(handle)).toBe(0.5);
+ });
+
+ test('keeps each reorder handle focusable and disabled, with the focus where it was', async ({
+ page,
+ }) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-transferlist--disabled&viewMode=story`,
+ );
+ const handle = page.getByRole('button', {name: 'Reorder Owner'});
+ await expect(handle).toBeVisible();
+ const order = async () =>
+ page.evaluate(
+ selector =>
+ Array.from(document.querySelectorAll(selector)).map(
+ element =>
+ element
+ .closest('[data-transfer-list-row]')
+ ?.getAttribute('data-transfer-list-row') ?? '',
+ ),
+ GRIP,
+ );
+ const before = await order();
+ await handle.focus();
+ // The switch is clicked from script, so the focus stays on the handle.
+ await page
+ .getByRole('switch', {name: 'Disable the list'})
+ .evaluate(element => (element as HTMLElement).click());
+ await expect(page.locator(GRIP)).toHaveCount(before.length);
+ for (const each of await page.locator(GRIP).all()) {
+ await expect(each).toHaveAttribute('aria-disabled', 'true');
+ }
+ await expect(handle).toBeFocused();
+ // A tooltip shows after a short delay. None opens, since the focus stays.
+ await sleep(800);
+ await expect(page.getByRole('tooltip')).toHaveCount(0);
+ // A key or a drag on a disabled handle changes nothing.
+ await page.keyboard.press('Enter');
+ await page.keyboard.press('ArrowDown');
+ await expect(handle).toHaveAttribute('aria-pressed', 'false');
+ const box = (await handle.boundingBox()) as {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2, box.y + 120, {steps: 8});
+ await page.mouse.up();
+ await sleep(300);
+ expect(await order()).toEqual(before);
+ // The handle says why the row does not move. Its description and a
+ // tooltip on hover and on keyboard focus give the reason.
+ const why = page
+ .getByRole('tooltip')
+ .filter({hasText: 'Owner cannot be reordered'});
+ await expect(handle).toHaveAccessibleDescription(
+ /Owner cannot be reordered/,
+ );
+ await page.mouse.move(0, 0);
+ await expect(why).toHaveCount(0);
+ await handle.hover();
+ await expect(why).toBeVisible();
+ await page.mouse.move(0, 0);
+ await expect(why).toHaveCount(0);
+ // The handle stays in the tab order.
+ await handle.focus();
+ await page.keyboard.press('Shift+Tab');
+ await expect(handle).not.toBeFocused();
+ await page.keyboard.press('Tab');
+ await expect(handle).toBeFocused();
+ await expect(why).toBeVisible();
+ });
+});
diff --git a/packages/lab/src/__tests__/ReorderGripPinchZoom.a11y.chromium.spec.ts b/packages/lab/src/__tests__/ReorderGripPinchZoom.a11y.chromium.spec.ts
index 79ab4ff650..2e60cb3237 100644
--- a/packages/lab/src/__tests__/ReorderGripPinchZoom.a11y.chromium.spec.ts
+++ b/packages/lab/src/__tests__/ReorderGripPinchZoom.a11y.chromium.spec.ts
@@ -7,10 +7,12 @@
* Default stories, a built Storybook and real Chromium touch input (CDP) on
* a phone viewport
* @output Browser evidence that a pinch which starts on, or reaches, a reorder
- * grip zooms the page and leaves the order as it was, while a one-finger
- * drag on the grip still reorders (WCAG 1.4.4)
- * @position Chromium proof for the shared Lab reorder grip's `touch-action`
- * (packages/lab/src/reorderStyles.ts)
+ * grip zooms the page and leaves the order as it was. That holds also for a
+ * grip whose first finger slid on it first. A one-finger drag on the grip
+ * still reorders (WCAG 1.4.4)
+ * @position Chromium proof for the Lab reorder grips' `touch-action`: the
+ * shared Lab grip (packages/lab/src/reorderStyles.ts, ListInput) and core
+ * List's reorder handle (TransferList)
*/
import {
@@ -56,6 +58,8 @@ interface Surface {
grip: string;
/** Every reorderable row, in display order, keyed by this attribute. */
rowAttribute: string;
+ /** How long a finger rests on the grip before a drag claims it. */
+ holdMs?: number;
}
const SURFACES: Surface[] = [
@@ -68,8 +72,11 @@ const SURFACES: Surface[] = [
{
name: 'TransferList',
story: 'lab-transferlist--default',
- grip: '[data-transfer-list-row]:not([data-transfer-list-row=""]) button[aria-pressed]',
+ grip: '[data-transfer-list-row] button[data-astryx-list-reorder]',
rowAttribute: 'data-transfer-list-row',
+ // Core List's handle claims a still finger after 150 ms, as UIKit's
+ // reorder control does.
+ holdMs: 250,
},
];
@@ -110,22 +117,21 @@ async function touch(
});
}
-// Two fingers land one after the other and spread apart, as a person pinches.
-// The spread is wide enough to clear the browser's minimum pinch span.
-async function pinch(cdp: CDPSession, first: Point, second: Point) {
+// A second finger lands beside the first (already down) and the two spread
+// apart, as a person pinches. The spread is wide enough to clear the
+// browser's minimum pinch span.
+async function spread(cdp: CDPSession, first: Point, second: Point) {
const steps = 12;
- const spread = 2.5;
+ const factor = 2.5;
const mid = {x: (first.x + second.x) / 2, y: (first.y + second.y) / 2};
const at = (p: Point, k: number) => ({
x: mid.x + (p.x - mid.x) * k,
y: mid.y + (p.y - mid.y) * k,
});
- await touch(cdp, 'touchStart', [first]);
- await sleep(30);
await touch(cdp, 'touchStart', [first, second]);
for (let i = 1; i <= steps; i++) {
await sleep(16);
- const k = 1 + ((spread - 1) * i) / steps;
+ const k = 1 + ((factor - 1) * i) / steps;
await touch(cdp, 'touchMove', [at(first, k), at(second, k)]);
}
await sleep(16);
@@ -133,6 +139,13 @@ async function pinch(cdp: CDPSession, first: Point, second: Point) {
await sleep(600);
}
+// Two fingers land one after the other and spread apart.
+async function pinch(cdp: CDPSession, first: Point, second: Point) {
+ await touch(cdp, 'touchStart', [first]);
+ await sleep(30);
+ await spread(cdp, first, second);
+}
+
for (const surface of SURFACES) {
test.describe(surface.name, () => {
test('a pinch whose first finger lands on a grip zooms the page', async ({
@@ -153,6 +166,26 @@ for (const surface of SURFACES) {
expect(await readOrder(page, surface)).toEqual(order);
});
+ test('a pinch whose first finger slid on a grip zooms and keeps the order', async ({
+ page,
+ }) => {
+ const {center, cdp, order} = await openStory(page, surface);
+ // The first finger slides 24 px on the grip right away, before the
+ // second lands, as a pinch often starts. The release must not drop the
+ // row. (A finger held still past core List's hold claims the drag
+ // instead, and a second finger then changes nothing: List's own spec.)
+ await touch(cdp, 'touchStart', [center]);
+ let first = center;
+ for (let i = 1; i <= 2; i++) {
+ await sleep(16);
+ first = {x: center.x, y: center.y + 12 * i};
+ await touch(cdp, 'touchMove', [first]);
+ }
+ await spread(cdp, first, {x: first.x + 40, y: first.y + 140});
+ expect(await zoom(page)).toBeGreaterThan(1.2);
+ expect(await readOrder(page, surface)).toEqual(order);
+ });
+
test('a one-finger drag on a grip still reorders', async ({page}) => {
const {center, cdp, order} = await openStory(page, surface);
const rows = await page.evaluate(
@@ -165,6 +198,9 @@ for (const surface of SURFACES) {
// Past the second row's centre: the first row lands second or later.
const distance = (rows[2] - rows[0]) * 0.9;
await touch(cdp, 'touchStart', [center]);
+ if (surface.holdMs != null) {
+ await sleep(surface.holdMs);
+ }
for (let i = 1; i <= 20; i++) {
await sleep(16);
await touch(cdp, 'touchMove', [
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 10310fbf9f..fcf38480bf 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -238,6 +238,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [
// public API, and allowed by lint only in Core and Lab
// (architecture:react-component-runtime INV13).
'internal/indicatorPress.stylex',
+ 'internal/reorder',
'internal/touchHitArea.stylex',
'internal/touch',
'internal/selectable-card',