@linzjs/step-ag-grid 35.0.3 → 35.2.0

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 (42) hide show
  1. package/dist/index.css +17 -0
  2. package/dist/src/components/Grid.d.ts +5 -1
  3. package/dist/src/components/GridRangeSelectContextMenu.d.ts +12 -1
  4. package/dist/src/components/gridFilter/GridFilterCopyButton.d.ts +9 -0
  5. package/dist/src/components/gridFilter/index.d.ts +1 -0
  6. package/dist/src/components/gridHook/copyGridCells.d.ts +19 -0
  7. package/dist/src/components/gridHook/copyGridCells.test.d.ts +1 -0
  8. package/dist/src/components/gridHook/useGridColumnStateStorage.d.ts +26 -0
  9. package/dist/src/components/gridHook/useGridColumnStateStorage.test.d.ts +1 -0
  10. package/dist/src/components/gridHook/useGridCopy.d.ts +5 -2
  11. package/dist/src/components/gridHook/useGridCopySettings.d.ts +2 -0
  12. package/dist/src/contexts/GridContext.d.ts +35 -0
  13. package/dist/src/contexts/GridContextProvider.copy.test.d.ts +1 -0
  14. package/dist/src/utils/storageKeySync.d.ts +6 -0
  15. package/dist/src/utils/storageKeySync.test.d.ts +1 -0
  16. package/dist/step-ag-grid.cjs +601 -265
  17. package/dist/step-ag-grid.cjs.map +1 -1
  18. package/dist/step-ag-grid.esm.js +602 -267
  19. package/dist/step-ag-grid.esm.js.map +1 -1
  20. package/package.json +1 -1
  21. package/src/components/Grid.tsx +69 -27
  22. package/src/components/GridRangeSelectContextMenu.tsx +54 -51
  23. package/src/components/gridFilter/GridFilterColumnsToggle.tsx +45 -12
  24. package/src/components/gridFilter/GridFilterCopyButton.tsx +93 -0
  25. package/src/components/gridFilter/index.ts +1 -0
  26. package/src/components/gridHook/copyGridCells.test.ts +142 -0
  27. package/src/components/gridHook/copyGridCells.ts +225 -0
  28. package/src/components/gridHook/useGridColumnStateStorage.test.tsx +127 -0
  29. package/src/components/gridHook/useGridColumnStateStorage.ts +114 -0
  30. package/src/components/gridHook/useGridCopy.ts +88 -211
  31. package/src/components/gridHook/useGridCopySettings.ts +21 -6
  32. package/src/contexts/GridContext.tsx +44 -0
  33. package/src/contexts/GridContextProvider.copy.test.tsx +158 -0
  34. package/src/contexts/GridContextProvider.tsx +129 -2
  35. package/src/stories/grid/GridColumnState.stories.tsx +161 -0
  36. package/src/stories/grid/GridCopy.stories.tsx +35 -20
  37. package/src/stories/grid/GridCopyEditable.stories.tsx +131 -0
  38. package/src/stories/grid/GridCopyMultiple.stories.tsx +119 -0
  39. package/src/styles/GridFilterCopyButton.scss +22 -0
  40. package/src/styles/index.scss +1 -0
  41. package/src/utils/storageKeySync.test.ts +48 -0
  42. package/src/utils/storageKeySync.ts +24 -0
@@ -1,3 +1,4 @@
1
+ import { useShowLUIMessage } from '@linzjs/lui';
1
2
  import {
2
3
  CellPosition,
3
4
  ColDef,
@@ -10,16 +11,39 @@ import {
10
11
  RowNode,
11
12
  } from 'ag-grid-community';
12
13
  import debounce from 'debounce-promise';
13
- import { compact, defer, delay, difference, filter, isEmpty, last, pull, remove, sortBy, sumBy } from 'lodash-es';
14
+ import {
15
+ compact,
16
+ defer,
17
+ delay,
18
+ difference,
19
+ filter,
20
+ get,
21
+ isEmpty,
22
+ last,
23
+ pull,
24
+ remove,
25
+ set,
26
+ sortBy,
27
+ sumBy,
28
+ } from 'lodash-es';
14
29
  import { PropsWithChildren, ReactElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
15
30
 
16
31
  import { agGridSelectRowColId, ColDefT, GridBaseRow } from '../components';
17
32
  import { GridCellFillerColId, isGridCellFiller } from '../components/GridCellFiller';
33
+ import { copyGridCells, isCopyableColId } from '../components/gridHook/copyGridCells';
34
+ import { CopyOptionsKey, getDefaultCopyType } from '../components/gridHook/useGridCopySettings';
18
35
  import { getColId, isFlexColumn } from '../components/gridUtil';
19
36
  import { isChromatic } from '../utils/isChromatic';
20
37
  import { fnOrVar, isNotEmpty, sanitiseFileName, wait } from '../utils/util';
21
38
  import { waitForCondition } from '../utils/waitForCondition';
22
- import { AutoSizeColumnsProps, AutoSizeColumnsResult, GridContext, GridFilterExternal } from './GridContext';
39
+ import {
40
+ AutoSizeColumnsProps,
41
+ AutoSizeColumnsResult,
42
+ GridContext,
43
+ GridCopyScope,
44
+ GridFilterExternal,
45
+ GridRangeCopy,
46
+ } from './GridContext';
23
47
  import { GridUpdatingContext } from './GridUpdatingContext';
24
48
 
25
49
  export const colStateId = (colState: ColumnState) => colState.colId;
@@ -33,10 +57,12 @@ export const colStateNotFlexed = (colState: ColumnState) => !colState.flex;
33
57
  */
34
58
  export const GridContextProvider = <TData extends GridBaseRow>(props: PropsWithChildren): ReactElement => {
35
59
  const { modifyUpdating, anyUpdating } = useContext(GridUpdatingContext);
60
+ const showToast = useShowLUIMessage();
36
61
  const [gridApi, setGridApi] = useState<GridApi>();
37
62
  const [gridReady, setGridReady] = useState(false);
38
63
  const [quickFilter, _setQuickFilter] = useState('');
39
64
  const [invisibleColumnIds, _setInvisibleColumnIds] = useState<string[]>();
65
+ const [copyEnabled, setCopyEnabled] = useState(false);
40
66
  const testId = useRef<string>(undefined);
41
67
  const hasExternallySelectedItemsRef = useRef(false);
42
68
  const enableMultilineBulkEditRef = useRef(false);
@@ -929,6 +955,100 @@ export const GridContextProvider = <TData extends GridBaseRow>(props: PropsWithC
929
955
  [gridApi],
930
956
  );
931
957
 
958
+ const rangeCopyRef = useRef<GridRangeCopy>(undefined);
959
+ const setRangeCopy = useCallback((rangeCopy: GridRangeCopy | undefined) => {
960
+ rangeCopyRef.current = rangeCopy;
961
+ }, []);
962
+
963
+ /**
964
+ * Rows to copy when no range is selected: the selected rows, or all rows if none are selected.
965
+ * Rows are in filtered and sorted order.
966
+ */
967
+ const getCopyRows = useCallback((): { scope: GridCopyScope; nodes: IRowNode[] } => {
968
+ const nodes: IRowNode[] = [];
969
+ if (gridApi && !gridApi.isDestroyed()) {
970
+ gridApi.forEachNodeAfterFilterAndSort((node) => {
971
+ if (node.data && !node.group) nodes.push(node);
972
+ });
973
+ }
974
+ const selectedNodes = nodes.filter((node) => node.isSelected());
975
+ return isEmpty(selectedNodes) ? { scope: 'all', nodes } : { scope: 'selection', nodes: selectedNodes };
976
+ }, [gridApi]);
977
+
978
+ /** Displayed columns, excluding the row select column */
979
+ const getDisplayedCopyColIds = useCallback(
980
+ (): string[] =>
981
+ gridApi && !gridApi.isDestroyed()
982
+ ? gridApi
983
+ .getAllDisplayedColumns()
984
+ .map((col) => col.getColId())
985
+ .filter((colId) => colId !== agGridSelectRowColId)
986
+ : [],
987
+ [gridApi],
988
+ );
989
+
990
+ /**
991
+ * Columns and rows that copyToClipboard would copy.
992
+ * Excludes the row select, filler and non-exportable columns.
993
+ */
994
+ const getCopyTarget = useCallback((): { colIds: string[]; nodes: IRowNode[] } => {
995
+ const rangeCopy = rangeCopyRef.current;
996
+ const { selectedColIds, selectedNodes } = rangeCopy?.hasRange()
997
+ ? rangeCopy.getRange()
998
+ : { selectedColIds: getDisplayedCopyColIds(), selectedNodes: getCopyRows().nodes };
999
+ return {
1000
+ colIds: selectedColIds.filter((colId) => colId !== agGridSelectRowColId && isCopyableColId(colId, getColDef)),
1001
+ nodes: selectedNodes,
1002
+ };
1003
+ }, [getColDef, getCopyRows, getDisplayedCopyColIds]);
1004
+
1005
+ const getSelectedDataForCopy = useCallback((): Partial<TData>[] => {
1006
+ const { colIds, nodes } = getCopyTarget();
1007
+ const fields = compact(colIds.map((colId) => getColDef(colId)?.field));
1008
+ return nodes.map((node) => {
1009
+ const data: Partial<TData> = {};
1010
+ fields.forEach((field) => set(data, field, get(node.data, field)));
1011
+ return data;
1012
+ });
1013
+ }, [getColDef, getCopyTarget]);
1014
+
1015
+ const getCopyData = useCallback((): Record<string, unknown>[] => {
1016
+ const { colIds, nodes } = getCopyTarget();
1017
+ return nodes.map((rowNode) =>
1018
+ Object.fromEntries(colIds.map((colKey) => [colKey, gridApi?.getCellValue({ rowNode, colKey })])),
1019
+ );
1020
+ }, [getCopyTarget, gridApi]);
1021
+
1022
+ const getCopyScope = useCallback(
1023
+ (): GridCopyScope => (rangeCopyRef.current?.hasRange() ? 'range' : getCopyRows().scope),
1024
+ [getCopyRows],
1025
+ );
1026
+
1027
+ /**
1028
+ * Copy the selected range if one is selected,
1029
+ * otherwise all displayed columns of the selected rows, or all rows if none are selected.
1030
+ */
1031
+ const copyToClipboard = useCallback(
1032
+ (type: CopyOptionsKey = getDefaultCopyType()) => {
1033
+ if (rangeCopyRef.current?.hasRange()) {
1034
+ rangeCopyRef.current.copy(type);
1035
+ return;
1036
+ }
1037
+ if (!gridApi || gridApi.isDestroyed()) return;
1038
+
1039
+ copyGridCells({
1040
+ type,
1041
+ selectedColIds: getDisplayedCopyColIds(),
1042
+ selectedNodes: getCopyRows().nodes,
1043
+ selectedRowIds: getSelectedRowIds(),
1044
+ getColDef,
1045
+ getCellValue,
1046
+ showToast,
1047
+ });
1048
+ },
1049
+ [getCellValue, getColDef, getCopyRows, getDisplayedCopyColIds, getSelectedRowIds, gridApi, showToast],
1050
+ );
1051
+
932
1052
  return (
933
1053
  <GridContext.Provider
934
1054
  value={{
@@ -972,6 +1092,13 @@ export const GridContextProvider = <TData extends GridBaseRow>(props: PropsWithC
972
1092
  isExternalFilterPresent,
973
1093
  doesExternalFilterPass,
974
1094
  downloadCsv,
1095
+ copyToClipboard,
1096
+ getCopyScope,
1097
+ getSelectedDataForCopy,
1098
+ getCopyData,
1099
+ setRangeCopy,
1100
+ copyEnabled,
1101
+ setCopyEnabled,
975
1102
  onBulkEditingComplete,
976
1103
  setOnBulkEditingComplete,
977
1104
  showNoRowsOverlay,
@@ -0,0 +1,161 @@
1
+ import { Meta, StoryObj } from '@storybook/react-vite';
2
+ import { ReactElement, useState } from 'react';
3
+ import { expect, userEvent, waitFor, within } from 'storybook/test';
4
+
5
+ import {
6
+ ColDefT,
7
+ Grid,
8
+ GridCell,
9
+ GridContextProvider,
10
+ GridFilters,
11
+ GridUpdatingContextProvider,
12
+ GridWrapper,
13
+ } from '../..';
14
+ import { GridFilterColumnsToggle } from '../../components';
15
+ import { clickColumnHeaderToSort, waitForGridRows } from '../../utils/__tests__/storybookTestUtil';
16
+
17
+ interface ITestRow {
18
+ id: number;
19
+ name: string;
20
+ description: string;
21
+ }
22
+
23
+ const columnDefs: ColDefT<ITestRow>[] = [
24
+ GridCell<ITestRow, ITestRow['id']>({ field: 'id', headerName: 'Id' }),
25
+ GridCell<ITestRow, ITestRow['name']>({ field: 'name', headerName: 'Name' }),
26
+ GridCell<ITestRow, ITestRow['description']>({ field: 'description', headerName: 'Description', flex: 1 }),
27
+ ];
28
+
29
+ const tabs: { label: string; rowData: ITestRow[] }[] = [
30
+ {
31
+ label: 'First tab',
32
+ rowData: [
33
+ { id: 1, name: 'Charlie', description: 'First tab row' },
34
+ { id: 2, name: 'Alpha', description: 'First tab row' },
35
+ ],
36
+ },
37
+ {
38
+ label: 'Second tab',
39
+ rowData: [
40
+ { id: 3, name: 'Bravo', description: 'Second tab row' },
41
+ { id: 4, name: 'Delta', description: 'Second tab row' },
42
+ ],
43
+ },
44
+ ];
45
+
46
+ const TabbedGrids = (): ReactElement => {
47
+ const [activeTab, setActiveTab] = useState(tabs[0].label);
48
+ return (
49
+ <>
50
+ <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
51
+ {tabs.map((tab) => (
52
+ <button
53
+ key={tab.label}
54
+ role="tab"
55
+ aria-selected={tab.label === activeTab}
56
+ onClick={() => setActiveTab(tab.label)}
57
+ >
58
+ {tab.label}
59
+ </button>
60
+ ))}
61
+ </div>
62
+ {tabs.map((tab) => (
63
+ <div
64
+ key={tab.label}
65
+ role="tabpanel"
66
+ aria-label={tab.label}
67
+ style={{ display: tab.label === activeTab ? 'flex' : 'none', flexDirection: 'column', flex: 1 }}
68
+ >
69
+ <GridUpdatingContextProvider>
70
+ <GridContextProvider>
71
+ <GridWrapper maxHeight={300}>
72
+ <GridFilters>
73
+ <GridFilterColumnsToggle />
74
+ </GridFilters>
75
+ <Grid data-testid={tab.label} columnDefs={columnDefs} rowData={tab.rowData} saveColumnState={true} />
76
+ </GridWrapper>
77
+ </GridContextProvider>
78
+ </GridUpdatingContextProvider>
79
+ </div>
80
+ ))}
81
+ </>
82
+ );
83
+ };
84
+
85
+ const meta: Meta<typeof TabbedGrids> = {
86
+ title: 'Components / Grids',
87
+ component: TabbedGrids,
88
+ beforeEach: () => {
89
+ Object.keys(window.localStorage)
90
+ .filter((key) => key.startsWith('stepAgGrid_columnState_') || key.startsWith('stepAgGrid_invisibleColumnIds_'))
91
+ .forEach((key) => window.localStorage.removeItem(key));
92
+ },
93
+ decorators: [
94
+ (Story) => (
95
+ <div style={{ width: 1024, height: 400, display: 'flex', flexDirection: 'column' }}>
96
+ <Story />
97
+ </div>
98
+ ),
99
+ ],
100
+ };
101
+ export default meta;
102
+
103
+ type Story = StoryObj<typeof meta>;
104
+
105
+ const panel = (canvasElement: HTMLElement, label: string) =>
106
+ within(canvasElement).getByRole('tabpanel', { name: label });
107
+ const headerCell = (canvasElement: HTMLElement, label: string, colId: string) =>
108
+ panel(canvasElement, label).querySelector<HTMLElement>(`.ag-header-cell[col-id="${colId}"]`)!;
109
+ const showTab = (canvasElement: HTMLElement, label: string) =>
110
+ userEvent.click(within(canvasElement).getByRole('tab', { name: label }));
111
+
112
+ export const GridColumnStateSharedBetweenTabs: Story = {
113
+ play: async ({ canvasElement }) => {
114
+ await waitForGridRows({ grid: panel(canvasElement, 'First tab') });
115
+
116
+ await clickColumnHeaderToSort('name', panel(canvasElement, 'First tab'));
117
+ await showTab(canvasElement, 'Second tab');
118
+ await waitFor(() =>
119
+ expect(headerCell(canvasElement, 'Second tab', 'name')).toHaveAttribute('aria-sort', 'ascending'),
120
+ );
121
+
122
+ const nameHeader = headerCell(canvasElement, 'Second tab', 'name');
123
+ const widthBefore = nameHeader.getBoundingClientRect().width;
124
+ const handle = nameHeader.querySelector<HTMLElement>('.ag-header-cell-resize')!;
125
+ const { left, top, width, height } = handle.getBoundingClientRect();
126
+ const start = { clientX: left + width / 2, clientY: top + height / 2 };
127
+ await userEvent.pointer([
128
+ { keys: '[MouseLeft>]', target: handle, coords: start },
129
+ { target: handle, coords: { ...start, clientX: start.clientX + 60 } },
130
+ { target: handle, coords: { ...start, clientX: start.clientX + 120 } },
131
+ { keys: '[/MouseLeft]', target: handle, coords: { ...start, clientX: start.clientX + 120 } },
132
+ ]);
133
+ await waitFor(() => expect(nameHeader.getBoundingClientRect().width).toBeGreaterThan(widthBefore + 60));
134
+ const resizedWidth = Math.round(nameHeader.getBoundingClientRect().width);
135
+
136
+ await showTab(canvasElement, 'First tab');
137
+ await waitFor(() =>
138
+ expect(Math.round(headerCell(canvasElement, 'First tab', 'name').getBoundingClientRect().width)).toBe(
139
+ resizedWidth,
140
+ ),
141
+ );
142
+ },
143
+ };
144
+
145
+ export const GridColumnVisibilitySharedBetweenTabs: Story = {
146
+ play: async ({ canvasElement }) => {
147
+ await waitForGridRows({ grid: panel(canvasElement, 'First tab') });
148
+ await showTab(canvasElement, 'Second tab');
149
+ await waitForGridRows({ grid: panel(canvasElement, 'Second tab') });
150
+ await showTab(canvasElement, 'First tab');
151
+
152
+ await userEvent.click(within(panel(canvasElement, 'First tab')).getByTitle('Column visibility'));
153
+ const menuItems = await within(document.body).findAllByRole('menuitem');
154
+ await userEvent.click(menuItems.find((item) => item.textContent === 'Name')!);
155
+ await userEvent.keyboard('{Escape}');
156
+ await waitFor(() => expect(headerCell(canvasElement, 'First tab', 'name')).toBeNull());
157
+
158
+ await showTab(canvasElement, 'Second tab');
159
+ await waitFor(() => expect(headerCell(canvasElement, 'Second tab', 'name')).toBeNull());
160
+ },
161
+ };
@@ -15,7 +15,7 @@ import {
15
15
  GridUpdatingContextProvider,
16
16
  GridWrapper,
17
17
  } from '../..';
18
- import { GridFilterColumnsToggle, GridFilterDownloadCsvButton } from '../../components';
18
+ import { GridFilterColumnsToggle, GridFilterCopyButton, GridFilterDownloadCsvButton } from '../../components';
19
19
  import { GridCellFiller } from '../../components/GridCellFiller';
20
20
  import { SeededRandomForTests } from '../../utils/__tests__/random';
21
21
  import { waitForGridReady } from '../../utils/__tests__/storybookTestUtil';
@@ -102,25 +102,40 @@ const GridCopyTemplate: StoryFn<typeof Grid<ITestRow>> = (props: GridProps<ITest
102
102
  });
103
103
 
104
104
  return (
105
- <GridWrapper>
106
- <GridFilters>
107
- <GridFilterQuick />
108
- <GridFilterColumnsToggle />
109
- <GridFilterDownloadCsvButton fileName={'readOnlyGrid'} />
110
- </GridFilters>
111
- <Grid
112
- data-testid={'readonly'}
113
- {...props}
114
- enableRangeSelection={true}
115
- selectable={true}
116
- enableSelectionWithoutKeys={true}
117
- autoSelectFirstRow={true}
118
- externalSelectedIds={externalSelectedIds}
119
- setExternalSelectedIds={setExternalSelectedIds}
120
- columnDefs={columnDefs}
121
- rowData={rowData}
122
- />
123
- </GridWrapper>
105
+ <>
106
+ <div style={{ fontSize: 14, marginBottom: 8 }}>
107
+ <p style={{ margin: 0 }}>
108
+ Test copying outside the grid. Drag a range, click this text and press ctrl+c to copy the range. Select some
109
+ of this text and press ctrl+c to copy the text instead. Paste below to check.
110
+ </p>
111
+ <textarea
112
+ aria-label={'Paste here'}
113
+ placeholder={'Paste here to see what was copied'}
114
+ style={{ width: '100%', height: 60, marginTop: 8, fontFamily: 'monospace' }}
115
+ />
116
+ </div>
117
+ <GridWrapper>
118
+ <GridFilters>
119
+ <GridFilterQuick />
120
+ <GridFilterColumnsToggle />
121
+ <GridFilterDownloadCsvButton fileName={'readOnlyGrid'} />
122
+ <GridFilterCopyButton />
123
+ </GridFilters>
124
+ <Grid
125
+ data-testid={'readonly'}
126
+ {...props}
127
+ enableRangeSelection={true}
128
+ enableCopy={true}
129
+ selectable={true}
130
+ enableSelectionWithoutKeys={true}
131
+ autoSelectFirstRow={true}
132
+ externalSelectedIds={externalSelectedIds}
133
+ setExternalSelectedIds={setExternalSelectedIds}
134
+ columnDefs={columnDefs}
135
+ rowData={rowData}
136
+ />
137
+ </GridWrapper>
138
+ </>
124
139
  );
125
140
  };
126
141
 
@@ -0,0 +1,131 @@
1
+ import { LuiMessagingContextProvider } from '@linzjs/lui';
2
+ import { Meta, StoryFn, StoryObj } from '@storybook/react-vite';
3
+ import { useMemo, useState } from 'react';
4
+
5
+ import {
6
+ ColDefT,
7
+ Grid,
8
+ GridCell,
9
+ GridContextProvider,
10
+ GridFilters,
11
+ GridInlineTextInput,
12
+ GridPopoverEditDropDown,
13
+ GridUpdatingContextProvider,
14
+ GridWrapper,
15
+ primitiveToSelectOption,
16
+ } from '../..';
17
+ import { GridFilterCopyButton } from '../../components';
18
+ import { GridCellFiller } from '../../components/GridCellFiller';
19
+ import { waitForGridReady } from '../../utils/__tests__/storybookTestUtil';
20
+
21
+ interface ITestRow {
22
+ id: number;
23
+ name: string | null;
24
+ position: string | null;
25
+ }
26
+
27
+ const positions = ['Architect', 'Developer', 'Product Owner', 'Scrum Master', 'Tester'];
28
+
29
+ const initialRows: ITestRow[] = Array.from({ length: 20 }, (_, i) => ({
30
+ id: 1000 + i,
31
+ name: `Name ${i + 1}`,
32
+ position: positions[i % positions.length],
33
+ }));
34
+
35
+ const EditableCopyGrid = ({ title, singleClickEdit }: { title: string; singleClickEdit: boolean }) => {
36
+ const [externalSelectedIds, setExternalSelectedIds] = useState<number[]>([]);
37
+ const [rowData, setRowData] = useState<ITestRow[]>(initialRows);
38
+
39
+ const columnDefs: ColDefT<ITestRow>[] = useMemo(
40
+ () => [
41
+ GridCell({ field: 'id', headerName: 'Id', lockVisible: true }),
42
+ GridInlineTextInput<ITestRow>(
43
+ { field: 'name', headerName: 'Name (inline text)' },
44
+ {
45
+ editorParams: {
46
+ onSave: ({ selectedRowIds, value }) => {
47
+ setRowData((current) =>
48
+ current.map((row) => (selectedRowIds.includes(row.id) ? { ...row, name: value } : row)),
49
+ );
50
+ return true;
51
+ },
52
+ },
53
+ },
54
+ ),
55
+ GridPopoverEditDropDown<ITestRow, ITestRow['position'], string | null>(
56
+ { field: 'position', headerName: 'Position (drop down)' },
57
+ {
58
+ multiEdit: true,
59
+ editorParams: {
60
+ options: positions.map(primitiveToSelectOption),
61
+ onSelectedItem: ({ selectedRows, value }) => {
62
+ const ids = selectedRows.map((row) => row.id);
63
+ setRowData((current) => current.map((row) => (ids.includes(row.id) ? { ...row, position: value } : row)));
64
+ },
65
+ },
66
+ },
67
+ ),
68
+ GridCellFiller(),
69
+ ],
70
+ [],
71
+ );
72
+
73
+ return (
74
+ <GridUpdatingContextProvider>
75
+ <GridContextProvider>
76
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
77
+ <h3 style={{ margin: '8px 0' }}>{title}</h3>
78
+ <GridWrapper>
79
+ <GridFilters>
80
+ <GridFilterCopyButton />
81
+ </GridFilters>
82
+ <Grid
83
+ data-testid={title}
84
+ enableRangeSelection={true}
85
+ enableCopy={true}
86
+ selectable={true}
87
+ singleClickEdit={singleClickEdit}
88
+ externalSelectedIds={externalSelectedIds}
89
+ setExternalSelectedIds={setExternalSelectedIds}
90
+ columnDefs={columnDefs}
91
+ rowData={rowData}
92
+ />
93
+ </GridWrapper>
94
+ </div>
95
+ </GridContextProvider>
96
+ </GridUpdatingContextProvider>
97
+ );
98
+ };
99
+
100
+ const GridCopyEditableTemplate: StoryFn = () => (
101
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '90vh' }}>
102
+ <p style={{ margin: 0, fontSize: 14 }}>
103
+ Check range selection doesn&apos;t break editing. Drag a range across cells, then edit a Name or Position cell:
104
+ the left grid edits on single click, the right grid on double click. Editing should start normally, and copying a
105
+ range should still work after editing.
106
+ </p>
107
+ <div style={{ flex: 1, display: 'flex', gap: 16, minHeight: 0 }}>
108
+ <EditableCopyGrid title={'Single click edit'} singleClickEdit={true} />
109
+ <EditableCopyGrid title={'Double click edit'} singleClickEdit={false} />
110
+ </div>
111
+ </div>
112
+ );
113
+
114
+ const meta: Meta<typeof GridCopyEditableTemplate> = {
115
+ title: 'Components / Grids',
116
+ component: GridCopyEditableTemplate,
117
+ decorators: [
118
+ (Story) => (
119
+ <LuiMessagingContextProvider version="v2">
120
+ <Story />
121
+ </LuiMessagingContextProvider>
122
+ ),
123
+ ],
124
+ };
125
+ export default meta;
126
+
127
+ type Story = StoryObj<typeof meta>;
128
+
129
+ export const GridCopyEditable: Story = {
130
+ play: waitForGridReady,
131
+ };
@@ -0,0 +1,119 @@
1
+ import { LuiMessagingContextProvider } from '@linzjs/lui';
2
+ import { Meta, StoryFn, StoryObj } from '@storybook/react-vite';
3
+ import { useMemo, useState } from 'react';
4
+
5
+ import {
6
+ ColDefT,
7
+ Grid,
8
+ GridCell,
9
+ GridCellBearingValueFormatter,
10
+ GridContextProvider,
11
+ GridFilterQuick,
12
+ GridFilters,
13
+ GridUpdatingContextProvider,
14
+ GridWrapper,
15
+ } from '../..';
16
+ import { GridFilterCopyButton, GridFilterDownloadCsvButton } from '../../components';
17
+ import { GridCellFiller } from '../../components/GridCellFiller';
18
+ import { SeededRandomForTests } from '../../utils/__tests__/random';
19
+ import { waitForGridReady } from '../../utils/__tests__/storybookTestUtil';
20
+
21
+ interface ITestRow {
22
+ id: number;
23
+ position?: string;
24
+ age: number;
25
+ bearing: number;
26
+ }
27
+
28
+ const CopyGrid = ({ name, seed }: { name: string; seed: number }) => {
29
+ const [externalSelectedIds, setExternalSelectedIds] = useState<number[]>([]);
30
+ const columnDefs: ColDefT<ITestRow>[] = useMemo(
31
+ () => [
32
+ GridCell({ field: 'id', headerName: 'Id', lockVisible: true }),
33
+ GridCell<ITestRow, ITestRow['position']>({ field: 'position', headerName: 'Position' }),
34
+ GridCell<ITestRow, ITestRow['age']>({ field: 'age', headerName: 'Age' }),
35
+ GridCell({ field: 'bearing', headerName: 'Bearing', valueFormatter: GridCellBearingValueFormatter }),
36
+ GridCellFiller(),
37
+ ],
38
+ [],
39
+ );
40
+
41
+ const [rowData] = useState<ITestRow[]>(() => {
42
+ const random = new SeededRandomForTests(seed);
43
+ const positions = ['Tester', 'Developer', 'Lawyer', 'Manager', 'CEO', 'Architect'];
44
+ return Array.from({ length: 50 }, (_, i) => ({
45
+ id: seed + i,
46
+ position: random.fromArray(positions),
47
+ age: 20 + random.next(40),
48
+ bearing: random.next(360000) / 1000,
49
+ }));
50
+ });
51
+
52
+ return (
53
+ <GridUpdatingContextProvider>
54
+ <GridContextProvider>
55
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
56
+ <h3 style={{ margin: '8px 0' }}>{name}</h3>
57
+ <GridWrapper>
58
+ <GridFilters>
59
+ <GridFilterQuick />
60
+ <GridFilterDownloadCsvButton fileName={name} />
61
+ <GridFilterCopyButton />
62
+ </GridFilters>
63
+ <Grid
64
+ data-testid={name}
65
+ enableRangeSelection={true}
66
+ enableCopy={true}
67
+ selectable={true}
68
+ enableSelectionWithoutKeys={true}
69
+ externalSelectedIds={externalSelectedIds}
70
+ setExternalSelectedIds={setExternalSelectedIds}
71
+ columnDefs={columnDefs}
72
+ rowData={rowData}
73
+ />
74
+ </GridWrapper>
75
+ </div>
76
+ </GridContextProvider>
77
+ </GridUpdatingContextProvider>
78
+ );
79
+ };
80
+
81
+ const GridCopyMultipleTemplate: StoryFn = () => (
82
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12, height: '90vh' }}>
83
+ <div style={{ fontSize: 14 }}>
84
+ <p style={{ margin: 0 }}>
85
+ Test ctrl+c with two grids. Drag a range in a grid, then click somewhere outside it (this text, the filter bar,
86
+ the copy button) and press ctrl+c: the range from the grid you used last is copied. Select some of this text and
87
+ press ctrl+c: the text is copied instead of the grid range. Ctrl+c inside an input copies the input text.
88
+ </p>
89
+ <textarea
90
+ aria-label={'Paste here'}
91
+ placeholder={'Paste here to see what was copied'}
92
+ style={{ width: '100%', height: 80, marginTop: 8, fontFamily: 'monospace' }}
93
+ />
94
+ </div>
95
+ <div style={{ flex: 1, display: 'flex', gap: 16, minHeight: 0 }}>
96
+ <CopyGrid name={'Grid A'} seed={1000} />
97
+ <CopyGrid name={'Grid B'} seed={2000} />
98
+ </div>
99
+ </div>
100
+ );
101
+
102
+ const meta: Meta<typeof GridCopyMultipleTemplate> = {
103
+ title: 'Components / Grids',
104
+ component: GridCopyMultipleTemplate,
105
+ decorators: [
106
+ (Story) => (
107
+ <LuiMessagingContextProvider version="v2">
108
+ <Story />
109
+ </LuiMessagingContextProvider>
110
+ ),
111
+ ],
112
+ };
113
+ export default meta;
114
+
115
+ type Story = StoryObj<typeof meta>;
116
+
117
+ export const GridCopyMultiple: Story = {
118
+ play: waitForGridReady,
119
+ };
@@ -0,0 +1,22 @@
1
+ // Uses LUI's split button styles (lui-split-button, popup-toggle-button-secondary) with our own react-menu3 menu.
2
+ // The copy button is lui-button-icon-only so LUI sizes it 40x40, the caret's width comes from its icon.
3
+ .GridFilterCopyButton.lui-split-button {
4
+ margin: 0 4px;
5
+
6
+ .GridFilterCopyButton-copy,
7
+ .GridFilterCopyButton-caret {
8
+ margin: 0;
9
+ display: flex;
10
+ align-items: center;
11
+ justify-content: center;
12
+ }
13
+
14
+ .GridFilterCopyButton-caret {
15
+ border-radius: 0 3px 3px 0;
16
+
17
+ // LUI's active state restores the left border, making the caret 1px wider while pressed
18
+ &:active:enabled {
19
+ border-left: 0;
20
+ }
21
+ }
22
+ }
@@ -12,5 +12,6 @@
12
12
  @use './GridLoadableCell';
13
13
  @use './GridPopoverMenu';
14
14
  @use './GridFilterColumnsToggle';
15
+ @use './GridFilterCopyButton';
15
16
  @use './GridFilterHeaderIconButton';
16
17
  @use './GridFormInlineTextInput';