@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
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@linzjs/step-ag-grid",
3
3
  "repository": "github:linz/step-ag-grid.git",
4
4
  "license": "MIT",
5
- "version": "35.0.3",
5
+ "version": "35.2.0",
6
6
  "keywords": [
7
7
  "aggrid",
8
8
  "ag-grid",
@@ -13,6 +13,7 @@ import {
13
13
  EditableCallback,
14
14
  EditableCallbackParams,
15
15
  GetRowIdParams,
16
+ GridApi,
16
17
  GridOptions,
17
18
  GridReadyEvent,
18
19
  GridSizeChangedEvent,
@@ -25,6 +26,7 @@ import {
25
26
  RowDragMoveEvent,
26
27
  SelectionChangedEvent,
27
28
  SelectionColumnDef,
29
+ SortChangedEvent,
28
30
  ValueFormatterParams,
29
31
  } from 'ag-grid-community';
30
32
  import { AgGridReact } from 'ag-grid-react';
@@ -41,6 +43,7 @@ import { compareNaturalInsensitive, fnOrVar, isNotEmpty } from '../utils/util';
41
43
  import { clickInputWhenContainingCellClicked } from './clickInputWhenContainingCellClicked';
42
44
  import { GridHeaderSelect } from './gridHeader';
43
45
  import { GridContextMenuComponent, useGridContextMenu } from './gridHook';
46
+ import { useGridColumnStateStorage } from './gridHook/useGridColumnStateStorage';
44
47
  import { useGridCopy } from './gridHook/useGridCopy';
45
48
  import { CellLocation, useGridRangeSelection } from './gridHook/useGridRangeSelection';
46
49
  import { GridNoRowsOverlay } from './GridNoRowsOverlay';
@@ -75,6 +78,8 @@ export interface GridProps<TData extends GridBaseRow = GridBaseRow> {
75
78
  autoSelectFirstRow?: boolean;
76
79
  enableClickSelection?: boolean;
77
80
  enableRangeSelection?: boolean;
81
+ /** Shows GridFilterCopyButton */
82
+ enableCopy?: boolean;
78
83
  enableSelectionWithoutKeys?: boolean;
79
84
  enableMultilineBulkEdit?: boolean;
80
85
  externalSelectedIds?: TData['id'][];
@@ -97,6 +102,8 @@ export interface GridProps<TData extends GridBaseRow = GridBaseRow> {
97
102
  // ─── Callbacks / Events ───────────────────────────────────────
98
103
  onCellFocused?: (props: { colDef: ColDef<TData>; data: TData }) => void;
99
104
  onColumnMoved?: GridOptions['onColumnMoved'];
105
+ /** Save user column widths and sort, shared by every grid with the same column ids */
106
+ saveColumnState?: boolean;
100
107
  onContentSize?: (props: { width: number }) => void;
101
108
 
102
109
  /**
@@ -144,6 +151,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
144
151
  // ─── Selection ────────────────────────────────
145
152
  autoSelectFirstRow,
146
153
  enableRangeSelection = false,
154
+ enableCopy = false,
147
155
  externalSelectedIds,
148
156
  externalSelectedItems,
149
157
  selectColumnPinned = 'left',
@@ -162,6 +170,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
162
170
  // ─── Callbacks / Events ───────────────────────
163
171
  onCellFocused: paramsOnCellFocused,
164
172
  onColumnMoved,
173
+ saveColumnState = false,
165
174
 
166
175
  // ─── Row Behavior ─────────────────────────────
167
176
  suppressColumnVirtualization = true,
@@ -182,6 +191,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
182
191
  setApis,
183
192
  setExternallySelectedItemsAreInSync,
184
193
  setOnBulkEditingComplete,
194
+ setCopyEnabled,
185
195
  gridReady,
186
196
  gridRenderState,
187
197
  externallySelectedItemsAreInSync,
@@ -212,6 +222,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
212
222
  );
213
223
 
214
224
  const { updatedDep, anyUpdating, updatingCols } = useContext(GridUpdatingContext);
225
+ const [gridApi, setGridApi] = useState<GridApi<TData>>();
215
226
 
216
227
  const gridDivRef = useRef<HTMLDivElement>(null);
217
228
  const lastSelectedIds = useRef<TData['id'][]>(undefined);
@@ -308,6 +319,8 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
308
319
  }, [autoSizeColumns, gridRenderState, maxInitialWidth, params, rowData, sizeColumns, sizeColumnsToFit]);
309
320
 
310
321
  const lastOwnerDocumentRef = useRef<Document>(undefined);
322
+ // The document the grid is in, changes when the grid is popped out into another window
323
+ const [gridDocument, setGridDocument] = useState<Document>();
311
324
  const wasVisibleRef = useRef(false);
312
325
 
313
326
  /**
@@ -335,6 +348,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
335
348
  const currentDocument = gridDivRef.current?.ownerDocument;
336
349
  if (currentDocument !== lastOwnerDocumentRef.current) {
337
350
  lastOwnerDocumentRef.current = currentDocument;
351
+ setGridDocument(currentDocument);
338
352
  if (currentDocument) {
339
353
  needsAutoSize.current = true;
340
354
  }
@@ -520,6 +534,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
520
534
  const onGridReady = useCallback(
521
535
  (event: GridReadyEvent) => {
522
536
  setApis(event.api, hasExternallySelectedItems, enableMultilineBulkEdit, dataTestId);
537
+ setGridApi(event.api);
523
538
  event.api.showNoRowsOverlay();
524
539
  synchroniseExternallySelectedItemsToGrid();
525
540
  },
@@ -670,6 +685,8 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
670
685
  });
671
686
 
672
687
  const { onCopyEvent, rangeSelectInterceptContextMenu, rangeSelectContextMenuComponent } = useGridCopy({
688
+ gridDivRef,
689
+ gridDocument,
673
690
  ranges,
674
691
  rangeStartRef,
675
692
  rangeEndRef,
@@ -677,10 +694,34 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
677
694
  cellContextMenu,
678
695
  });
679
696
 
680
- const onSortChanged = useCallback(() => {
681
- clearRangeSelection();
682
- ensureSelectedRowIsVisible();
683
- }, [clearRangeSelection, ensureSelectedRowIsVisible]);
697
+ // Show GridFilterCopyButton
698
+ useEffect(() => {
699
+ setCopyEnabled(enableCopy);
700
+ return () => setCopyEnabled(false);
701
+ }, [enableCopy, setCopyEnabled]);
702
+
703
+ /**
704
+ * Set of column I'd's that are prevented from auto-sizing as they are user set
705
+ */
706
+ const userSizedColIds = useRef(new Map<string, number>());
707
+
708
+ const { saveColumnState: saveColumnStateToStorage } = useGridColumnStateStorage({
709
+ enabled: saveColumnState,
710
+ gridApi,
711
+ gridDivRef,
712
+ userSizedColIds,
713
+ });
714
+
715
+ const onSortChanged = useCallback(
716
+ (e: SortChangedEvent) => {
717
+ clearRangeSelection();
718
+ ensureSelectedRowIsVisible();
719
+ if (e.source === 'uiColumnSorted') {
720
+ saveColumnStateToStorage(e.api);
721
+ }
722
+ },
723
+ [clearRangeSelection, ensureSelectedRowIsVisible, saveColumnStateToStorage],
724
+ );
684
725
 
685
726
  /**
686
727
  * Handle single click edits
@@ -713,32 +754,33 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
713
754
  [clearRangeSelection, enableRangeSelection, singleClickEdit, startCellEditing],
714
755
  );
715
756
 
716
- /**
717
- * Set of column I'd's that are prevented from auto-sizing as they are user set
718
- */
719
- const userSizedColIds = useRef(new Map<string, number>());
720
-
721
757
  /**
722
758
  * Lock/unlock column width on user edit/reset.
723
759
  */
724
- const onColumnResized = useCallback((e: ColumnResizedEvent) => {
725
- const colId = e.column?.getColId();
726
- if (colId == null) {
727
- return;
728
- }
729
- const width = e.column?.getActualWidth();
730
- if (width == null) {
731
- return;
732
- }
733
- switch (e.source) {
734
- case 'uiColumnResized':
735
- userSizedColIds.current.set(colId, width);
736
- break;
737
- case 'autosizeColumns':
738
- userSizedColIds.current.delete(colId);
739
- break;
740
- }
741
- }, []);
760
+ const onColumnResized = useCallback(
761
+ (e: ColumnResizedEvent) => {
762
+ const colId = e.column?.getColId();
763
+ if (colId == null) {
764
+ return;
765
+ }
766
+ const width = e.column?.getActualWidth();
767
+ if (width == null) {
768
+ return;
769
+ }
770
+ switch (e.source) {
771
+ case 'uiColumnResized':
772
+ userSizedColIds.current.set(colId, width);
773
+ if (e.finished) {
774
+ saveColumnStateToStorage(e.api);
775
+ }
776
+ break;
777
+ case 'autosizeColumns':
778
+ userSizedColIds.current.delete(colId);
779
+ break;
780
+ }
781
+ },
782
+ [saveColumnStateToStorage],
783
+ );
742
784
 
743
785
  const columnMoved = useCallback(
744
786
  (e: ColumnMovedEvent<TData>) => {
@@ -1,6 +1,6 @@
1
1
  import { LuiIcon } from '@linzjs/lui';
2
2
  import clsx from 'clsx';
3
- import { ReactElement, useCallback, useMemo } from 'react';
3
+ import { ReactElement } from 'react';
4
4
 
5
5
  import { typedEntries } from '../lui/tsUtils';
6
6
  import { MenuDivider, MenuHeader, MenuItem } from '../react-menu3';
@@ -14,60 +14,63 @@ export interface CopyOptionsContext {
14
14
  setCopyType: (copyType: CopyOptionsKey) => void;
15
15
  }
16
16
 
17
+ export interface GridCopyOptionsMenuItemsProps extends CopyOptionsContext {
18
+ /** Show developer only copy options, e.g. Json */
19
+ developer?: boolean;
20
+ /** Header above the copy formats, defaults to "Copy as" */
21
+ header?: string;
22
+ }
23
+
24
+ /**
25
+ * "Copy as" and "Set copy default" menu items.
26
+ * Used by the range select context menu and GridFilterCopyButton.
27
+ */
28
+ export const GridCopyOptionsMenuItems = ({
29
+ onCopy,
30
+ copyType,
31
+ setCopyType,
32
+ developer: showDeveloper = false,
33
+ header = 'Copy as',
34
+ }: GridCopyOptionsMenuItemsProps): ReactElement => (
35
+ <>
36
+ <MenuHeader>{header}</MenuHeader>
37
+ {typedEntries(gridCopyOptions).map(([key, { icon, text, developer }]) => {
38
+ return (
39
+ (!developer || showDeveloper) && (
40
+ <MenuItem key={key} onClick={() => onCopy(key)}>
41
+ <div className={'copyMenuMenuItem'}>
42
+ <LuiIcon name={icon} alt={text} size={'md'} />
43
+ <div className={'copyMenuMenuItem__text'}>{text}</div>
44
+ </div>
45
+ </MenuItem>
46
+ )
47
+ );
48
+ })}
49
+ <MenuDivider />
50
+ <MenuHeader>Set copy default</MenuHeader>
51
+ {typedEntries(gridCopyOptions).map(([key, { text, developer }]) => {
52
+ return (
53
+ !developer && (
54
+ <MenuItem key={'default_' + key} onClick={() => setCopyType(key)}>
55
+ <div
56
+ className={clsx('copyMenuMenuItem', copyType === key ? '' : 'copyMenuMenuItem__buttonDefault--hidden')}
57
+ >
58
+ <LuiIcon name={'ic_tick'} alt={'Default'} size={'sm'} />
59
+ <div className={'copyMenuMenuItem__text'}>{text}</div>
60
+ </div>
61
+ </MenuItem>
62
+ )
63
+ );
64
+ })}
65
+ </>
66
+ );
67
+
17
68
  export const GridRangeSelectContextMenu = <TData extends GridBaseRow>({
18
69
  event,
19
70
  context,
20
- }: GridContextMenuComponentProps<TData, CopyOptionsContext>): ReactElement => {
71
+ }: GridContextMenuComponentProps<TData, CopyOptionsContext>): ReactElement | null => {
21
72
  const developerContextMenu: boolean =
22
73
  !!(event?.event as { ctrlKey?: boolean })?.ctrlKey && !!(event?.event as { shiftKey?: boolean })?.shiftKey;
23
- const onCopy = useMemo(() => context?.onCopy, [context?.onCopy]);
24
- const onClick = useCallback(
25
- (type: CopyOptionsKey) => {
26
- onCopy?.(type);
27
- },
28
- [onCopy],
29
- );
30
74
 
31
- return (
32
- <>
33
- <MenuHeader>Copy as</MenuHeader>
34
- {typedEntries(gridCopyOptions).map(([key, { icon, text, developer }]) => {
35
- return (
36
- (!developer || developerContextMenu) && (
37
- <MenuItem key={key} onClick={() => void onClick(key)}>
38
- <div className={'copyMenuMenuItem'}>
39
- <LuiIcon name={icon} alt={text} size={'md'} />
40
- <div className={'copyMenuMenuItem__text'}>{text}</div>
41
- </div>
42
- </MenuItem>
43
- )
44
- );
45
- })}
46
- <MenuDivider />
47
- <MenuHeader>Set copy default</MenuHeader>
48
- {typedEntries(gridCopyOptions).map(([key, { text, developer }]) => {
49
- return (
50
- !developer && (
51
- <MenuItem
52
- key={'default_' + key}
53
- onClick={(e) => {
54
- context?.setCopyType(key);
55
- e.keepOpen = true;
56
- }}
57
- >
58
- <div
59
- className={clsx(
60
- 'copyMenuMenuItem',
61
- context?.copyType === key ? '' : 'copyMenuMenuItem__buttonDefault--hidden',
62
- )}
63
- >
64
- <LuiIcon name={'ic_tick'} alt={'CSV'} size={'sm'} />
65
- <div className={'copyMenuMenuItem__text'}>{text}</div>
66
- </div>
67
- </MenuItem>
68
- )
69
- );
70
- })}
71
- </>
72
- );
75
+ return context ? <GridCopyOptionsMenuItems {...context} developer={developerContextMenu} /> : null;
73
76
  };
@@ -1,13 +1,26 @@
1
1
  import { LuiCheckboxInput, LuiIcon } from '@linzjs/lui';
2
2
  import { ColDef } from 'ag-grid-community';
3
3
  import { isEmpty } from 'lodash-es';
4
- import { ReactElement, useCallback, useContext, useEffect, useMemo, useState } from 'react';
4
+ import { ReactElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
5
5
 
6
6
  import { GridContext } from '../../contexts/GridContext';
7
7
  import { Menu, MenuDivider, MenuItem } from '../../react-menu3';
8
8
  import { ClickEvent } from '../../react-menu3/types';
9
+ import { publishStorageKey, subscribeStorageKey } from '../../utils/storageKeySync';
9
10
  import { GridFilterHeaderIconButton } from './GridFilterHeaderIconButton';
10
11
 
12
+ const parseInvisibleIds = (stored: string): string[] | undefined => {
13
+ const invisibleIds = JSON.parse(stored);
14
+ if (!Array.isArray(invisibleIds)) {
15
+ console.error(`stored invisible ids not an array: ${stored}`);
16
+ } else if (!invisibleIds.every((id) => typeof id === 'string')) {
17
+ console.error(`stored invisible ids not strings: ${stored}`);
18
+ } else {
19
+ return invisibleIds;
20
+ }
21
+ return undefined;
22
+ };
23
+
11
24
  export interface GridFilterColumnsToggleProps {
12
25
  saveState?: boolean;
13
26
  }
@@ -39,14 +52,8 @@ export const GridFilterColumnsToggle = ({ saveState = true }: GridFilterColumnsT
39
52
  if (!stored) {
40
53
  resetColumns();
41
54
  } else {
42
- const invisibleIds = JSON.parse(stored ?? '[]');
43
- if (!Array.isArray(invisibleIds)) {
44
- console.error(`stored invisible ids not an array: ${stored}`);
45
- } else if (!invisibleIds.every((id) => typeof id === 'string')) {
46
- console.error(`stored invisible ids not strings: ${stored}`);
47
- } else {
48
- if (invisibleIds) setInvisibleColumnIds(invisibleIds);
49
- }
55
+ const invisibleIds = parseInvisibleIds(stored);
56
+ if (invisibleIds) setInvisibleColumnIds(invisibleIds);
50
57
  }
51
58
  } catch (ex) {
52
59
  console.error(ex);
@@ -62,16 +69,42 @@ export const GridFilterColumnsToggle = ({ saveState = true }: GridFilterColumnsT
62
69
  }
63
70
  }, [columnStorageKey, invisibleColumnIds, loaded, saveState]);
64
71
 
72
+ // Keep other mounted grids with the same columns, e.g. other tabs, in step
73
+ const listenerRef = useRef<(value: string) => void>(undefined);
74
+ useEffect(() => {
75
+ if (!columnStorageKey || !saveState) return;
76
+ const listener = (value: string) => {
77
+ try {
78
+ const invisibleIds = parseInvisibleIds(value);
79
+ if (invisibleIds) setInvisibleColumnIds(invisibleIds);
80
+ } catch (ex) {
81
+ console.error(ex);
82
+ }
83
+ };
84
+ listenerRef.current = listener;
85
+ return subscribeStorageKey(columnStorageKey, listener);
86
+ }, [columnStorageKey, saveState, setInvisibleColumnIds]);
87
+
88
+ const changeInvisibleColumnIds = useCallback(
89
+ (invisibleIds: string[]) => {
90
+ setInvisibleColumnIds(invisibleIds);
91
+ if (columnStorageKey && saveState) {
92
+ publishStorageKey(window.localStorage, columnStorageKey, JSON.stringify(invisibleIds), listenerRef.current);
93
+ }
94
+ },
95
+ [columnStorageKey, saveState, setInvisibleColumnIds],
96
+ );
97
+
65
98
  const toggleColumn = useCallback(
66
99
  (colId?: string) => {
67
100
  if (!colId || !invisibleColumnIds) return;
68
- setInvisibleColumnIds(
101
+ changeInvisibleColumnIds(
69
102
  invisibleColumnIds.includes(colId)
70
103
  ? invisibleColumnIds.filter((id) => id !== colId)
71
104
  : [...invisibleColumnIds, colId],
72
105
  );
73
106
  },
74
- [invisibleColumnIds, setInvisibleColumnIds],
107
+ [changeInvisibleColumnIds, invisibleColumnIds],
75
108
  );
76
109
 
77
110
  const numericRegExp = /^\d+$/;
@@ -125,7 +158,7 @@ export const GridFilterColumnsToggle = ({ saveState = true }: GridFilterColumnsT
125
158
  // Global react-menu MenuItem handler handles tabs
126
159
  if (e.key !== 'Tab') {
127
160
  e.keepOpen = e.key !== 'Enter';
128
- resetColumns();
161
+ changeInvisibleColumnIds(getColumnIds('initialHide'));
129
162
  }
130
163
  }}
131
164
  >
@@ -0,0 +1,93 @@
1
+ import { LuiButton, LuiIcon } from '@linzjs/lui';
2
+ import { ReactElement, useCallback, useState } from 'react';
3
+
4
+ import { GridCopyScope, useGridContext } from '../../contexts/GridContext';
5
+ import { Menu } from '../../react-menu3';
6
+ import { GridCopyOptionsMenuItems } from '../GridRangeSelectContextMenu';
7
+ import { CopyOptionsKey, gridCopyOptions, useGridCopySettings } from '../gridHook/useGridCopySettings';
8
+
9
+ const copyScopeHeader: Record<GridCopyScope, string> = {
10
+ range: 'Copy range',
11
+ selection: 'Copy selection',
12
+ all: 'Copy all',
13
+ };
14
+
15
+ /** Copy format as it reads mid-sentence in the tooltip, e.g. "Copy range as text / HTML" */
16
+ const copyTypeTooltipText = (copyType: CopyOptionsKey): string =>
17
+ copyType === 'html' ? 'text / HTML' : gridCopyOptions[copyType].text;
18
+
19
+ /**
20
+ * Rendered when the menu opens, so the header shows what will be copied at that point.
21
+ * Developer options (Json) are shown when the menu was opened with ctrl+shift click.
22
+ */
23
+ const GridFilterCopyMenuItems = ({ developer }: { developer: boolean }): ReactElement => {
24
+ const { copyToClipboard, getCopyScope } = useGridContext();
25
+ const { copyType, setCopyType } = useGridCopySettings();
26
+ return (
27
+ <GridCopyOptionsMenuItems
28
+ header={copyScopeHeader[getCopyScope()]}
29
+ onCopy={copyToClipboard}
30
+ copyType={copyType}
31
+ setCopyType={setCopyType}
32
+ developer={developer}
33
+ />
34
+ );
35
+ };
36
+
37
+ /**
38
+ * Copies the selected range to the clipboard if one is selected,
39
+ * otherwise the selected rows, or all rows if no rows are selected.
40
+ * The caret menu allows choosing the copy format and setting the default copy format.
41
+ *
42
+ * Only shown when the Grid has enableCopy.
43
+ */
44
+ export const GridFilterCopyButton = (): ReactElement | null => {
45
+ const { copyEnabled, copyToClipboard, getCopyScope } = useGridContext();
46
+ const { copyType } = useGridCopySettings();
47
+
48
+ // Selection changes don't re-render the button, so update the scope before the tooltip shows
49
+ const [copyScope, setCopyScope] = useState<GridCopyScope>('all');
50
+ const updateCopyScope = useCallback(() => setCopyScope(getCopyScope()), [getCopyScope]);
51
+
52
+ // Ctrl+shift click on the caret shows developer copy options, as with the range select context menu
53
+ const [developerMenu, setDeveloperMenu] = useState(false);
54
+
55
+ if (!copyEnabled) return null;
56
+
57
+ const copyTitle = `${copyScopeHeader[copyScope]} as ${copyTypeTooltipText(copyType)}`;
58
+
59
+ return (
60
+ <div className={'lui-split-button GridFilterCopyButton'} onMouseEnter={updateCopyScope} onFocus={updateCopyScope}>
61
+ <LuiButton
62
+ type={'button'}
63
+ level={'secondary'}
64
+ className={'lui-button-icon-only lui-split-button-primary-btn GridFilterCopyButton-copy'}
65
+ title={copyTitle}
66
+ buttonProps={{ 'aria-label': copyTitle }}
67
+ onClick={() => copyToClipboard(copyType)}
68
+ >
69
+ <LuiIcon name={'ic_copy'} alt={copyTitle} size={'md'} />
70
+ </LuiButton>
71
+ <Menu
72
+ menuButton={
73
+ <button
74
+ type={'button'}
75
+ className={'popup-toggle-button popup-toggle-button-secondary GridFilterCopyButton-caret'}
76
+ title={'Copy options'}
77
+ aria-label={'Copy options'}
78
+ onClick={(e) => setDeveloperMenu(e.ctrlKey && e.shiftKey)}
79
+ >
80
+ <LuiIcon name={'ic_expand_more'} alt={'Copy options'} size={'md'} />
81
+ </button>
82
+ }
83
+ menuClassName={'step-ag-grid-react-menu'}
84
+ className={'GridContextMenu'}
85
+ align={'end'}
86
+ portal={true}
87
+ unmountOnClose={true}
88
+ >
89
+ <GridFilterCopyMenuItems developer={developerMenu} />
90
+ </Menu>
91
+ </div>
92
+ );
93
+ };
@@ -1,6 +1,7 @@
1
1
  export * from './GridFilterButtons';
2
2
  export * from './GridFilterColumnsMultiSelect';
3
3
  export * from './GridFilterColumnsToggle';
4
+ export * from './GridFilterCopyButton';
4
5
  export * from './GridFilterDownloadCsvButton';
5
6
  export * from './GridFilterHeaderIconButton';
6
7
  export * from './GridFilterQuick';
@@ -0,0 +1,142 @@
1
+ import { ColDef, IRowNode } from 'ag-grid-community';
2
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
3
+
4
+ import { GridCellFillerColId } from '../GridCellFiller';
5
+ import { agGridSelectRowColId } from '../types';
6
+ import { copyGridCells, CopyGridCellsProps, isCopyableColId } from './copyGridCells';
7
+
8
+ interface TestRow {
9
+ id: number;
10
+ name: string | null;
11
+ bearing: number;
12
+ }
13
+
14
+ const colDefs: Record<string, ColDef> = {
15
+ id: { colId: 'id', field: 'id', headerName: 'Id' },
16
+ name: { colId: 'name', field: 'name', headerName: 'Name' },
17
+ bearing: { colId: 'bearing', field: 'bearing', headerName: 'Bearing' },
18
+ [GridCellFillerColId]: { colId: GridCellFillerColId },
19
+ menu: { colId: 'menu', headerName: 'Menu', headerComponentParams: { exportable: false } },
20
+ };
21
+ const getColDef = (colId?: string) => (colId ? colDefs[colId] : undefined);
22
+
23
+ const node = (data: TestRow) => ({ data }) as IRowNode<TestRow>;
24
+ const nodes = [
25
+ node({ id: 1, name: 'Smith, "Bob"', bearing: 90 }),
26
+ node({ id: 2, name: '-', bearing: 180 }),
27
+ node({ id: 3, name: null, bearing: 270 }),
28
+ ];
29
+
30
+ // Bearing has a value formatter, the other columns format to their value
31
+ const getCellValue = (({ rowNode, colKey, useFormatter }) => {
32
+ const value = rowNode.data[colKey as string];
33
+ return useFormatter && colKey === 'bearing' ? `${value}°` : value;
34
+ }) as CopyGridCellsProps['getCellValue'];
35
+
36
+ const writeText = vi.fn(() => Promise.resolve());
37
+ const write = vi.fn(() => Promise.resolve());
38
+ const showToast = vi.fn();
39
+
40
+ const copy = (props: Partial<CopyGridCellsProps>) =>
41
+ copyGridCells({
42
+ type: 'csv',
43
+ selectedColIds: ['id', 'name'],
44
+ selectedNodes: nodes,
45
+ selectedRowIds: [],
46
+ getColDef,
47
+ getCellValue,
48
+ showToast,
49
+ ...props,
50
+ });
51
+
52
+ beforeEach(() => {
53
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText, write }, configurable: true });
54
+ vi.stubGlobal(
55
+ 'ClipboardItem',
56
+ class {
57
+ constructor(public items: Record<string, { parts: string[] }>) {}
58
+ },
59
+ );
60
+ vi.stubGlobal(
61
+ 'Blob',
62
+ class {
63
+ constructor(public parts: string[]) {}
64
+ },
65
+ );
66
+ });
67
+
68
+ afterEach(() => {
69
+ vi.unstubAllGlobals();
70
+ vi.clearAllMocks();
71
+ });
72
+
73
+ describe('isCopyableColId', () => {
74
+ test('excludes the filler and non-exportable columns', () => {
75
+ expect(isCopyableColId('id', getColDef)).toBe(true);
76
+ expect(isCopyableColId(GridCellFillerColId, getColDef)).toBe(false);
77
+ expect(isCopyableColId('menu', getColDef)).toBe(false);
78
+ });
79
+ });
80
+
81
+ describe('copyGridCells', () => {
82
+ test('csv quotes values with commas and quotes, and blanks dashes and nulls', () => {
83
+ copy({ type: 'csv' });
84
+ expect(writeText).toHaveBeenCalledWith('Id, Name\n1, "Smith, ""Bob"""\n2, \n3, \n');
85
+ expect(showToast).toHaveBeenCalledWith(expect.objectContaining({ message: 'CSV copied' }));
86
+ });
87
+
88
+ test('csv quotes values with newlines', () => {
89
+ copy({ type: 'csv', selectedColIds: ['name'], selectedNodes: [node({ id: 1, name: 'a\nb', bearing: 0 })] });
90
+ expect(writeText).toHaveBeenCalledWith('Name\n"a\nb"\n');
91
+ });
92
+
93
+ test('uses the formatted value when it differs from the raw value', () => {
94
+ copy({ type: 'csv', selectedColIds: ['id', 'bearing'], selectedNodes: [nodes[0]] });
95
+ expect(writeText).toHaveBeenCalledWith('Id, Bearing\n1, 90°\n');
96
+ });
97
+
98
+ test('excludes the filler and non-exportable columns', () => {
99
+ copy({ type: 'csv', selectedColIds: ['id', GridCellFillerColId, 'menu'], selectedNodes: [nodes[0]] });
100
+ expect(writeText).toHaveBeenCalledWith('Id\n1\n');
101
+ });
102
+
103
+ test('includes the row select column as Selected', () => {
104
+ copy({ type: 'csv', selectedColIds: [agGridSelectRowColId, 'id'], selectedNodes: nodes, selectedRowIds: [2] });
105
+ expect(writeText).toHaveBeenCalledWith('Selected, Id\nfalse, 1\ntrue, 2\nfalse, 3\n');
106
+ });
107
+
108
+ test('text / html writes a padded text table and an html table', () => {
109
+ copy({ type: 'html' });
110
+
111
+ expect(writeText).not.toHaveBeenCalled();
112
+ const [[[clipboardItem]]] = write.mock.calls as unknown as [[[{ items: Record<string, { parts: string[] }> }]]];
113
+ const text = clipboardItem.items['text/plain'].parts[0];
114
+ const html = clipboardItem.items['text/html'].parts[0];
115
+
116
+ expect(text).toBe(
117
+ [
118
+ '| Id | Name |',
119
+ '|----|--------------|',
120
+ '| 1 | Smith, "Bob" |',
121
+ '| 2 | |',
122
+ '| 3 | |',
123
+ '',
124
+ ].join('\n'),
125
+ );
126
+ expect(html).toContain('<thead');
127
+ expect(html).toMatch(/<th[^>]*>Id<\/th><th[^>]*>Name<\/th>/);
128
+ expect(html).toMatch(/<td[^>]*>1<\/td><td[^>]*>Smith, "Bob"<\/td>/);
129
+ expect(showToast).toHaveBeenCalledWith(expect.objectContaining({ message: 'Text\xa0/\xa0HTML copied' }));
130
+ });
131
+
132
+ test('json keeps raw values and keys by column id', () => {
133
+ copy({ type: 'json', selectedColIds: ['id', 'name', 'bearing'] });
134
+
135
+ const [[text]] = writeText.mock.calls as unknown as [[string]];
136
+ expect(JSON.parse(text)).toEqual([
137
+ { id: 1, name: 'Smith, "Bob"', bearing: 90 },
138
+ { id: 2, name: '-', bearing: 180 },
139
+ { id: 3, name: null, bearing: 270 },
140
+ ]);
141
+ });
142
+ });