@linzjs/step-ag-grid 35.1.0 → 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 (32) hide show
  1. package/dist/index.css +17 -0
  2. package/dist/src/components/Grid.d.ts +3 -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/useGridCopy.d.ts +5 -2
  9. package/dist/src/components/gridHook/useGridCopySettings.d.ts +2 -0
  10. package/dist/src/contexts/GridContext.d.ts +35 -0
  11. package/dist/src/contexts/GridContextProvider.copy.test.d.ts +1 -0
  12. package/dist/step-ag-grid.cjs +431 -231
  13. package/dist/step-ag-grid.cjs.map +1 -1
  14. package/dist/step-ag-grid.esm.js +432 -233
  15. package/dist/step-ag-grid.esm.js.map +1 -1
  16. package/package.json +1 -1
  17. package/src/components/Grid.tsx +15 -0
  18. package/src/components/GridRangeSelectContextMenu.tsx +54 -51
  19. package/src/components/gridFilter/GridFilterCopyButton.tsx +93 -0
  20. package/src/components/gridFilter/index.ts +1 -0
  21. package/src/components/gridHook/copyGridCells.test.ts +142 -0
  22. package/src/components/gridHook/copyGridCells.ts +225 -0
  23. package/src/components/gridHook/useGridCopy.ts +88 -211
  24. package/src/components/gridHook/useGridCopySettings.ts +21 -6
  25. package/src/contexts/GridContext.tsx +44 -0
  26. package/src/contexts/GridContextProvider.copy.test.tsx +158 -0
  27. package/src/contexts/GridContextProvider.tsx +129 -2
  28. package/src/stories/grid/GridCopy.stories.tsx +35 -20
  29. package/src/stories/grid/GridCopyEditable.stories.tsx +131 -0
  30. package/src/stories/grid/GridCopyMultiple.stories.tsx +119 -0
  31. package/src/styles/GridFilterCopyButton.scss +22 -0
  32. package/src/styles/index.scss +1 -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.1.0",
5
+ "version": "35.2.0",
6
6
  "keywords": [
7
7
  "aggrid",
8
8
  "ag-grid",
@@ -78,6 +78,8 @@ export interface GridProps<TData extends GridBaseRow = GridBaseRow> {
78
78
  autoSelectFirstRow?: boolean;
79
79
  enableClickSelection?: boolean;
80
80
  enableRangeSelection?: boolean;
81
+ /** Shows GridFilterCopyButton */
82
+ enableCopy?: boolean;
81
83
  enableSelectionWithoutKeys?: boolean;
82
84
  enableMultilineBulkEdit?: boolean;
83
85
  externalSelectedIds?: TData['id'][];
@@ -149,6 +151,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
149
151
  // ─── Selection ────────────────────────────────
150
152
  autoSelectFirstRow,
151
153
  enableRangeSelection = false,
154
+ enableCopy = false,
152
155
  externalSelectedIds,
153
156
  externalSelectedItems,
154
157
  selectColumnPinned = 'left',
@@ -188,6 +191,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
188
191
  setApis,
189
192
  setExternallySelectedItemsAreInSync,
190
193
  setOnBulkEditingComplete,
194
+ setCopyEnabled,
191
195
  gridReady,
192
196
  gridRenderState,
193
197
  externallySelectedItemsAreInSync,
@@ -315,6 +319,8 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
315
319
  }, [autoSizeColumns, gridRenderState, maxInitialWidth, params, rowData, sizeColumns, sizeColumnsToFit]);
316
320
 
317
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>();
318
324
  const wasVisibleRef = useRef(false);
319
325
 
320
326
  /**
@@ -342,6 +348,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
342
348
  const currentDocument = gridDivRef.current?.ownerDocument;
343
349
  if (currentDocument !== lastOwnerDocumentRef.current) {
344
350
  lastOwnerDocumentRef.current = currentDocument;
351
+ setGridDocument(currentDocument);
345
352
  if (currentDocument) {
346
353
  needsAutoSize.current = true;
347
354
  }
@@ -678,6 +685,8 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
678
685
  });
679
686
 
680
687
  const { onCopyEvent, rangeSelectInterceptContextMenu, rangeSelectContextMenuComponent } = useGridCopy({
688
+ gridDivRef,
689
+ gridDocument,
681
690
  ranges,
682
691
  rangeStartRef,
683
692
  rangeEndRef,
@@ -685,6 +694,12 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
685
694
  cellContextMenu,
686
695
  });
687
696
 
697
+ // Show GridFilterCopyButton
698
+ useEffect(() => {
699
+ setCopyEnabled(enableCopy);
700
+ return () => setCopyEnabled(false);
701
+ }, [enableCopy, setCopyEnabled]);
702
+
688
703
  /**
689
704
  * Set of column I'd's that are prevented from auto-sizing as they are user set
690
705
  */
@@ -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
  };
@@ -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
+ });
@@ -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
+ };