@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.
- package/dist/index.css +17 -0
- package/dist/src/components/Grid.d.ts +5 -1
- package/dist/src/components/GridRangeSelectContextMenu.d.ts +12 -1
- package/dist/src/components/gridFilter/GridFilterCopyButton.d.ts +9 -0
- package/dist/src/components/gridFilter/index.d.ts +1 -0
- package/dist/src/components/gridHook/copyGridCells.d.ts +19 -0
- package/dist/src/components/gridHook/copyGridCells.test.d.ts +1 -0
- package/dist/src/components/gridHook/useGridColumnStateStorage.d.ts +26 -0
- package/dist/src/components/gridHook/useGridColumnStateStorage.test.d.ts +1 -0
- package/dist/src/components/gridHook/useGridCopy.d.ts +5 -2
- package/dist/src/components/gridHook/useGridCopySettings.d.ts +2 -0
- package/dist/src/contexts/GridContext.d.ts +35 -0
- package/dist/src/contexts/GridContextProvider.copy.test.d.ts +1 -0
- package/dist/src/utils/storageKeySync.d.ts +6 -0
- package/dist/src/utils/storageKeySync.test.d.ts +1 -0
- package/dist/step-ag-grid.cjs +601 -265
- package/dist/step-ag-grid.cjs.map +1 -1
- package/dist/step-ag-grid.esm.js +602 -267
- package/dist/step-ag-grid.esm.js.map +1 -1
- package/package.json +1 -1
- package/src/components/Grid.tsx +69 -27
- package/src/components/GridRangeSelectContextMenu.tsx +54 -51
- package/src/components/gridFilter/GridFilterColumnsToggle.tsx +45 -12
- package/src/components/gridFilter/GridFilterCopyButton.tsx +93 -0
- package/src/components/gridFilter/index.ts +1 -0
- package/src/components/gridHook/copyGridCells.test.ts +142 -0
- package/src/components/gridHook/copyGridCells.ts +225 -0
- package/src/components/gridHook/useGridColumnStateStorage.test.tsx +127 -0
- package/src/components/gridHook/useGridColumnStateStorage.ts +114 -0
- package/src/components/gridHook/useGridCopy.ts +88 -211
- package/src/components/gridHook/useGridCopySettings.ts +21 -6
- package/src/contexts/GridContext.tsx +44 -0
- package/src/contexts/GridContextProvider.copy.test.tsx +158 -0
- package/src/contexts/GridContextProvider.tsx +129 -2
- package/src/stories/grid/GridColumnState.stories.tsx +161 -0
- package/src/stories/grid/GridCopy.stories.tsx +35 -20
- package/src/stories/grid/GridCopyEditable.stories.tsx +131 -0
- package/src/stories/grid/GridCopyMultiple.stories.tsx +119 -0
- package/src/styles/GridFilterCopyButton.scss +22 -0
- package/src/styles/index.scss +1 -0
- package/src/utils/storageKeySync.test.ts +48 -0
- package/src/utils/storageKeySync.ts +24 -0
|
@@ -1,22 +1,40 @@
|
|
|
1
1
|
import { useShowLUIMessage } from '@linzjs/lui';
|
|
2
|
-
import { CellContextMenuEvent
|
|
3
|
-
import {
|
|
4
|
-
|
|
2
|
+
import { CellContextMenuEvent } from 'ag-grid-community';
|
|
3
|
+
import {
|
|
4
|
+
ClipboardEvent as ReactClipboardEvent,
|
|
5
|
+
MutableRefObject,
|
|
6
|
+
RefObject,
|
|
7
|
+
useCallback,
|
|
8
|
+
useEffect,
|
|
9
|
+
useRef,
|
|
10
|
+
} from 'react';
|
|
5
11
|
|
|
6
12
|
import { useGridContext } from '../../contexts/GridContext';
|
|
7
13
|
import { CopyOptionsContext, GridRangeSelectContextMenu } from '../GridRangeSelectContextMenu';
|
|
8
|
-
import {
|
|
14
|
+
import { GridBaseRow } from '../types';
|
|
15
|
+
import { copyGridCells } from './copyGridCells';
|
|
9
16
|
import { useGridContextMenu } from './useGridContextMenu';
|
|
10
|
-
import { CopyOptionsKey,
|
|
17
|
+
import { CopyOptionsKey, useGridCopySettings } from './useGridCopySettings';
|
|
11
18
|
import { CellLocation, GridRanges } from './useGridRangeSelection';
|
|
12
19
|
|
|
20
|
+
/** The grid the user last clicked or focused, so ctrl+c outside a grid copies from the right one */
|
|
21
|
+
let lastActiveGridElement: HTMLElement | null = null;
|
|
22
|
+
|
|
23
|
+
const isEditableElement = (el: EventTarget | null): boolean =>
|
|
24
|
+
el instanceof Element && (!!el.closest('input, textarea, select') || (el as HTMLElement).isContentEditable);
|
|
25
|
+
|
|
13
26
|
export const useGridCopy = <TData extends GridBaseRow>({
|
|
27
|
+
gridDivRef,
|
|
28
|
+
gridDocument,
|
|
14
29
|
ranges,
|
|
15
30
|
rangeStartRef,
|
|
16
31
|
rangeEndRef,
|
|
17
32
|
hasSelectedMoreThanOneCellRef,
|
|
18
33
|
cellContextMenu,
|
|
19
34
|
}: {
|
|
35
|
+
gridDivRef: RefObject<HTMLDivElement | null>;
|
|
36
|
+
/** The grid's current document, changes when the grid is popped out */
|
|
37
|
+
gridDocument: Document | undefined;
|
|
20
38
|
ranges: () => GridRanges<TData>;
|
|
21
39
|
rangeStartRef: MutableRefObject<CellLocation | null>;
|
|
22
40
|
rangeEndRef: MutableRefObject<CellLocation | null>;
|
|
@@ -24,15 +42,22 @@ export const useGridCopy = <TData extends GridBaseRow>({
|
|
|
24
42
|
cellContextMenu: (event: CellContextMenuEvent) => void;
|
|
25
43
|
}) => {
|
|
26
44
|
const showToast = useShowLUIMessage();
|
|
27
|
-
const { getSelectedRowIds } = useGridContext<TData>();
|
|
28
|
-
const { getColDef, getCellValue } = useGridContext<TData>();
|
|
45
|
+
const { getColDef, getCellValue, getSelectedRowIds, setRangeCopy } = useGridContext<TData>();
|
|
29
46
|
const { copyType, setCopyType } = useGridCopySettings();
|
|
30
47
|
|
|
48
|
+
const hasRange = useCallback(
|
|
49
|
+
() => rangeStartRef.current !== null && rangeEndRef.current !== null && hasSelectedMoreThanOneCellRef.current,
|
|
50
|
+
[rangeStartRef, rangeEndRef, hasSelectedMoreThanOneCellRef],
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Copy the selected range
|
|
55
|
+
*/
|
|
31
56
|
const onCopy = useCallback(
|
|
32
57
|
(type: CopyOptionsKey = copyType) => {
|
|
33
58
|
const rangeStart = rangeStartRef.current;
|
|
34
59
|
const rangeEnd = rangeEndRef.current;
|
|
35
|
-
if (rangeStart === null || rangeEnd === null || !
|
|
60
|
+
if (rangeStart === null || rangeEnd === null || !hasRange()) {
|
|
36
61
|
return;
|
|
37
62
|
}
|
|
38
63
|
|
|
@@ -40,198 +65,28 @@ export const useGridCopy = <TData extends GridBaseRow>({
|
|
|
40
65
|
type = 'html';
|
|
41
66
|
}
|
|
42
67
|
|
|
43
|
-
const json = type === 'json';
|
|
44
68
|
const { selectedColIds, selectedNodes } = ranges();
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
filteredSelectedColIds.map((colKey) => {
|
|
54
|
-
return (rowNode: IRowNode): string | number | boolean | null | undefined => {
|
|
55
|
-
if (colKey === agGridSelectRowColId) {
|
|
56
|
-
return selectedRowIds.includes(rowNode.data.id);
|
|
57
|
-
} else {
|
|
58
|
-
const v = getCellValue({ rowNode, colKey });
|
|
59
|
-
if (json && v !== undefined) {
|
|
60
|
-
return v;
|
|
61
|
-
}
|
|
62
|
-
const f = getCellValue({ rowNode, colKey, useFormatter: true });
|
|
63
|
-
// If it's a number, and it matches value return the original type
|
|
64
|
-
return v == f ? v : f;
|
|
65
|
-
}
|
|
66
|
-
};
|
|
67
|
-
}),
|
|
68
|
-
);
|
|
69
|
-
|
|
70
|
-
// Get and apply headers
|
|
71
|
-
const headers = filteredSelectedColIds.map((colId) => {
|
|
72
|
-
if (colId === agGridSelectRowColId) return type === 'json' ? 'selected' : 'Selected';
|
|
73
|
-
if (json) {
|
|
74
|
-
return colId;
|
|
75
|
-
}
|
|
76
|
-
return getColDef(colId)?.headerName ?? '?';
|
|
77
|
-
});
|
|
78
|
-
const maxCellLength: Record<string, number> = {};
|
|
79
|
-
headers.forEach((headerName, i) => {
|
|
80
|
-
const colId = filteredSelectedColIds[i];
|
|
81
|
-
maxCellLength[colId] = headerName.length;
|
|
82
|
-
});
|
|
83
|
-
|
|
84
|
-
const rows: string[][] = [];
|
|
85
|
-
if (type === 'csv' || type === 'html') {
|
|
86
|
-
rows.push(headers);
|
|
87
|
-
}
|
|
88
|
-
selectedNodes.forEach((node) => {
|
|
89
|
-
const row: string[] = [];
|
|
90
|
-
rows.push(row);
|
|
91
|
-
formatters.forEach((formatter, i) => {
|
|
92
|
-
const colId = filteredSelectedColIds[i];
|
|
93
|
-
let value = formatter(node);
|
|
94
|
-
if (typeof value === 'string') {
|
|
95
|
-
value = value.replaceAll('\xa0', ' ');
|
|
96
|
-
}
|
|
97
|
-
if (!json) {
|
|
98
|
-
if (value === '-' || value === '–' || value == null) {
|
|
99
|
-
value = '';
|
|
100
|
-
}
|
|
101
|
-
value = String(value);
|
|
102
|
-
if (value === '-' || value === '–') {
|
|
103
|
-
value = '';
|
|
104
|
-
}
|
|
105
|
-
maxCellLength[colId] = Math.max(maxCellLength[colId], value.length);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
switch (type) {
|
|
109
|
-
case 'json':
|
|
110
|
-
value =
|
|
111
|
-
value === 'undefined' || (value !== null && typeof value === 'object') || typeof value === 'string'
|
|
112
|
-
? JSON.stringify(value)
|
|
113
|
-
: value;
|
|
114
|
-
break;
|
|
115
|
-
case 'markdown':
|
|
116
|
-
value = encodeMarkdownValue(value as string);
|
|
117
|
-
break;
|
|
118
|
-
case 'csv':
|
|
119
|
-
value = encodeCSVValue(value as string);
|
|
120
|
-
break;
|
|
121
|
-
}
|
|
122
|
-
row.push(String(value));
|
|
123
|
-
});
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
let result = '';
|
|
127
|
-
let html = `<table style="
|
|
128
|
-
font-family: 'Open Sans', system-ui, sans-serif;
|
|
129
|
-
font-size: 10px;
|
|
130
|
-
line-height: 10px;
|
|
131
|
-
border: 1px solid #d1d9e0;
|
|
132
|
-
border-collapse: collapse;
|
|
133
|
-
">`;
|
|
134
|
-
if (json) {
|
|
135
|
-
result += '[\n';
|
|
136
|
-
}
|
|
137
|
-
rows.forEach((row, rowIndex) => {
|
|
138
|
-
if (json) {
|
|
139
|
-
result += ' { ';
|
|
140
|
-
}
|
|
141
|
-
if (rowIndex == 1) {
|
|
142
|
-
html += '<tbody style="font-weight: 400;">';
|
|
143
|
-
}
|
|
144
|
-
if (rowIndex == 0) {
|
|
145
|
-
html += '<thead style="font-weight: 600;">';
|
|
146
|
-
}
|
|
147
|
-
if (rowIndex === 0 || (rowIndex & 1) === 1) {
|
|
148
|
-
html += '<tr>';
|
|
149
|
-
} else {
|
|
150
|
-
html += '<tr style="background-color: #f6f8fa;">';
|
|
151
|
-
}
|
|
152
|
-
if (rowIndex === 1 && type === 'html') {
|
|
153
|
-
Object.values(maxCellLength).forEach((maxLength) => {
|
|
154
|
-
result += '|' + '-'.repeat(maxLength + 2);
|
|
155
|
-
});
|
|
156
|
-
result += '|\n';
|
|
157
|
-
}
|
|
158
|
-
row.forEach((cell, i) => {
|
|
159
|
-
switch (type) {
|
|
160
|
-
case 'csv':
|
|
161
|
-
if (i !== 0) {
|
|
162
|
-
result += ', ';
|
|
163
|
-
}
|
|
164
|
-
result += cell;
|
|
165
|
-
break;
|
|
166
|
-
case 'html':
|
|
167
|
-
if (i === 0) {
|
|
168
|
-
result += '|';
|
|
169
|
-
}
|
|
170
|
-
const colId = filteredSelectedColIds[i];
|
|
171
|
-
result += ' ' + cell.padEnd(maxCellLength[colId], ' ') + ' ';
|
|
172
|
-
result += '|';
|
|
173
|
-
html +=
|
|
174
|
-
rowIndex === 0
|
|
175
|
-
? '<th style="border: 1px solid #d1d9e0; padding:6px 13px; text-align: left;">'
|
|
176
|
-
: '<td style="border: 1px solid #d1d9e0; padding:6px 13px;">';
|
|
177
|
-
html += cell;
|
|
178
|
-
html += rowIndex === 0 ? '</th>' : '</td>';
|
|
179
|
-
break;
|
|
180
|
-
case 'json':
|
|
181
|
-
if (i !== 0) {
|
|
182
|
-
result += ', ';
|
|
183
|
-
}
|
|
184
|
-
result += JSON.stringify(headers[i]) + ': ' + cell;
|
|
185
|
-
break;
|
|
186
|
-
}
|
|
187
|
-
});
|
|
188
|
-
html += '</tr>';
|
|
189
|
-
if (rowIndex == 0) {
|
|
190
|
-
html += '</thead>';
|
|
191
|
-
}
|
|
192
|
-
if (rowIndex == rows.length - 1) {
|
|
193
|
-
html += '</tbody>';
|
|
194
|
-
}
|
|
195
|
-
if (json) {
|
|
196
|
-
result += ' }';
|
|
197
|
-
}
|
|
198
|
-
result += '\n';
|
|
199
|
-
});
|
|
200
|
-
if (json) {
|
|
201
|
-
result += ']\n';
|
|
202
|
-
}
|
|
203
|
-
html += '</table>';
|
|
204
|
-
|
|
205
|
-
showToast({
|
|
206
|
-
message: `${gridCopyOptions[type].text} copied`,
|
|
207
|
-
messageType: 'toast',
|
|
208
|
-
messageLevel: 'info',
|
|
69
|
+
copyGridCells({
|
|
70
|
+
type,
|
|
71
|
+
selectedColIds,
|
|
72
|
+
selectedNodes,
|
|
73
|
+
selectedRowIds: getSelectedRowIds(),
|
|
74
|
+
getColDef,
|
|
75
|
+
getCellValue,
|
|
76
|
+
showToast,
|
|
209
77
|
});
|
|
210
|
-
|
|
211
|
-
if (type === 'html') {
|
|
212
|
-
const clipboardItem = new ClipboardItem({
|
|
213
|
-
'text/html': new Blob([html], { type: 'text/html' }),
|
|
214
|
-
'text/plain': new Blob([result], { type: 'text/plain' }), // fallback
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
void navigator.clipboard.write([clipboardItem]).catch((err) => console.error('Failed to copy: ', err));
|
|
218
|
-
} else {
|
|
219
|
-
void navigator.clipboard.writeText(result).catch((err) => console.error('Failed to copy: ', err));
|
|
220
|
-
}
|
|
221
78
|
},
|
|
222
|
-
[
|
|
223
|
-
getCellValue,
|
|
224
|
-
ranges,
|
|
225
|
-
copyType,
|
|
226
|
-
rangeStartRef,
|
|
227
|
-
hasSelectedMoreThanOneCellRef,
|
|
228
|
-
rangeEndRef,
|
|
229
|
-
showToast,
|
|
230
|
-
getColDef,
|
|
231
|
-
getSelectedRowIds,
|
|
232
|
-
],
|
|
79
|
+
[getCellValue, ranges, copyType, rangeStartRef, hasRange, rangeEndRef, showToast, getColDef, getSelectedRowIds],
|
|
233
80
|
);
|
|
234
81
|
|
|
82
|
+
// Let GridContext copyToClipboard copy the range when one is selected
|
|
83
|
+
const onCopyRef = useRef(onCopy);
|
|
84
|
+
onCopyRef.current = onCopy;
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
setRangeCopy({ hasRange, getRange: ranges, copy: (type) => onCopyRef.current(type) });
|
|
87
|
+
return () => setRangeCopy(undefined);
|
|
88
|
+
}, [hasRange, ranges, setRangeCopy]);
|
|
89
|
+
|
|
235
90
|
const onCopyEvent = useCallback(
|
|
236
91
|
(e: ReactClipboardEvent<HTMLDivElement>) => {
|
|
237
92
|
const rangeStart = rangeStartRef.current;
|
|
@@ -253,6 +108,44 @@ export const useGridCopy = <TData extends GridBaseRow>({
|
|
|
253
108
|
[onCopy, rangeStartRef, rangeEndRef, hasSelectedMoreThanOneCellRef],
|
|
254
109
|
);
|
|
255
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Ctrl+c when focus is outside the grid, e.g. after clicking the copy button or the filter bar.
|
|
113
|
+
* Copies the range of the grid last used, unless the user is copying from an input or has selected text.
|
|
114
|
+
* Uses the grid's own document so it works in popped out windows.
|
|
115
|
+
*/
|
|
116
|
+
useEffect(() => {
|
|
117
|
+
const gridDiv = gridDivRef.current;
|
|
118
|
+
const doc = gridDocument ?? gridDiv?.ownerDocument;
|
|
119
|
+
if (!gridDiv || !doc) return;
|
|
120
|
+
|
|
121
|
+
const setActive = () => {
|
|
122
|
+
lastActiveGridElement = gridDiv;
|
|
123
|
+
};
|
|
124
|
+
const onDocumentCopy = (e: ClipboardEvent) => {
|
|
125
|
+
if (
|
|
126
|
+
gridDiv.contains(e.target as Node) || // handled by onCopyEvent
|
|
127
|
+
lastActiveGridElement !== gridDiv ||
|
|
128
|
+
!hasRange() ||
|
|
129
|
+
isEditableElement(e.target) ||
|
|
130
|
+
!doc.getSelection()?.isCollapsed
|
|
131
|
+
) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
e.preventDefault();
|
|
135
|
+
onCopyRef.current();
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
gridDiv.addEventListener('mousedown', setActive, true);
|
|
139
|
+
gridDiv.addEventListener('focusin', setActive, true);
|
|
140
|
+
doc.addEventListener('copy', onDocumentCopy);
|
|
141
|
+
return () => {
|
|
142
|
+
gridDiv.removeEventListener('mousedown', setActive, true);
|
|
143
|
+
gridDiv.removeEventListener('focusin', setActive, true);
|
|
144
|
+
doc.removeEventListener('copy', onDocumentCopy);
|
|
145
|
+
if (lastActiveGridElement === gridDiv) lastActiveGridElement = null;
|
|
146
|
+
};
|
|
147
|
+
}, [gridDivRef, gridDocument, hasRange]);
|
|
148
|
+
|
|
256
149
|
const { cellContextMenu: rangeSelectContextMenu, contextMenuComponent: rangeSelectContextMenuComponent } =
|
|
257
150
|
useGridContextMenu<TData, CopyOptionsContext>({
|
|
258
151
|
contextMenu: GridRangeSelectContextMenu<TData>,
|
|
@@ -274,19 +167,3 @@ export const useGridCopy = <TData extends GridBaseRow>({
|
|
|
274
167
|
rangeSelectContextMenuComponent,
|
|
275
168
|
};
|
|
276
169
|
};
|
|
277
|
-
|
|
278
|
-
const encodeMarkdownValue = (value: string): string => {
|
|
279
|
-
return value.replaceAll('|', '\\|');
|
|
280
|
-
};
|
|
281
|
-
|
|
282
|
-
const encodeCSVValue = (value: string): string => {
|
|
283
|
-
let str = String(value);
|
|
284
|
-
|
|
285
|
-
// Check if it needs quoting
|
|
286
|
-
if (/[",\n]/.test(str)) {
|
|
287
|
-
// Escape double quotes by doubling them
|
|
288
|
-
str = '"' + str.replace(/"/g, '""') + '"';
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
return str;
|
|
292
|
-
};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { IconName } from '@linzjs/lui/dist/components/LuiIcon/LuiIcon';
|
|
2
|
-
import { useCallback, useState } from 'react';
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
3
|
+
|
|
4
|
+
import { publishStorageKey, subscribeStorageKey } from '../../utils/storageKeySync';
|
|
3
5
|
|
|
4
6
|
export const gridCopyOptions: Record<string, { text: string; icon: IconName; developer?: boolean }> = {
|
|
5
7
|
html: { text: 'Text\xa0/\xa0HTML', icon: 'ic_product_list' },
|
|
@@ -10,14 +12,27 @@ export type CopyOptionsKey = keyof typeof gridCopyOptions;
|
|
|
10
12
|
|
|
11
13
|
const CopyOptionsStorageKey = 'stepAgGrid_defaultCopy';
|
|
12
14
|
|
|
15
|
+
const isCopyOptionsKey = (key: string): key is CopyOptionsKey => Object.keys(gridCopyOptions).includes(key);
|
|
16
|
+
|
|
17
|
+
/** The user's saved default copy format */
|
|
18
|
+
export const getDefaultCopyType = (): CopyOptionsKey => {
|
|
19
|
+
const defaultCopy = window.localStorage.getItem(CopyOptionsStorageKey) ?? '';
|
|
20
|
+
return isCopyOptionsKey(defaultCopy) ? defaultCopy : 'html';
|
|
21
|
+
};
|
|
22
|
+
|
|
13
23
|
export const useGridCopySettings = () => {
|
|
14
|
-
const [copyType, _setCopyType] = useState<CopyOptionsKey>(
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
24
|
+
const [copyType, _setCopyType] = useState<CopyOptionsKey>(getDefaultCopyType);
|
|
25
|
+
|
|
26
|
+
// Keep the grid range copy menu and the copy button in step
|
|
27
|
+
const listenerRef = useRef<(value: string) => void>(undefined);
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
const listener = (value: string) => isCopyOptionsKey(value) && _setCopyType(value);
|
|
30
|
+
listenerRef.current = listener;
|
|
31
|
+
return subscribeStorageKey(CopyOptionsStorageKey, listener);
|
|
32
|
+
}, []);
|
|
18
33
|
|
|
19
34
|
const setCopyType = useCallback((key: CopyOptionsKey) => {
|
|
20
|
-
window.localStorage
|
|
35
|
+
publishStorageKey(window.localStorage, CopyOptionsStorageKey, key, listenerRef.current);
|
|
21
36
|
_setCopyType(key);
|
|
22
37
|
}, []);
|
|
23
38
|
|
|
@@ -2,8 +2,21 @@ import { ColDef, GridApi, IRowNode, ISizeColumnsToFitParams } from 'ag-grid-comm
|
|
|
2
2
|
import { CsvExportParams } from 'ag-grid-community';
|
|
3
3
|
import { createContext, useContext } from 'react';
|
|
4
4
|
|
|
5
|
+
import type { CopyOptionsKey } from '../components/gridHook/useGridCopySettings';
|
|
6
|
+
import type { GridRanges } from '../components/gridHook/useGridRangeSelection';
|
|
5
7
|
import { ColDefT, GridBaseRow } from '../components/types';
|
|
6
8
|
|
|
9
|
+
/** What copyToClipboard will copy */
|
|
10
|
+
export type GridCopyScope = 'range' | 'selection' | 'all';
|
|
11
|
+
|
|
12
|
+
/** Registered by the Grid so copyToClipboard copies its selected range */
|
|
13
|
+
export interface GridRangeCopy {
|
|
14
|
+
hasRange: () => boolean;
|
|
15
|
+
/** Columns and rows of the selected range */
|
|
16
|
+
getRange: () => GridRanges<any>;
|
|
17
|
+
copy: (type?: CopyOptionsKey) => void;
|
|
18
|
+
}
|
|
19
|
+
|
|
7
20
|
export type GridFilterExternal<TData extends GridBaseRow> = (data: TData, rowNode: IRowNode) => boolean;
|
|
8
21
|
|
|
9
22
|
export interface AutoSizeColumnsProps {
|
|
@@ -72,6 +85,30 @@ export interface GridContextType<TData extends GridBaseRow> {
|
|
|
72
85
|
invisibleColumnIds: string[] | undefined;
|
|
73
86
|
setInvisibleColumnIds: (colIds: string[]) => void;
|
|
74
87
|
downloadCsv: (csvExportParams?: CsvExportParams) => void;
|
|
88
|
+
/**
|
|
89
|
+
* Copy to the clipboard, defaults to the user's default copy format.
|
|
90
|
+
* Copies the selected range if one is selected,
|
|
91
|
+
* otherwise the selected rows if any are selected, otherwise all rows.
|
|
92
|
+
* Rows are copied with all displayed columns.
|
|
93
|
+
*/
|
|
94
|
+
copyToClipboard: (type?: CopyOptionsKey) => void;
|
|
95
|
+
/** What copyToClipboard will copy right now */
|
|
96
|
+
getCopyScope: () => GridCopyScope;
|
|
97
|
+
/**
|
|
98
|
+
* The rows copyToClipboard would copy (see getCopyScope), with only the fields of the columns being copied.
|
|
99
|
+
* Values are the raw row data. Columns without a field are not included.
|
|
100
|
+
*/
|
|
101
|
+
getSelectedDataForCopy: () => Partial<TData>[];
|
|
102
|
+
/**
|
|
103
|
+
* The rows copyToClipboard would copy (see getCopyScope), keyed by column id.
|
|
104
|
+
* Values are the raw cell values before formatting.
|
|
105
|
+
*/
|
|
106
|
+
getCopyData: () => Record<string, unknown>[];
|
|
107
|
+
/** Used by Grid to copy its selected range */
|
|
108
|
+
setRangeCopy: (rangeCopy: GridRangeCopy | undefined) => void;
|
|
109
|
+
/** Grid enableCopy, shows GridFilterCopyButton */
|
|
110
|
+
copyEnabled: boolean;
|
|
111
|
+
setCopyEnabled: (copyEnabled: boolean) => void;
|
|
75
112
|
onBulkEditingComplete: () => Promise<void> | void;
|
|
76
113
|
setOnBulkEditingComplete: (callback: (() => Promise<void> | void) | undefined) => void;
|
|
77
114
|
showNoRowsOverlay: () => void;
|
|
@@ -124,6 +161,13 @@ export const GridContext = createContext<GridContextType<any>>({
|
|
|
124
161
|
isExternalFilterPresent: NoContext,
|
|
125
162
|
doesExternalFilterPass: NoContext,
|
|
126
163
|
downloadCsv: NoContext,
|
|
164
|
+
copyToClipboard: NoContext,
|
|
165
|
+
getCopyScope: () => 'all',
|
|
166
|
+
getSelectedDataForCopy: NoContext,
|
|
167
|
+
getCopyData: NoContext,
|
|
168
|
+
setRangeCopy: NoContext,
|
|
169
|
+
copyEnabled: false,
|
|
170
|
+
setCopyEnabled: NoContext,
|
|
127
171
|
onBulkEditingComplete: NoContext,
|
|
128
172
|
setOnBulkEditingComplete: NoContext,
|
|
129
173
|
showNoRowsOverlay: NoContext,
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { LuiMessagingContextProvider } from '@linzjs/lui';
|
|
2
|
+
import { act, renderHook } from '@testing-library/react';
|
|
3
|
+
import { ColDef, GridApi, IRowNode } from 'ag-grid-community';
|
|
4
|
+
import { get } from 'lodash-es';
|
|
5
|
+
import { PropsWithChildren } from 'react';
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { GridCellFillerColId } from '../components/GridCellFiller';
|
|
9
|
+
import { agGridSelectRowColId } from '../components/types';
|
|
10
|
+
import { GridRangeCopy, useGridContext } from './GridContext';
|
|
11
|
+
import { GridContextProvider } from './GridContextProvider';
|
|
12
|
+
|
|
13
|
+
interface TestRow {
|
|
14
|
+
id: number;
|
|
15
|
+
name: string;
|
|
16
|
+
address: { street: string; city: string };
|
|
17
|
+
a: number;
|
|
18
|
+
b: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const colDefs: Record<string, ColDef> = {
|
|
22
|
+
[agGridSelectRowColId]: { colId: agGridSelectRowColId, headerComponentParams: { exportable: false } },
|
|
23
|
+
id: { colId: 'id', field: 'id', headerName: 'Id' },
|
|
24
|
+
name: { colId: 'name', field: 'name', headerName: 'Name' },
|
|
25
|
+
street: { colId: 'street', field: 'address.street', headerName: 'Street' },
|
|
26
|
+
// valueGetter only column, has no field
|
|
27
|
+
total: { colId: 'total', headerName: 'Total' },
|
|
28
|
+
menu: { colId: 'menu', headerComponentParams: { exportable: false } },
|
|
29
|
+
[GridCellFillerColId]: { colId: GridCellFillerColId },
|
|
30
|
+
};
|
|
31
|
+
const displayedColIds = Object.keys(colDefs);
|
|
32
|
+
|
|
33
|
+
const rows: TestRow[] = [1, 2, 3].map((id) => ({
|
|
34
|
+
id,
|
|
35
|
+
name: `Name ${id}`,
|
|
36
|
+
address: { street: `${id} Street`, city: 'Wellington' },
|
|
37
|
+
a: id,
|
|
38
|
+
b: 10,
|
|
39
|
+
}));
|
|
40
|
+
|
|
41
|
+
/** Minimal GridApi: rows can be selected, and hidden by the filter */
|
|
42
|
+
const mockGridApi = ({
|
|
43
|
+
selectedIds = [],
|
|
44
|
+
filteredOutIds = [],
|
|
45
|
+
}: {
|
|
46
|
+
selectedIds?: number[];
|
|
47
|
+
filteredOutIds?: number[];
|
|
48
|
+
}) => {
|
|
49
|
+
const nodes = rows.map((data) => ({ data, group: false, isSelected: () => selectedIds.includes(data.id) }));
|
|
50
|
+
return {
|
|
51
|
+
isDestroyed: () => false,
|
|
52
|
+
setGridOption: vi.fn(),
|
|
53
|
+
getColumnDef: (colId: string) => colDefs[colId],
|
|
54
|
+
getAllDisplayedColumns: () => displayedColIds.map((colId) => ({ getColId: () => colId })),
|
|
55
|
+
forEachNodeAfterFilterAndSort: (callback: (node: IRowNode) => void) =>
|
|
56
|
+
nodes.filter((node) => !filteredOutIds.includes(node.data.id)).forEach((node) => callback(node as IRowNode)),
|
|
57
|
+
getSelectedRows: () => rows.filter((row) => selectedIds.includes(row.id)),
|
|
58
|
+
getCellValue: ({ rowNode, colKey }: { rowNode: IRowNode<TestRow>; colKey: string }) =>
|
|
59
|
+
colKey === 'total' ? rowNode.data!.a + rowNode.data!.b : get(rowNode.data, colDefs[colKey].field!),
|
|
60
|
+
} as unknown as GridApi;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const renderGridContext = (gridApi: GridApi) => {
|
|
64
|
+
const wrapper = ({ children }: PropsWithChildren) => (
|
|
65
|
+
<LuiMessagingContextProvider version="v2">
|
|
66
|
+
<GridContextProvider>{children}</GridContextProvider>
|
|
67
|
+
</LuiMessagingContextProvider>
|
|
68
|
+
);
|
|
69
|
+
const { result } = renderHook(() => useGridContext<TestRow>(), { wrapper });
|
|
70
|
+
act(() => result.current.setApis(gridApi, false, false));
|
|
71
|
+
return result;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const writeText = vi.fn(() => Promise.resolve());
|
|
75
|
+
|
|
76
|
+
beforeEach(() => {
|
|
77
|
+
window.localStorage.clear();
|
|
78
|
+
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
afterEach(() => {
|
|
82
|
+
vi.clearAllMocks();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('GridContext copy', () => {
|
|
86
|
+
test('all rows when nothing is selected', () => {
|
|
87
|
+
const result = renderGridContext(mockGridApi({}));
|
|
88
|
+
|
|
89
|
+
expect(result.current.getCopyScope()).toBe('all');
|
|
90
|
+
expect(result.current.getCopyData()).toEqual([
|
|
91
|
+
{ id: 1, name: 'Name 1', street: '1 Street', total: 11 },
|
|
92
|
+
{ id: 2, name: 'Name 2', street: '2 Street', total: 12 },
|
|
93
|
+
{ id: 3, name: 'Name 3', street: '3 Street', total: 13 },
|
|
94
|
+
]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('selected rows when rows are selected', () => {
|
|
98
|
+
const result = renderGridContext(mockGridApi({ selectedIds: [2, 3] }));
|
|
99
|
+
|
|
100
|
+
expect(result.current.getCopyScope()).toBe('selection');
|
|
101
|
+
expect(result.current.getCopyData().map((row) => row.id)).toEqual([2, 3]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('all rows when the selected rows are hidden by the filter', () => {
|
|
105
|
+
const result = renderGridContext(mockGridApi({ selectedIds: [2], filteredOutIds: [2] }));
|
|
106
|
+
|
|
107
|
+
expect(result.current.getCopyScope()).toBe('all');
|
|
108
|
+
expect(result.current.getCopyData().map((row) => row.id)).toEqual([1, 3]);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('getSelectedDataForCopy picks row data by field, including nested fields, and skips columns without one', () => {
|
|
112
|
+
const result = renderGridContext(mockGridApi({ selectedIds: [1] }));
|
|
113
|
+
|
|
114
|
+
expect(result.current.getSelectedDataForCopy()).toEqual([
|
|
115
|
+
{ id: 1, name: 'Name 1', address: { street: '1 Street' } },
|
|
116
|
+
]);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('the range is used when one is selected', () => {
|
|
120
|
+
const result = renderGridContext(mockGridApi({ selectedIds: [1] }));
|
|
121
|
+
const nodes: IRowNode[] = [];
|
|
122
|
+
mockGridApi({}).forEachNodeAfterFilterAndSort((node) => nodes.push(node));
|
|
123
|
+
const rangeCopy: GridRangeCopy = {
|
|
124
|
+
hasRange: () => true,
|
|
125
|
+
getRange: () => ({ selectedColIds: [agGridSelectRowColId, 'name', 'total'], selectedNodes: nodes.slice(1) }),
|
|
126
|
+
copy: vi.fn(),
|
|
127
|
+
};
|
|
128
|
+
act(() => result.current.setRangeCopy(rangeCopy));
|
|
129
|
+
|
|
130
|
+
expect(result.current.getCopyScope()).toBe('range');
|
|
131
|
+
expect(result.current.getCopyData()).toEqual([
|
|
132
|
+
{ name: 'Name 2', total: 12 },
|
|
133
|
+
{ name: 'Name 3', total: 13 },
|
|
134
|
+
]);
|
|
135
|
+
expect(result.current.getSelectedDataForCopy()).toEqual([{ name: 'Name 2' }, { name: 'Name 3' }]);
|
|
136
|
+
|
|
137
|
+
result.current.copyToClipboard('csv');
|
|
138
|
+
expect(rangeCopy.copy).toHaveBeenCalledWith('csv');
|
|
139
|
+
expect(writeText).not.toHaveBeenCalled();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
test('copyToClipboard copies the selected rows with all displayed columns', () => {
|
|
143
|
+
const result = renderGridContext(mockGridApi({ selectedIds: [1, 3] }));
|
|
144
|
+
|
|
145
|
+
result.current.copyToClipboard('csv');
|
|
146
|
+
expect(writeText).toHaveBeenCalledWith(
|
|
147
|
+
'Id, Name, Street, Total\n1, Name 1, 1 Street, 11\n3, Name 3, 3 Street, 13\n',
|
|
148
|
+
);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
test('copyToClipboard uses the saved default copy type', () => {
|
|
152
|
+
window.localStorage.setItem('stepAgGrid_defaultCopy', 'csv');
|
|
153
|
+
const result = renderGridContext(mockGridApi({}));
|
|
154
|
+
|
|
155
|
+
result.current.copyToClipboard();
|
|
156
|
+
expect(writeText).toHaveBeenCalledWith(expect.stringMatching(/^Id, Name, Street, Total\n/));
|
|
157
|
+
});
|
|
158
|
+
});
|