-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathHeaderCell.tsx
310 lines (274 loc) · 9.25 KB
/
HeaderCell.tsx
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
import { useState } from 'react';
import { css } from '@linaria/core';
import { useRovingTabIndex } from './hooks';
import {
getCellClassname,
getCellStyle,
getHeaderCellRowSpan,
getHeaderCellStyle,
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}`;
export const resizeHandleClassname = 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 cellDraggableClassname = 'rdg-cell-draggable';
const cellDragging = css`
opacity: 0.5;
`;
const cellDraggingClassname = `rdg-cell-dragging ${cellDragging}`;
const cellOver = css`
background-color: var(--rdg-header-draggable-background-color);
`;
const cellOverClassname = `rdg-cell-drag-over ${cellOver}`;
type SharedHeaderRowProps<R, SR> = Pick<
HeaderRowProps<R, SR, React.Key>,
| 'sortColumns'
| 'onSortColumnsChange'
| 'selectCell'
| 'onColumnResize'
| 'shouldFocusGrid'
| 'direction'
| 'onColumnsReorder'
>;
export interface HeaderCellProps<R, SR> extends SharedHeaderRowProps<R, SR> {
column: CalculatedColumn<R, SR>;
colSpan: number | undefined;
rowIdx: number;
isCellSelected: boolean;
dragDropKey: string;
}
export default function HeaderCell<R, SR>({
column,
colSpan,
rowIdx,
isCellSelected,
onColumnResize,
onColumnsReorder,
sortColumns,
onSortColumnsChange,
selectCell,
shouldFocusGrid,
direction,
dragDropKey
}: HeaderCellProps<R, SR>) {
const [isDragging, setIsDragging] = useState(false);
const [isOver, setIsOver] = useState(false);
const isRtl = direction === 'rtl';
const rowSpan = getHeaderCellRowSpan(column, rowIdx);
const { tabIndex, childTabIndex, onFocus } = useRovingTabIndex(isCellSelected);
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, {
[cellSortableClassname]: sortable,
[cellResizableClassname]: resizable,
[cellDraggableClassname]: draggable,
[cellDraggingClassname]: isDragging,
[cellOverClassname]: isOver
});
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
if (event.pointerType === 'mouse' && event.buttons !== 1) {
return;
}
// Fix column resizing on a draggable column in FF
event.preventDefault();
const { currentTarget, pointerId } = event;
const headerCell = currentTarget.parentElement!;
const { right, left } = headerCell.getBoundingClientRect();
const offset = isRtl ? event.clientX - left : right - event.clientX;
function onPointerMove(event: PointerEvent) {
const { width, right, left } = headerCell.getBoundingClientRect();
const newWidth = isRtl ? right + offset - event.clientX : event.clientX + offset - left;
if (width > 0 && newWidth !== width) {
onColumnResize(column, newWidth);
}
}
function onLostPointerCapture() {
currentTarget.removeEventListener('pointermove', onPointerMove);
currentTarget.removeEventListener('lostpointercapture', onLostPointerCapture);
}
currentTarget.setPointerCapture(pointerId);
currentTarget.addEventListener('pointermove', 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
currentTarget.addEventListener('lostpointercapture', onLostPointerCapture);
}
function onDoubleClick() {
onColumnResize(column, 'max-content');
}
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 onClick(event: React.MouseEvent<HTMLSpanElement>) {
selectCell({ idx: column.idx, rowIdx });
if (sortable) {
onSort(event.ctrlKey || event.metaKey);
}
}
function handleFocus(event: React.FocusEvent<HTMLDivElement>) {
onFocus?.(event);
if (shouldFocusGrid) {
// Select the first header cell if there is no selected cell
selectCell({ idx: 0, rowIdx });
}
}
function onKeyDown(event: React.KeyboardEvent<HTMLSpanElement>) {
if (event.key === ' ' || event.key === 'Enter') {
// prevent scrolling
event.preventDefault();
onSort(event.ctrlKey || event.metaKey);
}
}
function onDragStart(event: React.DragEvent<HTMLDivElement>) {
event.dataTransfer.setData(dragDropKey, column.key);
event.dataTransfer.dropEffect = 'move';
setIsDragging(true);
}
function onDragEnd() {
setIsDragging(false);
}
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);
// The dragDropKey is derived from the useId() hook, which can sometimes generate keys with uppercase letters.
// When setting data using event.dataTransfer.setData(), the key is automatically converted to lowercase in some browsers.
// To ensure consistent comparison, we normalize the dragDropKey to lowercase before checking its presence in the event's dataTransfer types.
// https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface
if (event.dataTransfer.types.includes(dragDropKey.toLowerCase())) {
const sourceKey = event.dataTransfer.getData(dragDropKey.toLowerCase());
if (sourceKey !== column.key) {
event.preventDefault();
onColumnsReorder?.(sourceKey, 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 draggableProps: React.ComponentProps<'div'> | undefined;
if (draggable) {
draggableProps = {
draggable: true,
/* events fired on the draggable target */
onDragStart,
onDragEnd,
/* events fired on the drop targets */
onDragOver,
onDragEnter,
onDragLeave,
onDrop
};
}
return (
<div
role="columnheader"
aria-colindex={column.idx + 1}
aria-colspan={colSpan}
aria-rowspan={rowSpan}
aria-selected={isCellSelected}
aria-sort={ariaSort}
// set the tabIndex to 0 when there is no selected cell so grid can receive focus
tabIndex={shouldFocusGrid ? 0 : tabIndex}
className={className}
style={{
...getHeaderCellStyle(column, rowIdx, rowSpan),
...getCellStyle(column, colSpan)
}}
onFocus={handleFocus}
onClick={onClick}
onKeyDown={sortable ? onKeyDown : undefined}
{...draggableProps}
>
{column.renderHeaderCell({
column,
sortDirection,
priority,
tabIndex: childTabIndex
})}
{resizable && (
<div
className={resizeHandleClassname}
onClick={stopPropagation}
onPointerDown={onPointerDown}
onDoubleClick={onDoubleClick}
/>
)}
</div>
);
}
// 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);
}