Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/reorder-internal-shared-parts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[chore] Internal: a new internal entry, `@astryxdesign/core/internal/reorder-mode`, reserved for Astryx's own packages, gives a collection that runs its own reorder mode the parts a List's uses: its mode hint, along either axis, its strings, its pointer input with a finger's hold, its edge autoscroll, scroll watch and bounds, the preview copy, and the text it names items by. The internal reorder entry gains a way for the object's `start(key)` to reach such a collection. The catalog gains Move left and Move right for the hint's inline moves. The entry is not part of the public API. Apps see no change.

@humbertovirtudes
277 changes: 277 additions & 0 deletions apps/storybook/stories/TableDragAndDropColumns.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

import {useMemo, useState, type Key} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {createReorderable} from '@astryxdesign/core';
import {
Table,
pixel,
useTableColumnSettings,
useTableColumnSettingsState,
useTableColumnsVirtualization,
useTableSelection,
useTableStickyColumns,
type TableColumn,
} from '@astryxdesign/core/Table';
import {VStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {useTableDragAndDropColumns} from '@astryxdesign/lab';

interface Task extends Record<string, unknown> {
id: string;
title: string;
owner: string;
status: string;
due: string;
points: number;
}

const TASKS: Task[] = [
{
id: 't1',
title: 'Draft the release notes',
owner: 'Ava Chen',
status: 'Open',
due: 'Mon',
points: 3,
},
{
id: 't2',
title: 'Review the theme tokens',
owner: 'Liam Park',
status: 'Open',
due: 'Tue',
points: 5,
},
{
id: 't3',
title: 'Check the empty states',
owner: 'Zoe Vega',
status: 'Done',
due: 'Wed',
points: 2,
},
{
id: 't4',
title: 'Record the demo',
owner: 'Max Ross',
status: 'Open',
due: 'Thu',
points: 8,
},
];

const COLUMNS: TableColumn<Task>[] = [
{key: 'title', header: 'Task', width: pixel(240)},
{key: 'owner', header: 'Owner', width: pixel(160)},
{key: 'status', header: 'Status', width: pixel(120)},
{key: 'due', header: 'Due', width: pixel(120)},
{key: 'points', header: 'Points', width: pixel(120), align: 'end'},
];

function moveKey(keys: ReadonlyArray<string>, key: Key, to: number): string[] {
const rest = keys.filter(item => item !== key);
return [...rest.slice(0, to), String(key), ...rest.slice(to)];
}

function byKeys<T extends Record<string, unknown>>(
columns: TableColumn<T>[],
keys: ReadonlyArray<string>,
): TableColumn<T>[] {
return keys.flatMap(key => columns.filter(column => column.key === key));
}

const meta: Meta = {
title: 'Lab/TableDragAndDropColumns',
tags: ['autodocs'],
};

export default meta;

function DefaultDemo() {
const [order, setOrder] = useState(() => COLUMNS.map(column => column.key));
const reorderable = useMemo(
() =>
createReorderable({
onReorder: ({key, to}) => setOrder(keys => moveKey(keys, key, to)),
}),
[],
);
const dragColumns = useTableDragAndDropColumns<Task>({
reorderable,
columnKeys: order,
});
return (
<VStack gap={2}>
<Table
aria-label="Tasks"
data={TASKS}
columns={byKeys(COLUMNS, order)}
idKey="id"
plugins={{dragColumns}}
/>
<Text type="supporting" data-testid="order">
{order.join(' ')}
</Text>
</VStack>
);
}

/**
* Focus the handle at the end of a column's header and press Space or Enter,
* then Left and Right, to move the column one place at a time. Or tap the
* handle, then the hint's moves. Escape or Done ends reorder mode.
*/
export const Default: StoryObj = {
render: () => <DefaultDemo />,
};

function ColumnSettingsDemo() {
const [active, setActive] = useState<ReadonlyArray<string>>([
'title',
'status',
'due',
'points',
]);
const settings = useTableColumnSettingsState({
columns: COLUMNS.map(column => ({
key: column.key,
label: String(column.header),
isAlwaysVisible: column.key === 'title',
})),
activeColumnKeys: active,
onChangeActiveColumnKeys: setActive,
});
const columnSettings = useTableColumnSettings<Task>(
settings.columnSettingsConfig,
);
const [selected, setSelected] = useState<ReadonlySet<string>>(new Set());
const selection = useTableSelection<Task>({
getIsItemSelected: task => selected.has(task.id),
onSelectItem: ({item, isSelected}) =>
setSelected(current => {
const next = new Set(current);
if (isSelected) {
next.add(item.id);
} else {
next.delete(item.id);
}
return next;
}),
onSelectAll: ({isAllSelected}) =>
setSelected(
isAllSelected ? new Set(TASKS.map(task => task.id)) : new Set(),
),
getIsAllSelected: () => selected.size === TASKS.length,
getRowLabel: task => task.title,
});
const reorderable = useMemo(
() =>
createReorderable({
onReorder: ({key, to}) => setActive(keys => moveKey(keys, key, to)),
// The task column starts every row and stays in place.
isReorderable: key => key !== 'title',
// Each handle starts its header cell, and shows while the cell is
// hovered or holds the focus where the pointer is fine.
handle: {placement: 'start', revealBehavior: 'adaptive'},
}),
[],
);
const dragColumns = useTableDragAndDropColumns<Task>({
reorderable,
columnKeys: settings.activeColumnKeys,
});
const sticky = useTableStickyColumns<Task>({startKeys: ['title']});
return (
<VStack width={560} gap={2}>
<Table
aria-label="Tasks"
data={TASKS}
columns={COLUMNS}
idKey="id"
plugins={{columnSettings, selection, sticky, dragColumns}}
/>
<Text type="supporting" data-testid="order">
{settings.activeColumnKeys.join(' ')}
</Text>
</VStack>
);
}

/**
* Column settings own the order: the moves count the active columns, and a
* hidden column keeps its place in the settings. The task column is pinned
* and stays first, and the selection column takes no part. Each handle
* starts its header cell and shows while the cell is hovered or focused.
*/
export const WithColumnSettingsSelectionAndPinnedColumn: StoryObj = {
render: () => <ColumnSettingsDemo />,
};

interface Metrics extends Record<string, unknown> {
id: string;
[metric: string]: string | number;
}

const METRIC_COLUMNS: TableColumn<Metrics>[] = Array.from(
{length: 60},
(_, index) => ({
key: `m${index + 1}`,
header: `Metric ${index + 1}`,
width: pixel(120),
}),
);

const METRIC_ROWS: Metrics[] = Array.from({length: 20}, (_, row) => ({
id: `r${row + 1}`,
...Object.fromEntries(
METRIC_COLUMNS.map((column, index) => [
column.key,
(row + 1) * (index + 1),
]),
),
}));

function WindowedDemo() {
const [order, setOrder] = useState(() =>
METRIC_COLUMNS.map(column => column.key),
);
const reorderable = useMemo(
() =>
createReorderable({
onReorder: ({key, to}) => setOrder(keys => moveKey(keys, key, to)),
}),
[],
);
const dragColumns = useTableDragAndDropColumns<Metrics>({
reorderable,
columnKeys: order,
});
const virtualization = useTableColumnsVirtualization({
initialViewportWidth: 800,
});
return (
<VStack width={800} gap={2}>
<Table
aria-label="Metrics"
data={METRIC_ROWS}
columns={byKeys(METRIC_COLUMNS, order)}
idKey="id"
virtualization={virtualization}
plugins={{dragColumns}}
dividers="grid"
/>
<Text type="supporting" data-testid="order">
{order.slice(0, 12).join(' ')}
</Text>
</VStack>
);
}

/**
* Sixty columns stay windowed. Each move reports its index among all the
* columns, and screen readers hear the column's place among all of them.
*/
export const WindowedColumns: StoryObj = {
render: () => <WindowedDemo />,
};
24 changes: 24 additions & 0 deletions docs/specs/components/List/List.spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ verified_by:
packages/core/src/List/listLayoutUpdates.test.tsx,
packages/core/src/List/__tests__/ListUpdates.interaction.browser.spec.ts,
packages/core/src/List/__tests__/ListReorder.test.tsx,
packages/core/src/internal/reorderShared.test.tsx,
packages/core/src/List/__tests__/ListReorderLayout.test.tsx,
packages/core/src/List/__tests__/ListReorderTouch.interaction.browser.spec.ts,
packages/core/src/List/__tests__/ListReorderPointer.interaction.browser.spec.ts,
Expand Down Expand Up @@ -116,6 +117,29 @@ Consumer migration instructions belong in consumer docs and release notes.
through `@astryxdesign/core/internal/reorder`. It tells whether an element
is a reorder handle, so a Lab collection that puts the handle beside its
own controls tells them apart: ListInput's field focus skips the handle.
- The parts of List's reorder that a Lab collection running its own reorder
mode shares, through the internal entry
`@astryxdesign/core/internal/reorder-mode` (`internal/reorder-mode.ts`):
- the mode's hint, `ReorderModeHint` (`List/ReorderModeHint.tsx`), with
Move up and Move down on the block axis or Move left and Move right on
the inline axis;
- its strings, `reorderMessagesFrom` (`List/reorderMessages.ts`);
- its pointer input, `attachReorderMouse` and `attachReorderHold`
(`List/reorderPointer.ts`): a mouse, or a pen where the primary pointer
is fine, drags at once; a finger, or a pen where it is coarse, after the
hold;
- its edge autoscroll, `reorderAutoscroll` (`List/reorderAutoscroll.ts`)
with `autoscrollStep`, and its watch of the scroller,
`watchReorderScroll` (`List/reorderScrollWatch.ts`), which folds a
scroll the drag did not cause into the drag in a later frame;
- its drop bounds, `movableRange`, and its preview copy, `previewCopyOf`
with the bare box `bareCopyOf` it falls back to, and
`paintedBackground`;
- the text it names an item's handle by, `getNodeText`.

`mountReorderStarter`, in `@astryxdesign/core/internal/reorder`, lets the
object's `start(key)` reach that collection (`spec:AST-103` FR4a).

- `@astryxdesign/core/internal/reorderHandle.stylex` holds the reorder
handle's grip and reach sizes (`grip`, `targetReach`, `touchReach`), which
List, ListInput and TransferList share. It is internal, like the other
Expand Down
24 changes: 24 additions & 0 deletions packages/cli/test/swizzle-proof/samples.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,30 @@ export const samples = {
}
return React.createElement(Sample);
},
// The hook takes a reorderable object and the keys of the columns it
// orders, as an app does.
lab__useTableDragAndDropColumns: ({React, mod, Core}) => {
function Sample() {
const [reorderable] = React.useState(() =>
Core.createReorderable({onReorder: noop}),
);
const dragColumns = mod.useTableDragAndDropColumns({
reorderable,
columnKeys: ['name', 'owner'],
});
return React.createElement(Core.Table, {
'aria-label': 'Tasks',
data: [{id: 't1', name: 'Notes', owner: 'Ava'}],
columns: [
{key: 'name', header: 'Name'},
{key: 'owner', header: 'Owner'},
],
idKey: 'id',
plugins: {dragColumns},
});
}
return React.createElement(Sample);
},
// The hook throws by design without a positive count and whole-pixel
// geometry, so the sample gives both, as an app does.
lab__useTableInfinityVirtualization: ({React, mod, Core}) => {
Expand Down
8 changes: 8 additions & 0 deletions packages/core/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,14 @@
"defaultMessage": "Move down",
"description": "Accessible label of the down-arrow button in the hint a List row's reorder mode shows: it moves the row one place down, as the Down arrow key does."
},
"@astryx.list.reorderMoveLeft": {
"defaultMessage": "Move left",
"description": "Accessible label of the left-arrow button in the hint that reorder mode shows for items in a row, such as a Table's columns: it moves the item one place to the left, as the Left arrow key does."
},
"@astryx.list.reorderMoveRight": {
"defaultMessage": "Move right",
"description": "Accessible label of the right-arrow button in the hint that reorder mode shows for items in a row, such as a Table's columns: it moves the item one place to the right, as the Right arrow key does."
},
"@astryx.list.reorderDone": {
"defaultMessage": "Done",
"description": "Button in the hint a List row's reorder mode shows: it ends the mode and keeps the moves, as Escape does."
Expand Down
5 changes: 5 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,11 @@
"types": "./dist/internal/reorder.d.ts",
"default": "./dist/internal/reorder.js"
},
"./internal/reorder-mode": {
"source": "./src/internal/reorder-mode.ts",
"types": "./dist/internal/reorder-mode.d.ts",
"default": "./dist/internal/reorder-mode.js"
},
"./internal/reorderHandle.stylex": {
"source": "./src/internal/reorderHandle.stylex.ts",
"types": "./dist/internal/reorderHandle.stylex.d.ts",
Expand Down
Loading
Loading