Skip to content

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

TypeScript

feat(lab): add TransferListSelector and Storybook examples (#4870)

Ernestdccdabea0b1a
diff --git a/apps/storybook/stories/TransferList.stories.tsx b/apps/storybook/stories/TransferList.stories.tsx
new file mode 100644
index 0000000000..837ee3f88c
--- /dev/null
+++ b/apps/storybook/stories/TransferList.stories.tsx
@@ -0,0 +1,748 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferList.stories.tsx
+ * @input TransferListSelector option data, commit behavior, and advanced Core selector and table primitives
+ * @output Storybook examples for immediate/staged selectors plus advanced TransferList composition
+ * @position Lab Storybook documentation and visual validation
+ *
+ * SYNC: When selector commit behavior or TransferList interaction changes, update source, docs, and tests.
+ */
+
+import {useEffect, useRef, useState, type SVGProps} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import * as stylex from '@stylexjs/stylex';
+import {TransferList, TransferListSelector} from '@astryxdesign/lab';
+import type {TransferListOption, TransferListProps} from '@astryxdesign/lab';
+import {Button} from '@astryxdesign/core/Button';
+import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';
+import {Divider} from '@astryxdesign/core/Divider';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Icon} from '@astryxdesign/core/Icon';
+import {IconButton} from '@astryxdesign/core/IconButton';
+import {Section} from '@astryxdesign/core/Section';
+import {Selector} from '@astryxdesign/core/Selector';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {
+ Table,
+ pixel,
+ proportional,
+ useTableColumnSettings,
+ useTableColumnSettingsState,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+import {Text} from '@astryxdesign/core/Text';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+function PlusIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ {...props}>
+ <path d="M5 12h14" />
+ <path d="M12 5v14" />
+ </svg>
+ );
+}
+
+const styles = stylex.create({
+ viewOptionsTrigger: {
+ backgroundColor: colorVars['--color-background-muted'],
+ borderRadius: radiusVars['--radius-element'],
+ },
+ viewOptionsContent: {
+ width: 'min(760px, calc(100vw - 32px))',
+ maxWidth: 'calc(100vw - 32px)',
+ maxHeight: 'min(680px, calc(100vh - 32px))',
+ padding: 0,
+ overflow: 'hidden',
+ },
+ narrowSelectorContent: {
+ width: 'min(360px, calc(100vw - 32px))',
+ maxWidth: 'min(360px, calc(100vw - 32px))',
+ maxHeight: 'calc(100vh - 32px)',
+ padding: 0,
+ },
+ viewOptionsSurface: {
+ display: 'flex',
+ flexDirection: 'column',
+ minWidth: 0,
+ maxHeight: 'min(680px, calc(100vh - 32px))',
+ },
+ viewOptionsHeader: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-3'],
+ },
+ presetsRow: {
+ display: 'grid',
+ gridTemplateColumns: 'auto minmax(0, 1fr) auto',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-3'],
+ },
+ transferListSection: {
+ minHeight: 0,
+ overflowY: 'auto',
+ overscrollBehavior: 'contain',
+ },
+ viewOptionsFooter: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-3'],
+ },
+});
+
+const meta: Meta<typeof TransferListSelector> = {
+ title: 'Lab/TransferListSelector',
+ component: TransferListSelector,
+ tags: ['autodocs'],
+ parameters: {
+ layout: 'centered',
+ },
+ decorators: [
+ Story => (
+ <div
+ style={{
+ width: 'min(900px, calc(100vw - 64px))',
+ minHeight: 480,
+ }}>
+ <Story />
+ </div>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const BASIC_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ {
+ value: 'name',
+ label: 'Name',
+ description: 'Primary display name for the record',
+ },
+ {
+ value: 'owner',
+ label: 'Owner',
+ description: 'Person responsible for the record',
+ },
+ {
+ value: 'status',
+ label: 'Status',
+ description: 'Current workflow state',
+ },
+ {
+ value: 'priority',
+ label: 'Priority',
+ description: 'Relative urgency',
+ },
+ {
+ value: 'team',
+ label: 'Team',
+ description: 'Owning team',
+ },
+ {
+ value: 'updated',
+ label: 'Last updated',
+ description: 'Most recent change time',
+ },
+ {
+ value: 'created',
+ label: 'Created',
+ description: 'Original creation time',
+ },
+];
+
+const BASIC_DESCRIPTION =
+ 'Choose which fields appear. Changes take effect immediately, and drag reorder commits on release.';
+
+const BASIC_TRANSFER_LIST_PROPS = {
+ label: 'Visible fields',
+ options: BASIC_OPTIONS,
+ selectedLabel: 'Visible fields',
+ availableLabel: 'Available fields',
+ hasSelectAll: true,
+ hasClear: true,
+} satisfies Omit<TransferListProps<string>, 'value' | 'onChange'>;
+
+function DefaultExample() {
+ const defaults = ['name', 'owner', 'status'];
+ const [value, setValue] = useState<readonly string[]>(defaults);
+ return (
+ <TransferListSelector
+ {...BASIC_TRANSFER_LIST_PROPS}
+ description={BASIC_DESCRIPTION}
+ value={value}
+ onChange={setValue}
+ triggerLabel={`${value.length} visible fields`}
+ />
+ );
+}
+
+export const Default: Story = {
+ render: () => <DefaultExample />,
+};
+
+function StagedChangesExample() {
+ const defaults = ['name', 'owner', 'status'];
+ const [value, setValue] = useState<readonly string[]>(defaults);
+ return (
+ <TransferListSelector
+ {...BASIC_TRANSFER_LIST_PROPS}
+ description="Review the complete field selection before applying it."
+ value={value}
+ onChange={setValue}
+ commitBehavior="staged"
+ triggerLabel={`${value.length} visible fields`}
+ />
+ );
+}
+
+export const StagedChanges: Story = {
+ render: () => <StagedChangesExample />,
+};
+
+const GROUPED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ {
+ value: 'name',
+ label: 'Name',
+ description: 'Required identity field',
+ group: 'Identity',
+ isTransferDisabled: true,
+ isReorderDisabled: true,
+ disabledMessage: 'Name is required and fixed in position.',
+ },
+ {
+ value: 'owner',
+ label: 'Owner',
+ description: 'Person responsible for the work',
+ group: 'Identity',
+ isTransferDisabled: true,
+ disabledMessage: 'Owner must remain visible but can be reordered.',
+ },
+ {
+ value: 'team',
+ label: 'Team',
+ description: 'Owning team',
+ group: 'Identity',
+ },
+ {
+ value: 'status',
+ 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',
+ label: 'Priority',
+ description: 'Relative urgency',
+ group: 'Planning',
+ },
+ {
+ value: 'due',
+ label: 'Due date',
+ description: 'Planned completion date',
+ group: 'Planning',
+ },
+ {
+ value: 'updated',
+ label: 'Last updated',
+ description: 'Most recent change time',
+ group: 'Activity',
+ },
+ {
+ value: 'created',
+ label: 'Created',
+ description: 'Original creation time',
+ group: 'Activity',
+ },
+];
+
+function GroupedAndLockedExample() {
+ const defaults = ['name', 'owner', 'status', 'updated'];
+ const [value, setValue] = useState<readonly string[]>(defaults);
+
+ return (
+ <TransferListSelector
+ label="Record fields"
+ description="Fields are grouped by purpose. Removal and reordering constraints can be applied independently."
+ options={GROUPED_OPTIONS}
+ value={value}
+ onChange={setValue}
+ selectedLabel="Shown"
+ availableLabel="Hidden"
+ hasSelectAll
+ hasClear
+ triggerLabel={`${value.length} shown fields`}
+ />
+ );
+}
+
+export const GroupedAndLocked: Story = {
+ render: () => <GroupedAndLockedExample />,
+};
+
+function UnorderedExample() {
+ const [value, setValue] = useState<readonly string[]>([
+ 'status',
+ 'priority',
+ 'team',
+ ]);
+
+ return (
+ <TransferListSelector
+ label="Included filters"
+ description="Use an unordered transfer list when selection matters but display order does not."
+ options={BASIC_OPTIONS}
+ value={value}
+ onChange={setValue}
+ selectedLabel="Included"
+ availableLabel="Not included"
+ isReorderable={false}
+ hasSelectAll
+ hasClear
+ triggerLabel={`${value.length} included filters`}
+ />
+ );
+}
+
+export const Unordered: Story = {
+ render: () => <UnorderedExample />,
+};
+
+function NarrowContainerExample() {
+ const [value, setValue] = useState<readonly string[]>([
+ 'name',
+ 'owner',
+ 'status',
+ ]);
+ return (
+ <TransferListSelector
+ label="Mobile field settings"
+ description="The two panels stack when horizontal space is limited."
+ options={BASIC_OPTIONS}
+ value={value}
+ onChange={setValue}
+ triggerLabel={`${value.length} visible fields`}
+ width="min(360px, calc(100vw - 32px))"
+ placement="below"
+ contentXstyle={styles.narrowSelectorContent}
+ selectedLabel="Visible"
+ availableLabel="Available"
+ isReorderable={false}
+ hasSelectAll
+ hasClear
+ />
+ );
+}
+
+export const NarrowContainer: Story = {
+ render: () => <NarrowContainerExample />,
+};
+
+const LARGE_POOL_OPTIONS: ReadonlyArray<TransferListOption<string>> =
+ Array.from({length: 200}, (_, index) => {
+ const number = index + 1;
+ return {
+ value: `field-${number}`,
+ label: `Field ${String(number).padStart(3, '0')}`,
+ description: `Configurable field ${number}`,
+ group: `Group ${Math.floor(index / 40) + 1}`,
+ };
+ });
+
+function LargePoolExample() {
+ const [value, setValue] = useState<readonly string[]>(
+ LARGE_POOL_OPTIONS.slice(0, 12).map(option => option.value),
+ );
+
+ return (
+ <TransferListSelector
+ label="Report fields"
+ description="Search a pool of 200 options while preserving the chosen display order."
+ options={LARGE_POOL_OPTIONS}
+ value={value}
+ onChange={setValue}
+ selectedLabel="In report"
+ availableLabel="Available"
+ hasSearch
+ searchPlaceholder="Search 200 fields"
+ hasSelectAll
+ hasClear
+ triggerLabel={`${value.length} report fields`}
+ />
+ );
+}
+
+export const LargePool: Story = {
+ render: () => <LargePoolExample />,
+};
+
+interface ProjectRow extends Record<string, unknown> {
+ id: string;
+ name: string;
+ owner: string;
+ status: string;
+ priority: string;
+ team: string;
+ updated: string;
+}
+
+type ProjectColumnKey =
+ 'name' | 'owner' | 'status' | 'priority' | 'team' | 'updated';
+
+const PROJECTS: ProjectRow[] = [
+ {
+ id: 'p-1',
+ name: 'Account migration',
+ owner: 'Mina Patel',
+ status: 'On track',
+ priority: 'High',
+ team: 'Platform',
+ updated: '12 min ago',
+ },
+ {
+ id: 'p-2',
+ name: 'Mobile refresh',
+ owner: 'Theo Martin',
+ status: 'At risk',
+ priority: 'High',
+ team: 'Product',
+ updated: '1 hr ago',
+ },
+ {
+ id: 'p-3',
+ name: 'Quarterly planning',
+ owner: 'Sam Lee',
+ status: 'In review',
+ priority: 'Medium',
+ team: 'Operations',
+ updated: 'Yesterday',
+ },
+ {
+ id: 'p-4',
+ name: 'Search improvements',
+ owner: 'Avery Chen',
+ status: 'On track',
+ priority: 'Medium',
+ team: 'Product',
+ updated: '2 days ago',
+ },
+];
+
+const PROJECT_COLUMNS: TableColumn<ProjectRow>[] = [
+ {key: 'name', header: 'Project', width: proportional(2)},
+ {key: 'owner', header: 'Owner', width: proportional(1)},
+ {key: 'status', header: 'Status', width: pixel(112)},
+ {key: 'priority', header: 'Priority', width: pixel(96)},
+ {key: 'team', header: 'Team', width: proportional(1)},
+ {key: 'updated', header: 'Updated', width: pixel(112)},
+];
+
+const PROJECT_COLUMN_OPTIONS: ReadonlyArray<{
+ key: ProjectColumnKey;
+ label: string;
+ group?: string;
+ isAlwaysVisible?: boolean;
+}> = [
+ {
+ key: 'name',
+ label: 'Project',
+ group: 'Identity',
+ isAlwaysVisible: true,
+ },
+ {key: 'owner', label: 'Owner', group: 'Identity'},
+ {key: 'team', label: 'Team', group: 'Identity'},
+ {key: 'status', label: 'Status', group: 'Planning'},
+ {key: 'priority', label: 'Priority', group: 'Planning'},
+ {key: 'updated', label: 'Updated', group: 'Activity'},
+];
+
+const PROJECT_TRANSFER_OPTIONS: ReadonlyArray<
+ TransferListOption<ProjectColumnKey>
+> = PROJECT_COLUMN_OPTIONS.map(option => ({
+ value: option.key,
+ label: option.label,
+ group: option.group,
+ isTransferDisabled: option.isAlwaysVisible,
+ disabledMessage: option.isAlwaysVisible
+ ? 'Project is the primary identity column and must stay visible.'
+ : undefined,
+}));
+
+const DEFAULT_PROJECT_COLUMNS: ReadonlyArray<ProjectColumnKey> = [
+ 'name',
+ 'owner',
+ 'status',
+ 'priority',
+ 'updated',
+];
+
+const SAVED_VIEWS: ReadonlyArray<{
+ value: string;
+ label: string;
+ columns: ReadonlyArray<ProjectColumnKey>;
+}> = [
+ {
+ value: 'standard',
+ label: 'Standard view',
+ columns: DEFAULT_PROJECT_COLUMNS,
+ },
+ {
+ value: 'ownership',
+ label: 'Ownership view',
+ columns: ['name', 'owner', 'team', 'status'],
+ },
+ {
+ value: 'planning',
+ label: 'Planning view',
+ columns: ['name', 'status', 'priority', 'owner', 'updated'],
+ },
+];
+
+function hasSameOrderedColumns(
+ left: ReadonlyArray<ProjectColumnKey>,
+ right: ReadonlyArray<ProjectColumnKey>,
+): boolean {
+ return (
+ left.length === right.length &&
+ left.every((column, index) => column === right[index])
+ );
+}
+
+function ResetTableDraftOnOpen({
+ isOpen,
+ appliedColumns,
+ savedViews,
+ setDraftColumns,
+ setActiveSavedView,
+}: {
+ isOpen: boolean;
+ appliedColumns: ReadonlyArray<ProjectColumnKey>;
+ savedViews: ReadonlyArray<(typeof SAVED_VIEWS)[number]>;
+ setDraftColumns: (columns: ReadonlyArray<ProjectColumnKey>) => void;
+ setActiveSavedView: (value: string) => void;
+}) {
+ const wasOpenRef = useRef(false);
+
+ useEffect(() => {
+ if (isOpen && !wasOpenRef.current) {
+ setDraftColumns([...appliedColumns]);
+ setActiveSavedView(
+ savedViews.find(view =>
+ hasSameOrderedColumns(view.columns, appliedColumns),
+ )?.value ?? 'custom',
+ );
+ }
+ wasOpenRef.current = isOpen;
+ }, [appliedColumns, isOpen, savedViews, setActiveSavedView, setDraftColumns]);
+
+ return null;
+}
+
+function TableColumnSettingsExample() {
+ const [appliedColumns, setAppliedColumns] = useState<
+ ReadonlyArray<ProjectColumnKey>
+ >(DEFAULT_PROJECT_COLUMNS);
+ const [draftColumns, setDraftColumns] = useState<
+ ReadonlyArray<ProjectColumnKey>
+ >(DEFAULT_PROJECT_COLUMNS);
+ const [savedViews, setSavedViews] = useState(SAVED_VIEWS);
+ const [activeSavedView, setActiveSavedView] = useState('standard');
+ const nextSavedViewNumberRef = useRef(1);
+
+ const columnSettingsState = useTableColumnSettingsState<ProjectColumnKey>({
+ columns: PROJECT_COLUMN_OPTIONS,
+ activeColumnKeys: appliedColumns,
+ onChangeActiveColumnKeys: setAppliedColumns,
+ defaultColumnKeys: DEFAULT_PROJECT_COLUMNS,
+ });
+ const columnSettingsPlugin = useTableColumnSettings<
+ ProjectRow,
+ ProjectColumnKey
+ >(columnSettingsState.columnSettingsConfig);
+
+ const savedViewOptions = [
+ ...savedViews.map(view => ({value: view.value, label: view.label})),
+ {value: 'custom', label: 'Custom', disabled: true},
+ ];
+
+ const findSavedViewValue = (
+ nextColumns: ReadonlyArray<ProjectColumnKey>,
+ ): string =>
+ savedViews.find(view => hasSameOrderedColumns(view.columns, nextColumns))
+ ?.value ?? 'custom';
+
+ const selectSavedView = (nextValue: string) => {
+ const nextView = savedViews.find(view => view.value === nextValue);
+ if (nextView == null) {
+ return;
+ }
+ setActiveSavedView(nextView.value);
+ setDraftColumns(nextView.columns);
+ };
+
+ const changeDraftColumns = (nextColumns: ReadonlyArray<ProjectColumnKey>) => {
+ setDraftColumns(nextColumns);
+ setActiveSavedView(findSavedViewValue(nextColumns));
+ };
+
+ const saveCurrentColumnsAsView = () => {
+ const nextNumber = nextSavedViewNumberRef.current;
+ nextSavedViewNumberRef.current += 1;
+ const nextView = {
+ value: `saved-${nextNumber}`,
+ label: `Saved view ${nextNumber}`,
+ columns: [...draftColumns],
+ };
+ setSavedViews(currentViews => [...currentViews, nextView]);
+ setActiveSavedView(nextView.value);
+ };
+
+ return (
+ <VStack gap={3} width="100%">
+ <HStack gap={3} hAlign="between" vAlign="center">
+ <VStack gap={0.5}>
+ <Heading level={2}>Projects</Heading>
+ <Text type="supporting" color="secondary">
+ Customize visible columns without changing the underlying data.
+ </Text>
+ </VStack>
+ <ComplexSelector
+ label="View options"
+ isLabelHidden
+ value={appliedColumns}
+ onChange={setAppliedColumns}
+ triggerLabel="View Options"
+ placement="below"
+ xstyle={styles.viewOptionsTrigger}
+ contentXstyle={styles.viewOptionsContent}>
+ {(_currentColumns, commit, close, state) => (
+ <div {...stylex.props(styles.viewOptionsSurface)}>
+ <ResetTableDraftOnOpen
+ isOpen={state.isOpen}
+ appliedColumns={appliedColumns}
+ savedViews={savedViews}
+ setDraftColumns={setDraftColumns}
+ setActiveSavedView={setActiveSavedView}
+ />
+ <div {...stylex.props(styles.viewOptionsHeader)}>
+ <Heading level={3}>View Options</Heading>
+ <IconButton
+ label="Close view options"
+ icon={<Icon icon="close" size="sm" color="inherit" />}
+ variant="ghost"
+ size="sm"
+ onClick={close}
+ />
+ </div>
+ <Divider />
+ <div {...stylex.props(styles.presetsRow)}>
+ <Text type="label" weight="semibold">
+ Presets
+ </Text>
+ <Selector
+ label="Column preset"
+ isLabelHidden
+ options={savedViewOptions}
+ value={activeSavedView}
+ onChange={selectSavedView}
+ width="100%"
+ />
+ <IconButton
+ label="Save current columns as a preset"
+ icon={<Icon icon={PlusIcon} size="sm" color="inherit" />}
+ variant="secondary"
+ size="sm"
+ onClick={saveCurrentColumnsAsView}
+ />
+ </div>
+ <div {...stylex.props(styles.transferListSection)}>
+ <TransferList
+ label="Table columns"
+ isLabelHidden
+ options={PROJECT_TRANSFER_OPTIONS}
+ value={draftColumns}
+ onChange={changeDraftColumns}
+ selectedLabel="Visible fields"
+ availableLabel="Available fields"
+ hasSearch
+ searchPlaceholder="Search columns"
+ hasSelectAll
+ hasClear
+ />
+ </div>
+ <Divider />
+ <div {...stylex.props(styles.viewOptionsFooter)}>
+ <Button
+ label="Restore columns to default"
+ variant="ghost"
+ onClick={() => {
+ setDraftColumns(DEFAULT_PROJECT_COLUMNS);
+ setActiveSavedView('standard');
+ }}>
+ Restore to default
+ </Button>
+ <HStack gap={2}>
+ <Button
+ label="Cancel column changes"
+ variant="ghost"
+ onClick={() => {
+ setDraftColumns(appliedColumns);
+ setActiveSavedView(findSavedViewValue(appliedColumns));
+ close();
+ }}>
+ Cancel
+ </Button>
+ <Button
+ label="Apply column changes"
+ variant="primary"
+ onClick={() => {
+ commit(draftColumns);
+ close();
+ }}>
+ Apply
+ </Button>
+ </HStack>
+ </div>
+ </div>
+ )}
+ </ComplexSelector>
+ </HStack>
+ <Section padding={0}>
+ <Table
+ data={PROJECTS}
+ columns={PROJECT_COLUMNS}
+ idKey="id"
+ plugins={{columnSettings: columnSettingsPlugin}}
+ hasHover
+ textOverflow="truncate"
+ />
+ </Section>
+ </VStack>
+ );
+}
+
+export const TableColumnSettings: Story = {
+ name: 'Advanced: Table column settings',
+ render: () => <TableColumnSettingsExample />,
+};
diff --git a/packages/lab/src/TransferList/TransferList.composition.test.tsx b/packages/lab/src/TransferList/TransferList.composition.test.tsx
new file mode 100644
index 0000000000..2457463fcb
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferList.composition.test.tsx
@@ -0,0 +1,288 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferList.composition.test.tsx
+ * @input Uses ComplexSelector, TransferList, React state, and Testing Library
+ * @output Integration coverage for staged transfer-list selector behavior
+ * @position Lab composition test; validates the two public component contracts together
+ *
+ * SYNC: When the ComplexSelector + TransferList staged contract changes, update this test.
+ */
+
+import {useEffect, useRef, useState} from 'react';
+import {describe, expect, it, vi} from 'vitest';
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {ComplexSelector} from '@astryxdesign/core/ComplexSelector';
+import {TransferList, type TransferListOption} from './TransferList';
+
+type Column = 'name' | 'owner' | 'status' | 'updated';
+
+const OPTIONS: ReadonlyArray<TransferListOption<Column>> = [
+ {value: 'name', label: 'Name'},
+ {value: 'owner', label: 'Owner'},
+ {value: 'status', label: 'Status'},
+ {value: 'updated', label: 'Updated'},
+];
+
+const PRESETS = {
+ compact: ['owner', 'name'],
+} as const satisfies Record<string, readonly Column[]>;
+
+const hidden = {hidden: true} as const;
+
+function ResetDraftOnOpen({
+ isOpen,
+ appliedValue,
+ onReset,
+}: {
+ isOpen: boolean;
+ appliedValue: readonly Column[];
+ onReset: (value: readonly Column[]) => void;
+}) {
+ const wasOpenRef = useRef(false);
+
+ useEffect(() => {
+ if (isOpen && !wasOpenRef.current) {
+ onReset([...appliedValue]);
+ }
+ wasOpenRef.current = isOpen;
+ }, [appliedValue, isOpen, onReset]);
+
+ return null;
+}
+
+function StagedColumnSelector({
+ initialValue = ['name', 'status'],
+ onCommit,
+}: {
+ initialValue?: readonly Column[];
+ onCommit: (value: readonly Column[]) => void;
+}) {
+ const [appliedValue, setAppliedValue] =
+ useState<readonly Column[]>(initialValue);
+ const [draftValue, setDraftValue] = useState<readonly Column[]>(initialValue);
+
+ return (
+ <>
+ <output data-testid="applied-value">
+ {JSON.stringify(appliedValue)}
+ </output>
+ <ComplexSelector
+ label="View options"
+ value={appliedValue}
+ onChange={nextValue => {
+ onCommit(nextValue);
+ setAppliedValue(nextValue);
+ }}
+ triggerLabel="View options">
+ {(_value, commit, close, state) => (
+ <div>
+ <ResetDraftOnOpen
+ isOpen={state.isOpen}
+ appliedValue={appliedValue}
+ onReset={setDraftValue}
+ />
+ <output data-testid="draft-value">
+ {JSON.stringify(draftValue)}
+ </output>
+ <button
+ type="button"
+ onClick={() => setDraftValue(PRESETS.compact)}>
+ Compact preset
+ </button>
+ <TransferList
+ label="Table columns"
+ isLabelHidden
+ selectedLabel="Visible fields"
+ availableLabel="Available fields"
+ options={OPTIONS}
+ value={draftValue}
+ onChange={setDraftValue}
+ />
+ <button type="button" onClick={close}>
+ Close
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ commit([...draftValue]);
+ close();
+ }}>
+ Apply
+ </button>
+ </div>
+ )}
+ </ComplexSelector>
+ </>
+ );
+}
+
+function openSelector(): void {
+ fireEvent.keyDown(screen.getByRole('button', {name: 'View options'}), {
+ key: 'ArrowDown',
+ });
+}
+
+describe('ComplexSelector + TransferList composition', () => {
+ it('keeps changes in a draft until Apply commits the ordered value once', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <StagedColumnSelector
+ initialValue={['status', 'name']}
+ onCommit={onCommit}
+ />,
+ );
+
+ openSelector();
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'View options'}),
+ ).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ await user.click(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ );
+
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["status","name","owner"]',
+ );
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["status","name"]',
+ );
+ expect(onCommit).not.toHaveBeenCalled();
+
+ await user.click(screen.getByRole('button', {name: 'Apply', ...hidden}));
+
+ expect(onCommit).toHaveBeenCalledOnce();
+ expect(onCommit).toHaveBeenCalledWith(['status', 'name', 'owner']);
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["status","name","owner"]',
+ );
+ });
+
+ it('discards closed and light-dismissed drafts before reopening', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(<StagedColumnSelector onCommit={onCommit} />);
+ const trigger = screen.getByRole('button', {name: 'View options'});
+
+ openSelector();
+ await user.click(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ );
+ expect(screen.getByTestId('draft-value')).toHaveTextContent('["status"]');
+
+ await user.click(screen.getByRole('button', {name: 'Close', ...hidden}));
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(onCommit).not.toHaveBeenCalled();
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+
+ openSelector();
+ await waitFor(() => {
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ });
+ await user.click(
+ screen.getByRole('button', {name: 'Remove Status', ...hidden}),
+ );
+ expect(screen.getByTestId('draft-value')).toHaveTextContent('["name"]');
+
+ const popover = screen
+ .getByRole('dialog', {name: 'View options', ...hidden})
+ .closest('[popover]');
+ expect(popover).not.toBeNull();
+ const dismissEvent = new Event('toggle');
+ Object.defineProperty(dismissEvent, 'newState', {value: 'closed'});
+ fireEvent(popover as HTMLElement, dismissEvent);
+
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+ expect(onCommit).not.toHaveBeenCalled();
+
+ openSelector();
+ await waitFor(() => {
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ });
+ });
+
+ it('lets a preset replace the draft without committing it', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(<StagedColumnSelector onCommit={onCommit} />);
+
+ openSelector();
+ await user.click(
+ screen.getByRole('button', {name: 'Compact preset', ...hidden}),
+ );
+
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["owner","name"]',
+ );
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ expect(onCommit).not.toHaveBeenCalled();
+
+ const selectedList = screen.getByRole('list', {
+ name: 'Visible fields',
+ ...hidden,
+ });
+ expect(
+ within(selectedList)
+ .getAllByRole('listitem', hidden)
+ .map(item => item.textContent?.trim()),
+ ).toEqual(['Owner', 'Name']);
+ });
+
+ it('lets Escape cancel an active reorder without closing the selector', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(<StagedColumnSelector onCommit={onCommit} />);
+ const trigger = screen.getByRole('button', {name: 'View options'});
+
+ openSelector();
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'Compact preset', ...hidden}),
+ ).toHaveFocus();
+ });
+
+ const reorder = screen.getByRole('button', {
+ name: 'Reorder Name',
+ ...hidden,
+ });
+ reorder.focus();
+ await user.keyboard('{Enter}{ArrowDown}');
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["status","name"]',
+ );
+
+ await user.keyboard('{Escape}');
+
+ expect(screen.getByTestId('draft-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ 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
new file mode 100644
index 0000000000..8d3846d871
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferList.doc.mjs
@@ -0,0 +1,749 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferList.doc.mjs
+ * @input TransferListSelector and TransferList public APIs, commit behavior, and usage guidance
+ * @output Documents the default-immediate selector, optional staged commits, and advanced TransferList composition
+ * @position Lab documentation consumed by component tooling
+ *
+ * SYNC: When modified, update TransferListSelector.tsx, TransferList.tsx, commit-behavior tests, and package exports.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'TransferListSelector',
+ displayName: 'Transfer List Selector',
+ group: 'Selector',
+ category: 'Data Input',
+ keywords: [
+ 'transfer list',
+ 'dual list',
+ 'pick list',
+ 'selector',
+ 'popover',
+ 'selection',
+ 'reorder',
+ 'columns',
+ 'available',
+ 'selected',
+ 'immediate',
+ 'draft',
+ 'apply',
+ ],
+ description:
+ 'A selector field for moving options between selected and available lists and optionally ordering the selected values. Changes commit immediately by default; staged commit behavior adds an internal draft and Apply/Cancel footer. TransferList remains the lower-level content primitive for custom ComplexSelector surfaces.',
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Accessible field label shown outside the popover unless isLabelHidden is true.',
+ required: true,
+ },
+ {
+ 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.',
+ required: true,
+ },
+ {
+ name: 'value',
+ type: 'readonly T[]',
+ description:
+ 'Committed selected values in display order. In staged behavior this is the applied value copied into a local draft when the selector opens.',
+ required: true,
+ },
+ {
+ name: 'onChange',
+ type: '(nextValue: readonly T[]) => void',
+ description:
+ 'Called after every permitted list edit in immediate behavior, or once when Apply commits a changed draft in staged behavior.',
+ required: true,
+ },
+ {
+ name: 'commitBehavior',
+ type: 'TransferListSelectorCommitBehavior',
+ description:
+ 'Controls when changes commit. Immediate updates on each list edit without a footer; staged waits for Apply and supports Cancel or dismiss.',
+ default: "'immediate'",
+ },
+ {
+ name: 'triggerLabel',
+ type: 'ReactNode',
+ description: 'Content shown in the closed selector trigger.',
+ default: '`${value.length} selected`',
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Supporting field guidance shown with the external label.',
+ },
+ {
+ name: 'isLabelHidden',
+ type: 'boolean',
+ description:
+ 'Visually hides the field label while preserving its accessible name.',
+ default: 'false',
+ },
+ {
+ name: 'selectedLabel',
+ type: 'string',
+ description: 'Heading and accessible name for the selected list.',
+ default: "'Selected'",
+ },
+ {
+ name: 'availableLabel',
+ type: 'string',
+ description: 'Heading and accessible name for the available list.',
+ default: "'Available'",
+ },
+ {
+ name: 'hasSearch',
+ type: 'boolean',
+ description:
+ 'Shows a shared search field that filters both lists by label and description.',
+ default: 'false',
+ },
+ {
+ name: 'searchLabel',
+ type: 'string',
+ description: 'Accessible label for the shared search field.',
+ default: "'Search ' followed by label",
+ },
+ {
+ name: 'searchPlaceholder',
+ type: 'string',
+ description: 'Placeholder shown in the shared search field.',
+ default: "'Search\u2026'",
+ },
+ {
+ name: 'isReorderable',
+ type: 'boolean',
+ 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',
+ },
+ {
+ name: 'hasSelectAll',
+ type: 'boolean',
+ description:
+ 'Shows Add all and adds every transfer-enabled available option to the current selection.',
+ default: 'false',
+ },
+ {
+ name: 'hasClear',
+ type: 'boolean',
+ description:
+ 'Shows Clear and removes every transfer-enabled selected option from the current selection.',
+ default: 'false',
+ },
+ {
+ name: 'renderOption',
+ type: '(option: TransferListOption<T>) => ReactNode',
+ description:
+ 'Customizes row content while retaining built-in labels, actions, constraints, and reorder interaction.',
+ },
+ {
+ name: 'selectedEmptyText',
+ type: 'string',
+ description: 'Message shown when the selected list is empty.',
+ default: "'No selected options'",
+ },
+ {
+ name: 'availableEmptyText',
+ type: 'string',
+ description: 'Message shown when every option has been selected.',
+ default: "'No available options'",
+ },
+ {
+ name: 'noResultsText',
+ type: 'string',
+ description: 'Message shown when search has no matches in a list.',
+ default: "'No results'",
+ },
+ {
+ name: 'applyLabel',
+ type: 'string',
+ description:
+ 'Label for the staged Apply action. Only valid with commitBehavior="staged".',
+ default: "'Apply'",
+ },
+ {
+ name: 'cancelLabel',
+ type: 'string',
+ description:
+ 'Label for the staged Cancel action. Only valid with commitBehavior="staged".',
+ default: "'Cancel'",
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: 'Trigger and field size.',
+ default: "'md'",
+ },
+ {
+ name: 'width',
+ type: 'SizeValue',
+ description:
+ 'Width of the external field. Its default matches the responsive popup width; use contentXstyle to override the popup.',
+ default: "'min(41rem, calc(100vw - 32px))'",
+ },
+ {
+ name: 'placement',
+ type: "'above' | 'below' | 'start' | 'end'",
+ description: 'Popover placement relative to the trigger.',
+ default: "'below'",
+ },
+ {
+ name: 'isOptional',
+ type: 'boolean',
+ description: 'Marks the field optional.',
+ },
+ {
+ name: 'isRequired',
+ type: 'boolean',
+ description: 'Marks the field required.',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: 'Disables the selector trigger and transfer interaction.',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description:
+ 'Shows loading state on the trigger and disables transfer interaction while busy.',
+ },
+ {
+ name: 'status',
+ type: "{type: 'warning' | 'error' | 'success', message?: string}",
+ description: 'Validation status for the field.',
+ },
+ {
+ name: 'statusVariant',
+ type: 'FieldStatusVariant',
+ description: 'Placement treatment for the status message.',
+ },
+ {
+ name: 'labelTooltip',
+ type: 'string',
+ description: 'Tooltip text displayed next to the field label.',
+ },
+ {
+ name: 'changeAction',
+ type: '(value: readonly T[]) => void | Promise<void>',
+ description:
+ 'Optional async action run after each immediate commit or a changed staged Apply; drives optimistic and busy state.',
+ },
+ {
+ name: 'contentXstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX styles composed after the default zero-padding, clipped popover content style.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: 'StyleX styles for the external selector field.',
+ },
+ {
+ name: 'className',
+ type: 'string',
+ description: 'Class name applied to the external selector field.',
+ },
+ {
+ name: 'style',
+ type: 'CSSProperties',
+ description: 'Inline styles applied to the external selector field.',
+ },
+ {
+ name: 'data-testid',
+ type: 'string',
+ description: 'Test ID for the selector trigger container.',
+ },
+ ],
+ components: [
+ {
+ name: 'TransferList',
+ displayName: 'Transfer List',
+ description:
+ 'Lower-level controlled content primitive for advanced selector compositions that add custom headers, saved views, presets, or actions. Changes are immediate to its controlled value.',
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible name for the complete transfer control.',
+ required: true,
+ },
+ {
+ name: 'isLabelHidden',
+ type: 'boolean',
+ description:
+ 'Visually hides the control label while retaining its accessible name.',
+ default: 'false',
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Supporting guidance shown below the control label.',
+ },
+ {
+ name: 'options',
+ type: 'readonly TransferListOption<T>[]',
+ description:
+ 'Complete option pool with optional metadata, grouping, transfer constraints, and reorder constraints.',
+ required: true,
+ },
+ {
+ name: 'value',
+ type: 'readonly T[]',
+ description: 'Selected option values in display order.',
+ required: true,
+ },
+ {
+ name: 'onChange',
+ type: '(nextValue: readonly T[]) => void',
+ description:
+ 'Called immediately after a permitted option is added, removed, bulk changed, or reordered.',
+ required: true,
+ },
+ {
+ name: 'selectedLabel',
+ type: 'string',
+ description: 'Heading and accessible name for the selected list.',
+ default: "'Selected'",
+ },
+ {
+ name: 'availableLabel',
+ type: 'string',
+ description: 'Heading and accessible name for the available list.',
+ default: "'Available'",
+ },
+ {
+ name: 'hasSearch',
+ type: 'boolean',
+ description:
+ 'Shows a shared search field that filters both lists by label and description.',
+ default: 'false',
+ },
+ {
+ name: 'searchLabel',
+ type: 'string',
+ description: 'Accessible label for the shared search field.',
+ },
+ {
+ name: 'searchPlaceholder',
+ type: 'string',
+ description: 'Placeholder shown in the shared search field.',
+ default: "'Search\u2026'",
+ },
+ {
+ name: 'isReorderable',
+ type: 'boolean',
+ description:
+ 'Enables pointer and keyboard ordering. Per-option isReorderDisabled keeps a visible disabled grip and fixed-order barrier.',
+ default: 'true',
+ },
+ {
+ name: 'hasSelectAll',
+ type: 'boolean',
+ description: 'Shows Add all for transfer-enabled available options.',
+ default: 'false',
+ },
+ {
+ name: 'hasClear',
+ type: 'boolean',
+ description:
+ 'Shows Clear for transfer-enabled selected options; transfer-disabled values remain selected.',
+ default: 'false',
+ },
+ {
+ name: 'renderOption',
+ type: '(option: TransferListOption<T>) => ReactNode',
+ description:
+ 'Customizes row content without replacing built-in actions and constraints.',
+ },
+ {
+ name: 'selectedEmptyText',
+ type: 'string',
+ description: 'Message shown when the selected list is empty.',
+ default: "'No selected options'",
+ },
+ {
+ name: 'availableEmptyText',
+ type: 'string',
+ description: 'Message shown when every option has been selected.',
+ default: "'No available options'",
+ },
+ {
+ name: 'noResultsText',
+ type: 'string',
+ description: 'Message shown when search has no matches in a list.',
+ default: "'No results'",
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: 'StyleX styles for the TransferList root.',
+ },
+ ],
+ },
+ ],
+ usage: {
+ description:
+ 'Use TransferListSelector by default for medium-to-large, inspectable sets where membership and selected order need explicit control. Immediate behavior commits each edit and renders no footer. Choose staged behavior when users must review a set of changes before Apply. Use TransferList directly only in a deliberately custom ComplexSelector surface, such as table column settings with saved views and a custom footer.',
+ bestPractices: [
+ {
+ 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.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set commitBehavior="staged" when the complete selection should be reviewed or persisted as one transaction. Apply commits a changed draft; Cancel, Escape, and light dismiss discard it.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use TransferList directly inside ComplexSelector only when the surface needs custom structure such as saved views, presets, headers, or footer actions. Keep applied and draft state separate and reset the draft whenever the surface opens.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use isTransferDisabled and isReorderDisabled independently. Provide disabledMessage whenever either action is unavailable so the constraint is discoverable.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep rows concise and single-line. Use option description as searchable metadata, or renderOption when richer visible content is necessary.',
+ },
+ {
+ 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.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use commitBehavior as a presentation or container choice. Both values render the same selector popover; use explicit composition for a different shell.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use a transfer list for a handful of simple choices; CheckboxInput or MultiSelector is more compact.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Field label and description',
+ required: true,
+ description:
+ 'Names and explains the selector outside the popover so placement does not change with supporting text.',
+ },
+ {
+ name: 'Selector trigger',
+ required: true,
+ description:
+ 'Summarizes the committed value and opens the transfer-list popover.',
+ },
+ {
+ name: 'Search',
+ required: false,
+ description:
+ 'Filters the selected and available lists without changing their values and uses a uniform 12px inset.',
+ },
+ {
+ name: 'Selected and available sections',
+ required: true,
+ description:
+ 'Places two unframed semantic lists beside one divider. Narrow containers stack the sections, use the body background behind each column header, expand both sections to their rows, and delegate overflow to one scrollable containing surface.',
+ },
+ {
+ 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.',
+ },
+ {
+ name: 'Bulk actions',
+ required: false,
+ description:
+ 'Optional Clear and Add all text actions that honor transfer-disabled options.',
+ },
+ {
+ name: 'Apply and Cancel footer',
+ required: false,
+ description:
+ 'Rendered only for staged behavior. Apply commits a changed draft; Cancel closes without changing the committed value.',
+ },
+ {
+ name: 'Live announcements',
+ required: true,
+ description:
+ 'Reports add, remove, bulk, and reorder results without relying on visual position alone.',
+ },
+ ],
+ },
+ examples: [
+ {
+ label: 'Default immediate selector',
+ code: `const [fields, setFields] = useState(['name', 'status']);
+
+<TransferListSelector
+ label="Visible fields"
+ description="Choose which fields appear. Changes take effect immediately."
+ triggerLabel={fields.length + ' visible fields'}
+ options={[
+ {value: 'name', label: 'Name'},
+ {value: 'status', label: 'Status'},
+ {value: 'owner', label: 'Owner'},
+ ]}
+ value={fields}
+ onChange={setFields}
+ selectedLabel="Visible fields"
+ availableLabel="Available fields"
+ hasSelectAll
+ hasClear
+/>`,
+ },
+ {
+ label: 'Staged commit',
+ code: `const [fields, setFields] = useState(['name', 'status']);
+
+<TransferListSelector
+ label="Visible fields"
+ description="Review the complete selection before applying it."
+ options={fieldOptions}
+ value={fields}
+ onChange={setFields}
+ commitBehavior="staged"
+ selectedLabel="Visible fields"
+ availableLabel="Available fields"
+ hasSelectAll
+ hasClear
+/>`,
+ },
+ {
+ label: 'Independent transfer and reorder constraints',
+ code: `<TransferListSelector
+ label="Visible fields"
+ options={[
+ {
+ value: 'name',
+ label: 'Name',
+ isTransferDisabled: true,
+ disabledMessage: 'Name must remain visible.',
+ },
+ {
+ value: 'status',
+ label: 'Status',
+ isReorderDisabled: true,
+ disabledMessage: 'Status is fixed in position but can be removed.',
+ },
+ {value: 'owner', label: 'Owner'},
+ ]}
+ value={fields}
+ onChange={setFields}
+/>`,
+ },
+ {
+ label: 'Saved views in a custom ComplexSelector',
+ code: `const savedViews = {
+ standard: ['name', 'status', 'owner'],
+ ownership: ['name', 'owner', 'team'],
+};
+const [applied, setApplied] = useState(savedViews.standard);
+const [draft, setDraft] = useState(applied);
+const activeSavedView =
+ Object.entries(savedViews).find(
+ ([, columns]) =>
+ columns.length === draft.length &&
+ columns.every((column, index) => column === draft[index]),
+ )?.[0] ?? 'custom';
+
+function ResetDraftOnOpen({isOpen, value, onReset}) {
+ const wasOpenRef = useRef(false);
+
+ useEffect(() => {
+ if (isOpen && !wasOpenRef.current) {
+ onReset([...value]);
+ }
+ wasOpenRef.current = isOpen;
+ }, [isOpen, onReset, value]);
+
+ return null;
+}
+
+<ComplexSelector
+ label="View options"
+ isLabelHidden
+ triggerLabel="View options"
+ value={applied}
+ onChange={setApplied}>
+ {(_appliedValue, commit, close, state) => (
+ <>
+ <ResetDraftOnOpen
+ isOpen={state.isOpen}
+ value={applied}
+ onReset={setDraft}
+ />
+ <Selector
+ label="Saved view"
+ options={savedViewOptions}
+ value={activeSavedView}
+ onChange={nextSavedView => {
+ setDraft(savedViews[nextSavedView]);
+ }}
+ />
+ <TransferList
+ label="Visible fields"
+ isLabelHidden
+ options={fieldOptions}
+ value={draft}
+ onChange={setDraft}
+ selectedLabel="Visible fields"
+ availableLabel="Available fields"
+ hasSelectAll
+ hasClear
+ />
+ <Button label="Cancel" variant="ghost" onClick={close} />
+ <Button
+ label="Apply"
+ variant="primary"
+ onClick={() => {
+ commit(draft);
+ close();
+ }}
+ />
+ </>
+ )}
+</ComplexSelector>`,
+ },
+ ],
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
+export const docsDense = {
+ description:
+ 'default-immediate transfer-list selector with optional staged commit behavior; TransferList is the advanced custom-composition primitive',
+ usage: {
+ description:
+ 'Use TransferListSelector with immediate behavior by default: each list edit commits and no footer renders. Use staged behavior to review a draft and commit from Apply. Use TransferList directly only inside a custom ComplexSelector surface with saved views, presets, or custom actions.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Default to immediate behavior; each edit calls onChange and dismiss keeps committed changes.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use commitBehavior="staged" for review or transactional persistence; Apply commits and Cancel/Escape/light dismiss discard.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use direct TransferList plus ComplexSelector only for custom saved views, presets, headers, or actions; reset draft from applied value on open.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set transfer and reorder constraints independently and explain either with disabledMessage.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep rows single-line; descriptions remain searchable metadata.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use commitBehavior for presentation/container choice; both values use the selector popover.',
+ },
+ {
+ guidance: false,
+ description: 'Use for a few simple choices; prefer CheckboxInput.',
+ },
+ ],
+ },
+ propDescriptions: {
+ label: 'External field label and accessible name.',
+ options:
+ 'Full pool: value, label, description?, group?, isTransferDisabled?, isReorderDisabled?, disabledMessage?.',
+ value: 'Committed selected values in display order.',
+ onChange:
+ 'Called per edit in immediate behavior or from changed Apply in staged behavior.',
+ commitBehavior:
+ 'TransferListSelectorCommitBehavior: immediate (default, no footer) or staged (draft plus Apply/Cancel).',
+ triggerLabel: 'Closed-trigger content; defaults to selected count.',
+ description: 'Supporting field guidance outside the popover.',
+ isLabelHidden: 'Hide field label visually, preserving its name.',
+ selectedLabel: 'Selected-list heading and name.',
+ availableLabel: 'Available-list heading and name.',
+ hasSearch: 'Shared list filter; default false.',
+ searchLabel: 'Accessible search label.',
+ searchPlaceholder: 'Search placeholder.',
+ isReorderable:
+ 'Enable grip-based pointer and keyboard ordering; default true.',
+ hasSelectAll: 'Add all transfer-enabled available options.',
+ hasClear: 'Remove all transfer-enabled selected options.',
+ renderOption: 'Custom row content.',
+ selectedEmptyText: 'Selected-list empty message.',
+ availableEmptyText: 'Available-list empty message.',
+ noResultsText: 'No search matches message.',
+ applyLabel: 'Staged Apply label; default Apply.',
+ cancelLabel: 'Staged Cancel label; default Cancel.',
+ size: 'Field and trigger size.',
+ width:
+ 'External field width; its default matches the responsive 41rem popup.',
+ placement: 'Popover placement relative to trigger.',
+ isOptional: 'Mark field optional.',
+ isRequired: 'Mark field required.',
+ isDisabled: 'Disable selector trigger and transfer interaction.',
+ isLoading: 'Show loading state and disable transfer interaction.',
+ status: 'Field validation status.',
+ statusVariant: 'Status placement treatment.',
+ labelTooltip: 'Field-label tooltip.',
+ changeAction:
+ 'Async action after each immediate commit or changed staged Apply.',
+ contentXstyle: 'Popover-content StyleX override.',
+ xstyle: 'External field StyleX override.',
+ className: 'External field class name.',
+ style: 'External field inline styles.',
+ 'data-testid': 'Selector trigger test ID.',
+ },
+ components: [
+ {
+ name: 'TransferList',
+ displayName: 'Transfer List',
+ description:
+ 'Lower-level controlled content for custom ComplexSelector surfaces; changes its controlled value immediately.',
+ propDescriptions: {
+ 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.',
+ value: 'Selected values in display order.',
+ onChange: 'Called after each add/remove/bulk/reorder change.',
+ selectedLabel: 'Selected-list heading and name.',
+ availableLabel: 'Available-list heading and name.',
+ hasSearch: 'Shared list filter; default false.',
+ searchLabel: 'Accessible search label.',
+ searchPlaceholder: 'Search placeholder.',
+ isReorderable: 'Enable pointer and keyboard ordering; default true.',
+ hasSelectAll: 'Add all transfer-enabled options.',
+ hasClear: 'Remove all transfer-enabled selected options.',
+ renderOption: 'Custom row content.',
+ selectedEmptyText: 'Selected-list empty message.',
+ availableEmptyText: 'Available-list empty message.',
+ noResultsText: 'No search matches message.',
+ xstyle: 'TransferList-root StyleX override.',
+ },
+ },
+ ],
+};
diff --git a/packages/lab/src/TransferList/TransferList.test.tsx b/packages/lab/src/TransferList/TransferList.test.tsx
new file mode 100644
index 0000000000..1fef237a4c
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferList.test.tsx
@@ -0,0 +1,888 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @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
+ * @position Lab tests; validates TransferList.tsx
+ *
+ * SYNC: When TransferList.tsx behavior changes, update these tests.
+ */
+
+import {useState} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import * as stylex from '@stylexjs/stylex';
+import {
+ TransferList,
+ type TransferListOption,
+ type TransferListProps,
+} from './TransferList';
+
+const OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ {
+ value: 'name',
+ label: 'Name',
+ description: 'Primary identifier',
+ group: 'Identity',
+ },
+ {value: 'owner', label: 'Owner', group: 'Identity'},
+ {value: 'status', label: 'Status', group: 'Details'},
+ {value: 'updated', label: 'Updated', group: 'Details'},
+];
+
+const LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ OPTIONS[0],
+ {
+ value: 'owner',
+ label: 'Owner',
+ group: 'Identity',
+ isTransferDisabled: true,
+ isReorderDisabled: true,
+ disabledMessage: 'Owner is required and fixed in position.',
+ },
+ OPTIONS[2],
+ OPTIONS[3],
+];
+
+const TRANSFER_LOCKED_OPTIONS: ReadonlyArray<TransferListOption<string>> = [
+ OPTIONS[0],
+ {
+ value: 'owner',
+ label: 'Owner',
+ group: 'Identity',
+ isTransferDisabled: true,
+ disabledMessage: 'Owner is required.',
+ },
+ OPTIONS[2],
+ 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],
+];
+
+type ControlledTransferListProps = Omit<
+ TransferListProps<string>,
+ 'label' | 'options' | 'value' | 'onChange'
+> & {
+ initialValue?: readonly string[];
+ onValueChange?: (value: readonly string[]) => void;
+ options?: ReadonlyArray<TransferListOption<string>>;
+};
+
+function ControlledTransferList({
+ initialValue = [],
+ onValueChange,
+ options = OPTIONS,
+ ...props
+}: ControlledTransferListProps) {
+ const [value, setValue] = useState<readonly string[]>(initialValue);
+
+ return (
+ <TransferList
+ label="Columns"
+ selectedLabel="Selected columns"
+ availableLabel="Available columns"
+ options={options}
+ value={value}
+ onChange={nextValue => {
+ onValueChange?.(nextValue);
+ setValue(nextValue);
+ }}
+ {...props}
+ />
+ );
+}
+
+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();
+});
+
+describe('TransferList', () => {
+ describe('semantics and content', () => {
+ it('renders a labelled pair of semantic lists without listbox roles', () => {
+ render(
+ <TransferList
+ label="Table columns"
+ description="Choose and order the columns shown in the table."
+ selectedLabel="Shown columns"
+ availableLabel="Hidden columns"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={() => {}}
+ />,
+ );
+
+ expect(screen.getByText('Table columns')).toBeInTheDocument();
+ expect(
+ screen.getByText('Choose and order the columns shown in the table.'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('list', {name: 'Shown columns'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('list', {name: 'Hidden columns'}),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
+ expect(screen.queryByRole('option')).not.toBeInTheDocument();
+ });
+
+ it('uses one divided collection with direction-neutral row actions', () => {
+ const {container} = render(
+ <ControlledTransferList
+ initialValue={['name', 'status']}
+ hasClear
+ hasSelectAll
+ />,
+ );
+
+ const collection = container.querySelector(
+ '.astryx-transfer-list-collection',
+ );
+ expect(collection).toBeInTheDocument();
+ expect(
+ collection?.querySelectorAll(':scope > .astryx-transfer-list-panel'),
+ ).toHaveLength(2);
+
+ expect(screen.queryByText('2 items')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Clear'})).toHaveAttribute(
+ 'data-transfer-list-header-action',
+ 'true',
+ );
+ expect(screen.getByRole('button', {name: 'Add all'})).toHaveAttribute(
+ 'data-transfer-list-header-action',
+ 'true',
+ );
+ const addButton = screen.getByRole('button', {name: 'Add Owner'});
+ const removeButton = screen.getByRole('button', {name: 'Remove Name'});
+ expect(addButton.querySelector('svg')).toHaveClass('lucide-plus');
+ expect(removeButton.querySelector('svg')).toHaveClass('lucide-x');
+
+ const selectedList = screen.getByRole('list', {
+ name: 'Selected columns',
+ });
+ const nameRow = within(selectedList).getByText('Name').closest('li');
+ expect(nameRow).not.toBeNull();
+ const rowButtons = within(nameRow as HTMLLIElement).getAllByRole(
+ 'button',
+ );
+ expect(rowButtons[0]).toHaveAccessibleName('Reorder Name');
+ expect(rowButtons[0].querySelector('svg')).toHaveClass(
+ 'lucide-grip-vertical',
+ );
+ expect(rowButtons[1]).toHaveAccessibleName('Remove Name');
+ });
+
+ it('keeps support metadata out of rows while retaining search and groups', async () => {
+ const user = userEvent.setup();
+ render(
+ <ControlledTransferList initialValue={['name', 'status']} hasSearch />,
+ );
+
+ expect(screen.queryByText('Primary identifier')).not.toBeInTheDocument();
+ expect(screen.getAllByText('Identity').length).toBeGreaterThan(0);
+ expect(screen.getAllByText('Details').length).toBeGreaterThan(0);
+
+ await user.type(screen.getByRole('searchbox'), 'primary identifier');
+ expect(screen.getByText('Name')).toBeInTheDocument();
+ expect(screen.queryByText('Owner')).not.toBeInTheDocument();
+ });
+
+ it('renders custom option content for selected and available values', () => {
+ render(
+ <ControlledTransferList
+ initialValue={['name']}
+ renderOption={option => (
+ <span data-testid={`custom-${option.value}`}>
+ Custom {option.label}
+ </span>
+ )}
+ />,
+ );
+
+ expect(screen.getByTestId('custom-name')).toHaveTextContent(
+ 'Custom Name',
+ );
+ expect(screen.getByTestId('custom-status')).toHaveTextContent(
+ 'Custom Status',
+ );
+ });
+
+ it('renders custom empty-state copy for both panels', () => {
+ const {rerender} = render(
+ <TransferList
+ label="Columns"
+ options={OPTIONS}
+ value={[]}
+ onChange={() => {}}
+ selectedEmptyText="Nothing is shown"
+ availableEmptyText="Nothing else is available"
+ />,
+ );
+
+ expect(screen.getByText('Nothing is shown')).toBeInTheDocument();
+
+ rerender(
+ <TransferList
+ label="Columns"
+ options={OPTIONS}
+ value={OPTIONS.map(option => option.value)}
+ onChange={() => {}}
+ selectedEmptyText="Nothing is shown"
+ availableEmptyText="Nothing else is available"
+ />,
+ );
+ expect(screen.getByText('Nothing else is available')).toBeInTheDocument();
+ });
+ });
+
+ describe('transfers and filtering', () => {
+ it('appends an added value and preserves selected order when removing', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ initialValue={['status', 'name']}
+ onValueChange={onValueChange}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Add Owner'}));
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'status',
+ 'name',
+ 'owner',
+ ]);
+
+ await user.click(screen.getByRole('button', {name: 'Remove Name'}));
+ expect(onValueChange).toHaveBeenLastCalledWith(['status', 'owner']);
+ });
+
+ it('filters both panels with the shared search field', async () => {
+ const user = userEvent.setup();
+ render(
+ <ControlledTransferList
+ initialValue={['name', 'status']}
+ hasSearch
+ searchLabel="Filter columns"
+ searchPlaceholder="Find a column"
+ noResultsText="No matching columns"
+ />,
+ );
+
+ const search = screen.getByRole('searchbox', {name: 'Filter columns'});
+ expect(search).toHaveAttribute('placeholder', 'Find a column');
+
+ await user.type(search, 'owner');
+ expect(screen.getByText('Owner')).toBeInTheDocument();
+ expect(screen.queryByText('Updated')).not.toBeInTheDocument();
+ expect(screen.getAllByText('No matching columns').length).toBeGreaterThan(
+ 0,
+ );
+ });
+
+ it('disables search and enables reordering by default', () => {
+ render(<ControlledTransferList initialValue={['name']} />);
+
+ expect(screen.queryByRole('searchbox')).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Reorder Name'}),
+ ).toBeInTheDocument();
+ });
+
+ it('can turn on search and turn off reordering', () => {
+ render(
+ <ControlledTransferList
+ initialValue={['name']}
+ hasSearch
+ isReorderable={false}
+ />,
+ );
+
+ expect(screen.getByRole('searchbox')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Reorder Name'}),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ describe('option constraints and bulk actions', () => {
+ it('keeps locked controls visible and disabled', () => {
+ render(
+ <ControlledTransferList
+ options={LOCKED_OPTIONS}
+ initialValue={['owner', 'status']}
+ />,
+ );
+
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner'}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ expect(
+ screen.getByRole('button', {name: 'Reorder Owner'}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it('applies transfer and reorder constraints independently', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ const constrainedOptions = [
+ {
+ ...OPTIONS[1],
+ isTransferDisabled: true,
+ disabledMessage: 'Owner is required.',
+ },
+ {
+ ...OPTIONS[2],
+ isReorderDisabled: true,
+ disabledMessage: 'Status has a fixed position.',
+ },
+ ];
+ render(
+ <ControlledTransferList
+ options={constrainedOptions}
+ initialValue={['owner', 'status']}
+ onValueChange={onValueChange}
+ />,
+ );
+
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner'}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ expect(
+ screen.getByRole('button', {name: 'Reorder Owner'}),
+ ).not.toHaveAttribute('aria-disabled');
+ expect(
+ screen.getByRole('button', {name: 'Remove Status'}),
+ ).not.toHaveAttribute('aria-disabled');
+ expect(
+ screen.getByRole('button', {name: 'Reorder Status'}),
+ ).toHaveAttribute('aria-disabled', 'true');
+
+ await user.click(screen.getByRole('button', {name: 'Remove Status'}));
+ expect(onValueChange).toHaveBeenCalledWith(['owner']);
+ });
+
+ it('adds all transfer-enabled available values in option order', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ options={TRANSFER_LOCKED_OPTIONS}
+ initialValue={['status']}
+ hasSelectAll
+ onValueChange={onValueChange}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Add all'}));
+ expect(onValueChange).toHaveBeenCalledWith(['status', 'name', 'updated']);
+ });
+
+ it('clears removable values but retains transfer-disabled values', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ options={TRANSFER_LOCKED_OPTIONS}
+ initialValue={['status', 'owner', 'updated']}
+ hasClear
+ onValueChange={onValueChange}
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Clear'}));
+ expect(onValueChange).toHaveBeenCalledWith(['owner']);
+ });
+ });
+
+ describe('root customization', () => {
+ it('provides a theme target and forwards root props and ref', () => {
+ const ref = {current: null as HTMLDivElement | null};
+ const onClick = vi.fn();
+ render(
+ <TransferList
+ ref={ref}
+ label="Columns"
+ options={OPTIONS}
+ value={['name']}
+ onChange={() => {}}
+ data-testid="transfer-list"
+ data-owner="tables"
+ className="consumer-class"
+ style={{marginTop: 12}}
+ xstyle={testStyles.root(0.75)}
+ onClick={onClick}
+ />,
+ );
+
+ const root = screen.getByTestId('transfer-list');
+ expect(ref.current).toBe(root);
+ expect(root).toHaveClass('astryx-transfer-list', 'consumer-class');
+ expect(root).toHaveAttribute('data-owner', 'tables');
+ expect(root).toHaveStyle({marginTop: '12px'});
+ expect(root.getAttribute('style')).toContain('0.75');
+ root.click();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('transfer updates', () => {
+ it('commits individual and bulk changes immediately', () => {
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ initialValue={['name']}
+ hasClear
+ hasSelectAll
+ onValueChange={onValueChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Add Owner'}));
+
+ expect(onValueChange).toHaveBeenLastCalledWith(['name', 'owner']);
+ expect(
+ within(screen.getByRole('list', {name: 'Selected columns'})).getByText(
+ 'Owner',
+ ),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', {name: 'Remove Owner'}));
+ expect(onValueChange).toHaveBeenLastCalledWith(['name']);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Add all'}));
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'name',
+ 'owner',
+ 'status',
+ 'updated',
+ ]);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Clear'}));
+ expect(onValueChange).toHaveBeenLastCalledWith([]);
+ });
+ });
+
+ describe('pointer reordering', () => {
+ it('mounts the drag preview in the nearest top-layer container', () => {
+ 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,
+ });
+
+ const preview = document.querySelector<HTMLElement>(
+ '[data-transfer-list-drag-preview]',
+ );
+ expect(preview?.parentElement).toBe(screen.getByTestId('popover-host'));
+ });
+
+ it('keeps rows stationary, locks X, follows pointer Y, and commits once', () => {
+ const onValueChange = vi.fn();
+ const {container} = render(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status']}
+ 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');
+ expect(preview!.style.getPropertyValue('--x-transform')).toBe(
+ 'translate3d(0px, 40px, 0)',
+ );
+ expect(
+ container.querySelector('[data-transfer-list-drop-target]'),
+ ).not.toBeInTheDocument();
+
+ fireEvent.pointerMove(handle, {
+ pointerId: 7,
+ clientX: 345,
+ clientY: 5,
+ });
+
+ expect(preview!.style.getPropertyValue('--x-transform')).toBe(
+ 'translate3d(0px, -5px, 0)',
+ );
+ 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!.style.getPropertyValue('--x-transform')).toBe(
+ 'translate3d(0px, 105px, 0)',
+ );
+ 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();
+ });
+
+ it('ignores a horizontal-only gesture without changing the value', () => {
+ const onValueChange = vi.fn();
+ const {container} = render(
+ <ControlledTransferList
+ initialValue={['name', 'owner']}
+ onValueChange={onValueChange}
+ />,
+ );
+ 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: 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();
+ expect(
+ document
+ .querySelector<HTMLElement>('[data-transfer-list-drag-preview]')
+ ?.style.getPropertyValue('--x-transform'),
+ ).toBe('translate3d(0px, 0px, 0)');
+ expect(
+ container.querySelector('[data-transfer-list-drop-target]'),
+ ).not.toBeInTheDocument();
+
+ 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(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status']}
+ onValueChange={onValueChange}
+ />,
+ );
+ 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,
+ });
+ fireEvent.pointerCancel(handle, {pointerId: 9});
+
+ expect(onValueChange).not.toHaveBeenCalled();
+ expect(
+ document.querySelector('[data-transfer-list-drag-preview]'),
+ ).not.toBeInTheDocument();
+ expect(
+ container.querySelector('[data-transfer-list-reorder-source]'),
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(handle);
+ expect(handle).toHaveAttribute('aria-pressed', 'true');
+ expect(onValueChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps reorder-disabled selected options as pointer-order barriers', () => {
+ const onValueChange = vi.fn();
+ const {container} = render(
+ <ControlledTransferList
+ options={REORDER_LOCKED_OPTIONS}
+ initialValue={['name', 'owner', 'status', 'updated']}
+ onValueChange={onValueChange}
+ />,
+ );
+ 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',
+ ]);
+ });
+ });
+
+ describe('keyboard reordering', () => {
+ it('moves immediately, keeps handle focus, and drops without another change', async () => {
+ 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('{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();
+ });
+
+ it('supports Home and End while a value is grabbed', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ initialValue={['name', 'owner', 'status', 'updated']}
+ onValueChange={onValueChange}
+ />,
+ );
+
+ const handle = screen.getByRole('button', {name: 'Reorder Owner'});
+ handle.focus();
+ await user.keyboard(' {End}{Home} ');
+
+ expect(onValueChange).toHaveBeenNthCalledWith(1, [
+ 'name',
+ 'status',
+ 'updated',
+ 'owner',
+ ]);
+ expect(onValueChange).toHaveBeenNthCalledWith(2, [
+ 'owner',
+ 'name',
+ 'status',
+ 'updated',
+ ]);
+ expect(onValueChange).toHaveBeenCalledTimes(2);
+ expect(handle).toHaveFocus();
+ });
+
+ it('restores the original order when a grabbed move is cancelled', async () => {
+ 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('{Enter}{ArrowDown}{Escape}');
+
+ expect(onValueChange).toHaveBeenNthCalledWith(1, [
+ 'name',
+ 'status',
+ 'owner',
+ ]);
+ expect(onValueChange).toHaveBeenNthCalledWith(2, [
+ 'name',
+ 'owner',
+ 'status',
+ ]);
+ expect(handle).toHaveFocus();
+ });
+
+ it('does not allow a value to cross a reorder-disabled value', async () => {
+ const user = userEvent.setup();
+ const onValueChange = vi.fn();
+ render(
+ <ControlledTransferList
+ options={REORDER_LOCKED_OPTIONS}
+ initialValue={['name', 'owner', 'status', 'updated']}
+ onValueChange={onValueChange}
+ />,
+ );
+
+ const beforeBarrier = screen.getByRole('button', {
+ name: 'Reorder Name',
+ });
+ beforeBarrier.focus();
+ await user.keyboard('{Enter}{ArrowDown}{Enter}');
+ expect(onValueChange).not.toHaveBeenCalled();
+
+ const afterBarrier = screen.getByRole('button', {
+ name: 'Reorder Updated',
+ });
+ afterBarrier.focus();
+ await user.keyboard('{Enter}{Home}');
+ expect(onValueChange).toHaveBeenLastCalledWith([
+ 'name',
+ 'owner',
+ 'updated',
+ 'status',
+ ]);
+ await user.keyboard('{ArrowUp}{Enter}');
+ expect(onValueChange).toHaveBeenCalledTimes(1);
+ expect(afterBarrier).toHaveFocus();
+ });
+ });
+});
diff --git a/packages/lab/src/TransferList/TransferList.tsx b/packages/lab/src/TransferList/TransferList.tsx
new file mode 100644
index 0000000000..8e13c09fac
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferList.tsx
@@ -0,0 +1,1323 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TransferList.tsx
+ * @input Controlled option data, React DOM portals, local action glyphs, and shared Lab reorder styles
+ * @output Exports TransferList with immediate transfers, vertical reordering, and responsive scroll ownership
+ * @position Lab collection input; consumed by index.ts, TransferListSelector, docs, and tests
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/TransferList/TransferList.doc.mjs
+ * - /packages/lab/src/TransferList/TransferList.test.tsx
+ * - /packages/lab/src/TransferList/index.ts
+ */
+
+import {
+ Fragment,
+ useCallback,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {createPortal, 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 {List} from '@astryxdesign/core/List';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
+import {useAnnounce} from '@astryxdesign/core/hooks';
+import {
+ borderVars,
+ colorVars,
+ spacingVars,
+ typeScaleVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';
+import {reorderStyles} from '../reorderStyles';
+import {transferListVars} from './tokens.stylex';
+
+function PlusIcon() {
+ return (
+ <svg
+ className="lucide lucide-plus"
+ width={16}
+ height={16}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden>
+ <path d="M5 12h14" />
+ <path d="M12 5v14" />
+ </svg>
+ );
+}
+
+function RemoveIcon() {
+ return (
+ <svg
+ className="lucide lucide-x"
+ width={16}
+ height={16}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden>
+ <path d="M18 6 6 18" />
+ <path d="m6 6 12 12" />
+ </svg>
+ );
+}
+
+function GripVerticalIcon() {
+ return (
+ <svg
+ className="lucide lucide-grip-vertical"
+ width={16}
+ height={16}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden>
+ <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;
+ /** Visible option name and the basis of action labels. */
+ label: string;
+ /** Optional searchable metadata. Not rendered in the default row. */
+ description?: ReactNode;
+ /** Optional group heading on the available side. */
+ 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. */
+ disabledMessage?: string;
+}
+
+export interface TransferListProps<T extends string = string> extends Omit<
+ BaseProps<HTMLDivElement>,
+ 'onChange'
+> {
+ /** Ref forwarded to the root group. */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Accessible name for the complete control. */
+ label: string;
+ /** Visually hides the label while retaining its accessible name. */
+ isLabelHidden?: boolean;
+ /** Supporting guidance shown below the label. */
+ description?: string;
+ /** Complete option catalog. Option values must be unique. */
+ options: readonly TransferListOption<T>[];
+ /** Ordered selected values. This array is the single source of truth. */
+ value: readonly T[];
+ /** Called with the next ordered selection after a committed change. */
+ onChange: (value: readonly T[]) => void;
+ /** Heading for the selected panel. @default 'Selected' */
+ selectedLabel?: string;
+ /** Heading for the available panel. @default 'Available' */
+ availableLabel?: string;
+ /** Shows one search field that filters both panels. @default false */
+ hasSearch?: boolean;
+ /** Accessible label for search. Defaults to `Search ${label}`. */
+ searchLabel?: string;
+ /** Search input placeholder. @default 'Search…' */
+ searchPlaceholder?: string;
+ /** Enables pointer and keyboard ordering on selected options. @default true */
+ isReorderable?: boolean;
+ /** Shows an Add all action. @default false */
+ hasSelectAll?: boolean;
+ /** Shows a Clear action. Transfer-disabled selected options are retained. */
+ hasClear?: boolean;
+ /** Customizes primary row content without changing built-in behavior. */
+ renderOption?: (option: TransferListOption<T>) => ReactNode;
+ /** Empty copy for the selected panel. */
+ selectedEmptyText?: string;
+ /** Empty copy for the available panel. */
+ availableEmptyText?: string;
+ /** Empty copy while a search query is active. */
+ 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({
+ root: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 0,
+ minWidth: 0,
+ containerType: 'inline-size',
+ },
+ heading: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-3'],
+ },
+ controls: {
+ display: 'flex',
+ alignItems: 'flex-end',
+ gap: spacingVars['--spacing-2'],
+ minWidth: 0,
+ padding: spacingVars['--spacing-3'],
+ },
+ search: {flex: 1, minWidth: 0},
+ panels: {
+ display: 'grid',
+ gridTemplateColumns: {
+ default: 'minmax(0, 1fr) minmax(0, 1fr)',
+ '@container (max-width: 40rem)': 'minmax(0, 1fr)',
+ },
+ gap: 0,
+ minWidth: 0,
+ },
+ panel: {
+ display: 'flex',
+ flexDirection: 'column',
+ minWidth: 0,
+ overflow: 'hidden',
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: -2,
+ },
+ panelDivider: {
+ borderInlineStartWidth: {
+ default: borderVars['--border-width'],
+ '@container (max-width: 40rem)': 0,
+ },
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border'],
+ borderBlockStartWidth: {
+ default: 0,
+ '@container (max-width: 40rem)': borderVars['--border-width'],
+ },
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: colorVars['--color-border'],
+ },
+ panelHeader: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ backgroundColor: {
+ default: 'transparent',
+ '@container (max-width: 40rem)': colorVars['--color-background-body'],
+ },
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-3'],
+ borderBlockEndWidth: borderVars['--border-width'],
+ borderBlockEndStyle: 'solid',
+ borderBlockEndColor: colorVars['--color-border'],
+ },
+ headerAction: {
+ height: 'auto',
+ paddingBlock: 0,
+ paddingInline: 0,
+ borderRadius: 0,
+ color: colorVars['--color-text-accent'],
+ backgroundImage: {
+ default: 'none',
+ ':hover': 'none',
+ ':active': 'none',
+ },
+ textDecoration: {
+ default: 'none',
+ ':hover': 'underline',
+ },
+ fontSize: typeScaleVars['--text-body-size'],
+ fontWeight: typeScaleVars['--text-body-weight'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ },
+ panelBody: {
+ minBlockSize: {
+ default: transferListVars['--transfer-list-panel-min-block-size'],
+ '@container (max-width: 40rem)': 0,
+ },
+ maxBlockSize: {
+ default: transferListVars['--transfer-list-panel-max-block-size'],
+ '@container (max-width: 40rem)': 'none',
+ },
+ overflowY: {
+ default: 'auto',
+ '@container (max-width: 40rem)': 'visible',
+ },
+ overscrollBehavior: {
+ default: 'contain',
+ '@container (max-width: 40rem)': 'auto',
+ },
+ scrollbarGutter: {
+ default: 'stable',
+ '@container (max-width: 40rem)': 'auto',
+ },
+ padding: 0,
+ },
+ groupHeading: {
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-3'],
+ marginBlockStart: {
+ default: spacingVars['--spacing-1'],
+ ':first-child': 0,
+ },
+ },
+ 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',
+ justifyContent: 'center',
+ minBlockSize: {
+ default: transferListVars['--transfer-list-panel-min-block-size'],
+ '@container (max-width: 40rem)': 0,
+ },
+ padding: spacingVars['--spacing-4'],
+ textAlign: 'center',
+ },
+});
+
+const dynamicStyles = stylex.create({
+ dragPreview: (x: number, y: number, width: number) => ({
+ width,
+ transform: `translate3d(${x}px, ${y}px, 0)`,
+ }),
+});
+
+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;
+}
+
+function matchesQuery<T extends string>(
+ option: TransferListOption<T>,
+ query: string,
+): boolean {
+ if (query === '') {
+ return true;
+ }
+ const description =
+ typeof option.description === 'string' ? option.description : '';
+ return [option.label, description, option.group ?? ''].some(part =>
+ part.toLocaleLowerCase().includes(query),
+ );
+}
+
+function itemCount(count: number): string {
+ return `${count} ${count === 1 ? 'item' : 'items'}`;
+}
+
+/**
+ * A controlled dual-panel collection input for choosing and ordering values.
+ * Selection, ordering, drafts, persistence, and saved views stay explicit in
+ * the consumer; this component owns only search and active gesture state.
+ *
+ * @example
+ * ```
+ * const [columns, setColumns] = useState(['name', 'status']);
+ * <TransferList
+ * label="Table columns"
+ * options={columnOptions}
+ * value={columns}
+ * onChange={setColumns}
+ * />
+ * ```
+ */
+export function TransferList<T extends string = string>({
+ label,
+ isLabelHidden = false,
+ description,
+ options,
+ value,
+ onChange,
+ selectedLabel = 'Selected',
+ availableLabel = 'Available',
+ hasSearch = false,
+ searchLabel,
+ searchPlaceholder = 'Search…',
+ isReorderable = true,
+ hasSelectAll = false,
+ hasClear = false,
+ renderOption,
+ selectedEmptyText = 'No selected options',
+ availableEmptyText = 'No available options',
+ noResultsText = 'No results',
+ xstyle,
+ className,
+ style,
+ ref,
+ role,
+ 'aria-labelledby': ariaLabelledBy,
+ 'aria-describedby': ariaDescribedBy,
+ ...restProps
+}: TransferListProps<T>): ReactNode {
+ const labelId = useId();
+ 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);
+ 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);
+ },
+ [],
+ );
+
+ const optionByValue = useMemo(() => {
+ const map = new Map<T, TransferListOption<T>>();
+ options.forEach(option => map.set(option.value, option));
+ return map;
+ }, [options]);
+ const selectedValues = useMemo(() => new Set(value), [value]);
+ const normalizedQuery = query.trim().toLocaleLowerCase();
+ const selectedOptions = useMemo(
+ () =>
+ value
+ .map(optionValue => optionByValue.get(optionValue))
+ .filter(
+ (option): option is TransferListOption<T> =>
+ option != null && matchesQuery(option, normalizedQuery),
+ ),
+ [normalizedQuery, optionByValue, value],
+ );
+ const availableOptions = useMemo(
+ () =>
+ options.filter(
+ option =>
+ !selectedValues.has(option.value) &&
+ matchesQuery(option, normalizedQuery),
+ ),
+ [normalizedQuery, options, selectedValues],
+ );
+ const groupedAvailable = useMemo(() => {
+ const groups = new Map<string, TransferListOption<T>[]>();
+ availableOptions.forEach(option => {
+ const group = option.group ?? '';
+ const items = groups.get(group);
+ if (items) {
+ items.push(option);
+ } else {
+ groups.set(group, [option]);
+ }
+ });
+ 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;
+ onChange(nextValue);
+ },
+ [onChange],
+ );
+
+ const focusAfterTransfer = useCallback(
+ (side: 'selected' | 'available', index: number) => {
+ const moveFocus = () => {
+ const panel =
+ side === 'selected'
+ ? selectedPanelRef.current
+ : availablePanelRef.current;
+ const actions = panel?.querySelectorAll<HTMLButtonElement>(
+ `[data-transfer-list-action="${side}"]:not([disabled]):not([aria-disabled="true"])`,
+ );
+ if (actions && actions.length > 0) {
+ actions[Math.min(index, actions.length - 1)]?.focus();
+ } else if (hasSearch) {
+ searchRef.current?.focus();
+ } else {
+ panel?.focus();
+ }
+ };
+ if (typeof requestAnimationFrame === 'function') {
+ requestAnimationFrame(moveFocus);
+ } else {
+ setTimeout(moveFocus, 0);
+ }
+ },
+ [hasSearch],
+ );
+
+ const addOption = useCallback(
+ (option: TransferListOption<T>, index: number) => {
+ if (
+ option.isTransferDisabled ||
+ currentValueRef.current.includes(option.value)
+ ) {
+ return;
+ }
+ const nextValue = [...currentValueRef.current, option.value];
+ commit(nextValue);
+ announce(
+ `${option.label} added. ${itemCount(nextValue.length)} selected.`,
+ );
+ focusAfterTransfer('available', index);
+ },
+ [announce, commit, focusAfterTransfer],
+ );
+
+ const removeOption = useCallback(
+ (option: TransferListOption<T>, index: number) => {
+ if (option.isTransferDisabled) {
+ return;
+ }
+ const nextValue = currentValueRef.current.filter(
+ item => item !== option.value,
+ );
+ commit(nextValue);
+ announce(
+ `${option.label} removed. ${itemCount(nextValue.length)} selected.`,
+ );
+ focusAfterTransfer('selected', index);
+ },
+ [announce, commit, focusAfterTransfer],
+ );
+
+ const addAll = useCallback(() => {
+ const additions = options
+ .filter(
+ option =>
+ !option.isTransferDisabled &&
+ !currentValueRef.current.includes(option.value),
+ )
+ .map(option => option.value);
+ if (additions.length > 0) {
+ commit([...currentValueRef.current, ...additions]);
+ announce(`${itemCount(additions.length)} added.`);
+ }
+ }, [announce, commit, options]);
+
+ const clearSelected = useCallback(() => {
+ const nextValue = currentValueRef.current.filter(optionValue => {
+ const option = optionByValue.get(optionValue);
+ return option == null || option.isTransferDisabled;
+ });
+ const removed = currentValueRef.current.length - nextValue.length;
+ if (removed > 0) {
+ commit(nextValue);
+ announce(`${itemCount(removed)} removed.`);
+ }
+ }, [announce, commit, optionByValue]);
+
+ 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],
+ );
+
+ const beginReorder = useCallback(
+ (
+ option: TransferListOption<T>,
+ mode: 'keyboard' | 'pointer',
+ pointerGeometry?: PointerGeometry,
+ ) => {
+ if (option.isReorderDisabled || !isReorderable) {
+ 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(
+ `${option.label} picked up, position ${index + 1} of ${currentValueRef.current.length}. Use arrow keys to move, Space or Enter to drop, or Escape to cancel.`,
+ );
+ }
+ },
+ [announce, isReorderable, setReorderSession],
+ );
+
+ const finishReorder = useCallback(
+ (cancelled: boolean) => {
+ const session = reorderSessionRef.current;
+ if (!session) {
+ return;
+ }
+ if (session.mode === 'pointer') {
+ if (cancelled || !session.hasPointerMoved) {
+ setReorderSession(null);
+ if (cancelled) {
+ announce(`${session.label} move cancelled.`);
+ }
+ return;
+ }
+ const hasChanged = session.fromIndex !== session.toIndex;
+ const nextValue = moveItem(
+ session.originalValue,
+ session.fromIndex,
+ session.toIndex,
+ );
+ flushSync(() => setReorderSession(null));
+ if (hasChanged) {
+ commit(nextValue);
+ announce(
+ `${session.label} dropped at position ${session.toIndex + 1} of ${session.originalValue.length}.`,
+ );
+ } else {
+ announce(
+ `${session.label} returned to position ${session.fromIndex + 1}.`,
+ );
+ }
+ return;
+ }
+ if (cancelled) {
+ commit(session.originalValue);
+ announce(`${session.label} move cancelled.`);
+ } else {
+ const index = currentValueRef.current.indexOf(session.value);
+ announce(
+ `${session.label} dropped at position ${index + 1} of ${currentValueRef.current.length}.`,
+ );
+ }
+ setReorderSession(null);
+ },
+ [announce, commit, setReorderSession],
+ );
+
+ 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 targets: Record<string, number> = {
+ ArrowUp: index - 1,
+ ArrowDown: index + 1,
+ Home: start,
+ End: end,
+ };
+ const target = targets[event.key];
+ if (target == null) {
+ return;
+ }
+ event.preventDefault();
+ if (moveOption(option.value, target)) {
+ const nextIndex = currentValueRef.current.indexOf(option.value);
+ announce(
+ `${option.label}, position ${nextIndex + 1} of ${currentValueRef.current.length}.`,
+ );
+ }
+ },
+ [announce, finishReorder, movableRange, moveOption],
+ );
+
+ 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(
+ `${option.label}, position ${targetIndex + 1} of ${session.originalValue.length}.`,
+ );
+ }
+ },
+ [announce, movableRange, setReorderSession],
+ );
+
+ 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],
+ );
+
+ const handleSearch = useCallback(
+ (nextQuery: string) => {
+ setQuery(nextQuery);
+ const normalized = nextQuery.trim().toLocaleLowerCase();
+ if (normalized === '') {
+ announce('');
+ } else {
+ const count = options.filter(option =>
+ matchesQuery(option, normalized),
+ ).length;
+ announce(`${itemCount(count)} found.`);
+ }
+ },
+ [announce, options],
+ );
+
+ const optionActions = (
+ option: TransferListOption<T>,
+ side: 'selected' | 'available',
+ index: number,
+ ) => {
+ const isTransferDisabled = option.isTransferDisabled === true;
+ const disabledReason =
+ option.disabledMessage ?? `${option.label} cannot be moved`;
+ if (side === 'available') {
+ return (
+ <IconButton
+ label={`Add ${option.label}`}
+ icon={<PlusIcon />}
+ size="sm"
+ variant="ghost"
+ isDisabled={isTransferDisabled}
+ tooltip={isTransferDisabled ? disabledReason : undefined}
+ data-transfer-list-action="available"
+ onClick={() => addOption(option, index)}
+ />
+ );
+ }
+ return (
+ <IconButton
+ label={`Remove ${option.label}`}
+ icon={<RemoveIcon />}
+ size="sm"
+ variant="ghost"
+ isDisabled={isTransferDisabled}
+ tooltip={isTransferDisabled ? disabledReason : undefined}
+ data-transfer-list-action="selected"
+ onClick={() => removeOption(option, index)}
+ />
+ );
+ };
+
+ 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 dragPreviewPortalTarget =
+ typeof document === 'undefined'
+ ? null
+ : (rootRef.current?.closest<HTMLElement>('[popover], dialog[open]') ??
+ document.body);
+
+ const reorderControl = (option: TransferListOption<T>) => {
+ if (!isReorderable) {
+ return undefined;
+ }
+ const active = reorderSession?.value === option.value;
+ const isReorderDisabled = option.isReorderDisabled === true;
+ const disabledReason =
+ option.disabledMessage ?? `${option.label} cannot be reordered`;
+ return (
+ <IconButton
+ label={`Reorder ${option.label}`}
+ aria-describedby={reorderInstructionsId}
+ aria-pressed={active}
+ icon={<GripVerticalIcon />}
+ 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);
+ }
+ }}
+ />
+ );
+ };
+
+ const transferItem = (
+ option: TransferListOption<T>,
+ 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);
+ 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',
+ })}
+ />
+ );
+ };
+
+ const describedBy =
+ [ariaDescribedBy, description != null ? descriptionId : undefined]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ return (
+ <div
+ ref={mergeRefs(ref, rootRef)}
+ {...restProps}
+ {...mergeProps(
+ themeProps('transfer-list'),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}
+ role={role ?? 'group'}
+ aria-labelledby={ariaLabelledBy ?? labelId}
+ aria-describedby={describedBy}>
+ <div {...stylex.props(styles.heading)}>
+ {isLabelHidden ? (
+ <VisuallyHidden id={labelId}>{label}</VisuallyHidden>
+ ) : (
+ <Text id={labelId} type="label" display="block">
+ {label}
+ </Text>
+ )}
+ {description != null && (
+ <Text id={descriptionId} type="supporting" display="block">
+ {description}
+ </Text>
+ )}
+ </div>
+
+ {hasSearch && (
+ <div {...stylex.props(styles.controls)}>
+ <TextInput
+ ref={searchRef}
+ role="searchbox"
+ label={searchLabel ?? `Search ${label}`}
+ isLabelHidden
+ value={query}
+ placeholder={searchPlaceholder}
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
+ hasClear
+ width="100%"
+ xstyle={styles.search}
+ onChange={handleSearch}
+ />
+ </div>
+ )}
+
+ <VisuallyHidden id={reorderInstructionsId}>
+ Press Space or Enter to pick up an item. Use Arrow Up, Arrow Down, Home,
+ or End to move it. Press Space or Enter to drop, or Escape to cancel.
+ </VisuallyHidden>
+
+ <div
+ {...mergeProps(
+ themeProps('transfer-list-collection'),
+ stylex.props(styles.panels),
+ )}>
+ <div
+ ref={selectedPanelRef}
+ role="group"
+ aria-labelledby={selectedHeadingId}
+ tabIndex={-1}
+ {...mergeProps(
+ themeProps('transfer-list-panel', {side: 'selected'}),
+ stylex.props(styles.panel),
+ )}>
+ <div {...stylex.props(styles.panelHeader)}>
+ <Text id={selectedHeadingId} type="label" color="secondary">
+ {selectedLabel}
+ </Text>
+ {hasClear && (
+ <Button
+ label="Clear"
+ size="sm"
+ variant="ghost"
+ xstyle={styles.headerAction}
+ data-transfer-list-header-action="true"
+ isDisabled={
+ !value.some(
+ optionValue =>
+ !optionByValue.get(optionValue)?.isTransferDisabled,
+ )
+ }
+ onClick={clearSelected}
+ />
+ )}
+ </div>
+ <div
+ data-transfer-list-panel-body="selected"
+ {...stylex.props(styles.panelBody)}>
+ {selectedOptions.length > 0 ? (
+ <List
+ density="compact"
+ header={<VisuallyHidden>{selectedLabel}</VisuallyHidden>}>
+ {selectedOptions.map((option, index) =>
+ transferItem(option, 'selected', index),
+ )}
+ </List>
+ ) : (
+ <div
+ data-transfer-list-empty="selected"
+ {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ {normalizedQuery === '' ? selectedEmptyText : noResultsText}
+ </Text>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div
+ ref={availablePanelRef}
+ role="group"
+ aria-labelledby={availableHeadingId}
+ tabIndex={-1}
+ {...mergeProps(
+ themeProps('transfer-list-panel', {side: 'available'}),
+ stylex.props(styles.panel, styles.panelDivider),
+ )}>
+ <div {...stylex.props(styles.panelHeader)}>
+ <Text id={availableHeadingId} type="label" color="secondary">
+ {availableLabel}
+ </Text>
+ {hasSelectAll && (
+ <Button
+ label="Add all"
+ size="sm"
+ variant="ghost"
+ xstyle={styles.headerAction}
+ data-transfer-list-header-action="true"
+ isDisabled={
+ !options.some(
+ option =>
+ !option.isTransferDisabled &&
+ !currentValueRef.current.includes(option.value),
+ )
+ }
+ onClick={addAll}
+ />
+ )}
+ </div>
+ <div
+ data-transfer-list-panel-body="available"
+ {...stylex.props(styles.panelBody)}>
+ {availableOptions.length > 0 ? (
+ <List
+ density="compact"
+ header={<VisuallyHidden>{availableLabel}</VisuallyHidden>}>
+ {groupedAvailable.map(([group, groupOptions]) => (
+ <Fragment key={group || 'ungrouped'}>
+ {(group !== '' || groupedAvailable.length > 1) && (
+ <li
+ role="presentation"
+ {...stylex.props(styles.groupHeading)}>
+ <Text type="body" weight="bold" color="primary">
+ {group || 'Other'}
+ </Text>
+ </li>
+ )}
+ {groupOptions.map(option =>
+ transferItem(
+ option,
+ 'available',
+ availableOptions.indexOf(option),
+ ),
+ )}
+ </Fragment>
+ ))}
+ </List>
+ ) : (
+ <div
+ data-transfer-list-empty="available"
+ {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ {normalizedQuery === '' ? availableEmptyText : noResultsText}
+ </Text>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ {dragPreviewPosition != null && dragPreviewPortalTarget != null
+ ? createPortal(
+ <div
+ ref={dragPreviewRef}
+ aria-hidden="true"
+ data-transfer-list-drag-preview=""
+ {...stylex.props(
+ reorderStyles.preview,
+ styles.dragPreviewContainer,
+ dynamicStyles.dragPreview(
+ dragPreviewPosition.x,
+ dragPreviewPosition.y,
+ dragPreviewPosition.width,
+ ),
+ )}
+ />,
+ dragPreviewPortalTarget,
+ )
+ : null}
+ </div>
+ );
+}
+
+TransferList.displayName = 'TransferList';
diff --git a/packages/lab/src/TransferList/TransferListSelector.test.tsx b/packages/lab/src/TransferList/TransferListSelector.test.tsx
new file mode 100644
index 0000000000..edd38bf57a
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferListSelector.test.tsx
@@ -0,0 +1,562 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TransferListSelector.test.tsx
+ * @input Uses TransferListSelector, React state, Vitest, and Testing Library
+ * @output Unit coverage for immediate and staged commits, uncontrolled dismissal, synchronization, disabled states, defaults, and prop forwarding
+ * @position Lab component test; validates the TransferListSelector public contract
+ *
+ * SYNC: When TransferListSelector.tsx behavior changes, update this test.
+ */
+
+import {useState} from 'react';
+import {afterAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {
+ TransferListSelector,
+ type TransferListSelectorProps,
+} from './TransferListSelector';
+import type {TransferListOption} from './TransferList';
+
+type Column = 'name' | 'owner' | 'status' | 'updated';
+
+const OPTIONS: ReadonlyArray<TransferListOption<Column>> = [
+ {value: 'name', label: 'Name'},
+ {value: 'owner', label: 'Owner'},
+ {value: 'status', label: 'Status'},
+ {value: 'updated', label: 'Updated'},
+];
+
+const hidden = {hidden: true} as const;
+const originalMatches = HTMLElement.prototype.matches;
+
+beforeEach(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ this.setAttribute('popover-open', '');
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ this.removeAttribute('popover-open');
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ Object.defineProperty(HTMLElement.prototype, 'matches', {
+ configurable: true,
+ value: function (this: HTMLElement, selector: string): boolean {
+ if (selector === ':popover-open') {
+ return this.hasAttribute('popover-open');
+ }
+ return originalMatches.call(this, selector);
+ },
+ });
+});
+
+afterAll(() => {
+ Object.defineProperty(HTMLElement.prototype, 'matches', {
+ configurable: true,
+ value: originalMatches,
+ });
+});
+
+type HarnessProps = {
+ initialValue?: readonly Column[];
+ onCommit: (value: readonly Column[]) => void;
+ selectorProps?: Partial<
+ Omit<
+ TransferListSelectorProps<Column>,
+ 'label' | 'options' | 'value' | 'onChange'
+ >
+ >;
+};
+
+function Harness({
+ initialValue = ['name', 'status'],
+ onCommit,
+ selectorProps,
+}: HarnessProps) {
+ const [value, setValue] = useState<readonly Column[]>(initialValue);
+
+ return (
+ <>
+ <output data-testid="applied-value">{JSON.stringify(value)}</output>
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={value}
+ onChange={nextValue => {
+ onCommit(nextValue);
+ setValue(nextValue);
+ }}
+ {...selectorProps}
+ />
+ </>
+ );
+}
+
+async function openSelector(
+ name = 'Visible fields',
+): Promise<HTMLButtonElement> {
+ const trigger = screen.getByRole('button', {
+ name,
+ }) as HTMLButtonElement;
+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+ return trigger;
+}
+
+describe('TransferListSelector', () => {
+ it('commits each edit immediately by default and renders no footer', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ const changeAction = vi.fn();
+ render(<Harness onCommit={onCommit} selectorProps={{changeAction}} />);
+
+ const trigger = await openSelector();
+ const dialog = screen.getByRole('dialog', {
+ name: 'Visible fields',
+ ...hidden,
+ });
+ expect(
+ within(dialog).queryByRole('button', {name: 'Apply', hidden: true}),
+ ).not.toBeInTheDocument();
+ expect(
+ within(dialog).queryByRole('button', {name: 'Cancel', hidden: true}),
+ ).not.toBeInTheDocument();
+
+ await user.click(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ );
+
+ expect(onCommit).toHaveBeenCalledOnce();
+ expect(onCommit).toHaveBeenCalledWith(['name', 'status', 'owner']);
+ await waitFor(() => {
+ expect(changeAction).toHaveBeenCalledOnce();
+ });
+ expect(changeAction).toHaveBeenCalledWith(['name', 'status', 'owner']);
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status","owner"]',
+ );
+ expect(trigger).toHaveTextContent('3 selected');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ const popover = dialog.closest('[popover]');
+ expect(popover).not.toBeNull();
+ popover?.removeAttribute('popover-open');
+ const dismissEvent = new Event('toggle');
+ Object.defineProperty(dismissEvent, 'newState', {value: 'closed'});
+ fireEvent(popover as HTMLElement, dismissEvent);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ await openSelector();
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status","owner"]',
+ );
+ });
+
+ it('discards a staged draft whenever commit behavior changes', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const view = render(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={onChange}
+ commitBehavior="staged"
+ />,
+ );
+ await openSelector();
+
+ await user.click(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ );
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),
+ ).toBeInTheDocument();
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={onChange}
+ commitBehavior="immediate"
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ ).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={onChange}
+ commitBehavior="staged"
+ />,
+ );
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ ).toBeInTheDocument();
+ });
+ expect(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Remove Status', ...hidden}),
+ ).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps edits in a staged draft and commits a changed ordered copy once', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ const changeAction = vi.fn();
+ render(
+ <Harness
+ onCommit={onCommit}
+ selectorProps={{commitBehavior: 'staged', changeAction}}
+ />,
+ );
+
+ const trigger = await openSelector();
+ await user.click(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ );
+
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ expect(trigger).toHaveTextContent('2 selected');
+ expect(onCommit).not.toHaveBeenCalled();
+
+ await user.click(screen.getByRole('button', {name: 'Apply', ...hidden}));
+
+ expect(onCommit).toHaveBeenCalledOnce();
+ expect(onCommit).toHaveBeenCalledWith(['name', 'status', 'owner']);
+ await waitFor(() => {
+ expect(changeAction).toHaveBeenCalledOnce();
+ });
+ expect(changeAction).toHaveBeenCalledWith(['name', 'status', 'owner']);
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status","owner"]',
+ );
+ expect(trigger).toHaveTextContent('3 selected');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('closes unchanged Apply without calling onChange or changeAction', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const changeAction = vi.fn();
+ render(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={onChange}
+ changeAction={changeAction}
+ commitBehavior="staged"
+ />,
+ );
+
+ const trigger = await openSelector();
+ await user.click(screen.getByRole('button', {name: 'Apply', ...hidden}));
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(changeAction).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('discards drafts after Cancel, Escape, and light dismiss', async () => {
+ const user = userEvent.setup();
+ const onCommit = vi.fn();
+ render(
+ <Harness
+ onCommit={onCommit}
+ selectorProps={{commitBehavior: 'staged'}}
+ />,
+ );
+
+ let trigger = await openSelector();
+ await user.click(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ );
+ await user.click(screen.getByRole('button', {name: 'Cancel', ...hidden}));
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ trigger = await openSelector();
+ expect(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ ).toBeInTheDocument();
+ await user.click(
+ screen.getByRole('button', {name: 'Remove Status', ...hidden}),
+ );
+ await user.keyboard('{Escape}');
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ trigger = await openSelector();
+ expect(
+ screen.getByRole('button', {name: 'Remove Status', ...hidden}),
+ ).toBeInTheDocument();
+ await user.click(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ );
+
+ const popover = screen
+ .getByRole('dialog', {name: 'Visible fields', ...hidden})
+ .closest('[popover]');
+ expect(popover).not.toBeNull();
+ popover?.removeAttribute('popover-open');
+ const dismissEvent = new Event('toggle');
+ Object.defineProperty(dismissEvent, 'newState', {value: 'closed'});
+ fireEvent(popover as HTMLElement, dismissEvent);
+ await waitFor(() => {
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ await openSelector();
+ expect(
+ screen.getByRole('button', {name: 'Remove Name', ...hidden}),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId('applied-value')).toHaveTextContent(
+ '["name","status"]',
+ );
+ expect(onCommit).not.toHaveBeenCalled();
+ });
+
+ it('syncs differing applied values without clearing a dirty draft for equal arrays', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const view = render(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'status']}
+ onChange={onChange}
+ commitBehavior="staged"
+ />,
+ );
+ await openSelector();
+
+ await user.click(
+ screen.getByRole('button', {name: 'Add Owner', ...hidden}),
+ );
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),
+ ).toBeInTheDocument();
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={[...(['name', 'status'] as const)]}
+ onChange={onChange}
+ commitBehavior="staged"
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),
+ ).toBeInTheDocument();
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['owner', 'updated']}
+ onChange={onChange}
+ commitBehavior="staged"
+ />,
+ );
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', {name: 'Remove Updated', ...hidden}),
+ ).toBeInTheDocument();
+ });
+ expect(
+ screen.getByRole('button', {name: 'Remove Owner', ...hidden}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Add Name', ...hidden}),
+ ).toBeInTheDocument();
+ });
+
+ it('defaults the trigger label to the applied selected count', () => {
+ render(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name', 'owner', 'updated']}
+ onChange={() => {}}
+ />,
+ );
+
+ expect(
+ screen.getByRole('button', {name: 'Visible fields'}),
+ ).toHaveTextContent('3 selected');
+ });
+
+ it('disables list controls and Apply while keeping Cancel operable', async () => {
+ const view = render(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name']}
+ onChange={() => {}}
+ commitBehavior="staged"
+ />,
+ );
+ await openSelector();
+ const dialog = screen.getByRole('dialog', {
+ name: 'Visible fields',
+ ...hidden,
+ });
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name']}
+ onChange={() => {}}
+ commitBehavior="staged"
+ isDisabled
+ />,
+ );
+ const fieldset = dialog.querySelector('fieldset');
+ expect(fieldset).not.toBeNull();
+ expect(fieldset).toBeDisabled();
+
+ const cancel = within(dialog).getByRole('button', {
+ name: 'Cancel',
+ hidden: true,
+ });
+ const apply = within(dialog).getByRole('button', {
+ name: 'Apply',
+ hidden: true,
+ });
+ expect(cancel).toBeEnabled();
+ expect(fieldset).not.toContainElement(cancel);
+ expect(apply).toBeDisabled();
+ expect(screen.getByRole('button', {name: 'Visible fields'})).toBeDisabled();
+
+ view.rerender(
+ <TransferListSelector
+ label="Visible fields"
+ options={OPTIONS}
+ value={['name']}
+ onChange={() => {}}
+ commitBehavior="staged"
+ isLoading
+ />,
+ );
+
+ await waitFor(() => {
+ expect(dialog.querySelector('[aria-busy="true"]')).not.toBeNull();
+ });
+ expect(dialog.querySelector('fieldset')).toBeDisabled();
+ expect(
+ within(dialog).getByRole('button', {name: 'Cancel', hidden: true}),
+ ).toBeEnabled();
+ expect(
+ within(dialog).getByRole('button', {name: 'Apply', hidden: true}),
+ ).toBeDisabled();
+ });
+
+ it('forwards intentional selector shell and transfer-list content props', async () => {
+ render(
+ <TransferListSelector
+ label="Table columns"
+ description="Choose the columns shown in the table."
+ options={OPTIONS}
+ value={['name']}
+ onChange={() => {}}
+ triggerLabel="Customize columns"
+ size="sm"
+ placement="below"
+ data-testid="column-selector"
+ selectedLabel="Shown"
+ availableLabel="Hidden"
+ hasSearch
+ searchPlaceholder="Find a column"
+ isReorderable={false}
+ hasSelectAll
+ hasClear
+ commitBehavior="staged"
+ applyLabel="Save columns"
+ cancelLabel="Discard changes"
+ />,
+ );
+
+ expect(
+ screen.getByText('Choose the columns shown in the table.'),
+ ).toBeVisible();
+ expect(screen.getByTestId('column-selector')).toHaveAttribute(
+ 'data-size',
+ 'sm',
+ );
+ expect(
+ screen.getByRole('button', {name: 'Table columns'}),
+ ).toHaveTextContent('Customize columns');
+ expect(
+ screen.getByTestId('column-selector').closest('.astryx-field'),
+ ).toHaveStyle({
+ '--x-width': 'min(41rem, calc(100vw - 32px))',
+ });
+
+ await openSelector('Table columns');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('dialog', {name: 'Table columns', ...hidden}),
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByPlaceholderText('Find a column')).toBeInTheDocument();
+ expect(screen.getAllByText('Shown')).not.toHaveLength(0);
+ expect(screen.getAllByText('Hidden')).not.toHaveLength(0);
+ expect(
+ screen.getByRole('button', {name: 'Save columns', ...hidden}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Discard changes', ...hidden}),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Reorder Name', ...hidden}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Add all', ...hidden}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Clear', ...hidden}),
+ ).toBeInTheDocument();
+
+ const popover = screen
+ .getByRole('dialog', {name: 'Table columns', ...hidden})
+ .closest('[popover]');
+ expect(popover?.getAttribute('style')).toContain(
+ 'position-area: self-block-end span-self-inline-end',
+ );
+ });
+});
diff --git a/packages/lab/src/TransferList/TransferListSelector.tsx b/packages/lab/src/TransferList/TransferListSelector.tsx
new file mode 100644
index 0000000000..ab45bf742c
--- /dev/null
+++ b/packages/lab/src/TransferList/TransferListSelector.tsx
@@ -0,0 +1,315 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TransferListSelector.tsx
+ * @input Controlled option data, uncontrolled ComplexSelector state, TransferList, and action controls
+ * @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
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/TransferList/TransferListSelector.test.tsx
+ * - /packages/lab/src/TransferList/TransferList.doc.mjs
+ * - /packages/lab/src/TransferList/index.ts
+ */
+
+import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {
+ ComplexSelector,
+ type ComplexSelectorProps,
+} from '@astryxdesign/core/ComplexSelector';
+import {HStack} from '@astryxdesign/core/Stack';
+import {borderVars, colorVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {TransferList, type TransferListProps} from './TransferList';
+
+const DEFAULT_SELECTOR_WIDTH = 'min(41rem, calc(100vw - 32px))';
+
+const styles = stylex.create({
+ content: {
+ width: DEFAULT_SELECTOR_WIDTH,
+ maxWidth: DEFAULT_SELECTOR_WIDTH,
+ maxHeight: 'calc(100vh - 32px)',
+ padding: 0,
+ overflow: 'hidden',
+ borderRadius: 'inherit',
+ },
+ surface: {
+ display: 'flex',
+ flexDirection: 'column',
+ minWidth: 0,
+ minHeight: 0,
+ maxHeight: 'inherit',
+ },
+ fieldset: {
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 'auto',
+ minWidth: 0,
+ minHeight: 0,
+ margin: 0,
+ padding: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ overflowY: 'auto',
+ overscrollBehavior: 'contain',
+ },
+ footer: {
+ flexShrink: 0,
+ borderBlockStartWidth: borderVars['--border-width'],
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: colorVars['--color-border'],
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+});
+
+type TransferListSelectorShellProp =
+ | 'label'
+ | 'triggerLabel'
+ | 'isLabelHidden'
+ | 'description'
+ | 'isOptional'
+ | 'isRequired'
+ | 'isDisabled'
+ | 'isLoading'
+ | 'status'
+ | 'statusVariant'
+ | 'labelTooltip'
+ | 'size'
+ | 'width'
+ | 'placement'
+ | 'contentXstyle'
+ | 'xstyle'
+ | 'className'
+ | 'style'
+ | 'data-testid';
+
+type TransferListContentProp =
+ | 'options'
+ | 'selectedLabel'
+ | 'availableLabel'
+ | 'hasSearch'
+ | 'searchLabel'
+ | 'searchPlaceholder'
+ | 'isReorderable'
+ | 'hasSelectAll'
+ | 'hasClear'
+ | 'renderOption'
+ | 'selectedEmptyText'
+ | 'availableEmptyText'
+ | 'noResultsText';
+
+export type TransferListSelectorCommitBehavior = 'immediate' | 'staged';
+
+export type TransferListSelectorProps<T extends string = string> = Pick<
+ ComplexSelectorProps<readonly T[]>,
+ TransferListSelectorShellProp
+> &
+ Pick<TransferListProps<T>, TransferListContentProp> & {
+ /** Ordered values applied outside the selector. */
+ value: readonly T[];
+ /** Called whenever a value is committed. */
+ onChange: (value: readonly T[]) => void;
+ /** Optional async action after a changed value is applied. */
+ changeAction?: (value: readonly T[]) => void | Promise<void>;
+ /**
+ * Controls when changes are committed. Immediate commits each list edit and
+ * staged waits for Apply. @default 'immediate'
+ */
+ commitBehavior?: TransferListSelectorCommitBehavior;
+ /** Label for the staged commit action. Only used in staged behavior. @default 'Apply' */
+ applyLabel?: string;
+ /** Label for the staged discard action. Only used in staged behavior. @default 'Cancel' */
+ cancelLabel?: string;
+ };
+
+function areOrderedValuesEqual<T>(
+ first: readonly T[],
+ second: readonly T[],
+): boolean {
+ return (
+ first.length === second.length &&
+ first.every((item, index) => item === second[index])
+ );
+}
+
+function ResetDraftAfterClose({
+ isOpen,
+ resetDraft,
+}: {
+ isOpen: boolean;
+ resetDraft: () => void;
+}): null {
+ const wasOpenRef = useRef(isOpen);
+
+ useEffect(() => {
+ if (wasOpenRef.current && !isOpen) {
+ resetDraft();
+ }
+ wasOpenRef.current = isOpen;
+ }, [isOpen, resetDraft]);
+
+ return null;
+}
+
+/**
+ * A transfer-list field that opens in a selector popover.
+ *
+ * The field label, description, and trigger remain outside the popup. Changes
+ * commit immediately by default. Set commitBehavior="staged" when the workflow
+ * needs explicit Apply and Cancel actions.
+ *
+ * @example
+ * ```
+ * <TransferListSelector
+ * label="Visible fields"
+ * options={columnOptions}
+ * value={visibleColumns}
+ * onChange={setVisibleColumns}
+ * />
+ * ```
+ */
+export function TransferListSelector<T extends string = string>({
+ label,
+ description,
+ options,
+ value,
+ onChange,
+ changeAction,
+ commitBehavior = 'immediate',
+ triggerLabel,
+ isDisabled,
+ isLoading,
+ width,
+ contentXstyle,
+ applyLabel = 'Apply',
+ cancelLabel = 'Cancel',
+ selectedLabel,
+ availableLabel,
+ hasSearch,
+ searchLabel,
+ searchPlaceholder,
+ isReorderable,
+ hasSelectAll,
+ hasClear,
+ renderOption,
+ selectedEmptyText,
+ availableEmptyText,
+ noResultsText,
+ ...selectorProps
+}: TransferListSelectorProps<T>): ReactNode {
+ const [draftValue, setDraftValue] = useState<readonly T[]>(value);
+ const previousAppliedValueRef = useRef<readonly T[]>([...value]);
+ const previousCommitBehaviorRef = useRef(commitBehavior);
+
+ const resetDraft = useCallback(() => {
+ setDraftValue([...value]);
+ }, [value]);
+
+ useEffect(() => {
+ const previousAppliedValue = previousAppliedValueRef.current;
+ previousAppliedValueRef.current = [...value];
+ if (!areOrderedValuesEqual(previousAppliedValue, value)) {
+ resetDraft();
+ }
+ }, [resetDraft, value]);
+
+ useEffect(() => {
+ if (previousCommitBehaviorRef.current !== commitBehavior) {
+ resetDraft();
+ }
+ previousCommitBehaviorRef.current = commitBehavior;
+ }, [commitBehavior, resetDraft]);
+
+ return (
+ <ComplexSelector
+ {...selectorProps}
+ label={label}
+ description={description}
+ value={value}
+ onChange={onChange}
+ changeAction={changeAction}
+ triggerLabel={triggerLabel ?? `${value.length} selected`}
+ isDisabled={isDisabled}
+ isLoading={isLoading}
+ width={width ?? DEFAULT_SELECTOR_WIDTH}
+ contentXstyle={[styles.content, contentXstyle]}>
+ {(appliedValue, commit, close, state) => {
+ const isStaged = commitBehavior === 'staged';
+ const transferListValue = isStaged ? draftValue : appliedValue;
+
+ return (
+ <div
+ aria-busy={state.isBusy || undefined}
+ {...stylex.props(styles.surface)}>
+ {isStaged && (
+ <ResetDraftAfterClose
+ isOpen={state.isOpen}
+ resetDraft={resetDraft}
+ />
+ )}
+ <fieldset
+ disabled={isDisabled || state.isBusy}
+ {...stylex.props(styles.fieldset)}>
+ <TransferList
+ label={label}
+ isLabelHidden
+ options={options}
+ value={transferListValue}
+ onChange={nextValue => {
+ if (isStaged) {
+ setDraftValue(nextValue);
+ } else {
+ commit([...nextValue]);
+ }
+ }}
+ selectedLabel={selectedLabel}
+ availableLabel={availableLabel}
+ hasSearch={hasSearch}
+ searchLabel={searchLabel}
+ searchPlaceholder={searchPlaceholder}
+ isReorderable={isReorderable}
+ hasSelectAll={hasSelectAll}
+ hasClear={hasClear}
+ renderOption={renderOption}
+ selectedEmptyText={selectedEmptyText}
+ availableEmptyText={availableEmptyText}
+ noResultsText={noResultsText}
+ />
+ </fieldset>
+ {isStaged && (
+ <HStack gap={2} hAlign="end" padding={3} xstyle={styles.footer}>
+ <Button
+ label={cancelLabel}
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ resetDraft();
+ close();
+ }}
+ />
+ <Button
+ label={applyLabel}
+ variant="primary"
+ size="sm"
+ isDisabled={isDisabled || state.isBusy}
+ isLoading={state.isBusy}
+ onClick={() => {
+ if (!areOrderedValuesEqual(draftValue, value)) {
+ commit([...draftValue]);
+ }
+ close();
+ }}
+ />
+ </HStack>
+ )}
+ </div>
+ );
+ }}
+ </ComplexSelector>
+ );
+}
+
+TransferListSelector.displayName = 'TransferListSelector';
diff --git a/packages/lab/src/TransferList/index.ts b/packages/lab/src/TransferList/index.ts
new file mode 100644
index 0000000000..c552c4914d
--- /dev/null
+++ b/packages/lab/src/TransferList/index.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input TransferListSelector, TransferList, and local layout variables
+ * @output Public selector, composition primitive, prop types, and layout variables
+ * @position Package boundary for the Lab TransferList selector experiment
+ */
+
+export {
+ TransferList,
+ type TransferListOption,
+ type TransferListProps,
+} from './TransferList';
+export {
+ TransferListSelector,
+ type TransferListSelectorCommitBehavior,
+ type TransferListSelectorProps,
+} from './TransferListSelector';
+export {transferListVars} from './tokens.stylex';
diff --git a/packages/lab/src/TransferList/tokens.stylex.ts b/packages/lab/src/TransferList/tokens.stylex.ts
new file mode 100644
index 0000000000..97195430e3
--- /dev/null
+++ b/packages/lab/src/TransferList/tokens.stylex.ts
@@ -0,0 +1,18 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file tokens.stylex.ts
+ * @input StyleX variable definitions
+ * @output Exports TransferList layout variables
+ * @position Lab component tokens consumed by TransferList.tsx
+ *
+ * SYNC: When modified, update TransferList.tsx usage and TransferList.doc.mjs.
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+/** Layout variables exposed for theme-level TransferList tuning. */
+export const transferListVars = stylex.defineVars({
+ '--transfer-list-panel-min-block-size': '12rem',
+ '--transfer-list-panel-max-block-size': '20rem',
+});
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 6188f41778..d8bb2a234c 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -24,6 +24,17 @@ export {
// InfoTip — accessible info-icon help affordance (RFC facebook/astryx#3349)
export {InfoTip, type InfoTipProps, type InfoTipSize} from './InfoTip';
+// TransferList — controlled dual-panel collection input
+export {
+ TransferList,
+ TransferListSelector,
+ transferListVars,
+ type TransferListOption,
+ type TransferListProps,
+ type TransferListSelectorCommitBehavior,
+ type TransferListSelectorProps,
+} from './TransferList';
+
// Chat — experimental reasoning display
export {
ChatReasoning,