-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathuseAttributeColumnDefinitions.tsx
More file actions
274 lines (251 loc) · 8.71 KB
/
Copy pathuseAttributeColumnDefinitions.tsx
File metadata and controls
274 lines (251 loc) · 8.71 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
/*
* Copyright (C) 2020 Graylog, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*/
import * as React from 'react';
import { useCallback, useMemo, useContext, useLayoutEffect } from 'react';
import type { createColumnHelper, Row, Column, HeaderContext, CellContext } from '@tanstack/react-table';
import camelCase from 'lodash/camelCase';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { styled, css } from 'styled-components';
import type {
EntityBase,
ColumnRenderersByAttribute,
ColumnMetaContext,
} from 'components/common/EntityDataTable/types';
import type { ColumnSchema } from 'components/common/EntityDataTable';
import DragHandle from 'components/common/SortableList/DragHandle';
import DndStylesContext from 'components/common/EntityDataTable/contexts/DndStylesContext';
import useHeaderSectionObserver from 'components/common/EntityDataTable/hooks/useHeaderSectionObserver';
import ResizeHandle from 'components/common/EntityDataTable/ResizeHandle';
import HeaderActionsDropdown from 'components/common/EntityDataTable/HeaderActionsDropdown';
import Icon from 'components/common/Icon';
import ActiveSliceColContext from 'components/common/EntityDataTable/contexts/ActiveSliceColContext';
import SortIcon from '../SortIcon';
// Column drag-to-reorder and resize controls are hidden until the header is hovered or focused,
// reducing visual clutter. Uses opacity (not display) so the reserved width stays stable for
// useHeaderSectionObserver and the label doesn't shift when the control appears. Devices
// without hover (touch) keep the controls always visible, since they could not reveal them.
const HandleSlot = styled.div<{ $forceVisible?: boolean }>(
({ $forceVisible }) => css`
opacity: ${$forceVisible ? 1 : 0};
transition: opacity 150ms ease-in-out;
th:hover &,
th:focus-within & {
opacity: 1;
}
@media (hover: none) {
opacity: 1;
}
`,
);
export const ThInner = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
height: 100%;
`;
export const LeftCol = styled.div`
display: flex;
align-items: center;
height: 100%;
`;
const RightCol = styled.div`
display: flex;
align-items: center;
`;
const ActiveSliceIcon = styled(Icon)(
({ theme }) => css`
margin-left: ${theme.spacings.xs};
color: ${theme.colors.gray[20]};
`,
);
const useSortableCol = (colId: string, disabled: boolean) => {
const { setColumnTransform } = useContext(DndStylesContext);
const { attributes, isDragging, listeners, setNodeRef, transform, setActivatorNodeRef } = useSortable({
id: colId,
disabled,
});
const cssTransform = CSS.Translate.toString(transform);
useLayoutEffect(() => {
setColumnTransform((cur) => {
if (cur[colId] === cssTransform) return cur;
return { ...cur, [colId]: cssTransform };
});
}, [colId, setColumnTransform, cssTransform]);
return {
attributes,
isDragging,
listeners,
setNodeRef,
setActivatorNodeRef,
};
};
const AttributeHeader = <Entity extends EntityBase>({
ctx,
onHeaderSectionResize,
onChangeSlicing,
appSection,
}: {
ctx: HeaderContext<Entity, unknown>;
onHeaderSectionResize: (colId: string, part: 'left' | 'right', width: number) => void;
onChangeSlicing: (sliceCol: string | undefined, slice?: string) => void;
appSection: string;
}) => {
const activeSliceCol = useContext(ActiveSliceColContext);
const colId = ctx.header.column.id;
const columnMeta = ctx.column.columnDef.meta as ColumnMetaContext<Entity>;
const { attributes, isDragging, listeners, setNodeRef, setActivatorNodeRef } = useSortableCol(
colId,
!columnMeta?.enableColumnOrdering,
);
const leftRef = useHeaderSectionObserver(colId, 'left', onHeaderSectionResize);
const rightRef = useHeaderSectionObserver(colId, 'right', onHeaderSectionResize);
const columnLabel = columnMeta?.label ?? colId;
const canSlice = columnMeta?.enableSlicing;
const isSliceActive = activeSliceCol === colId;
const canSort = ctx.header.column.getCanSort();
const sortDirection = ctx.header.column.getIsSorted();
return (
<ThInner ref={setNodeRef}>
<LeftCol ref={leftRef}>
{columnMeta?.enableColumnOrdering && (
<HandleSlot $forceVisible={isDragging}>
<DragHandle
ref={setActivatorNodeRef}
index={ctx.header.index}
dragHandleProps={{ ...attributes, ...listeners }}
isDragging={isDragging}
itemTitle={columnLabel}
/>
</HandleSlot>
)}
<HeaderActionsDropdown
label={columnLabel}
activeSort={sortDirection}
isSliceActive={isSliceActive}
onChangeSlicing={canSlice ? onChangeSlicing : undefined}
sliceColumnId={colId}
appSection={appSection}
onSort={canSort ? (desc) => ctx.table.setSorting([{ id: colId, desc }]) : undefined}>
{columnMeta?.columnRenderer?.renderHeader?.(columnLabel) ?? columnLabel}
</HeaderActionsDropdown>
{isSliceActive && <ActiveSliceIcon name="surgical" title={`Slicing by ${columnLabel}`} size="xs" />}
{sortDirection && <SortIcon<Entity> column={ctx.header.column} />}
</LeftCol>
<RightCol ref={rightRef}>
{ctx.header.column.getCanResize() && (
<HandleSlot $forceVisible={ctx.header.column.getIsResizing()}>
<ResizeHandle
onMouseDown={ctx.header.getResizeHandler()}
onTouchStart={ctx.header.getResizeHandler()}
colTitle={columnLabel}
/>
</HandleSlot>
)}
</RightCol>
</ThInner>
);
};
const useAttributeColumnDefinitions = <Entity extends EntityBase, Meta>({
columnHelper,
columnRenderersByAttribute,
columnSchemas,
columnWidths,
entityAttributesAreCamelCase,
enableSlicing,
meta,
onChangeSlicing,
onHeaderSectionResize,
appSection,
}: {
columnHelper: ReturnType<typeof createColumnHelper<Entity>>;
columnRenderersByAttribute: ColumnRenderersByAttribute<Entity, Meta>;
columnSchemas: Array<ColumnSchema>;
columnWidths: { [attributeId: string]: number };
entityAttributesAreCamelCase: boolean;
enableSlicing: boolean;
meta: Meta;
onChangeSlicing: (sliceCol: string | undefined, slice?: string) => void;
onHeaderSectionResize: (colId: string, part: 'left' | 'right', width: number) => void;
appSection?: string;
}) => {
const cell = useCallback(
({
row,
getValue,
column,
}: {
row: Row<Entity>;
getValue: CellContext<Entity, unknown>['getValue'];
column: Column<Entity>;
}) => {
const columnDefMeta = column.columnDef.meta as ColumnMetaContext<Entity>;
return columnDefMeta?.columnRenderer?.renderCell?.(getValue(), row.original, meta) ?? getValue();
},
[meta],
);
const header = useCallback(
(ctx) => (
<AttributeHeader<Entity>
ctx={ctx}
onHeaderSectionResize={onHeaderSectionResize}
onChangeSlicing={onChangeSlicing}
appSection={appSection}
/>
),
[appSection, onChangeSlicing, onHeaderSectionResize],
);
return useMemo(
() =>
columnSchemas.map((col) => {
const baseColDef = {
id: col.id,
cell,
header,
size: columnWidths[col.id],
enableHiding: true,
enableResizing: !columnRenderersByAttribute[col.id].staticWidth,
meta: {
label: col.title,
enableSlicing: enableSlicing && col.sliceable,
columnRenderer: columnRenderersByAttribute[col.id],
enableColumnOrdering: true,
},
};
if (col.isDerived) {
return columnHelper.display(baseColDef);
}
const attributeName = entityAttributesAreCamelCase ? camelCase(col.id) : col.id;
return columnHelper.accessor((row) => row[attributeName], {
enableSorting: col.sortable ?? false,
...baseColDef,
});
}),
[
columnSchemas,
cell,
header,
columnWidths,
columnRenderersByAttribute,
enableSlicing,
entityAttributesAreCamelCase,
columnHelper,
],
);
};
export default useAttributeColumnDefinitions;