@cloud-ru/ds-table 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +3 -3
  3. package/dist/cjs/components/Table/Table.js +12 -4
  4. package/dist/cjs/components/Table/hooks/useColumnOrderByDrag/useColumnOrderByDrag.d.ts +2 -0
  5. package/dist/cjs/components/Table/hooks/useColumnOrderByDrag/useColumnOrderByDrag.js +20 -3
  6. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/createColumnsSettingsOption.d.ts +2 -2
  7. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/createColumnsSettingsOption.js +2 -2
  8. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/getColumnSettingsMode.d.ts +8 -0
  9. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/getColumnSettingsMode.js +15 -0
  10. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/index.d.ts +1 -0
  11. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/index.js +1 -0
  12. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/isColumnEnabledInitially.js +3 -4
  13. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/isColumnVisibilityConfigurable.js +3 -15
  14. package/dist/cjs/components/Table/hooks/useColumnSettings/utils/isFilterableColumn.js +4 -2
  15. package/dist/cjs/components/Table/hooks/useTableScroll.js +15 -1
  16. package/dist/cjs/components/Table/styles.module.css +19 -1
  17. package/dist/cjs/components/Table/utils/alignOverlayToHeader.d.ts +6 -0
  18. package/dist/cjs/components/Table/utils/alignOverlayToHeader.js +28 -0
  19. package/dist/cjs/components/Table/utils/index.d.ts +1 -0
  20. package/dist/cjs/components/Table/utils/index.js +1 -0
  21. package/dist/cjs/constants.d.ts +1 -1
  22. package/dist/cjs/constants.js +1 -1
  23. package/dist/cjs/helperComponents/Cells/BodyCell/BodyCell.d.ts +3 -1
  24. package/dist/cjs/helperComponents/Cells/BodyCell/BodyCell.js +9 -10
  25. package/dist/cjs/helperComponents/Cells/HeaderCell/HeaderCell.js +7 -6
  26. package/dist/cjs/helperComponents/Cells/HeaderCell/ResizeHandle.js +1 -1
  27. package/dist/cjs/helperComponents/Cells/styles.module.css +3 -0
  28. package/dist/cjs/helperComponents/Rows/BodyRow.js +1 -2
  29. package/dist/cjs/helperComponents/Rows/styles.module.css +4 -0
  30. package/dist/cjs/helperComponents/TableEmptyState/hooks.js +0 -1
  31. package/dist/cjs/helperComponents/TableEmptyState/styles.module.css +3 -1
  32. package/dist/cjs/hooks/index.d.ts +1 -0
  33. package/dist/cjs/hooks/index.js +1 -0
  34. package/dist/cjs/hooks/useCellSizes.d.ts +0 -1
  35. package/dist/cjs/hooks/useCellSizes.js +1 -4
  36. package/dist/cjs/hooks/useColumnDragTransform.d.ts +15 -0
  37. package/dist/cjs/hooks/useColumnDragTransform.js +38 -0
  38. package/dist/cjs/locale/index.d.ts +0 -4
  39. package/dist/cjs/locale/index.js +0 -2
  40. package/dist/cjs/style.css +29 -2
  41. package/dist/cjs/types.d.ts +1 -0
  42. package/dist/esm/components/Table/Table.js +15 -7
  43. package/dist/esm/components/Table/hooks/useColumnOrderByDrag/useColumnOrderByDrag.d.ts +2 -0
  44. package/dist/esm/components/Table/hooks/useColumnOrderByDrag/useColumnOrderByDrag.js +21 -4
  45. package/dist/esm/components/Table/hooks/useColumnSettings/utils/createColumnsSettingsOption.d.ts +2 -2
  46. package/dist/esm/components/Table/hooks/useColumnSettings/utils/createColumnsSettingsOption.js +2 -2
  47. package/dist/esm/components/Table/hooks/useColumnSettings/utils/getColumnSettingsMode.d.ts +8 -0
  48. package/dist/esm/components/Table/hooks/useColumnSettings/utils/getColumnSettingsMode.js +11 -0
  49. package/dist/esm/components/Table/hooks/useColumnSettings/utils/index.d.ts +1 -0
  50. package/dist/esm/components/Table/hooks/useColumnSettings/utils/index.js +1 -0
  51. package/dist/esm/components/Table/hooks/useColumnSettings/utils/isColumnEnabledInitially.js +3 -4
  52. package/dist/esm/components/Table/hooks/useColumnSettings/utils/isColumnVisibilityConfigurable.js +3 -15
  53. package/dist/esm/components/Table/hooks/useColumnSettings/utils/isFilterableColumn.js +4 -2
  54. package/dist/esm/components/Table/hooks/useTableScroll.js +15 -1
  55. package/dist/esm/components/Table/styles.module.css +19 -1
  56. package/dist/esm/components/Table/utils/alignOverlayToHeader.d.ts +6 -0
  57. package/dist/esm/components/Table/utils/alignOverlayToHeader.js +24 -0
  58. package/dist/esm/components/Table/utils/index.d.ts +1 -0
  59. package/dist/esm/components/Table/utils/index.js +1 -0
  60. package/dist/esm/constants.d.ts +1 -1
  61. package/dist/esm/constants.js +1 -1
  62. package/dist/esm/helperComponents/Cells/BodyCell/BodyCell.d.ts +3 -1
  63. package/dist/esm/helperComponents/Cells/BodyCell/BodyCell.js +10 -11
  64. package/dist/esm/helperComponents/Cells/HeaderCell/HeaderCell.js +7 -6
  65. package/dist/esm/helperComponents/Cells/HeaderCell/ResizeHandle.js +1 -1
  66. package/dist/esm/helperComponents/Cells/styles.module.css +3 -0
  67. package/dist/esm/helperComponents/Rows/BodyRow.js +1 -2
  68. package/dist/esm/helperComponents/Rows/styles.module.css +4 -0
  69. package/dist/esm/helperComponents/TableEmptyState/hooks.js +0 -1
  70. package/dist/esm/helperComponents/TableEmptyState/styles.module.css +3 -1
  71. package/dist/esm/hooks/index.d.ts +1 -0
  72. package/dist/esm/hooks/index.js +1 -0
  73. package/dist/esm/hooks/useCellSizes.d.ts +0 -1
  74. package/dist/esm/hooks/useCellSizes.js +1 -4
  75. package/dist/esm/hooks/useColumnDragTransform.d.ts +15 -0
  76. package/dist/esm/hooks/useColumnDragTransform.js +35 -0
  77. package/dist/esm/locale/index.d.ts +0 -4
  78. package/dist/esm/locale/index.js +0 -2
  79. package/dist/esm/style.css +29 -2
  80. package/dist/esm/types.d.ts +1 -0
  81. package/dist/tsconfig.cjs.tsbuildinfo +1 -1
  82. package/dist/tsconfig.esm.tsbuildinfo +1 -1
  83. package/package.json +12 -11
  84. package/src/components/Table/Table.tsx +53 -26
  85. package/src/components/Table/hooks/useColumnOrderByDrag/useColumnOrderByDrag.ts +31 -7
  86. package/src/components/Table/hooks/useColumnSettings/utils/createColumnsSettingsOption.ts +2 -2
  87. package/src/components/Table/hooks/useColumnSettings/utils/getColumnSettingsMode.ts +18 -0
  88. package/src/components/Table/hooks/useColumnSettings/utils/index.ts +1 -0
  89. package/src/components/Table/hooks/useColumnSettings/utils/isColumnEnabledInitially.ts +3 -5
  90. package/src/components/Table/hooks/useColumnSettings/utils/isColumnVisibilityConfigurable.ts +3 -18
  91. package/src/components/Table/hooks/useColumnSettings/utils/isFilterableColumn.ts +4 -2
  92. package/src/components/Table/hooks/useTableScroll.ts +21 -1
  93. package/src/components/Table/styles.module.scss +23 -1
  94. package/src/components/Table/utils/alignOverlayToHeader.ts +36 -0
  95. package/src/components/Table/utils/index.ts +1 -0
  96. package/src/constants.ts +1 -1
  97. package/src/helperComponents/Cells/BodyCell/BodyCell.tsx +18 -15
  98. package/src/helperComponents/Cells/HeaderCell/HeaderCell.tsx +10 -7
  99. package/src/helperComponents/Cells/HeaderCell/ResizeHandle.tsx +1 -2
  100. package/src/helperComponents/Cells/styles.module.scss +11 -0
  101. package/src/helperComponents/Rows/BodyRow.tsx +9 -10
  102. package/src/helperComponents/Rows/styles.module.scss +5 -0
  103. package/src/helperComponents/TableEmptyState/hooks.ts +0 -1
  104. package/src/helperComponents/TableEmptyState/styles.module.scss +5 -1
  105. package/src/hooks/index.ts +1 -0
  106. package/src/hooks/useCellSizes.ts +1 -5
  107. package/src/hooks/useColumnDragTransform.ts +52 -0
  108. package/src/locale/index.ts +0 -2
  109. package/src/types.ts +3 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud-ru/ds-table",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Таблица данных: клиентская Table, серверная ServerTable и preset-обёртки с упрощённым API.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,23 +50,24 @@
50
50
  "classnames": "^2.5.1",
51
51
  "@cloud-ru/ds-adaptive": "^1.0.0",
52
52
  "@cloud-ru/ds-button": "^1.0.0",
53
- "@cloud-ru/ds-card": "^1.0.1",
53
+ "@cloud-ru/ds-card": "^1.0.2",
54
+ "@cloud-ru/ds-drag-and-drop": "^1.1.0",
54
55
  "@cloud-ru/ds-icons": "^1.0.0",
55
- "@cloud-ru/ds-chips": "^1.0.1",
56
56
  "@cloud-ru/ds-info-block": "^1.0.0",
57
- "@cloud-ru/ds-list": "^1.1.0",
58
- "@cloud-ru/ds-materials": "^1.0.0",
57
+ "@cloud-ru/ds-chips": "^1.0.2",
58
+ "@cloud-ru/ds-list": "^1.1.1",
59
59
  "@cloud-ru/ds-locale": "^1.0.0",
60
60
  "@cloud-ru/ds-pagination": "^1.0.0",
61
- "@cloud-ru/ds-skeleton": "^1.0.0",
62
- "@cloud-ru/ds-theme": "^1.0.0",
61
+ "@cloud-ru/ds-materials": "^1.0.0",
63
62
  "@cloud-ru/ds-scroll": "^1.0.0",
63
+ "@cloud-ru/ds-toggles": "^1.1.0",
64
+ "@cloud-ru/ds-skeleton": "^1.0.0",
64
65
  "@cloud-ru/ds-status": "^1.0.0",
65
- "@cloud-ru/ds-toolbar": "^1.0.2",
66
- "@cloud-ru/ds-utils": "^1.0.0",
67
- "@cloud-ru/ds-toggles": "^1.0.0",
66
+ "@cloud-ru/ds-theme": "^1.0.0",
67
+ "@cloud-ru/ds-toolbar": "^1.0.3",
68
+ "@cloud-ru/ds-tooltip": "^1.0.0",
68
69
  "@cloud-ru/ds-truncate-string": "^1.0.0",
69
- "@cloud-ru/ds-tooltip": "^1.0.0"
70
+ "@cloud-ru/ds-utils": "^1.0.0"
70
71
  },
71
72
  "publishConfig": {
72
73
  "access": "public"
@@ -1,10 +1,12 @@
1
- import { DndContext } from '@dnd-kit/core';
1
+ import { DndContext, DragOverlay } from '@dnd-kit/core';
2
2
  import { isMobileLayout, LayoutPresets, mergePresets, useAdaptiveLayout, useLayoutDefaults } from '@cloud-ru/ds-adaptive';
3
3
  import { FiltersState } from '@cloud-ru/ds-chips';
4
+ import { DragPreview } from '@cloud-ru/ds-drag-and-drop';
4
5
  import { BACKGROUND_PREDEFINED_FILL } from '@cloud-ru/ds-materials';
5
6
  import { useThemeClassnames } from '@cloud-ru/ds-theme';
6
7
  import { ToolbarPersistConfig } from '@cloud-ru/ds-toolbar';
7
8
  import { extractSupportProps } from '@cloud-ru/ds-utils';
9
+ import { flexRender } from '@tanstack/react-table';
8
10
  import cn from 'classnames';
9
11
  import { CSSProperties, ReactNode, Ref, RefObject, useEffect, useMemo } from 'react';
10
12
 
@@ -14,6 +16,7 @@ import {
14
16
  DEFAULT_ROW_SELECTION,
15
17
  DEFAULT_SORTING,
16
18
  DEFAULT_VIEW,
19
+ TABLE_COLUMN_CSS_VARS,
17
20
  VIEW,
18
21
  } from '../../constants';
19
22
  import { CellAutoResizeContext, TableContext, useCellAutoResizeController } from '../../contexts';
@@ -53,7 +56,7 @@ import {
53
56
  } from './hooks';
54
57
  import { isFilterableColumn } from './hooks/useColumnSettings/utils';
55
58
  import styles from './styles.module.scss';
56
- import { getColumnIdentifier, getPinnedGroups } from './utils';
59
+ import { alignOverlayToHeader, getColumnIdentifier, getPinnedGroups } from './utils';
57
60
 
58
61
  const TABLE_CONTENT_ACRYLIC = getControlsAcrylicAttrs(BACKGROUND_PREDEFINED_FILL.NeutralBackground1Level);
59
62
 
@@ -252,11 +255,12 @@ export function Table<TData extends object, TFilters extends FiltersState = Reco
252
255
  }
253
256
  }, [areColumnsSettingsEnabled, enabledColumns, hideableColumnIds, onSortingChange, sorting]);
254
257
 
255
- const { columnOrder, setColumnOrder, dndContextProps, enableColumnsOrderSortByDrag } = useColumnOrderByDrag({
256
- tableColumns: allTableColumns,
257
- savedState,
258
- columnSettings: columnsSettingsProp,
259
- });
258
+ const { columnOrder, setColumnOrder, dndContextProps, enableColumnsOrderSortByDrag, draggingColumnId } =
259
+ useColumnOrderByDrag({
260
+ tableColumns: allTableColumns,
261
+ savedState,
262
+ columnSettings: columnsSettingsProp,
263
+ });
260
264
 
261
265
  const manualPagination = infiniteLoading || manualPaginationProp;
262
266
  const columnsSettings = useMemo(() => getColumnsSettings(columnOrder), [columnOrder, getColumnsSettings]);
@@ -466,6 +470,25 @@ export function Table<TData extends object, TFilters extends FiltersState = Reco
466
470
  showHeader &&
467
471
  (isLoadingState || centerRows.length > 0 || filteredTopRows.length > 0 || (isEmptyBody && !dataError));
468
472
 
473
+ const draggingHeader = draggingColumnId
474
+ ? table.getFlatHeaders().find(header => header.column.id === draggingColumnId)
475
+ : undefined;
476
+
477
+ // Копия колонки едет за курсором в портале: внутри скролла она растила бы его ширину
478
+ // и ныряла под закреплённые колонки.
479
+ const draggingColumnPreview = (
480
+ <DragOverlay dropAnimation={null} modifiers={[alignOverlayToHeader]}>
481
+ {draggingHeader ? (
482
+ <DragPreview
483
+ className={styles.columnDragPreview}
484
+ style={{ width: `var(${TABLE_COLUMN_CSS_VARS.size(draggingHeader.column.id)})` } as CSSProperties}
485
+ >
486
+ {flexRender(draggingHeader.column.columnDef.header, draggingHeader.getContext())}
487
+ </DragPreview>
488
+ ) : null}
489
+ </DragOverlay>
490
+ );
491
+
469
492
  const tableHeaderElement = showTableHeader ? (
470
493
  <HeaderRow
471
494
  rowAutoHeight={rowAutoHeight}
@@ -595,7 +618,7 @@ export function Table<TData extends object, TFilters extends FiltersState = Reco
595
618
  const tableScrollContent = (
596
619
  <div className={styles.body} data-empty-body={isEmptyBody || undefined} style={columnSizes.vars as CSSProperties}>
597
620
  <CellAutoResizeContext.Provider value={{ updateCellMap, removeCellFromMap }}>
598
- <DndContext {...dndContextProps}>{tableScrollRows}</DndContext>
621
+ {tableScrollRows}
599
622
  </CellAutoResizeContext.Provider>
600
623
  </div>
601
624
  );
@@ -603,7 +626,7 @@ export function Table<TData extends object, TFilters extends FiltersState = Reco
603
626
  const tableContentWithProviders = (
604
627
  <div className={styles.body} data-empty-body={isEmptyBody || undefined} style={columnSizes.vars as CSSProperties}>
605
628
  <CellAutoResizeContext.Provider value={{ updateCellMap, removeCellFromMap }}>
606
- <DndContext {...dndContextProps}>{tableBody}</DndContext>
629
+ {tableBody}
607
630
  </CellAutoResizeContext.Provider>
608
631
  </div>
609
632
  );
@@ -724,23 +747,27 @@ export function Table<TData extends object, TFilters extends FiltersState = Reco
724
747
  </div>
725
748
  ) : null}
726
749
 
727
- <TableScrollHost
728
- view={view}
729
- isMobile={isMobile}
730
- isCardsView={isCardsView}
731
- usePageStickyHeader={usePageStickyHeader}
732
- scrollOverflow={scrollOverflow}
733
- scrollPaddingAbsolute={scrollPaddingAbsolute}
734
- internalScrollRef={internalScrollRef}
735
- scrollRef={scrollRef as Ref<HTMLDivElement>}
736
- scrollContainerRef={scrollContainerRef as RefObject<HTMLDivElement>}
737
- handleScrollInitialized={handleScrollInitialized}
738
- syncHeaderHorizontalScroll={syncHeaderHorizontalScroll}
739
- tableHeaderElement={tableHeaderElement}
740
- columnSizeVars={columnSizes.vars as CSSProperties}
741
- >
742
- {scrollContent}
743
- </TableScrollHost>
750
+ {/* Накрывает и шапку, и тело: sticky-шапка рендерится вне скролла. */}
751
+ <DndContext {...dndContextProps}>
752
+ {draggingColumnPreview}
753
+ <TableScrollHost
754
+ view={view}
755
+ isMobile={isMobile}
756
+ isCardsView={isCardsView}
757
+ usePageStickyHeader={usePageStickyHeader}
758
+ scrollOverflow={scrollOverflow}
759
+ scrollPaddingAbsolute={scrollPaddingAbsolute}
760
+ internalScrollRef={internalScrollRef}
761
+ scrollRef={scrollRef as Ref<HTMLDivElement>}
762
+ scrollContainerRef={scrollContainerRef as RefObject<HTMLDivElement>}
763
+ handleScrollInitialized={handleScrollInitialized}
764
+ syncHeaderHorizontalScroll={syncHeaderHorizontalScroll}
765
+ tableHeaderElement={tableHeaderElement}
766
+ columnSizeVars={columnSizes.vars as CSSProperties}
767
+ >
768
+ {scrollContent}
769
+ </TableScrollHost>
770
+ </DndContext>
744
771
  {!isCardsView && outline ? <span className={styles.contentBorder} aria-hidden /> : null}
745
772
  </div>
746
773
 
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  closestCenter,
3
+ CollisionDetection,
3
4
  DndContextProps,
4
5
  DragEndEvent,
5
- KeyboardSensor,
6
+ DragStartEvent,
6
7
  MouseSensor,
7
8
  TouchSensor,
8
9
  useSensor,
@@ -39,8 +40,11 @@ export function useColumnOrderByDrag<TData extends object>({
39
40
  setColumnOrder: Dispatch<SetStateAction<string[]>>;
40
41
  dndContextProps: DndContextProps;
41
42
  enableColumnsOrderSortByDrag: boolean;
43
+ /** Колонка под курсором прямо сейчас: по ней рендерится копия в портале. */
44
+ draggingColumnId?: string;
42
45
  } {
43
46
  const [columnOrder, setColumnOrderState] = useState<string[]>(() => prepareInitialState(tableColumns, savedState));
47
+ const [draggingColumnId, setDraggingColumnId] = useState<string>();
44
48
 
45
49
  useEffect(() => {
46
50
  setColumnOrderState(prev => {
@@ -78,8 +82,18 @@ export function useColumnOrderByDrag<TData extends object>({
78
82
  [columnOrder, savedState],
79
83
  );
80
84
 
85
+ const handleDragStart = useCallback(({ active }: DragStartEvent) => {
86
+ setDraggingColumnId(String(active.id));
87
+ }, []);
88
+
89
+ const handleDragCancel = useCallback(() => {
90
+ setDraggingColumnId(undefined);
91
+ }, []);
92
+
81
93
  const handleDragEnd = useCallback(
82
94
  ({ active, over }: DragEndEvent) => {
95
+ setDraggingColumnId(undefined);
96
+
83
97
  if (!active || !over) {
84
98
  return;
85
99
  }
@@ -105,12 +119,19 @@ export function useColumnOrderByDrag<TData extends object>({
105
119
  [columnOrder, setColumnOrder],
106
120
  );
107
121
 
108
- const sensors = useSensors(
109
- useSensor(MouseSensor, draggingOptions),
110
- useSensor(TouchSensor, {}),
111
- useSensor(KeyboardSensor, {}),
122
+ // `over` вне SortableContext сбрасывает transform'ы всей сортировки — колонка рывком
123
+ // возвращается на место. Держим `over` внутри колонок сортировки.
124
+ const collisionDetection = useCallback<CollisionDetection>(
125
+ args =>
126
+ closestCenter({
127
+ ...args,
128
+ droppableContainers: args.droppableContainers.filter(container => columnOrder.includes(String(container.id))),
129
+ }),
130
+ [columnOrder],
112
131
  );
113
132
 
133
+ const sensors = useSensors(useSensor(MouseSensor, draggingOptions), useSensor(TouchSensor, {}));
134
+
114
135
  const enableColumnsOrderSortByDrag = Boolean(columnSettings?.enableDrag);
115
136
 
116
137
  const dndContextProps = useMemo<DndContextProps>(() => {
@@ -119,17 +140,20 @@ export function useColumnOrderByDrag<TData extends object>({
119
140
  }
120
141
 
121
142
  return {
122
- collisionDetection: closestCenter,
143
+ collisionDetection,
123
144
  modifiers: [restrictToHorizontalAxis],
145
+ onDragStart: handleDragStart,
146
+ onDragCancel: handleDragCancel,
124
147
  onDragEnd: handleDragEnd,
125
148
  sensors,
126
149
  };
127
- }, [enableColumnsOrderSortByDrag, handleDragEnd, sensors]);
150
+ }, [collisionDetection, enableColumnsOrderSortByDrag, handleDragCancel, handleDragEnd, handleDragStart, sensors]);
128
151
 
129
152
  return {
130
153
  columnOrder,
131
154
  setColumnOrder,
132
155
  dndContextProps,
133
156
  enableColumnsOrderSortByDrag,
157
+ draggingColumnId,
134
158
  };
135
159
  }
@@ -10,7 +10,7 @@ const SETTINGS_MENU_EXCLUDED_IDS = new Set<string>([DefaultColumns.Selection, De
10
10
 
11
11
  /**
12
12
  * Колонка попадает в меню настроек: есть id/accessorKey и это не selection/row-actions.
13
- * Включая `mode: locked` и колонки без `columnSettings` (они рендерятся disabled).
13
+ * Включая `mode: locked` (рендерится disabled).
14
14
  */
15
15
  export function isColumnsSettingsMenuItem<TData extends object>(colDef: ColumnDefinition<TData>): boolean {
16
16
  if (!('id' in colDef || 'accessorKey' in colDef)) {
@@ -39,7 +39,7 @@ function getColumnsSettingsOptionLabel<TData extends object>(columnDefinition: C
39
39
  }
40
40
 
41
41
  /**
42
- * Пункт меню настроек колонок. Неактивные (нет `columnSettings` / `mode: locked`) —
42
+ * Пункт меню настроек колонок. Неактивные (`mode: locked` и служебные колонки) —
43
43
  * `disabled` + всегда включённый switch (`checked: true`); драг при этом остаётся
44
44
  * доступным. Видимость через `enabledColumns` не управляется.
45
45
  */
@@ -0,0 +1,18 @@
1
+ import { COLUMN_SETTINGS_MODE, DEFAULT_COLUMNS } from '../../../../../constants';
2
+ import { ColumnDefinition } from '../../../../../types';
3
+
4
+ type ColumnSettingsMode = (typeof COLUMN_SETTINGS_MODE)[keyof typeof COLUMN_SETTINGS_MODE];
5
+
6
+ /** Служебные колонки (`selection` / `rowActions` / `status`) видимостью не управляются. */
7
+ export function isServiceColumn<TData extends object>(colDef: ColumnDefinition<TData>): boolean {
8
+ const id = 'id' in colDef ? colDef.id : undefined;
9
+
10
+ return Boolean(id) && (DEFAULT_COLUMNS as string[]).includes(String(id));
11
+ }
12
+
13
+ /** Режим колонки в меню настроек; без `columnSettings.mode` — `defaultVisible`. */
14
+ export function getColumnSettingsMode<TData extends object>(colDef: ColumnDefinition<TData>): ColumnSettingsMode {
15
+ const mode = 'columnSettings' in colDef ? colDef.columnSettings?.mode : undefined;
16
+
17
+ return mode ?? COLUMN_SETTINGS_MODE.DefaultVisible;
18
+ }
@@ -1,3 +1,4 @@
1
+ export * from './getColumnSettingsMode';
1
2
  export * from './isFilterableColumn';
2
3
  export * from './isColumnEnabledInitially';
3
4
  export * from './isColumnVisibilityConfigurable';
@@ -1,13 +1,11 @@
1
+ import { COLUMN_SETTINGS_MODE } from '../../../../../constants';
1
2
  import { ColumnDefinition } from '../../../../../types';
3
+ import { getColumnSettingsMode } from './getColumnSettingsMode';
2
4
 
3
5
  /**
4
6
  * Проверка на то, должна ли колонка быть включена по умолчанию
5
7
  * @function isColumnEnabledInitially
6
8
  */
7
9
  export function isColumnEnabledInitially<TData extends object>(colDef: ColumnDefinition<TData>): boolean {
8
- if ('columnSettings' in colDef && colDef.columnSettings !== undefined) {
9
- return colDef.columnSettings?.mode !== 'defaultHidden';
10
- }
11
-
12
- return true;
10
+ return getColumnSettingsMode(colDef) !== COLUMN_SETTINGS_MODE.DefaultHidden;
13
11
  }
@@ -1,26 +1,11 @@
1
+ import { COLUMN_SETTINGS_MODE } from '../../../../../constants';
1
2
  import { ColumnDefinition } from '../../../../../types';
3
+ import { getColumnSettingsMode } from './getColumnSettingsMode';
2
4
 
3
5
  /**
4
6
  * Проверка на то, должна ли колонка отображаться в настройках колонок
5
7
  * @function isColumnVisibilityConfigurable
6
8
  */
7
9
  export function isColumnVisibilityConfigurable<TData extends object>(colDef: ColumnDefinition<TData>): boolean {
8
- if ('columnSettings' in colDef && colDef.columnSettings !== undefined) {
9
- const { mode } = colDef.columnSettings;
10
-
11
- if (!mode) {
12
- return true;
13
- }
14
-
15
- switch (mode) {
16
- case 'locked':
17
- return false;
18
- case 'defaultVisible':
19
- case 'defaultHidden':
20
- default:
21
- return true;
22
- }
23
- }
24
-
25
- return true;
10
+ return getColumnSettingsMode(colDef) !== COLUMN_SETTINGS_MODE.Locked;
26
11
  }
@@ -1,4 +1,6 @@
1
+ import { COLUMN_SETTINGS_MODE } from '../../../../../constants';
1
2
  import { ColumnDefinition, FilterableColumnDefinition } from '../../../../../types';
3
+ import { getColumnSettingsMode, isServiceColumn } from './getColumnSettingsMode';
2
4
 
3
5
  /**
4
6
  * Проверка на то, должна ли колонка отображаться в таблице
@@ -9,7 +11,7 @@ export function isFilterableColumn<TData extends object>(
9
11
  ): colDef is FilterableColumnDefinition<TData> {
10
12
  return (
11
13
  ('id' in colDef || 'accessorKey' in colDef) &&
12
- 'columnSettings' in colDef &&
13
- colDef.columnSettings?.mode !== 'locked'
14
+ !isServiceColumn(colDef) &&
15
+ getColumnSettingsMode(colDef) !== COLUMN_SETTINGS_MODE.Locked
14
16
  );
15
17
  }
@@ -67,7 +67,6 @@ export function useTableScroll({
67
67
 
68
68
  if (!usePageStickyHeader) {
69
69
  wrapper?.style.removeProperty(TABLE_CSS_VARS.headerScrollLeft);
70
- wrapper?.style.removeProperty(TABLE_CSS_VARS.viewportWidth);
71
70
 
72
71
  return;
73
72
  }
@@ -86,6 +85,27 @@ export function useTableScroll({
86
85
  return () => observer.disconnect();
87
86
  }, [usePageStickyHeader, isScrollReady, columnSizeVars, syncHeaderHorizontalScroll, view, isLoadingState]);
88
87
 
88
+ // Ширина вьюпорта нужна не только sticky-шапке: по ней центрируется пустое состояние.
89
+ useLayoutEffect(() => {
90
+ const wrapper = wrapperRef.current;
91
+ const viewport = internalScrollRef.current;
92
+
93
+ if (!wrapper || !viewport) {
94
+ return;
95
+ }
96
+
97
+ const syncViewportWidth = () => {
98
+ wrapper.style.setProperty(TABLE_CSS_VARS.viewportWidth, `${viewport.clientWidth}px`);
99
+ };
100
+
101
+ syncViewportWidth();
102
+
103
+ const observer = new ResizeObserver(syncViewportWidth);
104
+ observer.observe(viewport);
105
+
106
+ return () => observer.disconnect();
107
+ }, [isScrollReady, usePageStickyHeader, view, isCardsView, isLoadingState]);
108
+
89
109
  useLayoutEffect(() => {
90
110
  if (!usePageStickyHeader || !showToolbar) {
91
111
  wrapperRef.current?.style.removeProperty(TABLE_CSS_VARS.stickyToolbarOffset);
@@ -334,7 +334,8 @@ $divider-width: base.simple-var(
334
334
  flex-direction: column;
335
335
 
336
336
  width: 100%;
337
- min-width: 0;
337
+ // По колонкам, как и с данными: иначе тело схлопывается до вьюпорта.
338
+ min-width: max-content;
338
339
  min-height: 100%;
339
340
  }
340
341
 
@@ -508,3 +509,24 @@ $divider-width: base.simple-var(
508
509
  width: 100%;
509
510
  max-width: 100%;
510
511
  }
512
+
513
+ // Копия колонки под курсором (DragOverlay + DragPreview): паддинги ячейки шапки.
514
+ // Живёт в портале, вне DOM таблицы, поэтому типографику и цвет заголовка
515
+ // (в сетке они приходят от предков) задаём здесь явно.
516
+ .columnDragPreview {
517
+ display: flex;
518
+ align-items: center;
519
+
520
+ box-sizing: border-box;
521
+ height: base.simple-var(table.$table, 'anatomy', 'content', 'tableCell', 'min-height');
522
+ padding: base.simple-var(table.$table, 'anatomy', 'content', 'tableHead', 'padding-top')
523
+ base.simple-var(table.$table, 'anatomy', 'content', 'tableHead', 'padding-right')
524
+ base.simple-var(table.$table, 'anatomy', 'content', 'tableHead', 'padding-bottom')
525
+ base.simple-var(table.$table, 'anatomy', 'content', 'tableHead', 'padding-left');
526
+ border-radius: table.$sn-table-anatomy-content-borderRadius;
527
+
528
+ color: base.$sn-theme-color-available-version-textTertiary;
529
+ white-space: nowrap;
530
+
531
+ @include base.composite-var(base.$sn-regular-body-m);
532
+ }
@@ -0,0 +1,36 @@
1
+ import { Modifier } from '@dnd-kit/core';
2
+ import { isBrowser } from '@cloud-ru/ds-utils';
3
+
4
+ import { TEST_IDS } from '../../../constants';
5
+
6
+ function getHeaderCellTop(columnId: string): number | undefined {
7
+ if (isBrowser()) {
8
+ const headerCell = document.querySelector(
9
+ `[data-test-id="${TEST_IDS.headerCell}"][data-header-id="${CSS.escape(columnId)}"]`,
10
+ );
11
+
12
+ return headerCell?.getBoundingClientRect().top;
13
+ }
14
+
15
+ return undefined;
16
+ }
17
+
18
+ /**
19
+ * Копию тянет наверх к шапке: `useSortable` вызывают и ячейки тела с тем же id колонки,
20
+ * поэтому dnd-kit считает активным узлом последнюю из них и якорит оверлей по её строке.
21
+ */
22
+ export const alignOverlayToHeader: Modifier = ({ transform, active, activeNodeRect }) => {
23
+ const columnId = active?.id;
24
+
25
+ if (!columnId || !activeNodeRect) {
26
+ return transform;
27
+ }
28
+
29
+ const headerTop = getHeaderCellTop(String(columnId));
30
+
31
+ if (headerTop === undefined) {
32
+ return transform;
33
+ }
34
+
35
+ return { ...transform, y: transform.y + headerTop - activeNodeRect.top };
36
+ };
@@ -1,3 +1,4 @@
1
+ export * from './alignOverlayToHeader';
1
2
  export * from './columnSize';
2
3
  export * from './getColumnIdentifier';
3
4
  export * from './getColumnStyleVars';
package/src/constants.ts CHANGED
@@ -13,7 +13,7 @@ export const COLUMN_ALIGN = {
13
13
  export const COLUMN_SETTINGS_MODE = {
14
14
  /** В меню настроек `Switch` заблокирован, колонка всегда видима */
15
15
  Locked: 'locked',
16
- /** В меню, по умолчанию включена */
16
+ /** В меню, по умолчанию включена. Режим по умолчанию для любой колонки */
17
17
  DefaultVisible: 'defaultVisible',
18
18
  /** В меню, по умолчанию выключена */
19
19
  DefaultHidden: 'defaultHidden',
@@ -1,11 +1,10 @@
1
- import { useSortable } from '@dnd-kit/sortable';
2
1
  import { Cell as TableCell, flexRender } from '@tanstack/react-table';
3
2
  import cn from 'classnames';
4
3
  import { CSSProperties } from 'react';
5
4
 
6
5
  import { TEST_IDS } from '../../../constants';
7
- import { useCellSizes } from '../../../hooks';
8
- import { ColumnDefinition } from '../../../types';
6
+ import { useCellSizes, useColumnDragTransform } from '../../../hooks';
7
+ import { ColumnDefinition, ColumnOrder } from '../../../types';
9
8
  import { Cell, CellProps } from '../Cell';
10
9
  import styles from './styles.module.scss';
11
10
 
@@ -13,18 +12,19 @@ type BodyCellProps<TData> = Omit<CellProps, 'style' | 'children'> & {
13
12
  cell: TableCell<TData, unknown>;
14
13
  rowAutoHeight?: boolean;
15
14
  isDraggable?: boolean;
15
+ columnOrder?: ColumnOrder;
16
16
  };
17
17
 
18
- type BodyCellViewProps<TData> = Omit<BodyCellProps<TData>, 'isDraggable'> & {
18
+ type BodyCellViewProps<TData> = Omit<BodyCellProps<TData>, 'isDraggable' | 'columnOrder'> & {
19
19
  style: CSSProperties;
20
- setNodeRef?: (node: HTMLDivElement | null) => void;
20
+ isDragging?: boolean;
21
21
  };
22
22
  function BodyCellView<TData>({
23
23
  cell,
24
24
  className,
25
25
  rowAutoHeight,
26
26
  style,
27
- setNodeRef,
27
+ isDragging,
28
28
  ...props
29
29
  }: BodyCellViewProps<TData>) {
30
30
  const columnDef = cell.column.columnDef as ColumnDefinition<TData>;
@@ -32,13 +32,13 @@ function BodyCellView<TData>({
32
32
  return (
33
33
  <Cell
34
34
  {...props}
35
- ref={setNodeRef}
36
35
  style={style}
37
36
  className={cn(styles.tableBodyCell, className, columnDef.cellClassName)}
38
37
  data-row-auto-height={rowAutoHeight || undefined}
39
38
  data-align={columnDef.align}
40
39
  data-no-padding={columnDef.noBodyCellPadding || undefined}
41
40
  data-column-id={cell.column.id}
41
+ data-dragging={isDragging || undefined}
42
42
  data-test-id={TEST_IDS.bodyCell}
43
43
  >
44
44
  {flexRender(columnDef.cell, cell.getContext())}
@@ -46,22 +46,25 @@ function BodyCellView<TData>({
46
46
  );
47
47
  }
48
48
 
49
- function StaticBodyCell<TData>(props: Omit<BodyCellProps<TData>, 'isDraggable'>) {
49
+ function StaticBodyCell<TData>(props: Omit<BodyCellProps<TData>, 'isDraggable' | 'columnOrder'>) {
50
50
  const style = useCellSizes(props.cell);
51
51
 
52
52
  return <BodyCellView {...props} style={style} />;
53
53
  }
54
54
 
55
- function DraggableBodyCell<TData>(props: Omit<BodyCellProps<TData>, 'isDraggable'>) {
56
- const { setNodeRef, isDragging, transform } = useSortable({ id: props.cell.column.id });
57
- const style = useCellSizes(props.cell, { isDraggable: true, isDragging, transform });
55
+ function DraggableBodyCell<TData>({
56
+ columnOrder,
57
+ ...props
58
+ }: Omit<BodyCellProps<TData>, 'isDraggable'> & { columnOrder: ColumnOrder }) {
59
+ const { transform, isDragging } = useColumnDragTransform(props.cell.column.id, columnOrder);
60
+ const style = useCellSizes(props.cell, { isDraggable: true, transform });
58
61
 
59
- return <BodyCellView {...props} style={style} setNodeRef={setNodeRef} />;
62
+ return <BodyCellView {...props} style={style} isDragging={isDragging} />;
60
63
  }
61
64
 
62
- export function BodyCell<TData>({ isDraggable, ...props }: BodyCellProps<TData>) {
63
- if (isDraggable) {
64
- return <DraggableBodyCell {...props} />;
65
+ export function BodyCell<TData>({ isDraggable, columnOrder, ...props }: BodyCellProps<TData>) {
66
+ if (isDraggable && columnOrder) {
67
+ return <DraggableBodyCell {...props} columnOrder={columnOrder} />;
65
68
  }
66
69
 
67
70
  return <StaticBodyCell {...props} />;
@@ -1,4 +1,5 @@
1
1
  import { useSortable } from '@dnd-kit/sortable';
2
+ import { DRAG_MODE, DragGhost } from '@cloud-ru/ds-drag-and-drop';
2
3
  import { TruncateString } from '@cloud-ru/ds-truncate-string';
3
4
  import { flexRender, Header } from '@tanstack/react-table';
4
5
  import cn from 'classnames';
@@ -35,8 +36,8 @@ export function HeaderCell<TData>({
35
36
  const columnSizingInfo = header.getContext().table.getState().columnSizingInfo;
36
37
  const isSomeColumnResizing = columnSizingInfo.isResizingColumn;
37
38
  const columnDef = header.column.columnDef as ColumnDefinition<TData>;
38
- const { attributes, listeners, setNodeRef, isDragging, transform } = useSortable({ id: header.column.id });
39
- const style = useCellSizes(header, { isDraggable, isDragging, transform });
39
+ const { listeners, setNodeRef, isDragging, transform } = useSortable({ id: header.column.id });
40
+ const style = useCellSizes(header, { isDraggable, transform });
40
41
 
41
42
  const sortingHandler = (e: MouseEvent) => {
42
43
  if (isSomeColumnResizing) return;
@@ -51,8 +52,8 @@ export function HeaderCell<TData>({
51
52
  return {};
52
53
  }
53
54
 
54
- return { ...attributes, ...listeners };
55
- }, [attributes, header.column.id, isDraggable, listeners]);
55
+ return listeners;
56
+ }, [header.column.id, isDraggable, listeners]);
56
57
 
57
58
  return (
58
59
  <Cell
@@ -65,6 +66,7 @@ export function HeaderCell<TData>({
65
66
  data-test-id={TEST_IDS.headerCell}
66
67
  data-header-id={header.id}
67
68
  data-resizing={isResizing || undefined}
69
+ data-dragging={(isDraggable && isDragging) || undefined}
68
70
  data-pin-position={pinPosition || undefined}
69
71
  data-row-auto-height={rowAutoHeight || undefined}
70
72
  role='columnheader'
@@ -77,9 +79,10 @@ export function HeaderCell<TData>({
77
79
  cellRef.current = element;
78
80
  }}
79
81
  >
80
- <div
82
+ <DragGhost
83
+ dragging={isDraggable && isDragging}
84
+ mode={DRAG_MODE.Dynamic}
81
85
  className={styles.tableHeaderCellDragWrapper}
82
- data-dragging={(isDraggable && isDragging) || undefined}
83
86
  {...draggableProps}
84
87
  >
85
88
  <div className={styles.tableHeaderCellMain} data-align={columnDef.headerAlign || undefined}>
@@ -102,7 +105,7 @@ export function HeaderCell<TData>({
102
105
  </div>
103
106
  )}
104
107
  </div>
105
- </div>
108
+ </DragGhost>
106
109
  {Boolean(isResizable) && <ResizeHandle header={header} cellRef={cellRef} />}
107
110
  </Cell>
108
111
  );
@@ -53,8 +53,7 @@ export function ResizeHandle<TData>({ header, cellRef }: ResizeHandleProps<TData
53
53
  return (
54
54
  <>
55
55
  <div
56
- role='button'
57
- tabIndex={0}
56
+ aria-hidden
58
57
  className={cn(styles.tableHeaderIcon, styles.tableHeaderResizeHandle)}
59
58
  data-resizing={isResizing || undefined}
60
59
  onMouseDown={handleMouseDown}