/
DataGrid.js
610 lines (543 loc) 路 20.2 KB
/
DataGrid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
import React from "react";
import PropTypes from "prop-types";
import { VariableSizeGrid as Grid } from "react-window";
import "@paprika/helpers/lib/polyfills/elementScroll";
import * as constants from "@paprika/constants/lib/Constants";
import useI18n from "@paprika/l10n/lib/useI18n";
import { extractChildren } from "@paprika/helpers";
import { v4 as uuidv4 } from "uuid";
import useGridEventHandler, { getGridRefId } from "./hooks/useGridEventHandler";
import ColumnDefinition from "./components/ColumnDefinition";
import * as sc from "./DataGrid.styles";
import Basement, { End } from "./components/Basement";
import InfiniteScroll from "./components/InfiniteScroll";
import { Row, HeaderRow, StickyRow, StickyHeaderRow, createItemData } from "./DataGrid.Rows";
import getScrollbarWidth from "./helpers/getScrollbarWidth";
window.paprika = { dataGridRef: {} };
const outerElementType = React.forwardRef((props, ref) => <sc.OuterElementType role="rowgroup" ref={ref} {...props} />);
const innerElementType = React.forwardRef((props, ref) => <sc.InnerElementType role="row" ref={ref} {...props} />);
const outerElementTypeMainGrid = React.forwardRef((props, ref) => (
<sc.OuterElementTypeMainGrid role="rowgroup" ref={ref} {...props} />
));
const innerElementTypeMainGrid = React.forwardRef((props, ref) => (
<sc.InnerElementTypeMainGrid role="row" ref={ref} {...props} />
));
const DataGrid = React.forwardRef((props, ref) => {
const {
autofocus,
borderType,
children,
data,
forceTableWidthWithScrollBars,
hasZebraStripes,
height,
onClick,
onHighlighted,
onKeyDown,
onPressEnter,
onPressShiftSpaceBar,
onPressSpaceBar,
onRowChecked,
rowHeight,
width,
...moreProps
} = props;
const refScrollHeader = React.useRef(null);
const refContainer = React.useRef(null);
const refGridColumns = React.useRef(null);
const refGridStickyHeader = React.useRef(null);
const refGridHeader = React.useRef(null);
const refScrollStickyColumns = React.useRef(null);
const refScrollGrid = React.useRef(null);
const refScrollHappenedBy = React.useRef(null);
const refEnd = React.useRef(null);
const refPrevLastScrollHeight = React.useRef(null);
const refCurrentPage = React.useRef(null);
const refVisibleIndexes = React.useRef({
start: null,
stop: null,
});
const refTotalColumnWidth = React.useRef(0);
const refRemainingSpace = React.useRef(0);
const refTotalCanGrow = React.useRef(0);
const refPrevEventCellHighlighted = React.useRef({ columnIndex: null, rowIndex: null });
const [scrollBarWidth, setScrollBarWidth] = React.useState(getScrollbarWidth);
const [pageSize, setPageSize] = React.useState(null);
const i18n = useI18n();
// these two value are sensitive in Grids with lots of columns and can degradate performance alot.
// be caution when using them.
const overscanRowCount = 7;
const overscanColumnCount = 5;
const rowCount = data.length;
const {
"DataGrid.ColumnDefinition": extractedColumnDefinitions,
"DataGrid.Basement": extractedBasement,
"DataGrid.InfiniteScroll": extractedInfiniteScroll,
} = extractChildren(children, ["DataGrid.ColumnDefinition", "DataGrid.Basement", "DataGrid.InfiniteScroll"]);
let ColumnDefinitions = extractedColumnDefinitions;
let columnCount = ColumnDefinitions && ColumnDefinitions.length;
if (!Array.isArray(extractedColumnDefinitions)) {
// when there is only one component extracted function return the element not an array of elements
ColumnDefinitions = [extractedColumnDefinitions];
columnCount = ColumnDefinitions.length;
}
const columnHeadersA11yText = React.useMemo(
() =>
ColumnDefinitions.map(ColumnDefinition => {
const { header, headerA11yText } = ColumnDefinition.props;
return typeof header === "function" ? headerA11yText && headerA11yText() : header;
}),
[ColumnDefinitions]
);
const calculatedTableHeight = React.useMemo(
() => (rowHeight * rowCount > height ? height : rowHeight * rowCount + scrollBarWidth),
[height, rowCount, rowHeight, scrollBarWidth]
);
const calculatedTableWidth = React.useCallback(() => {
let width = 0;
ColumnDefinitions.forEach(ColumnDefinition => {
if (!ColumnDefinition.props.isSticky) {
width += Number.parseInt(ColumnDefinition.props.width, 10);
}
});
return width + scrollBarWidth;
}, [ColumnDefinitions, scrollBarWidth]);
const gridWidth = width === null ? calculatedTableWidth() : width;
const stickyColumnsIndexes = React.useMemo(
() =>
ColumnDefinitions.map((ColumnDefinition, index) => (ColumnDefinition.props.isSticky ? index : null)).filter(
chunk => chunk !== null
),
[ColumnDefinitions]
);
const stickyGridWidth = React.useMemo(() => {
let width = 0;
if (stickyColumnsIndexes.length) {
stickyColumnsIndexes.forEach(index => {
width += ColumnDefinitions[index].props.width;
});
}
return width;
}, [ColumnDefinitions, stickyColumnsIndexes]);
const [gridId] = React.useState(() => `PKA${uuidv4()}`);
const { handleKeyDown, handleKeyUp, handleClick, restoreHighlightFocus } = useGridEventHandler({
columnCount,
gridId,
onClick,
onKeyDown,
onPressEnter,
onPressShiftSpaceBar,
onPressSpaceBar,
onRowChecked,
refContainer,
refGrid: refGridColumns,
rowCount,
rowHeight,
scrollBarWidth,
stickyColumnsIndexes,
});
const a11yTextMessage = React.useCallback(
(value, column, rowIndex) =>
i18n.t("dataGrid.a11yTextMessage", {
value,
rowIndex,
columnIndex: column,
}),
[i18n]
);
const handleScroll = React.useCallback(parameters => {
const { scrollLeft, scrollTop } = parameters;
if (refScrollHeader.current) {
refScrollHeader.current.scrollTo({ left: scrollLeft, top: 0 });
}
// prevent re-scrolling when this scrollbar gets sync with the one in the sticky column
if (refScrollHappenedBy.current === null) {
refScrollHappenedBy.current = "handleScroll";
if (refScrollStickyColumns.current) {
refScrollStickyColumns.current.scrollTo({ left: 0, top: scrollTop });
}
} else {
refScrollHappenedBy.current = null;
}
if (
refScrollGrid.current &&
refEnd.current &&
refScrollGrid.current.scrollTop + refScrollGrid.current.offsetHeight >= refScrollGrid.current.scrollHeight
) {
refEnd.current.onScrollBarReachedBottom(true);
} else if (refEnd.current) {
refEnd.current.onScrollBarReachedBottom(false);
}
}, []);
const handleScrollStickyColumns = React.useCallback(
parameters => {
const { scrollTop } = parameters;
// prevent rescrolling when this scrollbar gets sync with the one in the main grid
if (refScrollHappenedBy.current === null) {
refScrollHappenedBy.current = "handleScrollStickyColumns";
if (refScrollGrid.current) {
refScrollGrid.current.scrollTo({ left: 0, top: scrollTop });
}
} else {
refScrollHappenedBy.current = null;
}
},
[refScrollGrid]
);
React.useLayoutEffect(() => {
if (!refContainer.current) return;
refScrollHeader.current = refContainer.current.querySelector(`.${gridId}-header`);
refScrollStickyColumns.current = refContainer.current.querySelector(`.${gridId}-sticky-columns`);
refScrollGrid.current = refContainer.current.querySelector(`.grid-${gridId}`);
}, [gridId]);
React.useLayoutEffect(() => {
const scrollContainer =
refContainer.current && refContainer.current.querySelector(`.grid-${gridId} [role="row"]`).parentElement;
if (!scrollContainer) return;
// https://stackoverflow.com/questions/21064101/understanding-offsetwidth-clientwidth-scrollwidth-and-height-respectively
// https://davidwalsh.name/detect-scrollbar-width
if (forceTableWidthWithScrollBars) {
return;
}
setScrollBarWidth(() => scrollContainer.offsetWidth - scrollContainer.clientWidth);
}, [forceTableWidthWithScrollBars, gridId]);
const handleFocusGrid = React.useCallback(() => {
const $isBlurred = refContainer.current.querySelector(".grid--is-blurred");
if ($isBlurred) $isBlurred.classList.remove("grid--is-blurred");
}, []);
const itemData = createItemData(
ColumnDefinitions,
data,
gridId,
hasZebraStripes,
stickyColumnsIndexes,
columnHeadersA11yText,
a11yTextMessage,
borderType
);
React.useEffect(() => {
if (data.length && pageSize === null) {
setPageSize(() => data.length);
}
}, [data.length, pageSize]);
React.useEffect(() => {
refPrevLastScrollHeight.current = refScrollGrid.current && refScrollGrid.current.scrollHeight;
}, []);
React.useImperativeHandle(
ref,
() => ({
focus: () => {
restoreHighlightFocus();
},
getVisibleIndexes: () => refVisibleIndexes.current,
getVisibleRows: () => {
const { start, stop } = refVisibleIndexes.current;
return data.slice(start, stop);
},
}),
[data, restoreHighlightFocus]
);
const handleBlurGrid = React.useCallback(() => {
const $isActive = refContainer.current.querySelector(".grid--is-active");
if ($isActive) $isActive.classList.toggle("grid--is-blurred");
}, []);
const handleMouseUpGrid = React.useCallback(
event => {
handleClick({ data, ColumnDefinitions })(event);
},
[ColumnDefinitions, data, handleClick]
);
const handleKeyDownGrid = React.useCallback(
event => {
handleKeyDown({ data, ColumnDefinitions })(event);
},
[ColumnDefinitions, data, handleKeyDown]
);
const handleKeyUpGrid = React.useCallback(
event => {
handleKeyUp({ data, ColumnDefinitions })(event);
},
[ColumnDefinitions, data, handleKeyUp]
);
const handleItemsRendered = React.useCallback(
({ visibleRowStartIndex, visibleRowStopIndex }) => {
refVisibleIndexes.current = {
start: visibleRowStartIndex,
stop: visibleRowStopIndex,
};
if (refCurrentPage.current === null) {
refCurrentPage.current = 0;
}
if (extractedInfiniteScroll) {
const { rowsOffset, onReachedOffset } = extractedInfiniteScroll.props;
if (visibleRowStopIndex + rowsOffset > rowCount) {
const currentPage = Math.floor(visibleRowStopIndex / pageSize);
const nextPage = currentPage + 1;
onReachedOffset({ currentPage, nextPage });
}
}
},
[extractedInfiniteScroll, pageSize, rowCount]
);
React.useEffect(() => {
// Using lazy import because in some cases document.body is null but mouse-wheel
// depends on document.body being not null. Therefore we need to lazy import the mouse-wheel library.
import("mouse-wheel").then(module => {
if (Array.isArray(data) && data.length) {
const { default: mouseWheel } = module;
mouseWheel(refScrollGrid.current, (dx, dy, dz, event) => {
event.preventDefault();
refScrollGrid.current.scrollTo(refScrollGrid.current.scrollLeft + dx, refScrollGrid.current.scrollTop + dy);
});
mouseWheel(refScrollStickyColumns.current, (dx, dy, dz, event) => {
event.preventDefault();
refScrollStickyColumns.current.scrollTo(
refScrollStickyColumns.current.scrollLeft + dx,
refScrollStickyColumns.current.scrollTop + dy
);
});
}
});
}, [gridId, data]);
React.useEffect(() => {
if (!refContainer.current) return;
if (refGridColumns.current && refGridStickyHeader.current && refGridHeader.current) {
refGridHeader.current.resetAfterColumnIndex(0);
refGridStickyHeader.current.resetAfterColumnIndex(0);
refGridColumns.current.resetAfterColumnIndex(0);
}
ColumnDefinitions.forEach(columnDefinition => {
refTotalColumnWidth.current += columnDefinition.props.width;
if (columnDefinition.props.canGrow) {
refTotalCanGrow.current += 1;
}
});
refRemainingSpace.current = refContainer.current.offsetWidth - refTotalColumnWidth.current - scrollBarWidth;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleCellHighlighted = React.useCallback(
event => {
const { rowIndex: prevRowIndex, columnIndex: prevColumnIndex } = refPrevEventCellHighlighted.current;
const key = getGridRefId({ gridId, columnIndex: event.detail.columnIndex, rowIndex: event.detail.rowIndex });
const prevKey = getGridRefId({ gridId, columnIndex: prevColumnIndex, rowIndex: prevRowIndex });
const nextRowIndex = event.detail.rowIndex | 0; // eslint-disable-line
const nextColumnIndex = event.detail.columnIndex | 0; // eslint-disable-line
const getElementFromDom = (gridId, columnIndex, rowIndex) => () =>
document.querySelector(`[data-pka-cell-key="${gridId}.${columnIndex}.${rowIndex}"]`);
const attributes = (columnIndex, rowIndex, gridId) => ({
columnIndex,
rowIndex,
gridId,
});
const nextRef = window.paprika.dataGridRef[key] || null;
const prevRef = window.paprika.dataGridRef[prevKey] || null;
onHighlighted({
next: {
attributes: attributes(nextColumnIndex, nextRowIndex, gridId),
getElementFromDom: getElementFromDom(gridId, nextColumnIndex, nextRowIndex),
ref: nextRef,
},
prev: {
attributes: attributes(prevColumnIndex, prevRowIndex, gridId),
getElementFromDom: getElementFromDom(gridId, prevColumnIndex, prevRowIndex),
ref: prevRef,
},
});
refPrevEventCellHighlighted.current = { columnIndex: nextColumnIndex, rowIndex: nextRowIndex };
},
[gridId, onHighlighted]
);
React.useEffect(() => {
document.addEventListener("dataGridCellHighlighted", handleCellHighlighted, false);
return () => {
document.removeEventListener("dataGridCellHighlighted", handleCellHighlighted, false);
};
}, [handleCellHighlighted]);
const calculateColumnWidth = columnIndex => {
if (stickyColumnsIndexes.includes(columnIndex)) {
return 0;
}
if (
ColumnDefinitions[columnIndex].props.canGrow &&
refTotalCanGrow.current !== 0 &&
refRemainingSpace.current > 0
) {
return ColumnDefinitions[columnIndex].props.width + refRemainingSpace.current / refTotalCanGrow.current;
}
return ColumnDefinitions[columnIndex].props.width;
};
if (data.length === 0) return null;
return (
<>
<sc.Grid
$width={gridWidth}
aria-colcount={columnCount}
gridId={gridId}
onBlur={handleBlurGrid}
onFocus={handleFocusGrid}
onKeyDown={handleKeyDownGrid}
onKeyUp={handleKeyUpGrid}
onMouseUp={handleMouseUpGrid}
ref={refContainer}
role="grid"
scrollBarWidth={scrollBarWidth}
tabIndex={0}
{...moreProps}
>
<sc.Flex>
{/** STICKY HEADER */}
<Grid
className={`${gridId}-sticky-header`}
columnCount={stickyColumnsIndexes.length}
columnWidth={columnIndex => ColumnDefinitions[stickyColumnsIndexes[columnIndex]].props.width}
itemData={itemData}
height={rowHeight}
ref={refGridStickyHeader}
rowCount={1}
rowHeight={() => rowHeight}
width={stickyGridWidth}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
>
{StickyHeaderRow}
</Grid>
{/** HEADER */}
<Grid
className={`${gridId}-header`}
columnCount={columnCount}
columnWidth={calculateColumnWidth}
height={rowHeight}
innerElementType={innerElementType}
itemData={itemData}
outerElementType={outerElementType}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
ref={refGridHeader}
rowCount={1}
rowHeight={() => rowHeight}
width={gridWidth - stickyGridWidth - scrollBarWidth}
>
{HeaderRow}
</Grid>
</sc.Flex>
{/** STICKY COLUMNS */}
<sc.Flex>
<Grid
className={`${gridId}-sticky-columns`}
columnCount={stickyColumnsIndexes.length}
columnWidth={columnIndex => ColumnDefinitions[stickyColumnsIndexes[columnIndex]].props.width}
height={calculatedTableHeight - scrollBarWidth}
innerElementType={innerElementType}
itemData={itemData}
onItemsRendered={handleItemsRendered}
onScroll={handleScrollStickyColumns}
outerElementType={outerElementType}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
rowCount={rowCount}
rowHeight={() => rowHeight}
width={stickyGridWidth}
>
{StickyRow}
</Grid>
{/** COLUMNS */}
<Grid
className={`grid-${gridId}`}
columnCount={columnCount}
columnWidth={calculateColumnWidth}
height={calculatedTableHeight}
innerElementType={innerElementTypeMainGrid}
itemData={itemData}
onItemsRendered={handleItemsRendered}
onScroll={handleScroll}
outerElementType={outerElementTypeMainGrid}
overscanColumnCount={overscanColumnCount}
overscanRowCount={overscanRowCount}
ref={refGridColumns}
rowCount={rowCount}
rowHeight={() => rowHeight}
width={gridWidth - stickyGridWidth}
>
{Row}
</Grid>
</sc.Flex>
<sc.FillerTopRight rowHeight={rowHeight} scrollBarWidth={scrollBarWidth} />
<sc.FillerBottomLeft stickyGridWidth={stickyGridWidth} scrollBarWidth={scrollBarWidth} />
</sc.Grid>
<sc.Footer $width={gridWidth}>
<sc.RowCount>
{i18n.t("dataGrid.rows", { rowCount })} {i18n.t("dataGrid.columns", { columnCount })}
</sc.RowCount>
</sc.Footer>
{extractedBasement ? (
<End width={gridWidth} ref={refEnd}>
{extractedBasement}
</End>
) : null}
</>
);
});
DataGrid.types = {
border: constants.gridTypes,
};
const propTypes = {
/** If the data cell should automatically get focus */
autofocus: PropTypes.bool,
/** Define the look for borders in the table types.DataGrid.GRID, types.DataGrid.NONE, etc. */
borderType: PropTypes.oneOf([
DataGrid.types.border.GRID,
DataGrid.types.border.NONE,
DataGrid.types.border.HORIZONTAL,
DataGrid.types.border.VERTICAL,
]),
children: PropTypes.node.isRequired,
/** This will force the table to include in the calculation of the table the scrollbar thickness */
forceTableWidthWithScrollBars: PropTypes.bool,
/** Add an alternate background on the DataGrid's rows */
hasZebraStripes: PropTypes.bool,
/** Array of data to be stored in the DataGrid */
data: PropTypes.arrayOf(PropTypes.shape({})),
/** Sets the height of the DataGrid */
height: PropTypes.number,
/** Callback onClick */
onClick: PropTypes.func,
/** Callback onKeyDown press */
onKeyDown: PropTypes.func,
/** Callback when Enter key is pressed */
onPressEnter: PropTypes.func,
/** Callback when Shift + Spacebar is pressed */
onPressShiftSpaceBar: PropTypes.func,
/** Callback when Spacebar is pressed */
onPressSpaceBar: PropTypes.func,
/** Callback when user click the f key. Might change in the future */
onRowChecked: PropTypes.func,
/** Callback with information about the prev and next highlighted cell */
onHighlighted: PropTypes.func,
/** Sets the row height */
rowHeight: PropTypes.number,
/** Sets the DataGrid width */
width: PropTypes.number,
};
const defaultProps = {
autofocus: true,
borderType: DataGrid.types.border.GRID,
data: [],
forceTableWidthWithScrollBars: false,
hasZebraStripes: false,
height: 600,
onClick: null,
onHighlighted: () => {},
onKeyDown: () => {},
onPressEnter: null,
onPressShiftSpaceBar: null,
onPressSpaceBar: null,
onRowChecked: () => {},
rowHeight: 36,
width: null,
};
DataGrid.ColumnDefinition = ColumnDefinition;
DataGrid.defaultProps = defaultProps;
DataGrid.InfiniteScroll = InfiniteScroll;
DataGrid.propTypes = propTypes;
DataGrid.Basement = Basement;
export default DataGrid;