@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
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { useShowLUIMessage } from '@linzjs/lui';
|
|
2
|
+
import { ColDef, GridApi, IRowNode } from 'ag-grid-community';
|
|
3
|
+
import { compact } from 'lodash-es';
|
|
4
|
+
|
|
5
|
+
import { agGridSelectRowColId } from '../types';
|
|
6
|
+
import { CopyOptionsKey, gridCopyOptions } from './useGridCopySettings';
|
|
7
|
+
|
|
8
|
+
export interface CopyGridCellsProps {
|
|
9
|
+
type: CopyOptionsKey;
|
|
10
|
+
selectedColIds: string[];
|
|
11
|
+
selectedNodes: IRowNode[];
|
|
12
|
+
selectedRowIds: unknown[];
|
|
13
|
+
getColDef: (colId?: string) => ColDef | undefined;
|
|
14
|
+
getCellValue: GridApi['getCellValue'];
|
|
15
|
+
showToast: ReturnType<typeof useShowLUIMessage>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Columns that are included when copying, excludes the filler column and non-exportable columns */
|
|
19
|
+
export const isCopyableColId = (colId: string, getColDef: (colId?: string) => ColDef | undefined): boolean =>
|
|
20
|
+
colId !== 'gridCellFiller' && getColDef(colId)?.headerComponentParams?.exportable !== false;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Formats the cells of the given columns and rows and writes them to the clipboard.
|
|
24
|
+
* Used by range select copy and GridContext copyToClipboard.
|
|
25
|
+
*/
|
|
26
|
+
export const copyGridCells = ({
|
|
27
|
+
type,
|
|
28
|
+
selectedColIds,
|
|
29
|
+
selectedNodes,
|
|
30
|
+
selectedRowIds,
|
|
31
|
+
getColDef,
|
|
32
|
+
getCellValue,
|
|
33
|
+
showToast,
|
|
34
|
+
}: CopyGridCellsProps): void => {
|
|
35
|
+
const json = type === 'json';
|
|
36
|
+
const filteredSelectedColIds = selectedColIds.filter(
|
|
37
|
+
(colId) => colId === agGridSelectRowColId || isCopyableColId(colId, getColDef),
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
const formatters = compact(
|
|
41
|
+
filteredSelectedColIds.map((colKey) => {
|
|
42
|
+
return (rowNode: IRowNode): string | number | boolean | null | undefined => {
|
|
43
|
+
if (colKey === agGridSelectRowColId) {
|
|
44
|
+
return selectedRowIds.includes(rowNode.data.id);
|
|
45
|
+
} else {
|
|
46
|
+
const v = getCellValue({ rowNode, colKey });
|
|
47
|
+
if (json && v !== undefined) {
|
|
48
|
+
return v;
|
|
49
|
+
}
|
|
50
|
+
const f = getCellValue({ rowNode, colKey, useFormatter: true });
|
|
51
|
+
// If it's a number, and it matches value return the original type
|
|
52
|
+
return v == f ? v : f;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
// Get and apply headers
|
|
59
|
+
const headers = filteredSelectedColIds.map((colId) => {
|
|
60
|
+
if (colId === agGridSelectRowColId) return type === 'json' ? 'selected' : 'Selected';
|
|
61
|
+
if (json) {
|
|
62
|
+
return colId;
|
|
63
|
+
}
|
|
64
|
+
return getColDef(colId)?.headerName ?? '?';
|
|
65
|
+
});
|
|
66
|
+
const maxCellLength: Record<string, number> = {};
|
|
67
|
+
headers.forEach((headerName, i) => {
|
|
68
|
+
const colId = filteredSelectedColIds[i];
|
|
69
|
+
maxCellLength[colId] = headerName.length;
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const rows: string[][] = [];
|
|
73
|
+
if (type === 'csv' || type === 'html') {
|
|
74
|
+
rows.push(headers);
|
|
75
|
+
}
|
|
76
|
+
selectedNodes.forEach((node) => {
|
|
77
|
+
const row: string[] = [];
|
|
78
|
+
rows.push(row);
|
|
79
|
+
formatters.forEach((formatter, i) => {
|
|
80
|
+
const colId = filteredSelectedColIds[i];
|
|
81
|
+
let value = formatter(node);
|
|
82
|
+
if (typeof value === 'string') {
|
|
83
|
+
value = value.replaceAll('\xa0', ' ');
|
|
84
|
+
}
|
|
85
|
+
if (!json) {
|
|
86
|
+
if (value === '-' || value === '–' || value == null) {
|
|
87
|
+
value = '';
|
|
88
|
+
}
|
|
89
|
+
value = String(value);
|
|
90
|
+
if (value === '-' || value === '–') {
|
|
91
|
+
value = '';
|
|
92
|
+
}
|
|
93
|
+
maxCellLength[colId] = Math.max(maxCellLength[colId], value.length);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
switch (type) {
|
|
97
|
+
case 'json':
|
|
98
|
+
value =
|
|
99
|
+
value === 'undefined' || (value !== null && typeof value === 'object') || typeof value === 'string'
|
|
100
|
+
? JSON.stringify(value)
|
|
101
|
+
: value;
|
|
102
|
+
break;
|
|
103
|
+
case 'markdown':
|
|
104
|
+
value = encodeMarkdownValue(value as string);
|
|
105
|
+
break;
|
|
106
|
+
case 'csv':
|
|
107
|
+
value = encodeCSVValue(value as string);
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
row.push(String(value));
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
let result = '';
|
|
115
|
+
let html = `<table style="
|
|
116
|
+
font-family: 'Open Sans', system-ui, sans-serif;
|
|
117
|
+
font-size: 10px;
|
|
118
|
+
line-height: 10px;
|
|
119
|
+
border: 1px solid #d1d9e0;
|
|
120
|
+
border-collapse: collapse;
|
|
121
|
+
">`;
|
|
122
|
+
if (json) {
|
|
123
|
+
result += '[\n';
|
|
124
|
+
}
|
|
125
|
+
rows.forEach((row, rowIndex) => {
|
|
126
|
+
if (json) {
|
|
127
|
+
result += ' { ';
|
|
128
|
+
}
|
|
129
|
+
if (rowIndex == 1) {
|
|
130
|
+
html += '<tbody style="font-weight: 400;">';
|
|
131
|
+
}
|
|
132
|
+
if (rowIndex == 0) {
|
|
133
|
+
html += '<thead style="font-weight: 600;">';
|
|
134
|
+
}
|
|
135
|
+
if (rowIndex === 0 || (rowIndex & 1) === 1) {
|
|
136
|
+
html += '<tr>';
|
|
137
|
+
} else {
|
|
138
|
+
html += '<tr style="background-color: #f6f8fa;">';
|
|
139
|
+
}
|
|
140
|
+
if (rowIndex === 1 && type === 'html') {
|
|
141
|
+
Object.values(maxCellLength).forEach((maxLength) => {
|
|
142
|
+
result += '|' + '-'.repeat(maxLength + 2);
|
|
143
|
+
});
|
|
144
|
+
result += '|\n';
|
|
145
|
+
}
|
|
146
|
+
row.forEach((cell, i) => {
|
|
147
|
+
switch (type) {
|
|
148
|
+
case 'csv':
|
|
149
|
+
if (i !== 0) {
|
|
150
|
+
result += ', ';
|
|
151
|
+
}
|
|
152
|
+
result += cell;
|
|
153
|
+
break;
|
|
154
|
+
case 'html':
|
|
155
|
+
if (i === 0) {
|
|
156
|
+
result += '|';
|
|
157
|
+
}
|
|
158
|
+
const colId = filteredSelectedColIds[i];
|
|
159
|
+
result += ' ' + cell.padEnd(maxCellLength[colId], ' ') + ' ';
|
|
160
|
+
result += '|';
|
|
161
|
+
html +=
|
|
162
|
+
rowIndex === 0
|
|
163
|
+
? '<th style="border: 1px solid #d1d9e0; padding:6px 13px; text-align: left;">'
|
|
164
|
+
: '<td style="border: 1px solid #d1d9e0; padding:6px 13px;">';
|
|
165
|
+
html += cell;
|
|
166
|
+
html += rowIndex === 0 ? '</th>' : '</td>';
|
|
167
|
+
break;
|
|
168
|
+
case 'json':
|
|
169
|
+
if (i !== 0) {
|
|
170
|
+
result += ', ';
|
|
171
|
+
}
|
|
172
|
+
result += JSON.stringify(headers[i]) + ': ' + cell;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
html += '</tr>';
|
|
177
|
+
if (rowIndex == 0) {
|
|
178
|
+
html += '</thead>';
|
|
179
|
+
}
|
|
180
|
+
if (rowIndex == rows.length - 1) {
|
|
181
|
+
html += '</tbody>';
|
|
182
|
+
}
|
|
183
|
+
if (json) {
|
|
184
|
+
result += rowIndex < rows.length - 1 ? ' },' : ' }';
|
|
185
|
+
}
|
|
186
|
+
result += '\n';
|
|
187
|
+
});
|
|
188
|
+
if (json) {
|
|
189
|
+
result += ']\n';
|
|
190
|
+
}
|
|
191
|
+
html += '</table>';
|
|
192
|
+
|
|
193
|
+
showToast({
|
|
194
|
+
message: `${gridCopyOptions[type].text} copied`,
|
|
195
|
+
messageType: 'toast',
|
|
196
|
+
messageLevel: 'info',
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
if (type === 'html') {
|
|
200
|
+
const clipboardItem = new ClipboardItem({
|
|
201
|
+
'text/html': new Blob([html], { type: 'text/html' }),
|
|
202
|
+
'text/plain': new Blob([result], { type: 'text/plain' }), // fallback
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
void navigator.clipboard.write([clipboardItem]).catch((err) => console.error('Failed to copy: ', err));
|
|
206
|
+
} else {
|
|
207
|
+
void navigator.clipboard.writeText(result).catch((err) => console.error('Failed to copy: ', err));
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const encodeMarkdownValue = (value: string): string => {
|
|
212
|
+
return value.replaceAll('|', '\\|');
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const encodeCSVValue = (value: string): string => {
|
|
216
|
+
let str = String(value);
|
|
217
|
+
|
|
218
|
+
// Check if it needs quoting
|
|
219
|
+
if (/[",\n]/.test(str)) {
|
|
220
|
+
// Escape double quotes by doubling them
|
|
221
|
+
str = '"' + str.replace(/"/g, '""') + '"';
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return str;
|
|
225
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { renderHook } from '@testing-library/react';
|
|
2
|
+
import { ColumnState, GridApi } from 'ag-grid-community';
|
|
3
|
+
import { PropsWithChildren } from 'react';
|
|
4
|
+
import { afterEach, describe, expect, test, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { GridContext } from '../../contexts/GridContext';
|
|
7
|
+
import { WindowChromaticProps } from '../../utils/isChromatic';
|
|
8
|
+
import { publishStorageKey } from '../../utils/storageKeySync';
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
applyStoredColumnState,
|
|
12
|
+
columnStateStorageKey,
|
|
13
|
+
parseStoredColumnState,
|
|
14
|
+
StoredColumn,
|
|
15
|
+
toStoredColumnState,
|
|
16
|
+
useGridColumnStateStorage,
|
|
17
|
+
} from './useGridColumnStateStorage';
|
|
18
|
+
|
|
19
|
+
const columnState: ColumnState[] = [
|
|
20
|
+
{ colId: 'id', width: 80, flex: null, sort: null, sortIndex: null, hide: false, pinned: null },
|
|
21
|
+
{ colId: 'name', width: 250, flex: null, sort: 'asc', sortIndex: 0, hide: true, pinned: 'left' },
|
|
22
|
+
];
|
|
23
|
+
const storedColumns: StoredColumn[] = [
|
|
24
|
+
{ colId: 'id', width: 80, flex: null, sort: null, sortIndex: null },
|
|
25
|
+
{ colId: 'name', width: 250, flex: null, sort: 'asc', sortIndex: 0 },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
describe('columnStateStorageKey', () => {
|
|
29
|
+
test('is keyed by the column ids', () => {
|
|
30
|
+
expect(columnStateStorageKey(['id', 'name'])).toBe('stepAgGrid_columnState_id_name');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('is null before the grid has columns', () => {
|
|
34
|
+
expect(columnStateStorageKey([])).toBeNull();
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
describe('toStoredColumnState', () => {
|
|
39
|
+
test('keeps only widths and sort, plus the user-sized column ids', () => {
|
|
40
|
+
expect(toStoredColumnState(columnState, ['name'])).toEqual({ columns: storedColumns, userSizedColIds: ['name'] });
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('parseStoredColumnState', () => {
|
|
45
|
+
test('reads stored column state', () => {
|
|
46
|
+
const stored = { columns: storedColumns, userSizedColIds: ['name'] };
|
|
47
|
+
expect(parseStoredColumnState(JSON.stringify(stored))).toEqual(stored);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('returns undefined when nothing is stored', () => {
|
|
51
|
+
expect(parseStoredColumnState(null)).toBeUndefined();
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test.each(['not json', '{"columns":"x","userSizedColIds":[]}', '{"columns":[{"colId":1}],"userSizedColIds":[]}'])(
|
|
55
|
+
'returns undefined for invalid state %s',
|
|
56
|
+
(stored) => {
|
|
57
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
58
|
+
expect(parseStoredColumnState(stored)).toBeUndefined();
|
|
59
|
+
},
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe('applyStoredColumnState', () => {
|
|
64
|
+
test('applies the stored widths and sort without changing column order', () => {
|
|
65
|
+
const api = { applyColumnState: vi.fn() };
|
|
66
|
+
applyStoredColumnState(api, { columns: storedColumns, userSizedColIds: [] }, new Map());
|
|
67
|
+
expect(api.applyColumnState).toHaveBeenCalledWith({ state: storedColumns, applyOrder: false });
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('marks stored user-sized columns as user-sized with their stored width', () => {
|
|
71
|
+
const userSizedColIds = new Map([['id', 60]]);
|
|
72
|
+
applyStoredColumnState(
|
|
73
|
+
{ applyColumnState: vi.fn() },
|
|
74
|
+
{ columns: storedColumns, userSizedColIds: ['name', 'missing'] },
|
|
75
|
+
userSizedColIds,
|
|
76
|
+
);
|
|
77
|
+
expect(userSizedColIds).toEqual(
|
|
78
|
+
new Map([
|
|
79
|
+
['id', 60],
|
|
80
|
+
['name', 250],
|
|
81
|
+
]),
|
|
82
|
+
);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('useGridColumnStateStorage', () => {
|
|
87
|
+
const storageKey = 'stepAgGrid_columnState_id_name';
|
|
88
|
+
const stored = JSON.stringify({ columns: storedColumns, userSizedColIds: [] });
|
|
89
|
+
|
|
90
|
+
const setup = (storedValue: string | null) => {
|
|
91
|
+
const storage = { getItem: vi.fn(() => storedValue), setItem: vi.fn() } as unknown as Storage;
|
|
92
|
+
const gridApi = { isDestroyed: () => false, applyColumnState: vi.fn() } as unknown as GridApi & {
|
|
93
|
+
applyColumnState: ReturnType<typeof vi.fn>;
|
|
94
|
+
};
|
|
95
|
+
const gridDivRef = { current: { ownerDocument: { defaultView: { localStorage: storage } } } } as never;
|
|
96
|
+
const wrapper = ({ children }: PropsWithChildren) => (
|
|
97
|
+
<GridContext.Provider value={{ getColumnIds: () => ['id', 'name'] } as never}>{children}</GridContext.Provider>
|
|
98
|
+
);
|
|
99
|
+
renderHook(
|
|
100
|
+
() => useGridColumnStateStorage({ enabled: true, gridApi, gridDivRef, userSizedColIds: { current: new Map() } }),
|
|
101
|
+
{ wrapper },
|
|
102
|
+
);
|
|
103
|
+
return { gridApi, storage };
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
afterEach(() => {
|
|
107
|
+
delete (window as WindowChromaticProps).FORCE_IS_CHROMATIC;
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('restores the saved column state on mount', () => {
|
|
111
|
+
const { gridApi } = setup(stored);
|
|
112
|
+
expect(gridApi.applyColumnState).toHaveBeenCalledWith({ state: storedColumns, applyOrder: false });
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('does not restore saved column state in Chromatic', () => {
|
|
116
|
+
(window as WindowChromaticProps).FORCE_IS_CHROMATIC = true;
|
|
117
|
+
const { gridApi } = setup(stored);
|
|
118
|
+
expect(gridApi.applyColumnState).not.toHaveBeenCalled();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('still applies column state published by another grid in Chromatic', () => {
|
|
122
|
+
(window as WindowChromaticProps).FORCE_IS_CHROMATIC = true;
|
|
123
|
+
const { gridApi, storage } = setup(null);
|
|
124
|
+
publishStorageKey(storage, storageKey, stored);
|
|
125
|
+
expect(gridApi.applyColumnState).toHaveBeenCalledWith({ state: storedColumns, applyOrder: false });
|
|
126
|
+
});
|
|
127
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { ColumnState, GridApi } from 'ag-grid-community';
|
|
2
|
+
import { isEmpty } from 'lodash-es';
|
|
3
|
+
import { RefObject, useCallback, useEffect, useMemo, useRef } from 'react';
|
|
4
|
+
|
|
5
|
+
import { useGridContext } from '../../contexts/GridContext';
|
|
6
|
+
import { isChromatic } from '../../utils/isChromatic';
|
|
7
|
+
import { publishStorageKey, subscribeStorageKey } from '../../utils/storageKeySync';
|
|
8
|
+
|
|
9
|
+
export type StoredColumn = Pick<ColumnState, 'colId' | 'width' | 'flex' | 'sort' | 'sortIndex'>;
|
|
10
|
+
|
|
11
|
+
export interface StoredColumnState {
|
|
12
|
+
columns: StoredColumn[];
|
|
13
|
+
/** Columns the user has resized, so auto-size leaves them alone */
|
|
14
|
+
userSizedColIds: string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const columnStateStorageKey = (colIds: string[]): string | null =>
|
|
18
|
+
isEmpty(colIds) ? null : 'stepAgGrid_columnState_' + colIds.join('_');
|
|
19
|
+
|
|
20
|
+
export const toStoredColumnState = (
|
|
21
|
+
columnState: ColumnState[],
|
|
22
|
+
userSizedColIds: Iterable<string>,
|
|
23
|
+
): StoredColumnState => ({
|
|
24
|
+
columns: columnState.map(({ colId, width, flex, sort, sortIndex }) => ({ colId, width, flex, sort, sortIndex })),
|
|
25
|
+
userSizedColIds: [...userSizedColIds],
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export const parseStoredColumnState = (stored: string | null): StoredColumnState | undefined => {
|
|
29
|
+
if (!stored) return undefined;
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(stored);
|
|
32
|
+
if (
|
|
33
|
+
Array.isArray(parsed?.columns) &&
|
|
34
|
+
parsed.columns.every((col: unknown) => typeof (col as StoredColumn)?.colId === 'string') &&
|
|
35
|
+
Array.isArray(parsed.userSizedColIds) &&
|
|
36
|
+
parsed.userSizedColIds.every((id: unknown) => typeof id === 'string')
|
|
37
|
+
) {
|
|
38
|
+
return parsed;
|
|
39
|
+
}
|
|
40
|
+
console.error(`stored column state is invalid: ${stored}`);
|
|
41
|
+
} catch (ex) {
|
|
42
|
+
console.error(ex);
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** Applies widths and sort only, so column visibility stays with GridFilterColumnsToggle */
|
|
48
|
+
export const applyStoredColumnState = (
|
|
49
|
+
api: Pick<GridApi, 'applyColumnState'>,
|
|
50
|
+
{ columns, userSizedColIds: storedUserSizedColIds }: StoredColumnState,
|
|
51
|
+
userSizedColIds: Map<string, number>,
|
|
52
|
+
): void => {
|
|
53
|
+
const widths = new Map(columns.map((col) => [col.colId, col.width]));
|
|
54
|
+
storedUserSizedColIds.forEach((colId) => {
|
|
55
|
+
const width = widths.get(colId);
|
|
56
|
+
if (width != null) {
|
|
57
|
+
userSizedColIds.set(colId, width);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
api.applyColumnState({ state: columns, applyOrder: false });
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
interface UseGridColumnStateStorageProps {
|
|
64
|
+
enabled: boolean;
|
|
65
|
+
gridApi: GridApi | undefined;
|
|
66
|
+
gridDivRef: RefObject<HTMLDivElement | null>;
|
|
67
|
+
userSizedColIds: { current: Map<string, number> };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Saves column widths and sort per set of column ids, and keeps grids with the same columns in step */
|
|
71
|
+
export const useGridColumnStateStorage = ({
|
|
72
|
+
enabled,
|
|
73
|
+
gridApi,
|
|
74
|
+
gridDivRef,
|
|
75
|
+
userSizedColIds,
|
|
76
|
+
}: UseGridColumnStateStorageProps) => {
|
|
77
|
+
const { getColumnIds } = useGridContext();
|
|
78
|
+
const storageKey = useMemo(() => (enabled ? columnStateStorageKey(getColumnIds()) : null), [enabled, getColumnIds]);
|
|
79
|
+
const getStorage = useCallback(() => gridDivRef.current?.ownerDocument.defaultView?.localStorage, [gridDivRef]);
|
|
80
|
+
|
|
81
|
+
const apply = useCallback(
|
|
82
|
+
(stored: string | null) => {
|
|
83
|
+
const columnState = parseStoredColumnState(stored);
|
|
84
|
+
if (gridApi && !gridApi.isDestroyed() && columnState) {
|
|
85
|
+
applyStoredColumnState(gridApi, columnState, userSizedColIds.current);
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
[gridApi, userSizedColIds],
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
const listenerRef = useRef<(value: string) => void>(undefined);
|
|
92
|
+
useEffect(() => {
|
|
93
|
+
if (!storageKey) return;
|
|
94
|
+
const listener = (value: string) => apply(value);
|
|
95
|
+
listenerRef.current = listener;
|
|
96
|
+
// Saved state from earlier stories would make snapshots depend on story order
|
|
97
|
+
if (!isChromatic()) {
|
|
98
|
+
apply(getStorage()?.getItem(storageKey) ?? null);
|
|
99
|
+
}
|
|
100
|
+
return subscribeStorageKey(storageKey, listener);
|
|
101
|
+
}, [apply, getStorage, storageKey]);
|
|
102
|
+
|
|
103
|
+
const saveColumnState = useCallback(
|
|
104
|
+
(api: GridApi) => {
|
|
105
|
+
const storage = getStorage();
|
|
106
|
+
if (!storageKey || !storage) return;
|
|
107
|
+
const value = JSON.stringify(toStoredColumnState(api.getColumnState(), userSizedColIds.current.keys()));
|
|
108
|
+
publishStorageKey(storage, storageKey, value, listenerRef.current);
|
|
109
|
+
},
|
|
110
|
+
[getStorage, storageKey, userSizedColIds],
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
return { saveColumnState };
|
|
114
|
+
};
|