@linzjs/step-ag-grid 35.0.2 → 35.1.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/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.2",
5
+ "version": "35.1.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';
@@ -97,6 +100,8 @@ export interface GridProps<TData extends GridBaseRow = GridBaseRow> {
97
100
  // ─── Callbacks / Events ───────────────────────────────────────
98
101
  onCellFocused?: (props: { colDef: ColDef<TData>; data: TData }) => void;
99
102
  onColumnMoved?: GridOptions['onColumnMoved'];
103
+ /** Save user column widths and sort, shared by every grid with the same column ids */
104
+ saveColumnState?: boolean;
100
105
  onContentSize?: (props: { width: number }) => void;
101
106
 
102
107
  /**
@@ -162,6 +167,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
162
167
  // ─── Callbacks / Events ───────────────────────
163
168
  onCellFocused: paramsOnCellFocused,
164
169
  onColumnMoved,
170
+ saveColumnState = false,
165
171
 
166
172
  // ─── Row Behavior ─────────────────────────────
167
173
  suppressColumnVirtualization = true,
@@ -212,6 +218,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
212
218
  );
213
219
 
214
220
  const { updatedDep, anyUpdating, updatingCols } = useContext(GridUpdatingContext);
221
+ const [gridApi, setGridApi] = useState<GridApi<TData>>();
215
222
 
216
223
  const gridDivRef = useRef<HTMLDivElement>(null);
217
224
  const lastSelectedIds = useRef<TData['id'][]>(undefined);
@@ -520,6 +527,7 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
520
527
  const onGridReady = useCallback(
521
528
  (event: GridReadyEvent) => {
522
529
  setApis(event.api, hasExternallySelectedItems, enableMultilineBulkEdit, dataTestId);
530
+ setGridApi(event.api);
523
531
  event.api.showNoRowsOverlay();
524
532
  synchroniseExternallySelectedItemsToGrid();
525
533
  },
@@ -677,10 +685,28 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
677
685
  cellContextMenu,
678
686
  });
679
687
 
680
- const onSortChanged = useCallback(() => {
681
- clearRangeSelection();
682
- ensureSelectedRowIsVisible();
683
- }, [clearRangeSelection, ensureSelectedRowIsVisible]);
688
+ /**
689
+ * Set of column I'd's that are prevented from auto-sizing as they are user set
690
+ */
691
+ const userSizedColIds = useRef(new Map<string, number>());
692
+
693
+ const { saveColumnState: saveColumnStateToStorage } = useGridColumnStateStorage({
694
+ enabled: saveColumnState,
695
+ gridApi,
696
+ gridDivRef,
697
+ userSizedColIds,
698
+ });
699
+
700
+ const onSortChanged = useCallback(
701
+ (e: SortChangedEvent) => {
702
+ clearRangeSelection();
703
+ ensureSelectedRowIsVisible();
704
+ if (e.source === 'uiColumnSorted') {
705
+ saveColumnStateToStorage(e.api);
706
+ }
707
+ },
708
+ [clearRangeSelection, ensureSelectedRowIsVisible, saveColumnStateToStorage],
709
+ );
684
710
 
685
711
  /**
686
712
  * Handle single click edits
@@ -713,32 +739,33 @@ export const Grid = <TData extends GridBaseRow = GridBaseRow>({
713
739
  [clearRangeSelection, enableRangeSelection, singleClickEdit, startCellEditing],
714
740
  );
715
741
 
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
742
  /**
722
743
  * Lock/unlock column width on user edit/reset.
723
744
  */
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
- }, []);
745
+ const onColumnResized = useCallback(
746
+ (e: ColumnResizedEvent) => {
747
+ const colId = e.column?.getColId();
748
+ if (colId == null) {
749
+ return;
750
+ }
751
+ const width = e.column?.getActualWidth();
752
+ if (width == null) {
753
+ return;
754
+ }
755
+ switch (e.source) {
756
+ case 'uiColumnResized':
757
+ userSizedColIds.current.set(colId, width);
758
+ if (e.finished) {
759
+ saveColumnStateToStorage(e.api);
760
+ }
761
+ break;
762
+ case 'autosizeColumns':
763
+ userSizedColIds.current.delete(colId);
764
+ break;
765
+ }
766
+ },
767
+ [saveColumnStateToStorage],
768
+ );
742
769
 
743
770
  const columnMoved = useCallback(
744
771
  (e: ColumnMovedEvent<TData>) => {
@@ -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,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
+ };
@@ -0,0 +1,161 @@
1
+ import { Meta, StoryObj } from '@storybook/react-vite';
2
+ import { ReactElement, useState } from 'react';
3
+ import { expect, userEvent, waitFor, within } from 'storybook/test';
4
+
5
+ import {
6
+ ColDefT,
7
+ Grid,
8
+ GridCell,
9
+ GridContextProvider,
10
+ GridFilters,
11
+ GridUpdatingContextProvider,
12
+ GridWrapper,
13
+ } from '../..';
14
+ import { GridFilterColumnsToggle } from '../../components';
15
+ import { clickColumnHeaderToSort, waitForGridRows } from '../../utils/__tests__/storybookTestUtil';
16
+
17
+ interface ITestRow {
18
+ id: number;
19
+ name: string;
20
+ description: string;
21
+ }
22
+
23
+ const columnDefs: ColDefT<ITestRow>[] = [
24
+ GridCell<ITestRow, ITestRow['id']>({ field: 'id', headerName: 'Id' }),
25
+ GridCell<ITestRow, ITestRow['name']>({ field: 'name', headerName: 'Name' }),
26
+ GridCell<ITestRow, ITestRow['description']>({ field: 'description', headerName: 'Description', flex: 1 }),
27
+ ];
28
+
29
+ const tabs: { label: string; rowData: ITestRow[] }[] = [
30
+ {
31
+ label: 'First tab',
32
+ rowData: [
33
+ { id: 1, name: 'Charlie', description: 'First tab row' },
34
+ { id: 2, name: 'Alpha', description: 'First tab row' },
35
+ ],
36
+ },
37
+ {
38
+ label: 'Second tab',
39
+ rowData: [
40
+ { id: 3, name: 'Bravo', description: 'Second tab row' },
41
+ { id: 4, name: 'Delta', description: 'Second tab row' },
42
+ ],
43
+ },
44
+ ];
45
+
46
+ const TabbedGrids = (): ReactElement => {
47
+ const [activeTab, setActiveTab] = useState(tabs[0].label);
48
+ return (
49
+ <>
50
+ <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
51
+ {tabs.map((tab) => (
52
+ <button
53
+ key={tab.label}
54
+ role="tab"
55
+ aria-selected={tab.label === activeTab}
56
+ onClick={() => setActiveTab(tab.label)}
57
+ >
58
+ {tab.label}
59
+ </button>
60
+ ))}
61
+ </div>
62
+ {tabs.map((tab) => (
63
+ <div
64
+ key={tab.label}
65
+ role="tabpanel"
66
+ aria-label={tab.label}
67
+ style={{ display: tab.label === activeTab ? 'flex' : 'none', flexDirection: 'column', flex: 1 }}
68
+ >
69
+ <GridUpdatingContextProvider>
70
+ <GridContextProvider>
71
+ <GridWrapper maxHeight={300}>
72
+ <GridFilters>
73
+ <GridFilterColumnsToggle />
74
+ </GridFilters>
75
+ <Grid data-testid={tab.label} columnDefs={columnDefs} rowData={tab.rowData} saveColumnState={true} />
76
+ </GridWrapper>
77
+ </GridContextProvider>
78
+ </GridUpdatingContextProvider>
79
+ </div>
80
+ ))}
81
+ </>
82
+ );
83
+ };
84
+
85
+ const meta: Meta<typeof TabbedGrids> = {
86
+ title: 'Components / Grids',
87
+ component: TabbedGrids,
88
+ beforeEach: () => {
89
+ Object.keys(window.localStorage)
90
+ .filter((key) => key.startsWith('stepAgGrid_columnState_') || key.startsWith('stepAgGrid_invisibleColumnIds_'))
91
+ .forEach((key) => window.localStorage.removeItem(key));
92
+ },
93
+ decorators: [
94
+ (Story) => (
95
+ <div style={{ width: 1024, height: 400, display: 'flex', flexDirection: 'column' }}>
96
+ <Story />
97
+ </div>
98
+ ),
99
+ ],
100
+ };
101
+ export default meta;
102
+
103
+ type Story = StoryObj<typeof meta>;
104
+
105
+ const panel = (canvasElement: HTMLElement, label: string) =>
106
+ within(canvasElement).getByRole('tabpanel', { name: label });
107
+ const headerCell = (canvasElement: HTMLElement, label: string, colId: string) =>
108
+ panel(canvasElement, label).querySelector<HTMLElement>(`.ag-header-cell[col-id="${colId}"]`)!;
109
+ const showTab = (canvasElement: HTMLElement, label: string) =>
110
+ userEvent.click(within(canvasElement).getByRole('tab', { name: label }));
111
+
112
+ export const GridColumnStateSharedBetweenTabs: Story = {
113
+ play: async ({ canvasElement }) => {
114
+ await waitForGridRows({ grid: panel(canvasElement, 'First tab') });
115
+
116
+ await clickColumnHeaderToSort('name', panel(canvasElement, 'First tab'));
117
+ await showTab(canvasElement, 'Second tab');
118
+ await waitFor(() =>
119
+ expect(headerCell(canvasElement, 'Second tab', 'name')).toHaveAttribute('aria-sort', 'ascending'),
120
+ );
121
+
122
+ const nameHeader = headerCell(canvasElement, 'Second tab', 'name');
123
+ const widthBefore = nameHeader.getBoundingClientRect().width;
124
+ const handle = nameHeader.querySelector<HTMLElement>('.ag-header-cell-resize')!;
125
+ const { left, top, width, height } = handle.getBoundingClientRect();
126
+ const start = { clientX: left + width / 2, clientY: top + height / 2 };
127
+ await userEvent.pointer([
128
+ { keys: '[MouseLeft>]', target: handle, coords: start },
129
+ { target: handle, coords: { ...start, clientX: start.clientX + 60 } },
130
+ { target: handle, coords: { ...start, clientX: start.clientX + 120 } },
131
+ { keys: '[/MouseLeft]', target: handle, coords: { ...start, clientX: start.clientX + 120 } },
132
+ ]);
133
+ await waitFor(() => expect(nameHeader.getBoundingClientRect().width).toBeGreaterThan(widthBefore + 60));
134
+ const resizedWidth = Math.round(nameHeader.getBoundingClientRect().width);
135
+
136
+ await showTab(canvasElement, 'First tab');
137
+ await waitFor(() =>
138
+ expect(Math.round(headerCell(canvasElement, 'First tab', 'name').getBoundingClientRect().width)).toBe(
139
+ resizedWidth,
140
+ ),
141
+ );
142
+ },
143
+ };
144
+
145
+ export const GridColumnVisibilitySharedBetweenTabs: Story = {
146
+ play: async ({ canvasElement }) => {
147
+ await waitForGridRows({ grid: panel(canvasElement, 'First tab') });
148
+ await showTab(canvasElement, 'Second tab');
149
+ await waitForGridRows({ grid: panel(canvasElement, 'Second tab') });
150
+ await showTab(canvasElement, 'First tab');
151
+
152
+ await userEvent.click(within(panel(canvasElement, 'First tab')).getByTitle('Column visibility'));
153
+ const menuItems = await within(document.body).findAllByRole('menuitem');
154
+ await userEvent.click(menuItems.find((item) => item.textContent === 'Name')!);
155
+ await userEvent.keyboard('{Escape}');
156
+ await waitFor(() => expect(headerCell(canvasElement, 'First tab', 'name')).toBeNull());
157
+
158
+ await showTab(canvasElement, 'Second tab');
159
+ await waitFor(() => expect(headerCell(canvasElement, 'Second tab', 'name')).toBeNull());
160
+ },
161
+ };
@@ -178,6 +178,10 @@ $grid-base-font-size: calc(#{lui.$base-font-size} - 1px);
178
178
  &.ag-header-group-cell-with-group {
179
179
  background-color: lui.$iceberg;
180
180
  }
181
+
182
+ .ag-header-group-cell-label {
183
+ justify-content: center;
184
+ }
181
185
  }
182
186
 
183
187
  div.ag-cell-wrapper .ag-selection-checkbox {