-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathHeaderCell.tsx
More file actions
350 lines (308 loc) · 9.76 KB
/
HeaderCell.tsx
File metadata and controls
350 lines (308 loc) · 9.76 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
import { memo, 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, Direction, Position, ResizedWidth, SortDirection } from './types';
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;
}
`;
export interface HeaderCellProps<R, SR> {
column: CalculatedColumn<R, SR>;
colSpan: number | undefined;
rowIdx: number;
isCellActive: boolean;
sortDirection: SortDirection | undefined;
priority: number | undefined;
onSort: (column: CalculatedColumn<R, SR>, ctrlClick: boolean) => void;
onColumnResize: (column: CalculatedColumn<R, SR>, width: ResizedWidth) => void;
onColumnResizeEnd: () => void;
onColumnsReorder: ((sourceColumnKey: string, targetColumnKey: string) => void) | undefined | null;
setPosition: (position: Position) => void;
shouldFocusGrid: boolean;
direction: Direction;
draggedColumnKey: string | undefined;
setDraggedColumnKey: (draggedColumnKey: string | undefined) => void;
}
function HeaderCell<R, SR>({
column,
colSpan,
rowIdx,
isCellActive,
sortDirection,
priority,
onSort,
onColumnResize,
onColumnResizeEnd,
onColumnsReorder,
setPosition,
shouldFocusGrid,
direction,
draggedColumnKey,
setDraggedColumnKey
}: HeaderCellProps<R, SR>) {
const [isOver, setIsOver] = useState(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 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 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(column, event.ctrlKey || event.metaKey);
}
}
function onKeyDown(event: React.KeyboardEvent<HTMLSpanElement>) {
const { key } = event;
if (sortable && (key === ' ' || key === 'Enter')) {
// prevent scrolling
event.preventDefault();
onSort(column, 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();
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 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}
{...dragTargetProps}
{...dropTargetProps}
>
{content}
{resizable && (
<ResizeHandle
direction={direction}
column={column}
onColumnResize={onColumnResize}
onColumnResizeEnd={onColumnResizeEnd}
/>
)}
</div>
</>
);
}
export default memo(HeaderCell) as <R, SR>(props: HeaderCellProps<R, SR>) => React.JSX.Element;
interface ResizeHandleProps<R, SR> {
direction: Direction;
column: CalculatedColumn<R, SR>;
onColumnResize: (column: CalculatedColumn<R, SR>, width: ResizedWidth) => void;
onColumnResizeEnd: () => void;
}
function ResizeHandle<R, SR>({
direction,
column,
onColumnResize,
onColumnResizeEnd
}: ResizeHandleProps<R, SR>) {
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;
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() {
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);
}