-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathHeaderCell.tsx
More file actions
408 lines (364 loc) · 11.5 KB
/
HeaderCell.tsx
File metadata and controls
408 lines (364 loc) · 11.5 KB
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
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { css } from 'ecij';
import { useRovingTabIndex } from './hooks';
import {
clampColumnWidth,
getCellClassname,
getCellStyle,
getHeaderCellRowSpan,
getHeaderCellStyle,
getLeftRightKey,
isCtrlKeyHeldDown,
stopPropagation
} from './utils';
import type { CalculatedColumn, SortColumn } from './types';
import type { HeaderRowProps } from './HeaderRow';
const cellSortableClassname = css`
@layer rdg.HeaderCell {
cursor: pointer;
}
`;
const cellResizable = css`
@layer rdg.HeaderCell {
touch-action: none;
}
`;
const cellResizableClassname = `rdg-cell-resizable ${cellResizable}`;
const resizeHandle = css`
@layer rdg.HeaderCell {
cursor: col-resize;
position: absolute;
inset-block-start: 0;
inset-inline-end: 0;
inset-block-end: 0;
inline-size: 10px;
}
`;
const resizeHandleClassname = `rdg-resize-handle ${resizeHandle}`;
const cellDraggableClassname = 'rdg-cell-draggable';
const cellDraggingOrOver = css`
@layer rdg.HeaderCell {
background-color: var(--rdg-header-draggable-background-color);
}
`;
const cellDraggingClassname = `rdg-cell-dragging ${cellDraggingOrOver}`;
const cellOverClassname = `rdg-cell-drag-over ${cellDraggingOrOver}`;
const dragImageClassname = css`
@layer rdg.HeaderCell {
border-radius: 4px;
width: fit-content;
outline: 2px solid hsl(207, 100%, 50%);
outline-offset: -2px;
}
`;
type SharedHeaderRowProps<R, SR> = Pick<
HeaderRowProps<R, SR, React.Key>,
| 'sortColumns'
| 'onSortColumnsChange'
| 'setPosition'
| 'onColumnResize'
| 'onColumnResizeEnd'
| 'shouldFocusGrid'
| 'direction'
| 'onColumnsReorder'
>;
export interface HeaderCellProps<R, SR> extends SharedHeaderRowProps<R, SR> {
column: CalculatedColumn<R, SR>;
colSpan: number | undefined;
rowIdx: number;
isCellActive: boolean;
draggedColumnKey: string | undefined;
setDraggedColumnKey: (draggedColumnKey: string | undefined) => void;
}
export default function HeaderCell<R, SR>({
column,
colSpan,
rowIdx,
isCellActive,
onColumnResize,
onColumnResizeEnd,
onColumnsReorder,
sortColumns,
onSortColumnsChange,
setPosition,
shouldFocusGrid,
direction,
draggedColumnKey,
setDraggedColumnKey
}: HeaderCellProps<R, SR>) {
const [isOver, setIsOver] = useState(false);
const resizingRef = useRef<boolean>(false);
const dragImageRef = useRef<HTMLDivElement>(null);
const isDragging = draggedColumnKey === column.key;
const rowSpan = getHeaderCellRowSpan(column, rowIdx);
// set the tabIndex to 0 when there is no active cell so grid can receive focus
const { tabIndex, childTabIndex, onFocus } = useRovingTabIndex(shouldFocusGrid || isCellActive);
const sortIndex = sortColumns?.findIndex((sort) => sort.columnKey === column.key);
const sortColumn =
sortIndex !== undefined && sortIndex > -1 ? sortColumns![sortIndex] : undefined;
const sortDirection = sortColumn?.direction;
const priority = sortColumn !== undefined && sortColumns!.length > 1 ? sortIndex! + 1 : undefined;
const ariaSort =
sortDirection && !priority ? (sortDirection === 'ASC' ? 'ascending' : 'descending') : undefined;
const { sortable, resizable, draggable } = column;
const className = getCellClassname(
column,
column.headerCellClass,
sortable && cellSortableClassname,
resizable && cellResizableClassname,
draggable && cellDraggableClassname,
isDragging && cellDraggingClassname,
isOver && cellOverClassname
);
function onSort(ctrlClick: boolean) {
if (onSortColumnsChange == null) return;
const { sortDescendingFirst } = column;
if (sortColumn === undefined) {
// not currently sorted
const nextSort: SortColumn = {
columnKey: column.key,
direction: sortDescendingFirst ? 'DESC' : 'ASC'
};
onSortColumnsChange(sortColumns && ctrlClick ? [...sortColumns, nextSort] : [nextSort]);
} else {
let nextSortColumn: SortColumn | undefined;
if (
(sortDescendingFirst === true && sortDirection === 'DESC') ||
(sortDescendingFirst !== true && sortDirection === 'ASC')
) {
nextSortColumn = {
columnKey: column.key,
direction: sortDirection === 'ASC' ? 'DESC' : 'ASC'
};
}
if (ctrlClick) {
const nextSortColumns = [...sortColumns!];
if (nextSortColumn) {
// swap direction
nextSortColumns[sortIndex!] = nextSortColumn;
} else {
// remove sort
nextSortColumns.splice(sortIndex!, 1);
}
onSortColumnsChange(nextSortColumns);
} else {
onSortColumnsChange(nextSortColumn ? [nextSortColumn] : []);
}
}
}
function handleFocus(event: React.FocusEvent<HTMLDivElement>) {
onFocus?.(event);
if (shouldFocusGrid) {
// Select the first header cell if there is no active cell
setPosition({ idx: 0, rowIdx });
}
}
function onMouseDown() {
setPosition({ idx: column.idx, rowIdx });
}
function onClick(event: React.MouseEvent<HTMLSpanElement>) {
if (sortable) {
onSort(event.ctrlKey || event.metaKey);
}
}
function onKeyDown(event: React.KeyboardEvent<HTMLSpanElement>) {
const { key } = event;
if (sortable && (key === ' ' || key === 'Enter')) {
// prevent scrolling
event.preventDefault();
onSort(event.ctrlKey || event.metaKey);
} else if (
resizable &&
isCtrlKeyHeldDown(event) &&
(key === 'ArrowLeft' || key === 'ArrowRight')
) {
// prevent navigation
// TODO: check if we can use `preventDefault` instead
event.stopPropagation();
resizingRef.current = true;
const { width } = event.currentTarget.getBoundingClientRect();
const { leftKey } = getLeftRightKey(direction);
const offset = key === leftKey ? -10 : 10;
const newWidth = clampColumnWidth(width + offset, column);
if (newWidth !== width) {
onColumnResize(column, newWidth);
}
}
}
function onKeyUp() {
if (resizingRef.current) {
resizingRef.current = false;
onColumnResizeEnd();
}
}
function onDragStart(event: React.DragEvent<HTMLDivElement>) {
// need flushSync to make sure the drag image is rendered before the drag starts
flushSync(() => {
setDraggedColumnKey(column.key);
});
event.dataTransfer.setDragImage(dragImageRef.current!, 0, 0);
event.dataTransfer.dropEffect = 'move';
}
function onDragEnd() {
setDraggedColumnKey(undefined);
}
function onDragOver(event: React.DragEvent<HTMLDivElement>) {
// prevent default to allow drop
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
}
function onDrop(event: React.DragEvent<HTMLDivElement>) {
setIsOver(false);
// prevent the browser from redirecting in some cases
event.preventDefault();
onColumnsReorder?.(draggedColumnKey!, column.key);
}
function onDragEnter(event: React.DragEvent<HTMLDivElement>) {
if (isEventPertinent(event)) {
setIsOver(true);
}
}
function onDragLeave(event: React.DragEvent<HTMLDivElement>) {
if (isEventPertinent(event)) {
setIsOver(false);
}
}
let dragTargetProps: React.ComponentProps<'div'> | undefined;
let dropTargetProps: React.ComponentProps<'div'> | undefined;
if (draggable) {
dragTargetProps = {
draggable: true,
onDragStart,
onDragEnd
};
if (draggedColumnKey !== undefined && draggedColumnKey !== column.key) {
dropTargetProps = {
onDragOver,
onDragEnter,
onDragLeave,
onDrop
};
}
}
const style: React.CSSProperties = {
...getHeaderCellStyle(column, rowIdx, rowSpan),
...getCellStyle(column, colSpan)
};
const content = column.renderHeaderCell({
column,
sortDirection,
priority,
tabIndex: childTabIndex
});
return (
<>
{isDragging && (
<div
ref={dragImageRef}
style={style}
className={getCellClassname(column, column.headerCellClass, dragImageClassname)}
>
{content}
</div>
)}
<div
role="columnheader"
aria-colindex={column.idx + 1}
aria-colspan={colSpan}
aria-rowspan={rowSpan}
aria-selected={isCellActive}
aria-sort={ariaSort}
tabIndex={tabIndex}
className={className}
style={style}
onMouseDown={onMouseDown}
onFocus={handleFocus}
onClick={onClick}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
{...dragTargetProps}
{...dropTargetProps}
>
{content}
{resizable && (
<ResizeHandle
direction={direction}
column={column}
onColumnResize={onColumnResize}
onColumnResizeEnd={onColumnResizeEnd}
/>
)}
</div>
</>
);
}
type ResizeHandleProps<R, SR> = Pick<
HeaderCellProps<R, SR>,
'direction' | 'column' | 'onColumnResize' | 'onColumnResizeEnd'
>;
function ResizeHandle<R, SR>({
direction,
column,
onColumnResize,
onColumnResizeEnd
}: ResizeHandleProps<R, SR>) {
const resizingRef = useRef<boolean>(false);
const resizingOffsetRef = useRef<number>(undefined);
const isRtl = direction === 'rtl';
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
if (event.pointerType === 'mouse' && event.button !== 0) {
return;
}
// Fix column resizing on a draggable column in FF
event.preventDefault();
const { currentTarget, pointerId } = event;
currentTarget.setPointerCapture(pointerId);
const headerCell = currentTarget.parentElement!;
const { right, left } = headerCell.getBoundingClientRect();
resizingOffsetRef.current = isRtl ? event.clientX - left : right - event.clientX;
}
function onPointerMove(event: React.PointerEvent<HTMLDivElement>) {
const offset = resizingOffsetRef.current;
if (offset === undefined) return;
resizingRef.current = true;
const { width, right, left } = event.currentTarget.parentElement!.getBoundingClientRect();
let newWidth = isRtl ? right + offset - event.clientX : event.clientX + offset - left;
newWidth = clampColumnWidth(newWidth, column);
if (width > 0 && newWidth !== width) {
onColumnResize(column, newWidth);
}
}
function onLostPointerCapture() {
// avoid calling onColumnResizeEnd if the pointer has not moved after pointed down,
// also to avoid conflicts with double-clicking
if (resizingRef.current) {
resizingRef.current = false;
onColumnResizeEnd();
}
resizingOffsetRef.current = undefined;
}
function onDoubleClick() {
onColumnResize(column, 'max-content');
}
return (
<div
aria-hidden
className={resizeHandleClassname}
onClick={stopPropagation}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
// we are not using pointerup because it does not fire in some cases
// pointer down -> alt+tab -> pointer up over another window -> pointerup event not fired
onLostPointerCapture={onLostPointerCapture}
onDoubleClick={onDoubleClick}
/>
);
}
// only accept pertinent drag events:
// - ignore drag events going from the container to an element inside the container
// - ignore drag events going from an element inside the container to the container
function isEventPertinent(event: React.DragEvent) {
const relatedTarget = event.relatedTarget as HTMLElement | null;
return !event.currentTarget.contains(relatedTarget);
}