forked from patternfly/react-data-view
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataViewTh.tsx
More file actions
350 lines (300 loc) · 10.8 KB
/
DataViewTh.tsx
File metadata and controls
350 lines (300 loc) · 10.8 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 {
FC,
useState,
MouseEvent as ReactMouseEvent,
TouchEvent as ReactTouchEvent,
KeyboardEvent as ReactKeyboardEvent,
ReactNode,
useCallback,
useRef,
useEffect,
Fragment
} from 'react';
import { Th, ThProps } from '@patternfly/react-table';
import { Button, getLanguageDirection } from '@patternfly/react-core';
import { createUseStyles } from 'react-jss';
import tableCellPaddingBlockEnd from '@patternfly/react-tokens/dist/esm/c_table_cell_PaddingBlockEnd';
import tableCellPaddingInlineEnd from '@patternfly/react-tokens/dist/esm/c_table_cell_PaddingInlineEnd';
import globalFontSizeBodyDefault from '@patternfly/react-tokens/dist/esm/t_global_font_size_body_default';
const ResizeIcon = () => (
<svg
className="pf-v6-svg"
viewBox="0 0 1024 1024"
fill="currentColor"
aria-hidden="true"
role="img"
width="1em"
height="1em"
>
<path
fillRule="evenodd"
d="M52.7,529.8l190.5,161.9c18.6,15.9,50.5,4.7,50.5-17.8v-324c0-22.4-31.8-33.6-50.5-17.8L52.7,494.2c-11.5,9.8-11.5,25.8,0,35.6ZM480.8,12.9h62.4v998.3h-62.4V12.9ZM971.3,529.8l-190.5,161.9c-18.6,15.9-50.5,4.7-50.5-17.8v-324c0-22.4,31.8-33.6,50.5-17.8l190.5,161.9c11.5,9.8,11.5,25.8,0,35.6Z"
/>
</svg>
);
const useStyles = createUseStyles({
dataViewResizeableTh: {
[tableCellPaddingInlineEnd.name]: `calc(${globalFontSizeBodyDefault.var} * 2)`
},
dataViewResizableButton: {
position: 'absolute',
insetInlineEnd: `calc(${globalFontSizeBodyDefault.var} / 2)`,
insetBlockEnd: tableCellPaddingBlockEnd.var,
cursor: 'grab',
'&:active': {
cursor: 'grabbing'
}
}
});
export interface DataViewThResizableProps {
/** Whether the column is resizable */
isResizable?: boolean;
/** Callback after the column is resized. Returns the triggering event, the column id passed in via cell props, and the new width of the column. */
onResize?: (
event: ReactMouseEvent | MouseEvent | ReactKeyboardEvent | KeyboardEvent | TouchEvent,
id: string | number | undefined,
width: number
) => void;
/** Starting width in pixels of the column */
width?: number;
/** Minimum resize width in pixels of the column */
minWidth?: number;
/** Increment in pixels for keyboard navigation */
increment?: number;
/** Increment in pixels for keyboard navigation while shift is held */
shiftIncrement?: number;
/** Provides an accessible name for the resizable column via a human readable string. */
resizeButtonAriaLabel?: string;
/** Screenreader text that gets announced when the column is resized. */
screenReaderText?: string;
}
export interface DataViewThProps {
/** Cell content */
content: ReactNode;
/** Resizable props */
resizableProps?: DataViewThResizableProps;
/** @hide Indicates whether the table has resizable columns */
hasResizableColumns?: boolean;
/** Props passed to Th */
thProps?: ThProps;
}
export const DataViewTh: FC<DataViewThProps> = ({
content,
resizableProps = {},
hasResizableColumns = false,
thProps,
...props
}: DataViewThProps) => {
const thRef = useRef<HTMLTableCellElement>(null);
const [width, setWidth] = useState(resizableProps?.width ? resizableProps.width : 0);
// Tracks the current column width for the onResize callback, because the width state is not updated until after the resize is complete
const trackedWidth = useRef(0);
const classes = useStyles();
const isResizable = resizableProps?.isResizable || false;
const increment = resizableProps?.increment || 5;
const shiftIncrement = resizableProps?.shiftIncrement || 25;
const resizeButtonAriaLabel = resizableProps?.resizeButtonAriaLabel;
const onResize = resizableProps?.onResize || undefined;
const screenReaderText = resizableProps?.screenReaderText || `Column ${width.toFixed(0)} pixels`;
const dataViewThClassName = isResizable ? classes.dataViewResizeableTh : undefined;
const resizeButtonRef = useRef<HTMLButtonElement>(null);
const setInitialVals = useRef(true);
const dragOffset = useRef(0);
const isResizing = useRef(false);
const isInView = useRef(true);
if (isResizable && !resizeButtonAriaLabel) {
// eslint-disable-next-line no-console
console.warn(
'DataViewTh: Missing resizeButtonAriaLabel. An aria label must be passed to each resizable column to provide a context specific label for its resize button.'
);
}
useEffect(() => {
if (!isResizable) {
return;
}
const observed = resizeButtonRef.current;
const observer = new IntersectionObserver(
([entry]) => {
isInView.current = entry.isIntersecting;
},
{ threshold: 0.3 }
);
if (observed) {
observer.observe(observed);
}
return () => {
if (observed) {
observer.unobserve(observed);
}
};
}, []);
useEffect(() => {
if ((isResizable || hasResizableColumns) && setInitialVals.current && width === 0) {
setWidth(thRef.current?.getBoundingClientRect().width || 0);
setInitialVals.current = false;
}
}, [isResizable, hasResizableColumns, setInitialVals]);
const setDragOffset = (e: ReactMouseEvent | ReactTouchEvent) => {
const isRTL = getLanguageDirection(thRef.current as HTMLElement) === 'rtl';
const startingMousePos = 'clientX' in e ? e.clientX : e.touches[0].clientX;
const startingColumnPos =
(isRTL ? thRef.current?.getBoundingClientRect().left : thRef.current?.getBoundingClientRect().right) || 0;
dragOffset.current = startingColumnPos - startingMousePos;
};
const handleMousedown = (e: ReactMouseEvent) => {
e.stopPropagation();
e.preventDefault();
document.addEventListener('mousemove', callbackMouseMove);
document.addEventListener('mouseup', callbackMouseUp);
// When a user begins resizing a column, set the drag offset so the drag motion aligns with the column edge
if (dragOffset.current === 0) {
setDragOffset(e);
}
isResizing.current = true;
};
const handleMouseMove = (e: MouseEvent) => {
const mousePos = e.clientX;
handleControlMove(e, dragOffset.current + mousePos);
};
const handleTouchStart = (e: ReactTouchEvent) => {
e.stopPropagation();
document.addEventListener('touchmove', callbackTouchMove, { passive: false });
document.addEventListener('touchend', callbackTouchEnd);
// When a user begins resizing a column, set the drag offset so the drag motion aligns with the column edge
if (dragOffset.current === 0) {
setDragOffset(e);
}
isResizing.current = true;
};
const handleTouchMove = (e: TouchEvent) => {
e.preventDefault();
e.stopImmediatePropagation();
const touchPos = e.touches[0].clientX;
handleControlMove(e, touchPos);
};
const handleControlMove = (e: MouseEvent | TouchEvent, controlPosition: number) => {
e.stopPropagation();
if (!isResizing.current) {
return;
}
const columnRect = thRef.current?.getBoundingClientRect();
if (columnRect === undefined) {
return;
}
const mousePos = controlPosition;
const isRTL = getLanguageDirection(thRef.current as HTMLElement) === 'rtl';
let newSize = isRTL ? columnRect?.right - mousePos : mousePos - columnRect?.left;
// Prevent the column from shrinking below a specified minimum width
if (resizableProps.minWidth && newSize < resizableProps.minWidth) {
newSize = resizableProps.minWidth;
}
thRef.current?.style.setProperty('min-width', newSize + 'px');
trackedWidth.current = newSize;
setWidth(newSize);
};
const handleMouseup = (e: MouseEvent) => {
if (!isResizing.current) {
return;
}
// Reset the isResizing and dragOffset values to their initial states
isResizing.current = false;
dragOffset.current = 0;
// Call the onResize callback with the new width
onResize && onResize(e, thProps?.id, trackedWidth.current);
// Handle scroll into view when column drag button is moved off screen
if (resizeButtonRef.current && !isInView.current) {
resizeButtonRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
document.removeEventListener('mousemove', callbackMouseMove);
document.removeEventListener('mouseup', callbackMouseUp);
};
const handleTouchEnd = (e: TouchEvent) => {
e.stopPropagation();
if (!isResizing) {
return;
}
// Reset the isResizing and dragOffset values to their initial states
isResizing.current = false;
dragOffset.current = 0;
// Call the onResize callback with the new width
onResize && onResize(e, thProps?.id, trackedWidth.current);
document.removeEventListener('touchmove', callbackTouchMove);
document.removeEventListener('touchend', callbackTouchEnd);
};
const callbackMouseMove = useCallback(handleMouseMove, []);
const callbackTouchEnd = useCallback(handleTouchEnd, []);
const callbackTouchMove = useCallback(handleTouchMove, []);
const callbackMouseUp = useCallback(handleMouseup, []);
const handleKeys = (e: ReactKeyboardEvent) => {
const key = e.key;
if (key === 'Tab') {
isResizing.current = false;
}
if (key !== 'ArrowLeft' && key !== 'ArrowRight') {
return;
}
e.preventDefault();
isResizing.current = true;
const isRTL = getLanguageDirection(thRef.current as HTMLElement) === 'rtl';
const columnRect = thRef.current?.getBoundingClientRect();
let newSize = columnRect?.width || 0;
let delta = 0;
const _increment = e.shiftKey ? shiftIncrement : increment;
if (key === 'ArrowRight') {
if (isRTL) {
delta = -_increment;
} else {
delta = _increment;
}
} else if (key === 'ArrowLeft') {
if (isRTL) {
delta = _increment;
} else {
delta = -_increment;
}
}
newSize = newSize + delta;
thRef.current?.style.setProperty('min-width', newSize + 'px');
setWidth(newSize);
onResize && onResize(e, thProps?.id, newSize);
};
const resizableContent = (
<Fragment>
<div aria-live="polite" className="pf-v6-screen-reader">
{screenReaderText}
</div>
<Button
ref={resizeButtonRef}
variant="plain"
hasNoPadding
icon={<ResizeIcon />}
onMouseDown={handleMousedown}
onKeyDown={handleKeys}
onTouchStart={handleTouchStart}
aria-label={resizeButtonAriaLabel}
className={classes.dataViewResizableButton}
/>
</Fragment>
);
const classNames: string[] = [];
if (thProps?.className) {
classNames.push(thProps.className);
}
if (dataViewThClassName) {
classNames.push(dataViewThClassName);
}
return (
<Th
modifier="truncate"
{...thProps}
{...props}
ref={thRef}
style={width > 0 ? { ...thProps?.style, minWidth: width } : thProps?.style}
className={classNames.length > 0 ? classNames.join(' ') : undefined}
{...(isResizable && { additionalContent: resizableContent })}
>
{content}
</Th>
);
};
export default DataViewTh;