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
48 changes: 48 additions & 0 deletions README-ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,54 @@ const ColumnReorderingExample = () => {
};
```

### Переупорядочивание строк и столбцов вместе

Вложите `ColumnReorderingProvider` и `ReorderingProvider`, чтобы включить обе оси перетаскивания. Порядок провайдеров не важен — внутри используется один общий dnd-kit-контекст.

```tsx
import type {ColumnReorderingProviderProps, ReorderingProviderProps} from '@gravity-ui/table';
import {ColumnReorderingProvider, ReorderingProvider, dragHandleColumn} from '@gravity-ui/table';

const columns: ColumnDef<Person>[] = [
dragHandleColumn,
{accessorKey: 'name', header: 'Name'},
{accessorKey: 'age', header: 'Age'},
];

const CombinedReorderingExample = () => {
const [data, setData] = React.useState(initialData);
const [columnOrder, setColumnOrder] = React.useState<string[]>([]);

const table = useTable({
columns,
data,
getRowId: (item) => item.id,
state: {columnOrder},
onColumnOrderChange: setColumnOrder,
});

const handleRowReorder = React.useCallback<
NonNullable<ReorderingProviderProps<Person>['onReorder']>
>(({draggedItemKey, baseItemKey}) => {
// обновить массив data
}, []);

const handleColumnReorder = React.useCallback<
NonNullable<ColumnReorderingProviderProps<Person>['onReorder']>
>(({columnOrder}) => {
setColumnOrder(columnOrder);
}, []);

return (
<ColumnReorderingProvider table={table} onReorder={handleColumnReorder}>
<ReorderingProvider table={table} onReorder={handleRowReorder}>
<Table table={table} />
</ReorderingProvider>
</ColumnReorderingProvider>
);
};
```

Если вы управляете `columnOrder` самостоятельно (например, чтобы сохранять его), передайте `onReorder` и примените полученный порядок:

```tsx
Expand Down
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,54 @@ const ColumnReorderingExample = () => {
};
```

### Row and column reordering together

Nest `ColumnReorderingProvider` and `ReorderingProvider` to enable both drag axes at once. The order of providers does not matter — they share a single dnd-kit context internally.

```tsx
import type {ColumnReorderingProviderProps, ReorderingProviderProps} from '@gravity-ui/table';
import {ColumnReorderingProvider, ReorderingProvider, dragHandleColumn} from '@gravity-ui/table';

const columns: ColumnDef<Person>[] = [
dragHandleColumn,
{accessorKey: 'name', header: 'Name'},
{accessorKey: 'age', header: 'Age'},
];

const CombinedReorderingExample = () => {
const [data, setData] = React.useState(initialData);
const [columnOrder, setColumnOrder] = React.useState<string[]>([]);

const table = useTable({
columns,
data,
getRowId: (item) => item.id,
state: {columnOrder},
onColumnOrderChange: setColumnOrder,
});

const handleRowReorder = React.useCallback<
NonNullable<ReorderingProviderProps<Person>['onReorder']>
>(({draggedItemKey, baseItemKey}) => {
// update data array
}, []);

const handleColumnReorder = React.useCallback<
NonNullable<ColumnReorderingProviderProps<Person>['onReorder']>
>(({columnOrder}) => {
setColumnOrder(columnOrder);
}, []);

return (
<ColumnReorderingProvider table={table} onReorder={handleColumnReorder}>
<ReorderingProvider table={table} onReorder={handleRowReorder}>
<Table table={table} />
</ReorderingProvider>
</ColumnReorderingProvider>
);
};
```

If you control `columnOrder` yourself (e.g. to persist it), pass `onReorder` and apply the resulting order:

```tsx
Expand Down
4 changes: 4 additions & 0 deletions src/components/BaseTable/BaseTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {BaseHeaderRowProps} from '../BaseHeaderRow';
import {BaseHeaderRow} from '../BaseHeaderRow';
import type {BaseRowProps} from '../BaseRow';
import {BaseRow} from '../BaseRow';
import {ColumnReorderingContext} from '../ColumnReorderingContext';
import {LastSelectedRowContextProvider} from '../LastSelectedRowContext';
import {SortableListContext} from '../SortableListContext';

Expand Down Expand Up @@ -166,7 +167,9 @@ export const BaseTable = React.forwardRef(
ref: React.Ref<HTMLTableElement>,
) => {
const draggableContext = React.useContext(SortableListContext);
const columnReorderingContext = React.useContext(ColumnReorderingContext);
const draggingRowIndex = draggableContext?.activeItemIndex ?? -1;
const isColumnDragActive = Boolean(columnReorderingContext?.activeColumnId);

const {rows, rowsById} = table.getRowModel();

Expand Down Expand Up @@ -272,6 +275,7 @@ export const BaseTable = React.forwardRef(
ref={ref}
className={b({'with-row-virtualization': Boolean(rowVirtualizer)}, className)}
data-dragging-row-index={draggingRowIndex > -1 ? draggingRowIndex : undefined}
data-column-drag-active={isColumnDragActive || undefined}
aria-colcount={colCount > 0 ? colCount : undefined}
aria-rowcount={rowCount > 0 ? rowCount : undefined}
aria-multiselectable={getAriaMultiselectable(table)}
Expand Down
5 changes: 5 additions & 0 deletions src/components/BaseTable/__stories__/BaseTable.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {ReorderingStory} from './stories/ReorderingStory';
import {ReorderingTreeStory} from './stories/ReorderingTreeStory';
import {ReorderingWithVirtualizationStory} from './stories/ReorderingWithVirtualizationStory';
import {ResizingStory} from './stories/ResizingStory';
import {RowAndColumnReorderingStory} from './stories/RowAndColumnReorderingStory';
import {SortingStory} from './stories/SortingStory';
import {StickyHeaderStory} from './stories/StickyHeaderStory';
import {TreeStory} from './stories/TreeStory';
Expand Down Expand Up @@ -94,6 +95,10 @@ export const ColumnReorderingWithPinning: StoryObj<typeof ColumnReorderingWithPi
render: ColumnReorderingWithPinningStory,
};

export const RowAndColumnReordering: StoryObj<typeof RowAndColumnReorderingStory> = {
render: RowAndColumnReorderingStory,
};

export const Virtualization: StoryObj<typeof VirtualizationStory> = {
render: VirtualizationStory,
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {useSortable} from '@dnd-kit/sortable';
import * as React from 'react';

import type {Row, Table} from '@tanstack/react-table';

import {useDraggableRowDepth} from '../../../../hooks';
import {SortableListContext} from '../../../SortableListContext';

import {TreeNameCell} from './TreeNameCell';

Expand All @@ -16,9 +18,8 @@ export const DraggableTreeNameCell = <TData,>({
table,
value,
}: DraggableTreeNameCellProps<TData>) => {
const {isDragging} = useSortable({
id: row.id,
});
const {useSortable} = React.useContext(SortableListContext) ?? {};
const {isDragging = false} = useSortable?.({id: row.id}) ?? {};

const {depth} = useDraggableRowDepth({row, table, isDragging});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import * as React from 'react';

import {dragHandleColumn} from '../../../../constants';
import {useTable} from '../../../../hooks';
import type {ColumnDef} from '../../../../types/base';
import {ColumnReorderingProvider} from '../../../ColumnReorderingProvider';
import type {ColumnReorderingProviderProps} from '../../../ColumnReorderingProvider';
import type {ReorderingProviderProps} from '../../../ReorderingProvider';
import {ReorderingProvider} from '../../../ReorderingProvider';
import {BaseTable} from '../../BaseTable';
import {columns as originalColumns} from '../constants/columns';
import {data as originalData} from '../constants/data';
import type {Item} from '../types';

const columns: ColumnDef<Item>[] = [dragHandleColumn as ColumnDef<Item>, ...originalColumns];

export const RowAndColumnReorderingStory = () => {
const [data, setData] = React.useState(originalData);
const [columnOrder, setColumnOrder] = React.useState<string[]>([]);

const table = useTable({
columns,
data,
getRowId: (item) => item.id,
enableColumnResizing: true,
columnResizeMode: 'onChange',
state: {columnOrder},
onColumnOrderChange: setColumnOrder,
});

const handleRowReorder = React.useCallback<
NonNullable<ReorderingProviderProps<Item>['onReorder']>
>(({draggedItemKey, baseItemKey}) => {
setData((prevData) => {
const dataClone = prevData.slice();
const index = dataClone.findIndex((item) => item.id === draggedItemKey);

if (index >= 0) {
const dragged = dataClone.splice(index, 1)[0] as Item;
const insertIndex = dataClone.findIndex((item) => item.id === baseItemKey);

if (insertIndex >= 0) {
dataClone.splice(insertIndex + 1, 0, dragged);
} else {
dataClone.unshift(dragged);
}
}

return dataClone;
});
}, []);

const handleColumnReorder = React.useCallback<
NonNullable<ColumnReorderingProviderProps<Item>['onReorder']>
>(({columnOrder: nextColumnOrder}) => {
setColumnOrder(nextColumnOrder);
}, []);

return (
<ColumnReorderingProvider table={table} onReorder={handleColumnReorder}>
<ReorderingProvider table={table} onReorder={handleRowReorder}>
<div style={{maxWidth: 800, overflow: 'auto'}}>
<BaseTable table={table} />
</div>
</ReorderingProvider>
</ColumnReorderingProvider>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import {block} from '../../utils';

export const b = block('column-drag-insertion-indicator');
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
@use '../variables';

$block: '.#{variables.$ns}column-drag-insertion-indicator';

#{$block} {
position: fixed;

pointer-events: none;

z-index: var(--gt-table-reordering-insertion-line-z-index, 2);

width: var(--gt-table-reordering-insertion-line-width, 2px);

background: var(--gt-table-reordering-insertion-line-color, #4d8bff);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import * as React from 'react';

import type {Table} from '@tanstack/react-table';

import {b} from './ColumnDragInsertionIndicator.classname';
import {getInsertionLineSide} from './utils/getInsertionLineSide';
import {measureIndicator} from './utils/measureIndicator';

import './ColumnDragInsertionIndicator.scss';

export interface ColumnDragInsertionIndicatorProps<TData> {
table: Table<TData>;
scopeRef: React.RefObject<HTMLElement>;
activeColumnId: string | null;
targetColumnId: string | null;
}

export function ColumnDragInsertionIndicator<TData>({
table,
scopeRef,
activeColumnId,
targetColumnId,
}: ColumnDragInsertionIndicatorProps<TData>) {
const side =
activeColumnId && targetColumnId
? getInsertionLineSide(table, activeColumnId, targetColumnId)
: null;

const [style, setStyle] = React.useState<React.CSSProperties | null>(null);

React.useLayoutEffect(() => {
if (!side || !targetColumnId) {
setStyle(null);
return;
}

const update = () => {
setStyle(measureIndicator(scopeRef, targetColumnId, side));
};

update();

window.addEventListener('scroll', update, true);
window.addEventListener('resize', update);

return () => {

Check warning on line 46 in src/components/ColumnDragInsertionIndicator/ColumnDragInsertionIndicator.tsx

View workflow job for this annotation

GitHub Actions / Verify Files

Arrow function expected no return value
window.removeEventListener('scroll', update, true);
window.removeEventListener('resize', update);
};
}, [scopeRef, side, targetColumnId]);

if (!style) {
return null;
}

return <div className={b()} style={style} aria-hidden="true" />;
}
2 changes: 2 additions & 0 deletions src/components/ColumnDragInsertionIndicator/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export {ColumnDragInsertionIndicator} from './ColumnDragInsertionIndicator';
export type {ColumnDragInsertionIndicatorProps} from './ColumnDragInsertionIndicator';
1 change: 1 addition & 0 deletions src/components/ColumnDragInsertionIndicator/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type InsertionLineSide = 'left' | 'right';
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type {Table} from '@tanstack/react-table';

import {getColumnGroup} from '../../ColumnReorderingProvider/utils/getColumnGroup';
import type {InsertionLineSide} from '../types';

export function getInsertionLineSide<TData>(
table: Table<TData>,
activeColumnId: string,
targetColumnId: string,
): InsertionLineSide | null {
if (activeColumnId === targetColumnId) {
return null;
}

const group = getColumnGroup(table, activeColumnId);

if (group !== getColumnGroup(table, targetColumnId)) {
return null;
}

const draggedIndex = table.getColumn(activeColumnId)?.getIndex(group) ?? -1;
const targetIndex = table.getColumn(targetColumnId)?.getIndex(group) ?? -1;

if (draggedIndex === -1 || targetIndex === -1) {
return null;
}

return targetIndex > draggedIndex ? 'right' : 'left';
}
Loading
Loading