@opencorestack/opengridx 0.1.6 → 0.1.8

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 (130) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README.md +9 -0
  3. package/dist/index.d.ts +12 -1
  4. package/dist/opengridx.css +1 -1
  5. package/dist/opengridx.es.js +2505 -2450
  6. package/dist/opengridx.es.js.map +1 -1
  7. package/dist/opengridx.umd.js +12 -12
  8. package/dist/opengridx.umd.js.map +1 -1
  9. package/docs/API_REFERENCE.md +177 -0
  10. package/docs/README.md +60 -0
  11. package/docs/components/cell.md +44 -0
  12. package/docs/components/column-group-header.md +57 -0
  13. package/docs/components/column-resize.md +63 -0
  14. package/docs/components/column-visibility.md +61 -0
  15. package/docs/components/datagrid.md +70 -0
  16. package/docs/components/filter-panel.md +26 -0
  17. package/docs/components/header.md +39 -0
  18. package/docs/components/pagination.md +34 -0
  19. package/docs/components/row.md +31 -0
  20. package/docs/components/toolbar.md +40 -0
  21. package/docs/components/tooltip.md +68 -0
  22. package/docs/customization/slots-api.md +227 -0
  23. package/docs/customization/theming.md +293 -0
  24. package/docs/features/aggregation-pivot.md +79 -0
  25. package/docs/features/cell-spanning.md +520 -0
  26. package/docs/features/clipboard.md +76 -0
  27. package/docs/features/custom-pagination.md +143 -0
  28. package/docs/features/data-source.md +72 -0
  29. package/docs/features/editing-reordering.md +99 -0
  30. package/docs/features/export-guide.md +434 -0
  31. package/docs/features/filtering.md +83 -0
  32. package/docs/features/infinite-scroll.md +87 -0
  33. package/docs/features/list-view.md +65 -0
  34. package/docs/features/loading-states.md +68 -0
  35. package/docs/features/master-detail.md +46 -0
  36. package/docs/features/pinning.md +67 -0
  37. package/docs/features/selection.md +70 -0
  38. package/docs/features/sorting-pagination.md +66 -0
  39. package/docs/features/state-persistence.md +67 -0
  40. package/docs/features/tree-data-grouping.md +67 -0
  41. package/docs/features/virtualization.md +188 -0
  42. package/docs/roadmap.md +71 -0
  43. package/lib/components/Cell/Cell.css +119 -0
  44. package/lib/components/Cell/Cell.tsx +264 -0
  45. package/lib/components/Cell/GridEditInputCell.css +62 -0
  46. package/lib/components/Cell/GridEditInputCell.tsx +152 -0
  47. package/lib/components/ColumnGroupHeader/ColumnGroupHeader.css +67 -0
  48. package/lib/components/ColumnGroupHeader/ColumnGroupHeader.tsx +220 -0
  49. package/lib/components/ColumnResizeHandle/ColumnResizeHandle.css +31 -0
  50. package/lib/components/ColumnResizeHandle/ColumnResizeHandle.tsx +85 -0
  51. package/lib/components/ColumnVisibilityPanel/ColumnVisibilityPanel.css +137 -0
  52. package/lib/components/ColumnVisibilityPanel/ColumnVisibilityPanel.tsx +190 -0
  53. package/lib/components/DataGrid/DataGrid.css +224 -0
  54. package/lib/components/DataGrid/DataGrid.tsx +2269 -0
  55. package/lib/components/DetailPanel/DetailPanel.css +36 -0
  56. package/lib/components/DetailPanel/DetailPanel.tsx +34 -0
  57. package/lib/components/FilterPanel/FilterPanel.css +196 -0
  58. package/lib/components/FilterPanel/FilterPanel.tsx +214 -0
  59. package/lib/components/FilterPanel/index.ts +1 -0
  60. package/lib/components/Header/ColumnMenu.css +68 -0
  61. package/lib/components/Header/ColumnMenu.tsx +249 -0
  62. package/lib/components/Header/Header.css +224 -0
  63. package/lib/components/Header/Header.tsx +516 -0
  64. package/lib/components/ListView/ListView.css +112 -0
  65. package/lib/components/ListView/ListViewRow.tsx +63 -0
  66. package/lib/components/Pagination/Pagination.css +91 -0
  67. package/lib/components/Pagination/Pagination.tsx +151 -0
  68. package/lib/components/QuickFilter/QuickFilter.css +23 -0
  69. package/lib/components/QuickFilter/QuickFilter.tsx +79 -0
  70. package/lib/components/Row/Row.css +126 -0
  71. package/lib/components/Row/Row.tsx +377 -0
  72. package/lib/components/Skeleton/Skeleton.css +55 -0
  73. package/lib/components/Skeleton/Skeleton.tsx +22 -0
  74. package/lib/components/SkeletonRow/SkeletonRow.css +32 -0
  75. package/lib/components/SkeletonRow/SkeletonRow.tsx +89 -0
  76. package/lib/components/SkeletonRow/index.ts +1 -0
  77. package/lib/components/Toolbar/GlobalSearch.css +110 -0
  78. package/lib/components/Toolbar/GlobalSearch.tsx +167 -0
  79. package/lib/components/Toolbar/GridToolbar.css +221 -0
  80. package/lib/components/Toolbar/GridToolbar.tsx +658 -0
  81. package/lib/components/Toolbar/PivotPanel.css +212 -0
  82. package/lib/components/Toolbar/PivotPanel.tsx +239 -0
  83. package/lib/components/Tooltip/Tooltip.css +59 -0
  84. package/lib/components/Tooltip/Tooltip.tsx +106 -0
  85. package/lib/components/ui/Button.css +89 -0
  86. package/lib/components/ui/Button.tsx +39 -0
  87. package/lib/components/ui/Checkbox.css +71 -0
  88. package/lib/components/ui/Checkbox.tsx +66 -0
  89. package/lib/components/ui/DragHandleIcon.css +19 -0
  90. package/lib/components/ui/DragHandleIcon.tsx +18 -0
  91. package/lib/components/ui/ExpandIcon.css +38 -0
  92. package/lib/components/ui/ExpandIcon.tsx +75 -0
  93. package/lib/components/ui/Input.css +59 -0
  94. package/lib/components/ui/Input.tsx +45 -0
  95. package/lib/components/ui/index.ts +15 -0
  96. package/lib/hooks/core/useDataGrid.ts +392 -0
  97. package/lib/hooks/core/useGridApiRef.ts +10 -0
  98. package/lib/hooks/features/useAggregation.ts +143 -0
  99. package/lib/hooks/features/useGridClipboard.ts +133 -0
  100. package/lib/hooks/features/useGridDataSource.ts +190 -0
  101. package/lib/hooks/features/useGridEditing.ts +100 -0
  102. package/lib/hooks/features/useGridSpanning.ts +349 -0
  103. package/lib/hooks/features/usePivot.ts +174 -0
  104. package/lib/hooks/useColumnReorder.ts +114 -0
  105. package/lib/hooks/useRowGrouping.ts +302 -0
  106. package/lib/hooks/useRowReorder.ts +83 -0
  107. package/lib/hooks/useTreeData.ts +323 -0
  108. package/lib/index.ts +106 -0
  109. package/lib/state/index.ts +17 -0
  110. package/lib/state/types.ts +48 -0
  111. package/lib/state/useGridStateStorage.ts +113 -0
  112. package/lib/styles/base/reset.css +21 -0
  113. package/lib/styles/base/variables.css +161 -0
  114. package/lib/styles/opengridx.css +27 -0
  115. package/lib/styles/opengridx.css.d.ts +4 -0
  116. package/lib/theme/DataGridThemeProvider.tsx +276 -0
  117. package/lib/theme/defaultStyles.ts +0 -0
  118. package/lib/theme/index.ts +21 -0
  119. package/lib/theme/presets.ts +148 -0
  120. package/lib/theme/types.ts +155 -0
  121. package/lib/types/index.ts +764 -0
  122. package/lib/utils/export/exportToExcelAdvanced.ts +516 -0
  123. package/lib/utils/export/index.ts +550 -0
  124. package/lib/utils/filtering/index.ts +240 -0
  125. package/lib/utils/pinning/index.ts +282 -0
  126. package/lib/utils/sorting/index.ts +55 -0
  127. package/lib/utils/virtualization/index.ts +106 -0
  128. package/lib/vite-env.d.ts +1 -0
  129. package/llms.txt +2 -1
  130. package/package.json +12 -4
@@ -0,0 +1,2269 @@
1
+ import React, { useRef, useEffect, useCallback, useMemo, useState } from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ import { ListViewRow } from '../ListView/ListViewRow';
4
+ import type { GridState } from '../../state/types';
5
+ import { Header } from '../Header/Header';
6
+ import { Row } from '../Row/Row';
7
+ import { SkeletonRow } from '../SkeletonRow';
8
+ import { Pagination } from '../Pagination/Pagination';
9
+ import { useDataGrid } from '../../hooks/core/useDataGrid';
10
+ import { useColumnReorder } from '../../hooks/useColumnReorder';
11
+ import { useRowReorder } from '../../hooks/useRowReorder';
12
+ import { useTreeData } from '../../hooks/useTreeData';
13
+ import { useRowGrouping } from '../../hooks/useRowGrouping';
14
+ import { useGridEditing } from '../../hooks/features/useGridEditing';
15
+ import { useGridSpanning } from '../../hooks/features/useGridSpanning';
16
+ import { useGridDataSource } from '../../hooks/features/useGridDataSource';
17
+ import { useAggregation, formatAggregationValue } from '../../hooks/features/useAggregation';
18
+ import { usePivot } from '../../hooks/features/usePivot';
19
+ import { useGridClipboard } from '../../hooks/features/useGridClipboard';
20
+ import { ExpandIcon } from '../ui/ExpandIcon';
21
+ import { ColumnVisibilityPanel } from '../ColumnVisibilityPanel/ColumnVisibilityPanel';
22
+ import { getPinnedRowGroups, isRowPinned, isColumnPinned } from '../../utils/pinning';
23
+ import { sortRows } from '../../utils/sorting';
24
+ import { filterRows } from '../../utils/filtering';
25
+ import type { DataGridProps, GridRowModel, GridRowId, GridSortDirection, GridColumnOrderChangeParams, GridColDef, GridRenderCellParams, GridRowParams, GridCellParams, GridPaginationModel, GridDataSource, GridAggregationResult, GridAggregationModel, GridPivotModel, GridColumnPinning, GridFilterModel } from '../../types';
26
+ import '../../styles/opengridx.css';
27
+
28
+ export function DataGrid<R extends GridRowModel = GridRowModel>(props: DataGridProps<R>) {
29
+ const {
30
+ rows,
31
+ columns,
32
+ getRowId,
33
+ rowHeight = 52,
34
+ headerHeight = 56,
35
+ autoHeight = false,
36
+ checkboxSelection = false,
37
+ rowSelectionModel: propRowSelectionModel,
38
+ onRowSelectionModelChange: propOnRowSelectionModelChange,
39
+ onRowClick,
40
+ onCellClick,
41
+
42
+ filterModel: propFilterModel,
43
+ onFilterModelChange,
44
+ sortModel: propSortModel,
45
+ onSortModelChange,
46
+ pagination: propPagination = false,
47
+ paginationModel = { page: 0, pageSize: 100 },
48
+ onPaginationModelChange,
49
+ pageSizeOptions = [10, 25, 50, 100],
50
+ pinnedColumns: propPinnedColumns,
51
+ onPinnedColumnsChange,
52
+ pinnedRows,
53
+
54
+ getDetailPanelContent,
55
+ getDetailPanelHeight,
56
+ detailPanelExpandedRowIds: controlledExpandedRowIds,
57
+ onDetailPanelExpandedRowIdsChange,
58
+ pinCheckboxColumn = true,
59
+ pinExpandColumn = true,
60
+ disableColumnReorder = false,
61
+ columnOrder,
62
+ onColumnOrderChange,
63
+ height,
64
+ rowReordering = false,
65
+ onRowOrderChange,
66
+ loading = false,
67
+
68
+ treeData = false,
69
+ getTreeDataPath,
70
+ defaultGroupingExpansionDepth,
71
+
72
+ rowGroupingModel: propRowGroupingModel,
73
+
74
+ aggregationModel: propAggregationModel,
75
+ onAggregationModelChange,
76
+ getAggregationPosition,
77
+
78
+ isCellEditable,
79
+ processRowUpdate,
80
+ onProcessRowUpdateError,
81
+
82
+ dataSource,
83
+ sortingMode = 'client',
84
+ filterMode = 'client',
85
+ paginationMode = 'client',
86
+ rowCount: propRowCount,
87
+
88
+ slots,
89
+ slotProps,
90
+
91
+ pivotMode = false,
92
+ pivotModel: propPivotModel,
93
+ onPivotModelChange,
94
+
95
+ className = '',
96
+ style,
97
+ onRowsScrollEnd,
98
+ ariaLabel,
99
+ initialState,
100
+ onStateChange,
101
+ // Column Visibility
102
+ columnVisibilityModel: propColumnVisibilityModel,
103
+ onColumnVisibilityModelChange,
104
+ listView = false,
105
+ listViewColumn,
106
+ columnGroupingModel,
107
+ noRowsLabel = 'No Data',
108
+ apiRef: propApiRef,
109
+ } = props;
110
+
111
+ // Stable defaults
112
+ const defaultFilterModel: GridFilterModel = useMemo(() => ({ items: [] }), []);
113
+ const filterModel = (propFilterModel || defaultFilterModel) as GridFilterModel;
114
+
115
+ const [internalSortModel, setInternalSortModel] = useState<{ field: string; sort: 'asc' | 'desc' }[]>(
116
+ () => initialState?.sorting?.sortModel ?? []
117
+ );
118
+ const isSortControlled = propSortModel !== undefined;
119
+ const sortModel = isSortControlled ? propSortModel : internalSortModel;
120
+
121
+ const defaultRowGroupingModel = useMemo(() => [], []);
122
+ const rowGroupingModel = propRowGroupingModel || defaultRowGroupingModel;
123
+ const isAggregationControlled = propAggregationModel !== undefined;
124
+
125
+ // ─── Stabilize toolbar component identity ────────────────────────────────
126
+ // Problem: demos/users often define their toolbar as an inline function
127
+ // INSIDE their component body, e.g.:
128
+ // const MyToolbar = (props) => <GridToolbar {...props} /> // inside render!
129
+ // This creates a NEW function reference on every parent re-render. React
130
+ // reconciles by component *identity*, so a new reference = unmount old
131
+ // toolbar + mount fresh one = all toolbar state (search expansion, filter
132
+ // open, typed text) is destroyed on every keystroke.
133
+ //
134
+ // Fix: a stable wrapper component created ONCE via useRef. Its identity
135
+ // never changes, so React keeps it mounted. It reads the latest toolbar
136
+ // from a separate ref that is updated on every render, so the rendered
137
+ // output is always current — zero stale closures.
138
+ const latestToolbarRef = useRef(slots?.toolbar);
139
+ latestToolbarRef.current = slots?.toolbar;
140
+ // The wrapper itself has a stable identity (created once via useRef).
141
+ // We call latestToolbarRef.current(props) as a PLAIN FUNCTION — not via
142
+ // React.createElement — so React never sees a changing component type.
143
+ // The elements the toolbar function returns are reconciled normally, so
144
+ // GridToolbar's internal state (filterOpen, search expansion) is preserved
145
+ // even when the toolbar is defined as an inline function inside the parent.
146
+ const StableToolbar = useRef((props: Record<string, unknown>) => {
147
+ const Toolbar = latestToolbarRef.current;
148
+ return Toolbar ? (Toolbar as (p: typeof props) => React.ReactElement | null)(props) : null;
149
+ }).current;
150
+ const [internalAggregationModel, setInternalAggregationModel] = useState<GridAggregationModel>(
151
+ () => propAggregationModel ?? {}
152
+ );
153
+ const aggregationModel = isAggregationControlled ? propAggregationModel : internalAggregationModel;
154
+
155
+ const handleAggregationModelChange = useCallback((model: GridAggregationModel) => {
156
+ if (!isAggregationControlled) {
157
+ setInternalAggregationModel(model);
158
+ }
159
+ onAggregationModelChange?.(model);
160
+ }, [isAggregationControlled, onAggregationModelChange]);
161
+
162
+ const [internalColumnVisibilityModel, setInternalColumnVisibilityModel] = useState<Record<string, boolean>>(
163
+ () => initialState?.columns?.columnVisibilityModel ?? {}
164
+ );
165
+ const isColumnVisibilityControlled = propColumnVisibilityModel !== undefined;
166
+ const columnVisibilityModel = isColumnVisibilityControlled ? propColumnVisibilityModel : internalColumnVisibilityModel;
167
+
168
+ const handleColumnVisibilityModelChange = useCallback((model: Record<string, boolean>) => {
169
+ if (!isColumnVisibilityControlled) {
170
+ setInternalColumnVisibilityModel(model);
171
+ }
172
+ onColumnVisibilityModelChange?.(model);
173
+ }, [isColumnVisibilityControlled, onColumnVisibilityModelChange]);
174
+
175
+ const [internalPinnedColumns, setInternalPinnedColumns] = useState<GridColumnPinning>(
176
+ () => initialState?.columns?.pinnedColumns ?? {}
177
+ );
178
+ const isPinnedColumnsControlled = propPinnedColumns !== undefined;
179
+ const pinnedColumns = isPinnedColumnsControlled ? propPinnedColumns : internalPinnedColumns;
180
+
181
+ const handlePinnedColumnsChange = useCallback((model: GridColumnPinning) => {
182
+ if (!isPinnedColumnsControlled) {
183
+ setInternalPinnedColumns(model);
184
+ }
185
+ onPinnedColumnsChange?.(model);
186
+ }, [isPinnedColumnsControlled, onPinnedColumnsChange]);
187
+
188
+ const EMPTY_PIVOT_MODEL: GridPivotModel = useMemo(() => ({ rowFields: [], columnFields: [], valueFields: [] }), []);
189
+ const [internalPivotModel, setInternalPivotModel] = useState<GridPivotModel>(propPivotModel ?? EMPTY_PIVOT_MODEL);
190
+ const currentPivotModel = propPivotModel ?? internalPivotModel;
191
+ const handlePivotModelChange = useCallback((model: GridPivotModel) => {
192
+ setInternalPivotModel(model);
193
+ onPivotModelChange?.(model);
194
+ }, [onPivotModelChange]);
195
+ const pivot = usePivot(rows as GridRowModel[], columns as unknown as GridColDef[], currentPivotModel, pivotMode);
196
+
197
+ const activeRows = (pivotMode && pivot.isValid ? pivot.pivotRows : rows) as unknown as R[];
198
+ const activeColumns = (pivotMode && pivot.isValid ? pivot.pivotColumns : columns) as unknown as GridColDef<R>[];
199
+
200
+ const [serverAggregationResults, setServerAggregationResults] = useState<GridAggregationResult | null>(null);
201
+
202
+ useEffect(() => {
203
+ setServerAggregationResults(null);
204
+ }, [aggregationModel]);
205
+
206
+ const [internalPaginationModel, setInternalPaginationModel] = useState(
207
+ () => initialState?.pagination?.paginationModel ?? paginationModel
208
+ );
209
+ const isPaginationControlled = props.paginationModel !== undefined;
210
+ const effectivePaginationModel = isPaginationControlled ? paginationModel : internalPaginationModel;
211
+
212
+ const handlePaginationModelChange = useCallback((newModel: GridPaginationModel) => {
213
+ if (!isPaginationControlled) {
214
+ setInternalPaginationModel(newModel);
215
+ }
216
+ onPaginationModelChange?.(newModel);
217
+ }, [isPaginationControlled, onPaginationModelChange]);
218
+
219
+ const [internalRowSelectionModel, setInternalRowSelectionModel] = useState<GridRowId[]>([]);
220
+ const isSelectionControlled = propRowSelectionModel !== undefined;
221
+ const rowSelectionModel = isSelectionControlled ? propRowSelectionModel : internalRowSelectionModel;
222
+ const selectedRowIds = useMemo(() => new Set(rowSelectionModel), [rowSelectionModel]);
223
+ const onRowSelectionModelChange = propOnRowSelectionModelChange;
224
+
225
+ const viewportRef = useRef<HTMLDivElement>(null);
226
+ const contentRef = useRef<HTMLDivElement>(null);
227
+ const gridRef = useRef<HTMLDivElement>(null);
228
+
229
+ const defaultGetRowId = useCallback((row: R) => row.id, []);
230
+ const effectiveGetRowId = getRowId || defaultGetRowId;
231
+
232
+ const [focusedCell, setFocusedCell] = useState<{ id: GridRowId; field: string } | null>(null);
233
+
234
+ // Keyboard-mode flag: toggled via DOM classname — no React state needed
235
+ // so the ring appears instantly without a re-render cycle.
236
+ const setKeyboardMode = useCallback((on: boolean) => {
237
+ containerRef.current?.classList.toggle('ogx--kb', on);
238
+ }, []);
239
+
240
+ const dataSourceRef = useRef<GridDataSource<R> | undefined>(dataSource);
241
+ dataSourceRef.current = dataSource;
242
+
243
+ const fetchChildrenRef = useRef<((parentId: GridRowId, groupKeys: string[]) => Promise<void>) | null>(null);
244
+ const treeDataRef = useRef<any>(null);
245
+
246
+ const handleNodeExpansion = useCallback((node: any) => {
247
+ if (dataSourceRef.current && treeData) {
248
+
249
+ if (node.serverChildrenCount > 0 && node.children.length === 0) {
250
+
251
+ const groupKeys = treeDataRef.current?.getNodePath(node.id) || [node.groupingKey];
252
+ fetchChildrenRef.current?.(node.id, groupKeys);
253
+ }
254
+ }
255
+ }, [treeData]);
256
+
257
+ const gridData = useDataGrid({
258
+ rows: activeRows,
259
+ columns: activeColumns,
260
+ rowHeight,
261
+ headerHeight,
262
+ rowCount: propRowCount,
263
+ columnVisibilityModel,
264
+ initialState: props.initialState
265
+ });
266
+ const {
267
+ state,
268
+ apiRef,
269
+ setRows,
270
+ setColumns,
271
+ setScroll,
272
+ setDimensions,
273
+ setDataSourceLoading,
274
+ setDataSourceError,
275
+ setRowCount
276
+ } = gridData;
277
+
278
+ useEffect(() => {
279
+ if (propApiRef) {
280
+ propApiRef.current = apiRef.current;
281
+ }
282
+ }, [propApiRef, apiRef]);
283
+
284
+ const { copySelectedRows } = useGridClipboard({
285
+ selectedRowIds,
286
+ columns: activeColumns as unknown as GridColDef[],
287
+ getVisibleRows: () => apiRef.current.getVisibleRows(),
288
+ getRowId: effectiveGetRowId as unknown as (row: GridRowModel) => GridRowId,
289
+ });
290
+
291
+ // Expose on apiRef for programmatic use
292
+ useEffect(() => {
293
+ apiRef.current.copySelectedRows = copySelectedRows;
294
+ apiRef.current.getSelectedRows = () => Array.from(selectedRowIds);
295
+ }, [copySelectedRows, selectedRowIds, apiRef]);
296
+
297
+ const isInternalLoading = state.dataSource.loading;
298
+ const effectiveLoading = loading || isInternalLoading;
299
+
300
+ const effectiveRows = useMemo(() => {
301
+ return state.rows.allRows.map(id => state.rows.idRowsLookup.get(id)!) as R[];
302
+ }, [state.rows]);
303
+
304
+ const treeDataHandlers = useTreeData({
305
+ rows: effectiveRows,
306
+ getRowId: effectiveGetRowId,
307
+ getTreeDataPath,
308
+ treeData,
309
+ defaultGroupingExpansionDepth,
310
+ filterModel,
311
+
312
+ sortModel,
313
+ onRowExpansionChange: handleNodeExpansion
314
+ });
315
+
316
+ useEffect(() => {
317
+ treeDataRef.current = treeDataHandlers;
318
+ }, [treeDataHandlers]);
319
+
320
+ const rowGroupingHandlers = useRowGrouping({
321
+ rows: effectiveRows,
322
+ getRowId: effectiveGetRowId,
323
+ rowGroupingModel,
324
+ aggregationModel,
325
+ defaultGroupingExpansionDepth,
326
+ filterModel,
327
+ sortModel,
328
+ getAggregationPosition
329
+ });
330
+
331
+ const editingHandlers = useGridEditing({
332
+ rows: effectiveRows,
333
+ getRowId: effectiveGetRowId,
334
+ processRowUpdate,
335
+ onProcessRowUpdateError,
336
+ onRowChange: (updatedRow) => {
337
+ // Dispatch a proper state update so React re-renders with the new row value
338
+ const { dispatch } = gridData;
339
+ const currentRows = Array.from(gridData.state.rows.idRowsLookup.values());
340
+ const nextRows = currentRows.map(r =>
341
+ (r as any).id === (updatedRow as any).id ? updatedRow : r
342
+ );
343
+ dispatch({ type: 'SET_ROWS', payload: nextRows });
344
+ },
345
+ });
346
+
347
+ const isTreeData = treeData;
348
+ const isRowGrouping = !!(rowGroupingModel && rowGroupingModel.length > 0);
349
+ const isHierarchyEnabled = isTreeData || isRowGrouping;
350
+ const activeHierarchyHandlers = isTreeData ? treeDataHandlers : (isRowGrouping ? rowGroupingHandlers : null);
351
+
352
+ const pagination = propPagination && !isRowGrouping;
353
+
354
+ const handleRowClick = useCallback((params: GridRowParams<R>) => {
355
+ const { row, id } = params;
356
+ const rowData = row as any;
357
+
358
+ if (isHierarchyEnabled && rowData._hasChildren) {
359
+ activeHierarchyHandlers?.toggleExpansion(id);
360
+ return;
361
+ }
362
+
363
+ onRowClick?.(params);
364
+ }, [isHierarchyEnabled, activeHierarchyHandlers, onRowClick]);
365
+
366
+ const effectiveColumns = useMemo(() => {
367
+ if (!isHierarchyEnabled) return activeColumns;
368
+
369
+ return activeColumns.map((col, index) => {
370
+
371
+ if (index === 0) {
372
+ return {
373
+ ...col,
374
+ renderCell: (params: GridRenderCellParams<R>) => {
375
+ const { _treeDepth, _hasChildren, _isExpanded, _groupingField, _groupingValue, _descendantCount } = params.row as any;
376
+ const depth = _treeDepth || 0;
377
+ const paddingLeft = depth * 24;
378
+
379
+ let content = col.renderCell ? col.renderCell(params) : params.value;
380
+
381
+ if (isTreeData && _hasChildren && params.row._isGroupRow) {
382
+ content = (
383
+ <div className="ogx__group-cell-content">
384
+ {params.value}
385
+ {_descendantCount !== undefined && _descendantCount > 0 ? ` (${_descendantCount})` : ''}
386
+ </div>
387
+ );
388
+ }
389
+
390
+ // For row grouping, override the first column content to show the group label
391
+ if (isRowGrouping && _hasChildren && _groupingField) {
392
+ content = (
393
+ <div className="ogx__group-cell-content">
394
+ {col.field === _groupingField ? '' : `${_groupingField}: `}
395
+ {String(_groupingValue)}
396
+ {_descendantCount !== undefined ? ` (${_descendantCount})` : ''}
397
+ </div>
398
+ );
399
+ }
400
+
401
+ return (
402
+ <div style={{ display: 'flex', alignItems: 'center', paddingLeft, width: '100%', height: '100%' }}>
403
+ <div
404
+ style={{
405
+ marginRight: 4,
406
+ width: 24,
407
+ height: 24,
408
+ display: 'flex',
409
+ alignItems: 'center',
410
+ justifyContent: 'center',
411
+ cursor: _hasChildren ? 'pointer' : 'default',
412
+ flexShrink: 0
413
+ }}
414
+ >
415
+
416
+ {_hasChildren ? (
417
+ <div
418
+ onClick={(e) => {
419
+ e.stopPropagation();
420
+ e.preventDefault();
421
+ activeHierarchyHandlers?.toggleExpansion(params.row.id);
422
+ }}
423
+ onMouseDown={(e) => {
424
+ e.stopPropagation();
425
+ }}
426
+ style={{
427
+ cursor: 'pointer',
428
+ display: 'flex',
429
+ alignItems: 'center',
430
+ justifyContent: 'center',
431
+ pointerEvents: 'auto',
432
+ zIndex: 10,
433
+ position: 'relative'
434
+ }}
435
+ >
436
+ <ExpandIcon
437
+ isExpanded={_isExpanded}
438
+ onClick={(e) => {
439
+ e.stopPropagation();
440
+ e.preventDefault();
441
+ activeHierarchyHandlers?.toggleExpansion(params.row.id);
442
+ }}
443
+ />
444
+ </div>
445
+ ) : null}
446
+ </div>
447
+ <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
448
+ {content}
449
+ </div>
450
+ </div>
451
+ );
452
+ }
453
+ };
454
+ }
455
+
456
+ return {
457
+ ...col,
458
+ renderCell: (params: GridRenderCellParams<R>) => {
459
+ const { _hasChildren, _groupingField } = params.row as any;
460
+
461
+ if (isRowGrouping && _hasChildren) {
462
+
463
+ if (col.field === _groupingField) {
464
+ return null;
465
+ }
466
+
467
+ if (params.value !== undefined && params.value !== null) {
468
+ return col.renderCell ? col.renderCell(params) : params.value;
469
+ }
470
+
471
+ return null;
472
+ }
473
+
474
+ return col.renderCell ? col.renderCell(params) : params.value;
475
+ }
476
+ };
477
+ }) as GridColDef<R>[];
478
+ }, [activeColumns, isHierarchyEnabled, isRowGrouping, activeHierarchyHandlers]);
479
+
480
+ const dataSourceHandlers = useGridDataSource({
481
+ dataSource,
482
+ sortModel,
483
+ filterModel,
484
+ paginationModel: effectivePaginationModel,
485
+ paginationMode,
486
+ sortingMode,
487
+ filterMode,
488
+ aggregationModel,
489
+ setRows,
490
+ setRowCount,
491
+ setDataSourceLoading,
492
+ setDataSourceError,
493
+ onAggregationResults: setServerAggregationResults,
494
+ });
495
+
496
+ useEffect(() => {
497
+ if (dataSourceHandlers.fetchChildren) {
498
+ fetchChildrenRef.current = dataSourceHandlers.fetchChildren;
499
+ }
500
+ }, [dataSourceHandlers.fetchChildren]);
501
+
502
+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(
503
+ () => initialState?.columns?.columnWidths ?? {}
504
+ );
505
+
506
+ const [internalColumnOrder, setInternalColumnOrder] = useState<string[]>(() =>
507
+ initialState?.columns?.columnOrder ?? activeColumns.map(col => col.field)
508
+ );
509
+
510
+ const effectiveColumnOrder = columnOrder || internalColumnOrder;
511
+
512
+ useEffect(() => {
513
+ if (!dataSource) {
514
+ setRows(activeRows);
515
+ }
516
+ }, [activeRows, setRows, dataSource]);
517
+
518
+ useEffect(() => {
519
+ setColumns(activeColumns as any);
520
+ }, [activeColumns, setColumns]);
521
+
522
+ useEffect(() => {
523
+ if (pivotMode) {
524
+ setInternalColumnOrder(activeColumns.map(col => col.field));
525
+ }
526
+ }, [pivotMode, activeColumns]);
527
+
528
+ const orderedColumns = useMemo(() => {
529
+ if (disableColumnReorder) return effectiveColumns as GridColDef<R>[];
530
+
531
+ const orderMap = new Map(effectiveColumnOrder.map((field, index) => [field, index]));
532
+ return [...(effectiveColumns as GridColDef<R>[])].sort((a, b) => {
533
+ const aIndex = orderMap.get(a.field) ?? effectiveColumns.indexOf(a);
534
+ const bIndex = orderMap.get(b.field) ?? effectiveColumns.indexOf(b);
535
+ return aIndex - bIndex;
536
+ });
537
+ }, [effectiveColumns, effectiveColumnOrder, disableColumnReorder]);
538
+
539
+ const visibleOrderedColumns = useMemo(() => {
540
+ return orderedColumns.filter(col => columnVisibilityModel[col.field] !== false);
541
+ }, [orderedColumns, columnVisibilityModel]);
542
+
543
+ const columnReorderHandlers = useColumnReorder({
544
+ columns: orderedColumns,
545
+ onColumnOrderChange: useCallback((params: GridColumnOrderChangeParams) => {
546
+ const { oldIndex, targetIndex } = params;
547
+
548
+ const newOrder = [...effectiveColumnOrder];
549
+ const [movedField] = newOrder.splice(oldIndex, 1);
550
+ newOrder.splice(targetIndex, 0, movedField);
551
+
552
+ if (!columnOrder) {
553
+ setInternalColumnOrder(newOrder);
554
+ }
555
+
556
+ onColumnOrderChange?.(params);
557
+ }, [effectiveColumnOrder, columnOrder, onColumnOrderChange]),
558
+ disableColumnReorder,
559
+ });
560
+
561
+ const [internalExpandedRowIds, setInternalExpandedRowIds] = useState<Set<GridRowId>>(new Set());
562
+ const expandedRowIds = controlledExpandedRowIds ?? internalExpandedRowIds;
563
+ const hasDetailPanel = Boolean(getDetailPanelContent);
564
+
565
+ const handleDetailPanelToggle = useCallback((rowId: GridRowId) => {
566
+ const newExpandedRowIds = new Set(expandedRowIds);
567
+ if (newExpandedRowIds.has(rowId)) {
568
+ newExpandedRowIds.delete(rowId);
569
+ } else {
570
+ newExpandedRowIds.add(rowId);
571
+ }
572
+
573
+ if (controlledExpandedRowIds === undefined) {
574
+ setInternalExpandedRowIds(newExpandedRowIds);
575
+ }
576
+ onDetailPanelExpandedRowIdsChange?.(newExpandedRowIds);
577
+ }, [expandedRowIds, controlledExpandedRowIds, onDetailPanelExpandedRowIdsChange]);
578
+
579
+ const navigationColumns = useMemo(() => {
580
+ const cols: { field: string; editable?: boolean }[] = [];
581
+ if (rowReordering) cols.push({ field: '__reorder_col__' });
582
+ if (hasDetailPanel) cols.push({ field: '__expand_col__' });
583
+ if (checkboxSelection) cols.push({ field: '__checkbox_col__' });
584
+ return [...cols, ...orderedColumns];
585
+ }, [orderedColumns, checkboxSelection, hasDetailPanel, rowReordering]);
586
+
587
+ const handleColumnResize = useCallback((field: string, newWidth: number) => {
588
+ setColumnWidths(prev => ({ ...prev, [field]: newWidth }));
589
+ }, []);
590
+
591
+ const onStateChangeRef = useRef(onStateChange);
592
+ onStateChangeRef.current = onStateChange;
593
+
594
+ useEffect(() => {
595
+ if (!onStateChangeRef.current) return;
596
+
597
+ const snapshot: GridState = {
598
+ sorting: { sortModel: sortModel as { field: string; sort: 'asc' | 'desc' }[] },
599
+ filter: { filterModel },
600
+ pagination: { paginationModel: effectivePaginationModel },
601
+ columns: {
602
+ columnWidths,
603
+ columnOrder: effectiveColumnOrder,
604
+ columnVisibilityModel,
605
+ pinnedColumns: pinnedColumns,
606
+ },
607
+ };
608
+
609
+ onStateChangeRef.current(snapshot);
610
+ }, [
611
+ sortModel,
612
+ filterModel,
613
+ effectivePaginationModel,
614
+ columnWidths,
615
+ effectiveColumnOrder,
616
+ columnVisibilityModel,
617
+ pinnedColumns,
618
+ ]);
619
+
620
+ const baseRows = useMemo(() => {
621
+ return effectiveRows;
622
+ }, [effectiveRows]);
623
+
624
+ const filteredRows = useMemo(() => {
625
+ if (activeHierarchyHandlers) {
626
+
627
+ return (activeHierarchyHandlers.getVisibleRows() || []) as R[];
628
+ }
629
+
630
+ if (filterMode === 'server' && dataSource) {
631
+ return baseRows;
632
+ }
633
+
634
+ return filterRows(baseRows, filterModel);
635
+ }, [baseRows, filterModel, activeHierarchyHandlers, filterMode, dataSource]);
636
+
637
+ const { top: pinnedTopRows, center: unpinnedRows, bottom: pinnedBottomRows } = useMemo(() => {
638
+ if (activeHierarchyHandlers) {
639
+
640
+ return { top: [], center: filteredRows, bottom: [] };
641
+ }
642
+ return getPinnedRowGroups(filteredRows, pinnedRows);
643
+ }, [filteredRows, pinnedRows, activeHierarchyHandlers]);
644
+
645
+ const sortedUnpinnedRows = useMemo(() => {
646
+ if (activeHierarchyHandlers) {
647
+ return unpinnedRows;
648
+ }
649
+
650
+ if (sortingMode === 'server' && dataSource) {
651
+ return unpinnedRows;
652
+ }
653
+
654
+ return sortRows(unpinnedRows, sortModel);
655
+ }, [unpinnedRows, sortModel, activeHierarchyHandlers, sortingMode, dataSource]);
656
+
657
+ const paginatedUnpinnedRows = useMemo(() => {
658
+ if (!pagination) return sortedUnpinnedRows;
659
+
660
+ if (paginationMode === 'server' && dataSource) {
661
+ return sortedUnpinnedRows;
662
+ }
663
+
664
+ const start = effectivePaginationModel.page * effectivePaginationModel.pageSize;
665
+ const end = start + effectivePaginationModel.pageSize;
666
+ return sortedUnpinnedRows.slice(start, end);
667
+ }, [sortedUnpinnedRows, pagination, effectivePaginationModel.page, effectivePaginationModel.pageSize, paginationMode, dataSource]);
668
+
669
+ useEffect(() => {
670
+ gridData.apiRef.current.getVisibleRows = () => sortedUnpinnedRows;
671
+ gridData.apiRef.current.getVisibleColumns = () => effectiveColumns as any[];
672
+ }, [sortedUnpinnedRows, effectiveColumns, gridData.apiRef]);
673
+
674
+ const rowReorderHandlers = useRowReorder({
675
+ rows: pagination ? paginatedUnpinnedRows : sortedUnpinnedRows,
676
+ getRowId: (row) => row.id,
677
+ onRowOrderChange,
678
+ rowReordering
679
+ });
680
+
681
+ const allRenderableRows = useMemo(() => {
682
+
683
+ if (activeHierarchyHandlers) {
684
+ return unpinnedRows;
685
+ }
686
+ const centerRows = pagination ? paginatedUnpinnedRows : sortedUnpinnedRows;
687
+ const base = [...pinnedTopRows, ...centerRows, ...pinnedBottomRows];
688
+
689
+ // Append skeleton rows while an infinite-scroll fetch is in flight
690
+ if (paginationMode === 'infinite' && state.dataSource.loading && base.length > 0) {
691
+ const skeletonCount = Math.min(effectivePaginationModel.pageSize, 20);
692
+ const skeletons = Array.from({ length: skeletonCount }, (_, i) => ({
693
+ id: `__skeleton_${i}__`,
694
+ _isSkeleton: true,
695
+ }));
696
+ return [...base, ...skeletons] as typeof base;
697
+ }
698
+
699
+ return base;
700
+ }, [pinnedTopRows, paginatedUnpinnedRows, sortedUnpinnedRows, pinnedBottomRows, pagination,
701
+ activeHierarchyHandlers, unpinnedRows, paginationMode, state.dataSource.loading,
702
+ effectivePaginationModel.pageSize]);
703
+
704
+ const spanning = useGridSpanning(
705
+ allRenderableRows,
706
+ navigationColumns,
707
+ columnWidths
708
+ );
709
+
710
+ const { aggregationResult } = useAggregation({
711
+ rows: filteredRows,
712
+ aggregationModel,
713
+ isServerSide: !!(dataSource && (paginationMode === 'server' || sortingMode === 'server')),
714
+ dataSource: dataSource as any,
715
+ filterModel,
716
+ sortModel,
717
+ serverAggregationResults,
718
+ });
719
+
720
+ const hasAggregation = Object.keys(aggregationModel).length > 0;
721
+
722
+ useEffect(() => {
723
+ gridData.apiRef.current.getAggregationResult = () => hasAggregation ? aggregationResult : null;
724
+ gridData.apiRef.current.getAggregationModel = () => hasAggregation ? aggregationModel : null;
725
+ }, [aggregationResult, aggregationModel, hasAggregation, gridData.apiRef]);
726
+
727
+ const layout = useMemo(() => {
728
+ const baseRowHeight = rowHeight;
729
+
730
+ const unpinnedRows = pagination ? paginatedUnpinnedRows : sortedUnpinnedRows;
731
+ const rowHeights = unpinnedRows.map((row, index) => {
732
+ let height = baseRowHeight;
733
+ if (expandedRowIds.has(row.id)) {
734
+ const detailHeight = getDetailPanelHeight?.({ row, id: row.id, rowIndex: pinnedTopRows.length + index }) ?? 200;
735
+ height += typeof detailHeight === 'number' ? detailHeight : parseInt(String(detailHeight), 10) || 200;
736
+ }
737
+ return height;
738
+ });
739
+
740
+ const cumulativeHeights = rowHeights.reduce((acc, height, index) => {
741
+ acc.push((acc[index - 1] || 0) + height);
742
+ return acc;
743
+ }, [] as number[]);
744
+
745
+ const skeletonCount = (paginationMode === 'infinite' && state.dataSource.loading && (unpinnedRows.length > 0))
746
+ ? Math.min(effectivePaginationModel.pageSize, 20)
747
+ : 0;
748
+ const skeletonRowsHeight = skeletonCount * baseRowHeight;
749
+ const unpinnedRowsHeight = (cumulativeHeights[cumulativeHeights.length - 1] || 0) + skeletonRowsHeight;
750
+ const pinnedTopHeight = pinnedTopRows.length * baseRowHeight;
751
+ const pinnedBottomHeight = pinnedBottomRows.length * baseRowHeight;
752
+
753
+ const rawLeftPinnedCols: GridColDef<R>[] = [];
754
+ const rawRightPinnedCols: GridColDef<R>[] = [];
755
+ const unpinnedCols: GridColDef<R>[] = [];
756
+ const unpinnedColWidths: number[] = [];
757
+
758
+ visibleOrderedColumns.forEach(col => {
759
+ const pinned = isColumnPinned(col.field, pinnedColumns);
760
+ if (pinned === 'left') {
761
+ rawLeftPinnedCols.push(col);
762
+ } else if (pinned === 'right') {
763
+ rawRightPinnedCols.push(col);
764
+ } else {
765
+ unpinnedCols.push(col);
766
+ }
767
+ });
768
+
769
+ const viewportWidth = state.dimensions.viewportWidth || 1000;
770
+ const systemColumnsWidth = (checkboxSelection ? 48 : 0) + (hasDetailPanel ? 48 : 0) + (rowReordering ? 48 : 0);
771
+
772
+ const getColWidth = (c: GridColDef<R>) => columnWidths[c.field] ?? c.width;
773
+
774
+ const parseWidth = (width: number | string | undefined): { type: 'fixed' | 'percentage' | 'auto', value: number } => {
775
+ if (width === undefined) return { type: 'auto', value: 0 };
776
+ if (typeof width === 'number') return { type: 'fixed', value: width };
777
+ if (typeof width === 'string') {
778
+ if (width.toLowerCase() === 'auto') return { type: 'auto', value: 0 };
779
+ if (width.endsWith('%')) {
780
+ const percentage = parseFloat(width);
781
+ return { type: 'percentage', value: percentage };
782
+ }
783
+ const floatVal = parseFloat(width);
784
+ if (!isNaN(floatVal)) return { type: 'fixed', value: floatVal };
785
+ }
786
+ return { type: 'fixed', value: 100 };
787
+ };
788
+
789
+ const leftWidth = rawLeftPinnedCols.reduce((sum, c) => {
790
+ const parsed = parseWidth(getColWidth(c));
791
+ return sum + (parsed.type === 'fixed' ? parsed.value : 100);
792
+ }, 0);
793
+ const rightWidth = rawRightPinnedCols.reduce((sum, c) => {
794
+ const parsed = parseWidth(getColWidth(c));
795
+ return sum + (parsed.type === 'fixed' ? parsed.value : 100);
796
+ }, 0);
797
+
798
+ const naturalFlexWidth = unpinnedCols.reduce((sum, col) => {
799
+ const hasManualWidth = Object.prototype.hasOwnProperty.call(columnWidths, col.field);
800
+ if (!hasManualWidth && col.flex && col.flex > 0) {
801
+ const minWidth = col.minWidth ?? 150;
802
+ const width = typeof col.width === 'number' ? col.width : 150;
803
+ return sum + (minWidth || width);
804
+ }
805
+ const parsed = parseWidth(getColWidth(col));
806
+ if (parsed.type === 'fixed') return sum + parsed.value;
807
+ if (parsed.type === 'percentage') return sum + 100;
808
+ return sum + (col.minWidth ?? 150);
809
+ }, 0);
810
+
811
+ const availableWidth = Math.max(
812
+ viewportWidth - systemColumnsWidth - leftWidth - rightWidth,
813
+ naturalFlexWidth
814
+ );
815
+
816
+ const fixedWidthCols: Array<{ col: GridColDef<R>, width: number }> = [];
817
+ const percentageCols: Array<{ col: GridColDef<R>, percentage: number }> = [];
818
+ const flexCols: Array<{ col: GridColDef<R>, flex: number }> = [];
819
+ let totalFlexUnits = 0;
820
+
821
+ unpinnedCols.forEach(col => {
822
+ // If the user has manually resized this column, columnWidths has an explicit
823
+ // entry for it. Respect that stored width as fixed-width so the resize sticks,
824
+ // even if the column definition originally had flex.
825
+ const hasManualWidth = Object.prototype.hasOwnProperty.call(columnWidths, col.field);
826
+
827
+ const parsed = parseWidth(getColWidth(col));
828
+
829
+ if (!hasManualWidth && col.flex && col.flex > 0) {
830
+ flexCols.push({ col, flex: col.flex });
831
+ totalFlexUnits += col.flex;
832
+ return;
833
+ }
834
+
835
+ if (parsed.type === 'fixed') {
836
+ fixedWidthCols.push({ col, width: parsed.value });
837
+ } else if (parsed.type === 'percentage') {
838
+ percentageCols.push({ col, percentage: parsed.value });
839
+ } else {
840
+
841
+ const implicitFlex = 1;
842
+ flexCols.push({ col, flex: implicitFlex });
843
+ totalFlexUnits += implicitFlex;
844
+ }
845
+ });
846
+
847
+ const fixedWidth = fixedWidthCols.reduce((sum, { width }) => sum + width, 0);
848
+
849
+ let remainingSpaceForFlex = Math.max(0, availableWidth - fixedWidth);
850
+
851
+ const percentageWidthMap = new Map<string, number>();
852
+ percentageCols.forEach(({ col, percentage }) => {
853
+ const calculatedWidth = (percentage / 100) * remainingSpaceForFlex;
854
+ percentageWidthMap.set(col.field, calculatedWidth);
855
+
856
+ remainingSpaceForFlex -= calculatedWidth;
857
+ });
858
+
859
+ remainingSpaceForFlex = Math.max(0, remainingSpaceForFlex);
860
+
861
+ const finalFlexWidths = new Map<string, number>();
862
+
863
+ const flexItems = flexCols.map(f => ({
864
+ ...f,
865
+ minWidth: f.col.minWidth ?? 50,
866
+ maxWidth: f.col.maxWidth ?? Infinity,
867
+ frozen: false,
868
+ computedWidth: 0
869
+ }));
870
+
871
+ const solveFlexAllocation = () => {
872
+
873
+ let iterations = 0;
874
+ const maxIterations = flexItems.length * 2;
875
+
876
+ while (iterations < maxIterations) {
877
+ iterations++;
878
+
879
+ const unfrozen = flexItems.filter(f => !f.frozen);
880
+
881
+ if (unfrozen.length === 0) break;
882
+
883
+ const unfrozenFlexTotal = unfrozen.reduce((sum, f) => sum + f.flex, 0);
884
+
885
+ const frozenWidthTotal = flexItems.reduce((sum, f) => f.frozen ? sum + f.computedWidth : sum, 0);
886
+ const currentFreeSpace = Math.max(0, remainingSpaceForFlex - frozenWidthTotal);
887
+
888
+ if (unfrozenFlexTotal <= 0) {
889
+ unfrozen.forEach(f => {
890
+ f.computedWidth = f.minWidth;
891
+ f.frozen = true;
892
+ });
893
+ break;
894
+ }
895
+
896
+ const pixelsPerFlex = currentFreeSpace / unfrozenFlexTotal;
897
+
898
+ let totalViolation = 0;
899
+ const minViolators: typeof flexItems = [];
900
+ const maxViolators: typeof flexItems = [];
901
+
902
+ unfrozen.forEach(f => {
903
+ const rawWidth = pixelsPerFlex * f.flex;
904
+
905
+ if (rawWidth < f.minWidth) {
906
+ const diff = f.minWidth - rawWidth;
907
+ totalViolation += diff;
908
+ minViolators.push(f);
909
+ } else if (rawWidth > f.maxWidth) {
910
+ const diff = f.maxWidth - rawWidth;
911
+ totalViolation += diff;
912
+ maxViolators.push(f);
913
+ } else {
914
+
915
+ f.computedWidth = rawWidth;
916
+ }
917
+ });
918
+
919
+ if (minViolators.length === 0 && maxViolators.length === 0) {
920
+ unfrozen.forEach(f => f.frozen = true);
921
+ break;
922
+ }
923
+
924
+ if (totalViolation > 0) {
925
+ minViolators.forEach(f => {
926
+ f.computedWidth = f.minWidth;
927
+ f.frozen = true;
928
+ });
929
+ } else if (totalViolation < 0) {
930
+ maxViolators.forEach(f => {
931
+ f.computedWidth = f.maxWidth;
932
+ f.frozen = true;
933
+ });
934
+ } else {
935
+
936
+ minViolators.forEach(f => { f.computedWidth = f.minWidth; f.frozen = true; });
937
+ maxViolators.forEach(f => { f.computedWidth = f.maxWidth; f.frozen = true; });
938
+ }
939
+ }
940
+ };
941
+
942
+ solveFlexAllocation();
943
+ flexItems.forEach(f => finalFlexWidths.set(f.col.field, f.computedWidth));
944
+
945
+ const computedWidthMap = new Map<string, number>();
946
+
947
+ unpinnedCols.forEach(col => {
948
+ let computedWidth: number;
949
+
950
+ if (finalFlexWidths.has(col.field)) {
951
+ computedWidth = finalFlexWidths.get(col.field)!;
952
+ } else {
953
+ const fixedCol = fixedWidthCols.find(f => f.col.field === col.field);
954
+ const pctCol = percentageCols.find(p => p.col.field === col.field);
955
+
956
+ if (fixedCol) {
957
+ computedWidth = fixedCol.width;
958
+ } else if (pctCol) {
959
+ const rawPctWidth = percentageWidthMap.get(col.field) || 0;
960
+ computedWidth = Math.max(col.minWidth ?? 50, rawPctWidth || 100);
961
+ } else {
962
+ computedWidth = 100;
963
+ }
964
+ }
965
+
966
+ unpinnedColWidths.push(computedWidth);
967
+ computedWidthMap.set(col.field, computedWidth);
968
+ });
969
+
970
+ const unpinnedColsWithWidth = unpinnedCols.map(col => {
971
+ const flexItem = flexItems.find(f => f.col.field === col.field);
972
+ return {
973
+ ...col,
974
+ width: computedWidthMap.get(col.field) ?? (typeof col.width === 'number' ? col.width : 100),
975
+ flex: flexItem ? flexItem.flex : col.flex
976
+ };
977
+ });
978
+
979
+ const baseLeftZ = 11;
980
+ const leftPinnedCols = rawLeftPinnedCols.map((col, i) => {
981
+ const parsed = parseWidth(getColWidth(col));
982
+ const numericWidth = parsed.type === 'fixed' ? parsed.value : 100;
983
+ return {
984
+ ...col,
985
+ width: numericWidth,
986
+ zIndex: baseLeftZ + i
987
+ };
988
+ });
989
+
990
+ const baseRightZ = 11;
991
+ const rightPinnedCols = rawRightPinnedCols.map((col, i) => {
992
+ const parsed = parseWidth(getColWidth(col));
993
+ const numericWidth = parsed.type === 'fixed' ? parsed.value : 100;
994
+ return {
995
+ ...col,
996
+ width: numericWidth,
997
+ zIndex: baseRightZ + (rawRightPinnedCols.length - 1 - i)
998
+ };
999
+ });
1000
+
1001
+ const unpinnedTotalWidth = unpinnedColWidths.reduce((sum, w) => sum + w, 0);
1002
+ const totalWidth = leftWidth + unpinnedTotalWidth + rightWidth + systemColumnsWidth;
1003
+
1004
+ const unpinnedAccWidths = unpinnedColWidths.reduce((acc, w, i) => {
1005
+ acc.push((acc[i - 1] || 0) + w);
1006
+ return acc;
1007
+ }, [] as number[]);
1008
+
1009
+ return {
1010
+ rowHeights,
1011
+ cumulativeHeights,
1012
+ unpinnedRowsHeight,
1013
+ pinnedTopHeight,
1014
+ pinnedBottomHeight,
1015
+ leftPinnedCols,
1016
+ rightPinnedCols,
1017
+ unpinnedColsWithWidth,
1018
+ unpinnedColWidths,
1019
+ unpinnedAccWidths,
1020
+ totalWidth,
1021
+ leftWidth,
1022
+ rightWidth,
1023
+ unpinnedTotalWidth,
1024
+ systemColumnsWidth,
1025
+ pinnedTopRowsLength: pinnedTopRows.length,
1026
+ pinnedBottomRowsLength: pinnedBottomRows.length,
1027
+ unpinnedRowsLength: unpinnedRows.length
1028
+ };
1029
+ }, [
1030
+ rowHeight,
1031
+ pagination,
1032
+ paginatedUnpinnedRows,
1033
+ sortedUnpinnedRows,
1034
+ expandedRowIds,
1035
+ getDetailPanelHeight,
1036
+ pinnedTopRows.length,
1037
+ pinnedBottomRows.length,
1038
+ expandedRowIds,
1039
+ getDetailPanelHeight,
1040
+ pinnedTopRows.length,
1041
+ pinnedBottomRows.length,
1042
+ visibleOrderedColumns,
1043
+ pinnedColumns,
1044
+ columnWidths,
1045
+ state.dimensions.viewportWidth,
1046
+ checkboxSelection,
1047
+ hasDetailPanel,
1048
+ rowReordering,
1049
+ pinCheckboxColumn,
1050
+ pinExpandColumn,
1051
+ autoHeight,
1052
+ paginationMode,
1053
+ state.dataSource.loading,
1054
+ effectivePaginationModel.pageSize
1055
+ ]);
1056
+
1057
+ const virtualization = useMemo(() => {
1058
+ const {
1059
+ unpinnedAccWidths,
1060
+ unpinnedColsWithWidth,
1061
+ leftPinnedCols,
1062
+ rightPinnedCols,
1063
+ totalWidth,
1064
+ leftWidth,
1065
+ rightWidth,
1066
+ unpinnedTotalWidth,
1067
+ systemColumnsWidth,
1068
+ cumulativeHeights,
1069
+ pinnedTopHeight,
1070
+ pinnedBottomHeight,
1071
+ unpinnedRowsHeight,
1072
+ rowHeights,
1073
+ unpinnedRowsLength
1074
+ } = layout;
1075
+
1076
+ const scrollLeft = state.virtualization.scrollLeft;
1077
+ const scrollTop = state.virtualization.scrollTop;
1078
+ const viewportWidth = state.dimensions.viewportWidth || 1000;
1079
+ const viewportHeight = autoHeight ? (pinnedTopHeight + unpinnedRowsHeight + pinnedBottomHeight + 50) : (state.dimensions.viewportHeight || 600);
1080
+
1081
+ const overscanCols = 6;
1082
+
1083
+ const visibleLocalStart = Math.max(0, scrollLeft - leftWidth);
1084
+ const visibleLocalEnd = scrollLeft + viewportWidth - leftWidth;
1085
+
1086
+ let firstUnpinnedIndex = 0;
1087
+ let lastUnpinnedIndex = unpinnedColsWithWidth.length - 1;
1088
+
1089
+ let low = 0, high = unpinnedAccWidths.length - 1;
1090
+ while (low <= high) {
1091
+ const mid = (low + high) >>> 1;
1092
+ if (unpinnedAccWidths[mid] < visibleLocalStart) {
1093
+ low = mid + 1;
1094
+ } else {
1095
+ high = mid - 1;
1096
+ }
1097
+ }
1098
+ firstUnpinnedIndex = Math.max(0, low - overscanCols);
1099
+
1100
+ for (let i = firstUnpinnedIndex; i < unpinnedAccWidths.length; i++) {
1101
+ if ((i === 0 ? 0 : unpinnedAccWidths[i - 1]) > visibleLocalEnd) {
1102
+ lastUnpinnedIndex = Math.min(unpinnedColsWithWidth.length - 1, i + overscanCols);
1103
+ break;
1104
+ }
1105
+ lastUnpinnedIndex = Math.min(unpinnedColsWithWidth.length - 1, i + overscanCols);
1106
+ }
1107
+
1108
+ const leftSpacerWidth = firstUnpinnedIndex > 0 ? unpinnedAccWidths[firstUnpinnedIndex - 1] : 0;
1109
+ const rightSpacerWidth = unpinnedTotalWidth - unpinnedAccWidths[lastUnpinnedIndex];
1110
+
1111
+ const virtualColumns: any[] = [
1112
+ ...leftPinnedCols,
1113
+ ...(leftSpacerWidth > 0 ? [{ field: '__spacer_left__', width: leftSpacerWidth, isSpacer: true }] : []),
1114
+ ...unpinnedColsWithWidth.slice(firstUnpinnedIndex, lastUnpinnedIndex + 1),
1115
+ ...(rightSpacerWidth > 0 ? [{ field: '__spacer_right__', width: rightSpacerWidth, isSpacer: true }] : []),
1116
+ ...rightPinnedCols
1117
+ ];
1118
+
1119
+ const hasHorizontalScroll = viewportWidth > 0 && totalWidth > viewportWidth;
1120
+ const scrollbarBuffer = hasHorizontalScroll ? 16 : 0;
1121
+ const totalHeight = pinnedTopHeight + unpinnedRowsHeight + pinnedBottomHeight + scrollbarBuffer + 2;
1122
+
1123
+ const overscanRows = 5;
1124
+ let firstRowIndex = 0;
1125
+ let lastRowIndex = unpinnedRowsLength - 1;
1126
+ let offsetTop = 0;
1127
+
1128
+ let rLow = 0, rHigh = cumulativeHeights.length - 1;
1129
+ while (rLow <= rHigh) {
1130
+ const mid = (rLow + rHigh) >>> 1;
1131
+ if (cumulativeHeights[mid] < scrollTop) {
1132
+ rLow = mid + 1;
1133
+ } else {
1134
+ rHigh = mid - 1;
1135
+ }
1136
+ }
1137
+ firstRowIndex = Math.max(0, rLow - overscanRows);
1138
+ offsetTop = firstRowIndex > 0 ? cumulativeHeights[firstRowIndex - 1] : 0;
1139
+
1140
+ for (let i = firstRowIndex; i < cumulativeHeights.length; i++) {
1141
+ if (cumulativeHeights[i] >= scrollTop + viewportHeight) {
1142
+ lastRowIndex = Math.min(unpinnedRowsLength - 1, i + overscanRows);
1143
+ break;
1144
+ }
1145
+ }
1146
+
1147
+ return {
1148
+ renderContext: {
1149
+ firstRowIndex,
1150
+ lastRowIndex,
1151
+ firstColumnIndex: firstUnpinnedIndex,
1152
+ lastColumnIndex: lastUnpinnedIndex
1153
+ },
1154
+ offsetTop,
1155
+ offsetLeft: 0,
1156
+ totalHeight,
1157
+ pinnedTopHeight,
1158
+ pinnedBottomHeight,
1159
+ totalWidth,
1160
+ rowHeights,
1161
+ cumulativeHeights,
1162
+ virtualColumns,
1163
+ columnMetrics: {
1164
+ leftPinnedWidth: leftWidth,
1165
+ rightPinnedWidth: rightWidth,
1166
+ unpinnedAccWidths,
1167
+ unpinnedCols: unpinnedColsWithWidth,
1168
+ totalSpecialsWidth: systemColumnsWidth,
1169
+ pinnedSpecialsWidth: (rowReordering ? 48 : 0) + (hasDetailPanel && pinExpandColumn ? 48 : 0) + (checkboxSelection && pinCheckboxColumn ? 48 : 0)
1170
+ }
1171
+ };
1172
+ }, [
1173
+ layout,
1174
+ state.virtualization.scrollTop,
1175
+ state.virtualization.scrollLeft,
1176
+ state.dimensions.viewportHeight,
1177
+ state.dimensions.viewportWidth,
1178
+ autoHeight
1179
+ ]);
1180
+
1181
+ const handleScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
1182
+ const target = event.currentTarget;
1183
+ setScroll(target.scrollTop, target.scrollLeft);
1184
+
1185
+ if (onRowsScrollEnd) {
1186
+ const { scrollTop, scrollHeight, clientHeight } = target;
1187
+ const scrollThreshold = 100;
1188
+
1189
+ if (scrollHeight - scrollTop - clientHeight < scrollThreshold) {
1190
+
1191
+ onRowsScrollEnd({
1192
+ visibleTop: scrollTop,
1193
+ visibleBottom: scrollTop + clientHeight,
1194
+ viewportHeight: clientHeight
1195
+ });
1196
+ }
1197
+ }
1198
+ }, [setScroll, onRowsScrollEnd]);
1199
+
1200
+ useEffect(() => {
1201
+ if (!viewportRef.current) return;
1202
+
1203
+ const resizeObserver = new ResizeObserver((entries) => {
1204
+ for (const entry of entries) {
1205
+ const { width, height } = entry.contentRect;
1206
+ setDimensions(width, height);
1207
+ }
1208
+ });
1209
+
1210
+ resizeObserver.observe(viewportRef.current);
1211
+
1212
+ return () => {
1213
+ resizeObserver.disconnect();
1214
+ };
1215
+ }, [setDimensions]);
1216
+
1217
+ const handleSelectionChange = useCallback((rowId: GridRowId, isSelected: boolean) => {
1218
+ const newSelection = new Set(selectedRowIds);
1219
+ if (isSelected) {
1220
+ newSelection.add(rowId);
1221
+ } else {
1222
+ newSelection.delete(rowId);
1223
+ }
1224
+ const newSelectionArray = Array.from(newSelection);
1225
+
1226
+ if (!isSelectionControlled) {
1227
+ setInternalRowSelectionModel(newSelectionArray);
1228
+ }
1229
+ onRowSelectionModelChange?.(newSelectionArray);
1230
+ }, [selectedRowIds, isSelectionControlled, onRowSelectionModelChange]);
1231
+
1232
+ const handleSelectAll = useCallback((isSelected: boolean) => {
1233
+ let newSelection: GridRowId[] = [];
1234
+ if (isSelected) {
1235
+ newSelection = baseRows.map(row => row.id);
1236
+ }
1237
+
1238
+ if (!isSelectionControlled) {
1239
+ setInternalRowSelectionModel(newSelection);
1240
+ }
1241
+ onRowSelectionModelChange?.(newSelection);
1242
+ }, [rows, isSelectionControlled, onRowSelectionModelChange]);
1243
+
1244
+ const handleSort = useCallback((field: string, direction: GridSortDirection) => {
1245
+ const newSortModel = direction ? [{ field, sort: direction }] : [];
1246
+
1247
+ if (!isSortControlled) {
1248
+ setInternalSortModel(newSortModel as any);
1249
+ }
1250
+ onSortModelChange?.(newSortModel as any);
1251
+ }, [isSortControlled, onSortModelChange]);
1252
+
1253
+ const handleCellClick = useCallback((params: GridCellParams<R>) => {
1254
+ setKeyboardMode(false);
1255
+ setFocusedCell({ id: params.row.id, field: params.field });
1256
+
1257
+ gridRef.current?.focus({ preventScroll: true });
1258
+ onCellClick?.(params);
1259
+ }, [onCellClick, setKeyboardMode]);
1260
+
1261
+ const prevEditingCellRef = useRef(editingHandlers.editingCell);
1262
+ useEffect(() => {
1263
+ const wasEditing = Boolean(prevEditingCellRef.current);
1264
+ const isEditing = Boolean(editingHandlers.editingCell);
1265
+
1266
+ if (wasEditing && !isEditing) {
1267
+
1268
+ gridRef.current?.focus({ preventScroll: true });
1269
+ }
1270
+
1271
+ prevEditingCellRef.current = editingHandlers.editingCell;
1272
+ }, [editingHandlers.editingCell]);
1273
+
1274
+ const visibleRows = useMemo(() => {
1275
+ const { firstRowIndex, lastRowIndex } = virtualization.renderContext;
1276
+
1277
+ const topPinnedCount = pinnedTopRows.length;
1278
+
1279
+ const topPinned = pinnedTopRows.map((row, index) => ({ row, rowIndex: index }));
1280
+ const bottomPinned = pinnedBottomRows.map((row, index) => ({
1281
+ row,
1282
+ rowIndex: topPinnedCount + (pagination ? paginatedUnpinnedRows.length : sortedUnpinnedRows.length) + index
1283
+ }));
1284
+
1285
+ const centerStartIndex = Math.max(0, firstRowIndex - topPinnedCount);
1286
+ const centerEndIndex = Math.min(
1287
+ pagination ? paginatedUnpinnedRows.length : sortedUnpinnedRows.length,
1288
+ lastRowIndex - topPinnedCount + 1
1289
+ );
1290
+
1291
+ const centerRows = (pagination ? paginatedUnpinnedRows : sortedUnpinnedRows)
1292
+ .slice(centerStartIndex, centerEndIndex)
1293
+ .map((row, index) => ({
1294
+ row,
1295
+ rowIndex: topPinnedCount + centerStartIndex + index
1296
+ }));
1297
+
1298
+ const combined = [...topPinned, ...centerRows, ...bottomPinned];
1299
+
1300
+ const seenIds = new Set<GridRowId>();
1301
+ const deduplicated = combined.filter(item => {
1302
+ if (seenIds.has(item.row.id)) {
1303
+ return false;
1304
+ }
1305
+ seenIds.add(item.row.id);
1306
+ return true;
1307
+ });
1308
+
1309
+ return deduplicated;
1310
+ }, [virtualization.renderContext, pinnedTopRows, pinnedBottomRows, paginatedUnpinnedRows, sortedUnpinnedRows, pagination,
1311
+ paginationMode, state.dataSource.loading, effectivePaginationModel.pageSize, rowHeight]);
1312
+
1313
+
1314
+ const allSelected = rows.length > 0 && selectedRowIds.size === rows.length;
1315
+ const someSelected = selectedRowIds.size > 0 && selectedRowIds.size < rows.length;
1316
+
1317
+ const handleFocus = useCallback((event: React.FocusEvent<HTMLDivElement>) => {
1318
+
1319
+ if (event.target === event.currentTarget) {
1320
+ setFocusedCell(prev => {
1321
+ if (prev) return prev;
1322
+
1323
+ if (checkboxSelection) {
1324
+ return { id: 'HEADER', field: '__checkbox_col__' };
1325
+ }
1326
+
1327
+ const firstRow = allRenderableRows[0];
1328
+ const firstCol = navigationColumns[0];
1329
+ if (firstRow && firstCol) {
1330
+ return { id: firstRow.id, field: firstCol.field };
1331
+ }
1332
+ return null;
1333
+ });
1334
+ }
1335
+ }, [allRenderableRows, navigationColumns]);
1336
+
1337
+ const handleBlur = useCallback((event: React.FocusEvent<HTMLDivElement>) => {
1338
+
1339
+ if (!event.currentTarget.contains(event.relatedTarget as Node)) {
1340
+ setFocusedCell(null);
1341
+ }
1342
+ }, []);
1343
+
1344
+ const handleKeyDown = useCallback((event: React.KeyboardEvent) => {
1345
+ setKeyboardMode(true);
1346
+
1347
+ if (!focusedCell) return;
1348
+
1349
+ const { id, field } = focusedCell;
1350
+
1351
+ const isEditing = Boolean(editingHandlers.editingCell);
1352
+
1353
+ if (event.key === 'Enter') {
1354
+ event.preventDefault();
1355
+ if (isEditing) {
1356
+ editingHandlers.stopCellEdit();
1357
+ } else {
1358
+
1359
+ const col = navigationColumns.find(c => c.field === field);
1360
+ if (col?.editable) {
1361
+ const row = allRenderableRows.find(r => r.id === id);
1362
+ if (row) {
1363
+ editingHandlers.startCellEdit({
1364
+ id,
1365
+ field,
1366
+ value: (row as any)[field]
1367
+ });
1368
+ }
1369
+ }
1370
+ }
1371
+ return;
1372
+ }
1373
+
1374
+ if (event.key === ' ' || event.key === 'Spacebar') {
1375
+ if (!isEditing) {
1376
+ if (field === '__checkbox_col__') {
1377
+ event.preventDefault();
1378
+ handleSelectionChange(id, !selectedRowIds.has(id));
1379
+ return;
1380
+ }
1381
+ if (field === '__expand_col__') {
1382
+ event.preventDefault();
1383
+ handleDetailPanelToggle(id);
1384
+ return;
1385
+ }
1386
+ }
1387
+ }
1388
+
1389
+ if (id === 'HEADER' && (event.key === 'Enter' || event.key === ' ')) {
1390
+ event.preventDefault();
1391
+
1392
+ const col = navigationColumns.find(c => c.field === field);
1393
+ if (col && (col as any).sortable !== false) {
1394
+ const currentSort = sortModel.find(item => item.field === field);
1395
+ let newDirection: GridSortDirection = 'asc';
1396
+
1397
+ if (currentSort) {
1398
+ if (currentSort.sort === 'asc') {
1399
+ newDirection = 'desc';
1400
+ } else {
1401
+ newDirection = null;
1402
+ }
1403
+ }
1404
+ handleSort(field, newDirection);
1405
+ }
1406
+ return;
1407
+ }
1408
+
1409
+ if (event.key === 'Escape') {
1410
+ if (isEditing) {
1411
+ event.preventDefault();
1412
+ editingHandlers.stopCellEdit({ cancel: true });
1413
+ }
1414
+ return;
1415
+ }
1416
+
1417
+ if (isEditing && event.key !== 'Tab') {
1418
+ return;
1419
+ }
1420
+
1421
+ const isHeader = id === 'HEADER';
1422
+ const rowIndex = isHeader ? -1 : allRenderableRows.findIndex(r => r.id === id);
1423
+ const colIndex = navigationColumns.findIndex(c => c.field === field);
1424
+
1425
+ if (!isHeader && rowIndex === -1) return;
1426
+ if (colIndex === -1) return;
1427
+
1428
+ // Find the next FOCUSABLE cell (any cell — editability not required for arrow navigation)
1429
+ const findNextCell = (
1430
+ startRow: number,
1431
+ startCol: number,
1432
+ deltaRow: number,
1433
+ deltaCol: number,
1434
+ wrapRow: boolean,
1435
+ allowHeader: boolean = false
1436
+ ) => {
1437
+ let r = startRow + deltaRow;
1438
+ let c = startCol + deltaCol;
1439
+
1440
+ if (wrapRow && deltaCol !== 0) {
1441
+ if (deltaCol > 0 && c >= navigationColumns.length) { c = 0; r++; }
1442
+ else if (deltaCol < 0 && c < 0) { c = navigationColumns.length - 1; r--; }
1443
+ }
1444
+
1445
+ if (!wrapRow && (c < 0 || c >= navigationColumns.length)) return null;
1446
+ if (r < (allowHeader ? -1 : 0) || r >= allRenderableRows.length) return null;
1447
+
1448
+ return { r, c };
1449
+ };
1450
+
1451
+ // Find the next EDITABLE cell (for Tab key navigation)
1452
+ const findNextEditable = (
1453
+ startRow: number,
1454
+ startCol: number,
1455
+ deltaRow: number,
1456
+ deltaCol: number,
1457
+ wrapRow: boolean,
1458
+ allowHeader: boolean = false
1459
+ ) => {
1460
+ let r = startRow;
1461
+ let c = startCol;
1462
+ let steps = 0;
1463
+
1464
+ const maxSteps = allRenderableRows.length * navigationColumns.length + navigationColumns.length;
1465
+
1466
+ while (steps < maxSteps) {
1467
+ steps++;
1468
+
1469
+ r += deltaRow;
1470
+ c += deltaCol;
1471
+
1472
+ if (wrapRow && deltaCol !== 0) {
1473
+ if (deltaCol > 0) {
1474
+ if (c >= navigationColumns.length) { c = 0; r++; }
1475
+ } else {
1476
+ if (c < 0) { c = navigationColumns.length - 1; r--; }
1477
+ }
1478
+ } else {
1479
+ if (c < 0 || c >= navigationColumns.length) return null;
1480
+ }
1481
+
1482
+ if (r < -1 || r >= allRenderableRows.length) return null;
1483
+
1484
+ if (r === -1) {
1485
+ if (!allowHeader) continue;
1486
+ const col = navigationColumns[c];
1487
+ const isSortable = (col as any).sortable !== false;
1488
+ const isInteractive = ['__checkbox_col__'].includes(col.field) || isSortable;
1489
+ if (isInteractive) return { r, c };
1490
+ continue;
1491
+ }
1492
+
1493
+ const row = allRenderableRows[r];
1494
+ const col = navigationColumns[c];
1495
+
1496
+ const isInteractable = ['__checkbox_col__', '__expand_col__', '__reorder_col__'].includes(col.field);
1497
+ let isEditable = col.editable || isInteractable;
1498
+
1499
+ if (isCellEditable && !isInteractable) {
1500
+ try {
1501
+ isEditable = isCellEditable({
1502
+ row,
1503
+ field: col.field,
1504
+ value: (row as any)[col.field],
1505
+ colDef: col,
1506
+ rowIndex: r,
1507
+ colIndex: c
1508
+ });
1509
+ } catch (e) {
1510
+ console.error('Error in isCellEditable:', e);
1511
+ }
1512
+ }
1513
+
1514
+ if (isEditable) return { r, c };
1515
+ }
1516
+ return null;
1517
+ };
1518
+
1519
+ let nextRowIndex = rowIndex;
1520
+ let nextColIndex = colIndex;
1521
+ let handled = false;
1522
+
1523
+ if (event.key === 'Tab') {
1524
+ // Tab moves to next EDITABLE cell
1525
+ const dir = event.shiftKey ? -1 : 1;
1526
+ const res = findNextEditable(rowIndex, colIndex, 0, dir, true, false);
1527
+ if (res) {
1528
+ nextRowIndex = res.r;
1529
+ nextColIndex = res.c;
1530
+ handled = true;
1531
+ }
1532
+ } else if (event.key === 'ArrowRight') {
1533
+ const res = findNextCell(rowIndex, colIndex, 0, 1, true, true);
1534
+ if (res) { nextRowIndex = res.r; nextColIndex = res.c; handled = true; }
1535
+ } else if (event.key === 'ArrowLeft') {
1536
+ const res = findNextCell(rowIndex, colIndex, 0, -1, true, true);
1537
+ if (res) { nextRowIndex = res.r; nextColIndex = res.c; handled = true; }
1538
+ } else if (event.key === 'ArrowDown') {
1539
+ const res = findNextCell(rowIndex, colIndex, 1, 0, false, true);
1540
+ if (res) { nextRowIndex = res.r; nextColIndex = res.c; handled = true; }
1541
+ } else if (event.key === 'ArrowUp') {
1542
+ const res = findNextCell(rowIndex, colIndex, -1, 0, false, true);
1543
+ if (res) { nextRowIndex = res.r; nextColIndex = res.c; handled = true; }
1544
+ } else if (event.key === 'Home') {
1545
+ if (event.ctrlKey || event.metaKey) {
1546
+ nextRowIndex = -1;
1547
+ nextColIndex = 0;
1548
+ } else {
1549
+ nextColIndex = 0;
1550
+ }
1551
+ handled = true;
1552
+ } else if (event.key === 'End') {
1553
+ if (event.ctrlKey || event.metaKey) {
1554
+ nextRowIndex = allRenderableRows.length - 1;
1555
+ nextColIndex = navigationColumns.length - 1;
1556
+ } else {
1557
+ nextColIndex = navigationColumns.length - 1;
1558
+ }
1559
+ handled = true;
1560
+ } else if (event.key === 'PageUp') {
1561
+ const pageSize = pagination ? effectivePaginationModel.pageSize : 10;
1562
+ nextRowIndex = Math.max(-1, nextRowIndex - pageSize);
1563
+ handled = true;
1564
+ } else if (event.key === 'PageDown') {
1565
+ const pageSize = pagination ? effectivePaginationModel.pageSize : 10;
1566
+ nextRowIndex = Math.min(allRenderableRows.length - 1, nextRowIndex + pageSize);
1567
+ handled = true;
1568
+ }
1569
+
1570
+ if (handled) {
1571
+ event.preventDefault();
1572
+
1573
+ if (isEditing && event.key === 'Tab') {
1574
+ editingHandlers.stopCellEdit();
1575
+ }
1576
+
1577
+ if (nextRowIndex >= -1 && nextRowIndex < allRenderableRows.length &&
1578
+ nextColIndex >= 0 && nextColIndex < navigationColumns.length) {
1579
+
1580
+ const nextCol = navigationColumns[nextColIndex];
1581
+
1582
+ if (nextRowIndex === -1) {
1583
+ setFocusedCell({ id: 'HEADER', field: nextCol.field });
1584
+ } else {
1585
+ const nextRow = allRenderableRows[nextRowIndex];
1586
+ setFocusedCell({ id: nextRow.id, field: nextCol.field });
1587
+ }
1588
+
1589
+ if (viewportRef.current) {
1590
+ const { cumulativeHeights, pinnedTopHeight } = virtualization;
1591
+ const { clientHeight, clientWidth, scrollTop, scrollLeft } = viewportRef.current;
1592
+
1593
+ const rowTop = nextRowIndex === 0 ? 0 : cumulativeHeights[nextRowIndex - 1];
1594
+ const rowBottom = cumulativeHeights[nextRowIndex];
1595
+ const pinnedOffset = pinnedTopHeight;
1596
+ const visibleTop = scrollTop + pinnedOffset;
1597
+ const visibleBottom = scrollTop + clientHeight;
1598
+
1599
+ let newScrollTop = scrollTop;
1600
+ if (rowTop < visibleTop) {
1601
+ newScrollTop = Math.max(0, rowTop - pinnedOffset);
1602
+ } else if (rowBottom > visibleBottom) {
1603
+ newScrollTop = rowBottom - clientHeight;
1604
+ }
1605
+
1606
+ if (newScrollTop !== scrollTop) {
1607
+ viewportRef.current.scrollTop = newScrollTop;
1608
+ }
1609
+
1610
+ if (virtualization.columnMetrics) {
1611
+ const { leftPinnedWidth, rightPinnedWidth, unpinnedAccWidths, unpinnedCols, totalSpecialsWidth, pinnedSpecialsWidth } = virtualization.columnMetrics;
1612
+ const field = nextCol.field;
1613
+ const unpinnedIndex = unpinnedCols.findIndex((c: any) => c.field === field);
1614
+
1615
+ if (unpinnedIndex !== -1) {
1616
+ const colLeft = totalSpecialsWidth + leftPinnedWidth + (unpinnedIndex > 0 ? unpinnedAccWidths[unpinnedIndex - 1] : 0);
1617
+ const colRight = totalSpecialsWidth + leftPinnedWidth + unpinnedAccWidths[unpinnedIndex];
1618
+
1619
+ const visibleStart = scrollLeft + pinnedSpecialsWidth + leftPinnedWidth;
1620
+ const visibleEnd = scrollLeft + clientWidth - rightPinnedWidth;
1621
+
1622
+ let newScrollLeft = scrollLeft;
1623
+
1624
+ if (colLeft < visibleStart) {
1625
+ newScrollLeft = Math.max(0, colLeft - pinnedSpecialsWidth - leftPinnedWidth);
1626
+ } else if (colRight > visibleEnd) {
1627
+ newScrollLeft = colRight - clientWidth + rightPinnedWidth;
1628
+ }
1629
+
1630
+ if (newScrollLeft !== scrollLeft) {
1631
+ viewportRef.current.scrollLeft = newScrollLeft;
1632
+ }
1633
+ }
1634
+ }
1635
+ }
1636
+ }
1637
+ }
1638
+ }, [focusedCell, allRenderableRows, navigationColumns, editingHandlers, virtualization, selectedRowIds, handleSelectionChange, handleDetailPanelToggle]);
1639
+
1640
+ const hasRowSpanning = React.useMemo(() => effectiveColumns.some(c => !!c.rowSpan), [effectiveColumns]);
1641
+ const [columnsPanelOpen, setColumnsPanelOpen] = React.useState(false);
1642
+ const containerRef = React.useRef<HTMLDivElement>(null);
1643
+
1644
+ // Click-outside handler for standalone column panel
1645
+ useEffect(() => {
1646
+ if (!columnsPanelOpen || slots?.toolbar) return;
1647
+ function handleClickOutside(e: MouseEvent) {
1648
+ const panel = document.getElementById('ogx-standalone-col-panel');
1649
+ if (panel && !panel.contains(e.target as Node)) {
1650
+ setColumnsPanelOpen(false);
1651
+ }
1652
+ }
1653
+ document.addEventListener('mousedown', handleClickOutside);
1654
+ return () => document.removeEventListener('mousedown', handleClickOutside);
1655
+ }, [columnsPanelOpen, slots?.toolbar]);
1656
+
1657
+ return (
1658
+ <div
1659
+ ref={containerRef}
1660
+ className={['ogx', className, autoHeight && 'ogx--auto-height', hasRowSpanning && 'ogx--row-spanning', listView && 'ogx--list-view'].filter(Boolean).join(' ')}
1661
+ style={{
1662
+ ...style,
1663
+ height: height ?? style?.height,
1664
+ '--ogx-row-height': `${rowHeight}px`,
1665
+ '--ogx-header-height': `${headerHeight}px`
1666
+ } as any}
1667
+ aria-busy={effectiveLoading}
1668
+ >
1669
+ { }
1670
+ {slots?.toolbar && (() => {
1671
+ const toolbarProps = {
1672
+ apiRef: gridData.apiRef,
1673
+ columns: effectiveColumns as unknown as GridColDef[],
1674
+ baseColumns: columns as unknown as GridColDef[],
1675
+ aggregationModel,
1676
+ onAggregationModelChange: handleAggregationModelChange,
1677
+
1678
+ ...(pivotMode || propPivotModel || onPivotModelChange ? {
1679
+ pivotModel: currentPivotModel,
1680
+ onPivotModelChange: handlePivotModelChange,
1681
+ } : {}),
1682
+
1683
+ filterModel,
1684
+ onFilterModelChange,
1685
+ columnVisibilityModel,
1686
+ onColumnVisibilityModelChange: handleColumnVisibilityModelChange,
1687
+
1688
+ onColumnReorder: disableColumnReorder ? undefined : (fromField: string, toField: string) => {
1689
+ const currentOrder = [...effectiveColumnOrder];
1690
+ const fromIdx = currentOrder.indexOf(fromField);
1691
+ const toIdx = currentOrder.indexOf(toField);
1692
+ if (fromIdx === -1 || toIdx === -1) return;
1693
+ const newOrder = [...currentOrder];
1694
+ newOrder.splice(fromIdx, 1);
1695
+ newOrder.splice(toIdx, 0, fromField);
1696
+ if (!columnOrder) setInternalColumnOrder(newOrder);
1697
+ const col = effectiveColumns.find(c => c.field === fromField); if (col) onColumnOrderChange?.({ oldIndex: fromIdx, targetIndex: toIdx, column: col as any });
1698
+ },
1699
+
1700
+ forceColumnsOpen: columnsPanelOpen,
1701
+ onColumnsPanelClose: () => setColumnsPanelOpen(false),
1702
+
1703
+ ...slotProps?.toolbar,
1704
+ };
1705
+ return <StableToolbar {...toolbarProps} />;
1706
+ })()}
1707
+
1708
+ {/* Fallback standalone column panel when no toolbar is present */}
1709
+ {!slots?.toolbar && columnsPanelOpen && ReactDOM.createPortal(
1710
+ <div
1711
+ id="ogx-standalone-col-panel"
1712
+ style={(() => {
1713
+ const rect = containerRef.current?.getBoundingClientRect();
1714
+ return {
1715
+ position: 'fixed',
1716
+ top: rect ? rect.top + 8 : 16,
1717
+ right: rect ? window.innerWidth - rect.right + 8 : 16,
1718
+ zIndex: 9999,
1719
+ display: 'inline-block',
1720
+ };
1721
+ })()}
1722
+ >
1723
+ <button
1724
+ onClick={() => setColumnsPanelOpen(false)}
1725
+ style={{
1726
+ position: 'absolute',
1727
+ top: -12,
1728
+ right: -12,
1729
+ width: 24,
1730
+ height: 24,
1731
+ display: 'flex',
1732
+ alignItems: 'center',
1733
+ justifyContent: 'center',
1734
+ background: '#334155',
1735
+ color: '#fff',
1736
+ border: 'none',
1737
+ borderRadius: '50%',
1738
+ cursor: 'pointer',
1739
+ fontSize: 14,
1740
+ lineHeight: 1,
1741
+ zIndex: 1,
1742
+ boxShadow: '0 1px 4px rgba(0,0,0,0.2)',
1743
+ }}
1744
+ aria-label="Close"
1745
+ >×</button>
1746
+ <ColumnVisibilityPanel
1747
+ columns={effectiveColumns}
1748
+ visibleColumns={new Set(
1749
+ effectiveColumns
1750
+ .filter(col => columnVisibilityModel[col.field] !== false)
1751
+ .map(col => col.field)
1752
+ )}
1753
+ onVisibilityChange={(field, isVisible) => {
1754
+ handleColumnVisibilityModelChange({ ...columnVisibilityModel, [field]: isVisible });
1755
+ }}
1756
+ onShowAll={() => {
1757
+ const next = { ...columnVisibilityModel };
1758
+ effectiveColumns.forEach(col => { if (col.hideable !== false) next[col.field] = true; });
1759
+ handleColumnVisibilityModelChange(next);
1760
+ }}
1761
+ onHideAll={() => {
1762
+ const next = { ...columnVisibilityModel };
1763
+ effectiveColumns.forEach(col => { if (col.hideable !== false) next[col.field] = false; });
1764
+ handleColumnVisibilityModelChange(next);
1765
+ }}
1766
+ onColumnReorder={disableColumnReorder ? undefined : (fromField, toField) => {
1767
+ const currentOrder = [...effectiveColumnOrder];
1768
+ const fromIdx = currentOrder.indexOf(fromField);
1769
+ const toIdx = currentOrder.indexOf(toField);
1770
+ if (fromIdx === -1 || toIdx === -1) return;
1771
+ const newOrder = [...currentOrder];
1772
+ newOrder.splice(fromIdx, 1);
1773
+ newOrder.splice(toIdx, 0, fromField);
1774
+ if (!columnOrder) {
1775
+ setInternalColumnOrder(newOrder);
1776
+ }
1777
+ onColumnOrderChange?.({ oldIndex: fromIdx, targetIndex: toIdx, column: effectiveColumns.find(c => c.field === fromField) as any });
1778
+ }}
1779
+ />
1780
+ </div>,
1781
+ containerRef.current?.closest('.ogx-theme-provider') || document.body
1782
+ )}
1783
+
1784
+ {/* ═══════════════════════════════════════════════════════════════
1785
+ LIST VIEW — single-column card layout
1786
+ ═══════════════════════════════════════════════════════════════ */}
1787
+ {listView && listViewColumn && (
1788
+ <div
1789
+ className="ogx-list-view"
1790
+ role="grid"
1791
+ aria-label={ariaLabel || 'Data grid list view'}
1792
+ aria-rowcount={allRenderableRows.length + 1}
1793
+ >
1794
+ {/* Info bar */}
1795
+ <div className="ogx-list-view__toolbar">
1796
+ <span>
1797
+ {filteredRows.length} {filteredRows.length === 1 ? 'item' : 'items'}
1798
+ {pagination ? ` · page ${effectivePaginationModel.page + 1} of ${Math.ceil(filteredRows.length / effectivePaginationModel.pageSize) || 1}` : ''}
1799
+ {selectedRowIds.size > 0 ? ` · ${selectedRowIds.size} selected` : ''}
1800
+ </span>
1801
+ </div>
1802
+
1803
+ {/* Scrollable rows — pagination stays OUTSIDE this div */}
1804
+ <div className="ogx-list-view__rows">
1805
+ {allRenderableRows.length === 0 ? (
1806
+ <div className="ogx-list-view__empty" aria-live="polite" role="status">
1807
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
1808
+ <rect x="3" y="3" width="18" height="18" rx="2" />
1809
+ <path d="M3 9h18M9 21V9" />
1810
+ </svg>
1811
+ {noRowsLabel}
1812
+ </div>
1813
+ ) : (
1814
+ allRenderableRows.map((row, idx) => (
1815
+ <ListViewRow<R>
1816
+ key={row.id}
1817
+ row={row as R}
1818
+ rowIndex={idx}
1819
+ listViewColumn={listViewColumn as any}
1820
+ isSelected={selectedRowIds.has(row.id)}
1821
+ checkboxSelection={checkboxSelection}
1822
+ rowHeight={rowHeight}
1823
+ onRowClick={(r) => handleRowClick({ row: r, id: r.id, rowIndex: idx })}
1824
+ onSelectionChange={handleSelectionChange}
1825
+ />
1826
+ ))
1827
+ )}
1828
+ </div>
1829
+
1830
+ {/* Pagination in list view — use filteredRows.length as total since state.pagination.rowCount is only set for server-side */}
1831
+ {pagination && (() => {
1832
+ const PaginationComponent = slots?.pagination || Pagination;
1833
+ const totalRowCount = (paginationMode === 'server' && dataSource)
1834
+ ? (state.pagination.rowCount || 0)
1835
+ : filteredRows.length;
1836
+ const paginationProps = {
1837
+ page: effectivePaginationModel.page,
1838
+ pageSize: effectivePaginationModel.pageSize,
1839
+ rowCount: totalRowCount,
1840
+ pageSizeOptions: pageSizeOptions,
1841
+ onPageChange: (newPage: number) => handlePaginationModelChange({ ...effectivePaginationModel, page: newPage }),
1842
+ onPageSizeChange: (newPageSize: number) => handlePaginationModelChange({ ...effectivePaginationModel, pageSize: newPageSize, page: 0 }),
1843
+ ...slotProps?.pagination
1844
+ };
1845
+ return <PaginationComponent {...paginationProps} />;
1846
+ })()}
1847
+ </div>
1848
+ )}
1849
+
1850
+ {/* ══════════════════════════════════════════════════════════════
1851
+ STANDARD GRID VIEWPORT (hidden when listView=true)
1852
+ ══════════════════════════════════════════════════════════════ */}
1853
+ {!listView && (
1854
+ <div
1855
+ ref={(el) => {
1856
+ viewportRef.current = el;
1857
+ gridRef.current = el;
1858
+ }}
1859
+ className="ogx__viewport"
1860
+ onScroll={handleScroll}
1861
+ role="grid"
1862
+ aria-label={ariaLabel || 'Data grid'}
1863
+ aria-rowcount={filteredRows.length + 1}
1864
+ aria-colcount={
1865
+ columns.length +
1866
+ (checkboxSelection ? 1 : 0) +
1867
+ (hasDetailPanel ? 1 : 0) +
1868
+ (rowReordering ? 1 : 0)
1869
+ }
1870
+ aria-busy={effectiveLoading}
1871
+ tabIndex={0}
1872
+ onKeyDownCapture={() => { setKeyboardMode(true); }}
1873
+ onMouseDownCapture={() => { setKeyboardMode(false); }}
1874
+ onKeyDown={handleKeyDown}
1875
+ onFocus={handleFocus}
1876
+ onBlur={handleBlur}
1877
+ >
1878
+ <div
1879
+ ref={contentRef}
1880
+ className="ogx__content"
1881
+ style={{
1882
+ width: virtualization.totalWidth
1883
+ }}
1884
+ role="presentation"
1885
+ >
1886
+ { }
1887
+ <Header
1888
+ columns={virtualization.virtualColumns}
1889
+ allColumns={effectiveColumns as any}
1890
+ columnGroupingModel={columnGroupingModel}
1891
+ checkboxSelection={checkboxSelection}
1892
+ allSelected={allSelected}
1893
+ someSelected={someSelected}
1894
+ onSelectAll={handleSelectAll}
1895
+ sortModel={sortModel}
1896
+ onSort={handleSort}
1897
+
1898
+ onColumnResize={handleColumnResize}
1899
+ columnWidths={columnWidths}
1900
+ pinnedColumns={pinnedColumns}
1901
+
1902
+ focusedCell={focusedCell}
1903
+ onHeaderClick={(field) => {
1904
+ setFocusedCell({ id: 'HEADER', field });
1905
+ setKeyboardMode(false);
1906
+ gridRef.current?.focus({ preventScroll: true });
1907
+ }}
1908
+ onDragStart={columnGroupingModel ? undefined : columnReorderHandlers.onDragStart}
1909
+ onDragOver={columnGroupingModel ? undefined : columnReorderHandlers.onDragOver}
1910
+ onDragEnd={columnGroupingModel ? undefined : columnReorderHandlers.onDragEnd}
1911
+ onDrop={columnGroupingModel ? undefined : columnReorderHandlers.onDrop}
1912
+ draggedColumn={columnGroupingModel ? undefined : columnReorderHandlers.draggedColumn}
1913
+ dragOverColumn={columnGroupingModel ? undefined : columnReorderHandlers.dragOverColumn}
1914
+ rowReordering={rowReordering}
1915
+ hasDetailPanel={hasDetailPanel}
1916
+ pinCheckboxColumn={pinCheckboxColumn}
1917
+ pinExpandColumn={pinExpandColumn}
1918
+ aggregationModel={aggregationModel}
1919
+ onHideColumn={(field) => {
1920
+ handleColumnVisibilityModelChange({
1921
+ ...columnVisibilityModel,
1922
+ [field]: false,
1923
+ });
1924
+ }}
1925
+ onManageColumns={() => setColumnsPanelOpen(true)}
1926
+ onPinColumn={(field, side) => {
1927
+ const left = [...(pinnedColumns?.left ?? [])];
1928
+ const right = [...(pinnedColumns?.right ?? [])];
1929
+
1930
+ const cleanLeft = left.filter(f => f !== field);
1931
+ const cleanRight = right.filter(f => f !== field);
1932
+ if (side === 'left') {
1933
+ handlePinnedColumnsChange({ left: [...cleanLeft, field], right: cleanRight });
1934
+ } else if (side === 'right') {
1935
+ handlePinnedColumnsChange({ left: cleanLeft, right: [...cleanRight, field] });
1936
+ } else {
1937
+ handlePinnedColumnsChange({ left: cleanLeft, right: cleanRight });
1938
+ }
1939
+ }}
1940
+ />
1941
+
1942
+ {/* Empty State Overlay (Standard View) — showing after header */}
1943
+ {!effectiveLoading && !state.dataSource.error && filteredRows.length === 0 && (
1944
+ <div className="ogx__empty" style={{ width: virtualization.totalWidth }}>
1945
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
1946
+ <rect x="3" y="3" width="18" height="18" rx="2" />
1947
+ <path d="M3 9h18M9 21V9" />
1948
+ </svg>
1949
+ <span>{noRowsLabel}</span>
1950
+ </div>
1951
+ )}
1952
+
1953
+ { }
1954
+ {pinnedTopRows.length > 0 && (
1955
+ <div className="ogx__pinned-rows ogx__pinned-rows--top" role="rowgroup">
1956
+ {pinnedTopRows.map((row, index) => (
1957
+ <Row
1958
+ key={row.id}
1959
+ row={row}
1960
+ columns={virtualization.virtualColumns}
1961
+ rowIndex={index}
1962
+ isSelected={selectedRowIds.has(row.id)}
1963
+ checkboxSelection={checkboxSelection}
1964
+ onRowClick={handleRowClick}
1965
+ onCellClick={handleCellClick}
1966
+ onSelectionChange={handleSelectionChange}
1967
+ columnWidths={columnWidths}
1968
+ pinnedColumns={pinnedColumns}
1969
+ pinnedRows={pinnedRows}
1970
+
1971
+ hasDetailPanel={hasDetailPanel}
1972
+ isDetailPanelExpanded={expandedRowIds.has(row.id)}
1973
+ detailPanelContent={getDetailPanelContent ? getDetailPanelContent({ row, id: row.id, rowIndex: index }) : null}
1974
+ detailPanelHeight={getDetailPanelHeight?.({ row, id: row.id, rowIndex: index }) || 200}
1975
+ onDetailPanelToggle={handleDetailPanelToggle}
1976
+ pinCheckboxColumn={pinCheckboxColumn}
1977
+ pinExpandColumn={pinExpandColumn}
1978
+
1979
+ focusedCellField={focusedCell?.id === row.id ? focusedCell.field : null}
1980
+
1981
+ colspanMap={spanning.colspanMap}
1982
+ rowSpanningCaches={spanning.rowSpanningState.caches}
1983
+ rowHeight={rowHeight}
1984
+ />
1985
+ ))}
1986
+ </div>
1987
+ )}
1988
+
1989
+ { }
1990
+ <div
1991
+ className="ogx__virtual-container"
1992
+ style={{
1993
+ height: `${virtualization.totalHeight - virtualization.pinnedTopHeight - virtualization.pinnedBottomHeight}px`
1994
+ }}
1995
+ role="presentation"
1996
+ >
1997
+ { }
1998
+ <div
1999
+ className="ogx__rows"
2000
+ style={{
2001
+ transform: `translateY(${virtualization.renderContext.firstRowIndex * rowHeight}px)`
2002
+ }}
2003
+ role="rowgroup"
2004
+ >
2005
+ {effectiveLoading && visibleRows.length === 0 ? (
2006
+
2007
+ (() => {
2008
+
2009
+ const skeletonColumns = columns.length > 0
2010
+ ? columns
2011
+ : (() => {
2012
+
2013
+ const availableWidth = (state.dimensions.viewportWidth || 1000) -
2014
+ (checkboxSelection ? 48 : 0) -
2015
+ (getDetailPanelContent ? 48 : 0) -
2016
+ (rowReordering ? 48 : 0);
2017
+
2018
+ const columnWidth = 150;
2019
+ const columnCount = Math.max(1, Math.ceil(availableWidth / columnWidth));
2020
+
2021
+ return Array.from({ length: columnCount }, (_, i) => ({
2022
+ field: `placeholder_${i}`,
2023
+ headerName: '',
2024
+ width: columnWidth
2025
+ }));
2026
+ })();
2027
+
2028
+ return Array.from({ length: 10 }).map((_, index) => (
2029
+ <SkeletonRow
2030
+ key={`skeleton-${index}`}
2031
+ columns={skeletonColumns}
2032
+ rowHeight={rowHeight}
2033
+ checkboxSelection={checkboxSelection}
2034
+ hasDetailPanel={!!getDetailPanelContent}
2035
+ rowReordering={rowReordering}
2036
+ />
2037
+ ));
2038
+ })()
2039
+ ) : (
2040
+ visibleRows
2041
+ .filter(({ row }) => !isRowPinned(row.id, pinnedRows))
2042
+ // Defensive deduplication to prevent React key collision
2043
+ .filter((item, index, self) =>
2044
+ index === self.findIndex(t => t.row.id === item.row.id)
2045
+ )
2046
+ .map(({ row, rowIndex: actualIndex }) => {
2047
+ return (
2048
+ <Row
2049
+ key={`${row.id}-${virtualization.totalWidth}`}
2050
+ row={row}
2051
+ columns={virtualization.virtualColumns}
2052
+ rowIndex={actualIndex}
2053
+ isSelected={selectedRowIds.has(row.id)}
2054
+ checkboxSelection={checkboxSelection}
2055
+ onRowClick={handleRowClick}
2056
+ onCellClick={handleCellClick}
2057
+ onSelectionChange={handleSelectionChange}
2058
+ columnWidths={columnWidths}
2059
+ pinnedColumns={pinnedColumns}
2060
+ pinnedRows={pinnedRows}
2061
+ // Detail Panel
2062
+ hasDetailPanel={hasDetailPanel}
2063
+ isDetailPanelExpanded={expandedRowIds.has(row.id)}
2064
+ detailPanelContent={getDetailPanelContent ? getDetailPanelContent({ row, id: row.id, rowIndex: actualIndex }) : null}
2065
+ detailPanelHeight={getDetailPanelHeight?.({ row, id: row.id, rowIndex: actualIndex }) || 200}
2066
+ onDetailPanelToggle={handleDetailPanelToggle}
2067
+ pinCheckboxColumn={pinCheckboxColumn}
2068
+ pinExpandColumn={pinExpandColumn}
2069
+ // Row Reordering
2070
+ rowReordering={rowReordering}
2071
+ onDragStart={rowReorderHandlers.onDragStart}
2072
+ onDragOver={rowReorderHandlers.onDragOver}
2073
+ onDragEnd={rowReorderHandlers.onDragEnd}
2074
+ onDrop={rowReorderHandlers.onDrop}
2075
+ isDragging={rowReorderHandlers.draggedRowId === row.id}
2076
+ isDragOver={rowReorderHandlers.dragOverRowId === row.id}
2077
+ // Editing
2078
+ editingCell={editingHandlers.editingCell}
2079
+ onEditStart={editingHandlers.startCellEdit}
2080
+ onEditStop={editingHandlers.stopCellEdit}
2081
+ onEditCellValueChange={editingHandlers.setEditCellValue}
2082
+ // Focus
2083
+ focusedCellField={focusedCell != null && focusedCell.id === row.id ? focusedCell.field : null}
2084
+ // Spanning
2085
+ colspanMap={spanning.colspanMap}
2086
+ rowSpanningCaches={spanning.rowSpanningState.caches}
2087
+ rowHeight={rowHeight}
2088
+ />
2089
+ );
2090
+ })
2091
+ )}
2092
+
2093
+ {/* Infinite Scroll Skeletons (Inline with flow, inside translateY container) */}
2094
+ {paginationMode === 'infinite' && state.dataSource.loading && sortedUnpinnedRows.length > 0 && (() => {
2095
+ const skeletonCount = Math.min(effectivePaginationModel.pageSize, 20);
2096
+ // The virtual container translates its children down by `firstRowIndex * rowHeight`.
2097
+ // Since these skeletons are at the VERY BOTTOM of all rows, their actual array index
2098
+ // is precisely after the last real row.
2099
+ const startIdx = layout.unpinnedRowsLength;
2100
+
2101
+ // However, they are rendered INSIDE the translateY block. The real rows handled this nicely
2102
+ // because they just layout one after another. Skeletons can do exactly the same, EXCEPT we might
2103
+ // need to offset them so they sit at the bottom.
2104
+ return (
2105
+ <div className="ogx__skeleton-group">
2106
+ {Array.from({ length: skeletonCount }).map((_, i) => (
2107
+ <Row
2108
+ key={`__skeleton_${i}__`}
2109
+ row={{ id: `__skeleton_${i}__`, _isSkeleton: true } as any}
2110
+ columns={virtualization.virtualColumns}
2111
+ rowIndex={startIdx + i}
2112
+ rowHeight={rowHeight}
2113
+ />
2114
+ ))}
2115
+ </div>
2116
+ );
2117
+ })()}
2118
+ </div>
2119
+
2120
+ </div>
2121
+
2122
+ {/* Pinned Bottom Rows */}
2123
+ {pinnedBottomRows.length > 0 && (
2124
+ <div className="ogx__pinned-rows ogx__pinned-rows--bottom" role="rowgroup">
2125
+ {pinnedBottomRows.map((row, index) => (
2126
+ <Row
2127
+ key={row.id}
2128
+ row={row}
2129
+ columns={virtualization.virtualColumns}
2130
+ rowIndex={index}
2131
+ isSelected={selectedRowIds.has(row.id)}
2132
+ checkboxSelection={checkboxSelection}
2133
+ onRowClick={handleRowClick}
2134
+ onCellClick={handleCellClick}
2135
+ onSelectionChange={handleSelectionChange}
2136
+ columnWidths={columnWidths}
2137
+ pinnedColumns={pinnedColumns}
2138
+ pinnedRows={pinnedRows}
2139
+ // Detail Panel
2140
+ hasDetailPanel={hasDetailPanel}
2141
+ isDetailPanelExpanded={expandedRowIds.has(row.id)}
2142
+ detailPanelContent={getDetailPanelContent ? getDetailPanelContent({ row, id: row.id, rowIndex: index }) : null}
2143
+ detailPanelHeight={getDetailPanelHeight?.({ row, id: row.id, rowIndex: index }) || 200}
2144
+ onDetailPanelToggle={handleDetailPanelToggle}
2145
+ pinCheckboxColumn={pinCheckboxColumn}
2146
+ pinExpandColumn={pinExpandColumn}
2147
+ // Focus
2148
+ focusedCellField={focusedCell?.id === row.id ? focusedCell.field : null}
2149
+ // Spanning
2150
+ colspanMap={spanning.colspanMap}
2151
+ rowSpanningCaches={spanning.rowSpanningState.caches}
2152
+ rowHeight={rowHeight}
2153
+ />
2154
+ ))}
2155
+ </div>
2156
+ )}
2157
+
2158
+ {/* Aggregation Footer Row — suppressed in pivot mode because pivot rows
2159
+ already contain pre-aggregated values with synthetic field keys
2160
+ (e.g. 'Q1\u001frevenue\u001fsum') that don't match aggregationModel keys. */}
2161
+ {hasAggregation && !pivotMode && (
2162
+ <div
2163
+ className="ogx__aggregation-footer"
2164
+ role="row"
2165
+ aria-label="Aggregation totals"
2166
+ aria-live="polite"
2167
+ style={{
2168
+ minHeight: `${rowHeight}px`
2169
+ }}
2170
+ >
2171
+ {checkboxSelection && (
2172
+ <div style={{ width: 48, flexShrink: 0 }} />
2173
+ )}
2174
+ {hasDetailPanel && (
2175
+ <div style={{ width: 48, flexShrink: 0 }} />
2176
+ )}
2177
+ {rowReordering && (
2178
+ <div style={{ width: 48, flexShrink: 0 }} />
2179
+ )}
2180
+ {orderedColumns.map((col) => {
2181
+ const fnName = (aggregationModel as Record<string, string>)[col.field];
2182
+ const rawValue = aggregationResult[col.field];
2183
+ const colWidth = columnWidths[col.field] ?? (typeof col.width === 'number' ? col.width : 120);
2184
+
2185
+ return (
2186
+ <div
2187
+ key={col.field}
2188
+ className="ogx__aggregation-cell"
2189
+ role="gridcell"
2190
+ style={{
2191
+ width: colWidth,
2192
+ minWidth: colWidth,
2193
+ maxWidth: colWidth,
2194
+ textAlign: (col.align as React.CSSProperties['textAlign']) || 'left',
2195
+ }}
2196
+ >
2197
+ {fnName ? (
2198
+ <>
2199
+ <span className="ogx__aggregation-label">
2200
+ {fnName}
2201
+ </span>
2202
+ <span className="ogx__aggregation-value">
2203
+ {formatAggregationValue(rawValue, fnName)}
2204
+ </span>
2205
+ </>
2206
+ ) : null}
2207
+ </div>
2208
+ );
2209
+ })}
2210
+ </div>
2211
+ )}
2212
+
2213
+ </div>
2214
+ </div>
2215
+ )}
2216
+
2217
+ {/* Pagination — shared between grid and list view when not inside list view block */}
2218
+ {!listView && pagination && (() => {
2219
+ const PaginationComponent = slots?.pagination || Pagination;
2220
+ const paginationProps = {
2221
+ page: effectivePaginationModel.page,
2222
+ pageSize: effectivePaginationModel.pageSize,
2223
+ rowCount: state.pagination.rowCount,
2224
+ pageSizeOptions: pageSizeOptions,
2225
+ onPageChange: (newPage: number) => handlePaginationModelChange({ ...effectivePaginationModel, page: newPage }),
2226
+ onPageSizeChange: (newPageSize: number) => handlePaginationModelChange({ ...effectivePaginationModel, pageSize: newPageSize, page: 0 }),
2227
+ ...slotProps?.pagination
2228
+ };
2229
+
2230
+ return <PaginationComponent {...paginationProps} />;
2231
+ })()}
2232
+
2233
+ {/* Accessibility Live Region */}
2234
+ <div className="ogx-aria-live-status" role="status" aria-live="polite">
2235
+ {effectiveLoading ? 'Loading data...' : ''}
2236
+ {state.dataSource.error ? `Error: ${state.dataSource.error.message || 'Unknown error'}` : ''}
2237
+ {!loading && !state.dataSource.error && (
2238
+ filteredRows.length === 0
2239
+ ? noRowsLabel
2240
+ : (filterModel && ((filterModel.quickFilterValues?.length || 0) > 0 || (filterModel.items?.length || 0) > 0))
2241
+ ? `${filteredRows.length} ${filteredRows.length === 1 ? 'row' : 'rows'} found`
2242
+ : ''
2243
+ )}
2244
+ </div>
2245
+
2246
+ {state.dataSource.error && (
2247
+ <div className="ogx-error-overlay" aria-live="assertive" role="alert">
2248
+ <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="var(--ogx-color-error)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
2249
+ <circle cx="12" cy="12" r="10" />
2250
+ <line x1="12" y1="8" x2="12" y2="12" />
2251
+ <line x1="12" y1="16" x2="12.01" y2="16" />
2252
+ </svg>
2253
+ <div className="ogx-error-overlay__title">
2254
+ Oops! Something went wrong
2255
+ </div>
2256
+ <div className="ogx-error-overlay__message">
2257
+ {state.dataSource.error.message || 'An unexpected error occurred while loading the data.'}
2258
+ </div>
2259
+ <button
2260
+ onClick={() => window.location.reload()}
2261
+ className="ogx-button ogx-button--primary"
2262
+ >
2263
+ Retry
2264
+ </button>
2265
+ </div>
2266
+ )}
2267
+ </div>
2268
+ );
2269
+ }