-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrenderers.tsx
More file actions
490 lines (442 loc) · 18.9 KB
/
renderers.tsx
File metadata and controls
490 lines (442 loc) · 18.9 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
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
/*
* Copyright (c) 2019 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import classNames from 'classnames';
import React, {
ChangeEvent,
CSSProperties,
Dispatch,
FC,
memo,
SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { Filter } from '@labkey/api';
import { createPortal } from 'react-dom';
import { QueryColumn } from '../public/QueryColumn';
import { useEnterEscape } from '../public/useEnterEscape';
import { QueryModel } from '../public/QueryModel/QueryModel';
import { HelpTipRenderer } from './components/forms/HelpTipRenderer';
import { APP_FIELD_CANNOT_BE_REMOVED_MESSAGE, GRID_CHECKBOX_OPTIONS, GRID_HEADER_CELL_BODY } from './constants';
import { GridColumn } from './components/base/models/GridColumn';
import { LabelHelpTip } from './components/base/LabelHelpTip';
import { DisableableMenuItem } from './components/samples/DisableableMenuItem';
import { usePortalRef } from './hooks';
import { MenuDivider, MenuItem } from './dropdowns';
import { LabelOverlay } from './components/forms/LabelOverlay';
import { DOMAIN_FIELD } from './components/forms/DomainFieldHelpTipContents';
import { SORT_ASC, SORT_DESC } from '../public/QuerySort';
export function isFilterColumnNameMatch(filter: Filter.IFilter, col: QueryColumn): boolean {
return filter.getColumnName() === col.name || filter.getColumnName() === col.resolveFieldKey();
}
interface EditableColumnTitleProps {
column: QueryColumn;
editing?: boolean;
hideToolTip?: boolean;
onCancel: () => void;
onChange: (newValue: string) => void;
}
// exported for jest tests
export const EditableColumnTitle: FC<EditableColumnTitleProps> = memo(props => {
const { column, editing, hideToolTip, onChange, onCancel } = props;
const initialTitle = useMemo(() => {
return column.caption ?? column.name;
}, [column.caption, column.name]);
const [title, setTitle] = useState<string>(initialTitle);
const showLabelOverlay: boolean = useMemo(() => {
return !hideToolTip && column.hasHelpTipData;
}, [column, hideToolTip]);
const titleInput: React.RefObject<HTMLInputElement> = React.createRef();
useEffect(() => {
setTitle(initialTitle);
}, [initialTitle]);
const onTitleChange = useCallback((evt: ChangeEvent<HTMLInputElement>) => {
setTitle(evt.target.value);
}, []);
const onCancelEdit = useCallback(() => {
onCancel();
setTitle(initialTitle);
}, [initialTitle, onCancel]);
const onEditFinish = useCallback(() => {
const trimmedTitle = title?.trim();
if (trimmedTitle && trimmedTitle !== initialTitle) {
onChange(trimmedTitle);
return;
}
setTitle(initialTitle);
onCancel();
}, [initialTitle, onCancel, onChange, title]);
const onKeyDown = useEnterEscape(onEditFinish, onCancelEdit);
if (initialTitle === ' ') {
return <></>;
}
if (editing) {
return (
<input
autoFocus
defaultValue={title}
onBlur={onEditFinish}
onChange={onTitleChange}
onKeyDown={onKeyDown}
ref={titleInput}
/>
);
}
return (
<>
{!showLabelOverlay && initialTitle}
{showLabelOverlay && <LabelOverlay column={column} />}
</>
);
});
EditableColumnTitle.displayName = 'EditableColumnTitle';
interface SharedHeaderCellProps {
handleAddColumn?: (column: QueryColumn) => void;
handleFilter?: (column: QueryColumn, remove?: boolean) => void;
handleHideColumn?: (column: QueryColumn) => void;
handleSort?: (column: QueryColumn, dir?: string) => void;
model?: QueryModel;
}
interface HeaderCellDropdownMenuProps extends SharedHeaderCellProps {
allowColFilter: boolean;
allowColSort: boolean;
colFilters: Filter.IFilter[];
isSortAsc: boolean;
isSortDesc: boolean;
onEditTitleClicked?: () => void;
open: boolean;
queryColumn: QueryColumn;
setOpen: Dispatch<SetStateAction<boolean>>;
}
const HeaderCellDropdownMenu: FC<HeaderCellDropdownMenuProps> = memo(props => {
const {
allowColFilter,
allowColSort,
colFilters,
handleAddColumn,
handleFilter,
handleHideColumn,
handleSort,
isSortAsc,
isSortDesc,
model,
onEditTitleClicked,
open,
queryColumn,
setOpen,
} = props;
const showGridCustomization = handleHideColumn || handleAddColumn;
const toggleEl = useRef<HTMLSpanElement>(undefined);
const menuEl = useRef<HTMLUListElement>(undefined);
const portalRef = usePortalRef('header-cell-dropdown-menu-portal');
// Note: We need to make sure we cancel all events in our menu handlers or we also trigger the click handler in
// HeaderCellDropdown, which will reset the open value to true, which will keep the menu open.
const openFilterPanel = useCallback(() => {
handleFilter(queryColumn, false);
}, [handleFilter, queryColumn]);
const removeFilter = useCallback(() => {
handleFilter(queryColumn, true);
}, [queryColumn, handleFilter]);
const sort = useCallback(
(dir?: string) => {
handleSort(queryColumn, dir);
},
[queryColumn, handleSort]
);
// There is something wrong with the React Bootstrap types, the only way to get these callbacks properly typed is to
// use "as SelectCallback", even though their type signature matches perfectly.
const sortAsc = useCallback((): void => sort('+'), [sort]);
const sortDesc = useCallback((): void => sort('-'), [sort]);
const clearSort = useCallback((): void => sort(), [sort]);
const hideColumn = useCallback((): void => {
handleHideColumn(queryColumn);
}, [queryColumn, handleHideColumn]);
const addColumn = useCallback((): void => {
handleAddColumn(queryColumn);
}, [queryColumn, handleAddColumn]);
const editColumnTitle = useCallback((): void => {
onEditTitleClicked();
}, [onEditTitleClicked]);
const [menuStyle, setMenuStyle] = useState<CSSProperties>({});
const updateMenuStyle = useCallback(() => {
let top;
let left;
if (toggleEl.current && menuEl.current) {
// The third parentElement is the <th> element, and we want to pin the menu to the bottom of that
const headerRect = toggleEl.current.parentElement.parentElement.parentElement.getBoundingClientRect();
const menuRect = menuEl.current.getBoundingClientRect();
left = headerRect.right - menuRect.width + 'px';
top = headerRect.bottom + 'px';
// Issue 45553
// Render the dropdown menu above the header if the header is too close to the bottom of the screen.
if (headerRect.bottom + menuRect.height > window.innerHeight) {
top = headerRect.top - menuRect.height - 10 + 'px';
}
}
setMenuStyle({
left,
// use visibility so we can know the rendered size of the menu before making it visible
visibility: open ? 'visible' : 'hidden',
top,
});
}, [open]);
// In order to close the menu when the user clicks outside of it we have to add a click handler to the document and
// close the menu when the user clicks on anything outside the menu.
const documentClickHandler = useCallback(
event => {
// Don't handle the event if the target is the toggle element or the grandparent (GRID_HEADER_CELL_BODY),
// because we call setOpen in those handlers, and we don't want to negate what they set the value to.
const isToggle = event.target === toggleEl.current;
const insideToggle = toggleEl.current?.contains(event.target);
if (isToggle || insideToggle) return;
const grandParent = toggleEl.current?.parentElement?.parentElement;
const isGrandParent = event.target === grandParent;
const insideGrandParent = grandParent?.contains(event.target);
if (isGrandParent || insideGrandParent) return;
setOpen(false);
},
[setOpen]
);
useEffect(() => {
if (open) {
document.addEventListener('click', documentClickHandler);
}
return () => {
document.removeEventListener('click', documentClickHandler);
};
}, [documentClickHandler, open]);
// TODO: investigate passing down a ref of the .table-responsive div so we can add a scroll handler to it here the
// same way we add one to the document, then we can update the menu positions when the table is also scrolled.
useEffect(() => {
updateMenuStyle();
window.addEventListener('scroll', updateMenuStyle);
return () => {
window.removeEventListener('scroll', updateMenuStyle);
};
}, [updateMenuStyle, open]);
// Technically we don't need to add and remove this open class because it doesn't affect visibility, we do that
// above via the visibility css property. We need this class so tests can look for the currently open menu.
const className = classNames('grid-header-cell__dropdown-menu dropdown-menu', { open });
const body = (
<ul className={className} ref={menuEl} style={menuStyle}>
{allowColFilter && (
<>
<MenuItem onClick={openFilterPanel}>
<span className="fa fa-filter grid-panel__menu-icon" />
Filter...
</MenuItem>
<MenuItem disabled={!colFilters || colFilters?.length === 0} onClick={removeFilter}>
<span className="grid-panel__menu-icon-spacer" />
Remove filter{colFilters?.length > 1 ? 's' : ''}
</MenuItem>
{allowColSort && <MenuDivider />}
</>
)}
{allowColSort && (
<>
<MenuItem disabled={isSortAsc} onClick={sortAsc}>
<span className="fa fa-sort-amount-asc grid-panel__menu-icon" />
Sort ascending
</MenuItem>
<MenuItem disabled={isSortDesc} onClick={sortDesc}>
<span className="fa fa-sort-amount-desc grid-panel__menu-icon" />
Sort descending
</MenuItem>
{/* Clear sort only applies for the grids that are backed by QueryModel */}
{model && (
<MenuItem disabled={!isSortDesc && !isSortAsc} onClick={clearSort}>
<span className="grid-panel__menu-icon-spacer" />
Clear sort
</MenuItem>
)}
</>
)}
{showGridCustomization && (
<>
{(allowColSort || allowColFilter) && <MenuDivider />}
<MenuItem onClick={editColumnTitle}>
<span className="fa fa-pencil grid-panel__menu-icon" />
Edit Label
</MenuItem>
{handleAddColumn && (
<MenuItem onClick={addColumn}>
<span className="fa fa-plus grid-panel__menu-icon" />
Insert Column
</MenuItem>
)}
<DisableableMenuItem
disabled={!(handleHideColumn && !!model)}
disabledMessage={APP_FIELD_CANNOT_BE_REMOVED_MESSAGE}
onClick={hideColumn}
>
<span className="fa fa-eye-slash grid-panel__menu-icon" />
Hide Column
</DisableableMenuItem>
</>
)}
</ul>
);
return (
<div className="grid-panel__menu-toggle">
{/* Note: we don't need a click handler on this icon because there is one on the wrapping div above */}
<span className="fa fa-chevron-circle-down" ref={toggleEl} />
{createPortal(body, portalRef)}
</div>
);
});
HeaderCellDropdownMenu.displayName = 'HeaderCellDropdownMenu';
interface HeaderCellDropdownProps extends SharedHeaderCellProps {
column: GridColumn;
columnCount?: number;
i: number;
onColumnTitleChange?: (column: QueryColumn) => void;
onColumnTitleEdit?: (column: QueryColumn) => void;
selectable?: boolean;
}
// exported for jest testing
export const HeaderCellDropdown: FC<HeaderCellDropdownProps> = memo(props => {
const {
column,
handleSort,
handleFilter,
handleAddColumn,
handleHideColumn,
model,
onColumnTitleChange,
onColumnTitleEdit,
} = props;
const queryColumn: QueryColumn = column.raw;
const [editingTitle, setEditingTitle] = useState<boolean>(false);
const [open, setOpen] = useState<boolean>(false);
const click = useCallback(() => setOpen(isOpen => !isOpen), []);
const allowColSort = handleSort && queryColumn?.sortable;
const allowColFilter = handleFilter && queryColumn?.filterable;
const allowColumnViewChange = (handleHideColumn || handleAddColumn) && !!model;
const includeDropdown = allowColSort || allowColFilter || allowColumnViewChange;
const onColumnTitleUpdate = useCallback(
(newTitle: string) => {
setEditingTitle(false);
onColumnTitleChange(queryColumn.mutate({ caption: newTitle }));
onColumnTitleEdit?.(queryColumn);
},
[onColumnTitleChange, queryColumn, onColumnTitleEdit]
);
const editTitle = useCallback(() => {
setOpen(false);
onColumnTitleEdit?.(queryColumn);
setEditingTitle(true);
}, [onColumnTitleEdit, queryColumn]);
const cancelEditTitle = useCallback(() => {
setEditingTitle(false);
onColumnTitleEdit?.(queryColumn);
}, [onColumnTitleEdit, queryColumn]);
const view = useMemo(() => model?.queryInfo?.getView(model?.viewName, true), [model?.queryInfo, model?.viewName]);
if (!queryColumn) return null;
// using filterArray to indicate user-defined filters only and concatenating with any view filters
let colFilters = model?.filterArray.filter(filter => isFilterColumnNameMatch(filter, queryColumn));
const viewColFilters = view?.filters.filter(filter => isFilterColumnNameMatch(filter, queryColumn));
if (viewColFilters?.length) colFilters = colFilters.concat(viewColFilters);
// first check the model users (user-defined) and then fall back to the view sorts
const colQuerySortDir =
model?.sorts?.find(sort => sort.fieldKey === queryColumn.resolveFieldKey())?.dir ??
view?.sorts?.find(sort => sort.fieldKey === queryColumn.resolveFieldKey())?.dir;
const sortDir = queryColumn.sorts || colQuerySortDir;
const isSortAsc = sortDir === SORT_ASC;
const isSortDesc = sortDir === SORT_DESC;
return (
<div className={GRID_HEADER_CELL_BODY} onClick={click}>
<div className="grid-header-cell__title-wrapper">
<EditableColumnTitle
column={queryColumn}
editing={editingTitle}
hideToolTip={!!column.helpTipRenderer}
onCancel={cancelEditTitle}
onChange={onColumnTitleUpdate}
/>
{!editingTitle && colFilters?.length > 0 && (
<span
className="fa fa-filter grid-panel__col-header-icon"
title={colFilters?.length + ' filter' + (colFilters?.length > 1 ? 's' : '') + ' applied'}
/>
)}
{!editingTitle && isSortAsc && (
<span className="fa fa-sort-amount-asc grid-panel__col-header-icon" title="Sorted ascending" />
)}
{!editingTitle && isSortDesc && (
<span className="fa fa-sort-amount-desc grid-panel__col-header-icon" title="Sorted descending" />
)}
{!editingTitle && column.helpTipRenderer && (
<LabelHelpTip
placement="bottom"
popoverClassName={column.helpTipRenderer === DOMAIN_FIELD ? undefined : 'label-help-arrow-left'}
title={column.title}
>
<HelpTipRenderer column={queryColumn} type={column.helpTipRenderer} />
</LabelHelpTip>
)}
</div>
{includeDropdown && !editingTitle && (
<HeaderCellDropdownMenu
allowColFilter={allowColFilter}
allowColSort={allowColSort}
colFilters={colFilters}
handleAddColumn={handleAddColumn}
handleFilter={handleFilter}
handleHideColumn={handleHideColumn}
handleSort={handleSort}
isSortAsc={isSortAsc}
isSortDesc={isSortDesc}
model={model}
onEditTitleClicked={editTitle}
open={open}
queryColumn={queryColumn}
setOpen={setOpen}
/>
)}
</div>
);
});
HeaderCellDropdown.displayName = 'HeaderCellDropdown';
interface HeaderSelectionCellProps {
className?: string;
disabled: boolean;
handleSelection: React.ChangeEventHandler<HTMLInputElement>;
selectedState: GRID_CHECKBOX_OPTIONS;
}
export const HeaderSelectionCell: FC<HeaderSelectionCellProps> = memo(props => {
const { className, disabled, handleSelection, selectedState } = props;
const isIndeterminate = selectedState === GRID_CHECKBOX_OPTIONS.SOME;
const checkboxRef = useRef<HTMLInputElement>(undefined);
useEffect(() => {
if (checkboxRef.current) {
checkboxRef.current.indeterminate = isIndeterminate;
}
}, [isIndeterminate]);
return (
<input
checked={selectedState === GRID_CHECKBOX_OPTIONS.ALL}
className={className}
disabled={disabled}
onChange={handleSelection}
ref={checkboxRef}
type="checkbox"
/>
);
});
HeaderSelectionCell.displayName = 'HeaderSelectionCell';