-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathEntityDataTable.tsx
More file actions
366 lines (346 loc) · 13.6 KB
/
Copy pathEntityDataTable.tsx
File metadata and controls
366 lines (346 loc) · 13.6 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
/*
* 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 { useMemo, useState, useCallback, useRef } from 'react';
import styled, { css } from 'styled-components';
import { ButtonGroup } from 'components/bootstrap';
import ColumnsVisibilitySelect from 'components/common/EntityDataTable/ColumnsVisibilitySelect';
import type { Sort } from 'stores/PaginationTypes';
import { PageSizeSelect } from 'components/common';
import SelectedEntitiesProvider from 'components/common/EntityDataTable/contexts/SelectedEntitiesProvider';
import MetaDataProvider from 'components/common/EntityDataTable/contexts/MetaDataProvider';
import useTable from 'components/common/EntityDataTable/hooks/useTable';
import useElementWidths from 'components/common/EntityDataTable/hooks/useElementWidths';
import useVisibleColumnOrder from 'components/common/EntityDataTable/hooks/useVisibleColumnOrder';
import TableDndProvider from 'components/common/EntityDataTable/TableDndProvider';
import Table from 'components/common/EntityDataTable/Table';
import DndStylesContext from 'components/common/EntityDataTable/contexts/DndStylesContext';
import {
actionsHeaderWidthVar,
columnOpacityVar,
columnTransition,
columnTransformVar,
columnWidthVar,
displayScrollRightIndicatorVar,
scrollContainerWidthVar,
} from 'components/common/EntityDataTable/CSSVariables';
import useHeaderMinWidths from 'components/common/EntityDataTable/hooks/useHeaderMinWidths';
import useColumnDefinitions from 'components/common/EntityDataTable/hooks/useColumnDefinitions';
import useColumnRenderers from 'components/common/EntityDataTable/hooks/useColumnRenderers';
import useAuthorizedColumnSchemas from 'components/common/EntityDataTable/hooks/useAuthorizedColumnSchemas';
import useIntersectionObserver from 'hooks/useIntersectionObserver';
import { CELL_PADDING } from 'components/common/EntityDataTable/Constants';
import ActiveSliceColContext from 'components/common/EntityDataTable/contexts/ActiveSliceColContext';
import useInternalLayoutPreferences from 'components/common/EntityDataTable/hooks/useInternalLayoutPreferences';
import type {
ColumnRenderers,
ColumnSchema,
EntityBase,
ColumnPreferences,
ExpandedSectionRenderers,
RowOverride,
} from './types';
import ExpandedSectionsProvider from './contexts/ExpandedSectionsProvider';
import BulkActionsRow from './BulkActionsRow';
const cssVariable = (variable: string, value: string | number) => css`
${variable}: ${value};
`;
const ScrollContainer = styled.div<{
$columnWidths: { [_attributeId: string]: number };
$activeColId: string | null;
$columnTransform: { [_attributeId: string]: string };
$actionsHeaderWidth: number;
$canScrollRight: boolean;
$scrollContainerWidth: number;
}>(
({
$columnWidths,
$activeColId,
$columnTransform,
$actionsHeaderWidth,
$canScrollRight,
$scrollContainerWidth,
}) => css`
width: 100%;
overflow-x: auto;
${Object.entries($columnWidths).map(([id, width]) => cssVariable(columnWidthVar(id), `${width}px`))}
${Object.entries($columnTransform).map(([id, transform]) => cssVariable(columnTransformVar(id), transform))}
${$actionsHeaderWidth ? cssVariable(actionsHeaderWidthVar, `${$actionsHeaderWidth}px`) : ''}
${$canScrollRight ? cssVariable(displayScrollRightIndicatorVar, 'block') : ''}
${$scrollContainerWidth ? cssVariable(scrollContainerWidthVar, `${$scrollContainerWidth}px`) : ''}
${$activeColId
? css`
${cssVariable(columnOpacityVar($activeColId), 0.4)}
${cssVariable(columnTransition(), 'transform 0.2s ease-in-out')}
`
: ''}
`,
);
const InnerContainer = styled.div`
position: relative;
height: 100%;
width: fit-content;
`;
const ScrollRightIndicator = styled.div`
position: absolute;
top: 0;
bottom: 0;
right: 0;
width: ${CELL_PADDING}px;
pointer-events: none;
z-index: 2;
`;
const ActionsRow = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
min-height: 22px;
width: 100%;
`;
const LayoutConfigRow = styled.div`
display: flex;
align-items: center;
gap: 5px;
`;
type Props<Entity extends EntityBase, Meta = unknown> = {
/** Currently active sort */
activeSort?: Sort;
/** Currently active slicing column */
activeSliceCol?: string;
/**
* The column ids are always snake case. By default, entity attributes are camel case.
* This prop controls if the column ids need to be transformed to camel case to connect them with the entity attributes.
*/
entityAttributesAreCamelCase: boolean;
bulkSelection?: {
/** Supported bulk actions */
actions?: React.ReactNode;
/** Callback which runs on selection change */
onChangeSelection?: (selectedEntities: Array<Entity['id']>, data: Readonly<Array<Entity>>) => void;
/** Initial selected items */
initialSelection?: Array<Entity['id']>;
isEntitySelectable?: (entity: Entity) => boolean;
};
/** List of all available columns. Column ids need to be snake case. */
columnSchemas: Array<ColumnSchema>;
/** Custom cell and header renderer for a column. Column ids need to be snake case. */
columnRenderers?: ColumnRenderers<Entity, Meta>;
defaultDisplayedColumns: Array<string>;
defaultColumnOrder: Array<string>;
/** The table data. */
entities: ReadonlyArray<Entity>;
/** show slice by action for columns if they support it via their schema **/
enableSlicing?: boolean;
/** Allows you to extend a row with additional information * */
expandedSectionRenderers?: ExpandedSectionRenderers<Entity>;
rowOverride?: RowOverride<Entity>;
/** User layout preferences */
layoutPreferences: {
attributes?: ColumnPreferences;
order?: Array<string>;
};
/** Function to handle update of user layout preferences */
onLayoutPreferencesChange: ({
attributes,
order,
}: {
attributes?: ColumnPreferences;
order?: Array<string>;
}) => Promise<void>;
onChangeSlicing: (sliceCol: string | undefined, slice?: string) => void;
/** Function to handle sort changes */
onSortChange: (newSort: Sort) => void;
/** Function to handle page size changes */
onPageSizeChange?: (newPageSize: number) => void;
/** Function to handle layout preferences reset */
onResetLayoutPreferences: () => Promise<void>;
/** Active page size */
pageSize?: number;
appSection?: string;
/** Actions for each row. */
entityActions?: (entity: Entity) => React.ReactNode;
/** Meta data. */
meta?: Meta;
/** Disable column reordering */
noColumnReordering?: boolean;
/** Disable page size select */
noPageSizeSelect?: boolean;
};
/**
* Flexible data table component which allows defining custom column renderers.
*/
const EntityDataTable = <Entity extends EntityBase, Meta = unknown>({
activeSort = undefined,
activeSliceCol = undefined,
bulkSelection: { actions, onChangeSelection, initialSelection, isEntitySelectable } = {},
columnRenderers: customColumnRenderers = undefined,
columnSchemas,
defaultColumnOrder,
defaultDisplayedColumns,
entities,
entityActions = undefined,
entityAttributesAreCamelCase,
enableSlicing = false,
expandedSectionRenderers = undefined,
rowOverride = undefined,
layoutPreferences,
meta = undefined,
onChangeSlicing,
onLayoutPreferencesChange,
onPageSizeChange = undefined,
onResetLayoutPreferences,
onSortChange,
pageSize = undefined,
appSection = undefined,
noColumnReordering = false,
noPageSizeSelect = false,
}: Props<Entity, Meta>) => {
const [selectedEntities, setSelectedEntities] = useState<Array<Entity['id']>>(initialSelection ?? []);
const hasRowActions = typeof entityActions === 'function';
const displayBulkAction = !!actions;
const displayBulkSelectCol = typeof onChangeSelection === 'function' || displayBulkAction;
const displayPageSizeSelect = typeof onPageSizeChange === 'function';
const authorizedColumnSchemas = useAuthorizedColumnSchemas(columnSchemas);
const columnRenderersByAttribute = useColumnRenderers<Entity, Meta>(authorizedColumnSchemas, customColumnRenderers);
const { headerMinWidths, handleHeaderSectionResize } = useHeaderMinWidths();
const scrollContainerRef = useRef<HTMLDivElement>(null);
const scrolledToRightIndicator = useRef<HTMLDivElement>();
const scrolledToRight = useIntersectionObserver(scrollContainerRef, scrolledToRightIndicator);
const { setInternalAttributeColumnOrder, setInternalColumnWidthPreferences, internalColumnWidthPreferences, internalAttributeColumnOrder } = useInternalLayoutPreferences({ layoutPreferences, defaultColumnOrder });
const columnOrder = useVisibleColumnOrder(
layoutPreferences?.attributes,
internalAttributeColumnOrder,
defaultDisplayedColumns,
displayBulkSelectCol,
);
const { columnWidths, handleActionsWidthChange, tableIsCompressed, actionsColMinWidth, scrollContainerWidth } =
useElementWidths<Entity, Meta>({
columnRenderersByAttribute,
columnSchemas: authorizedColumnSchemas,
columnWidthPreferences: internalColumnWidthPreferences,
displayBulkSelectCol,
entities,
hasRowActions,
headerMinWidths,
scrollContainerRef,
visibleColumns: columnOrder,
});
const columnDefinitions = useColumnDefinitions<Entity, Meta>({
actionsColMinWidth,
columnRenderersByAttribute,
columnSchemas: authorizedColumnSchemas,
columnWidths,
displayBulkSelectCol,
enableSlicing,
entityActions,
entityAttributesAreCamelCase,
hasRowActions,
meta,
onActionsWidthChange: handleActionsWidthChange,
onChangeSlicing,
onHeaderSectionResize: handleHeaderSectionResize,
appSection,
});
const table = useTable<Entity>({
columnOrder,
columnWidths,
columnDefinitions,
defaultColumnOrder,
displayBulkSelectCol,
entities,
headerMinWidths,
internalColumnWidthPreferences,
isEntitySelectable,
layoutPreferences,
onChangeSelection,
onLayoutPreferencesChange,
onSortChange,
selectedEntities,
setInternalAttributeColumnOrder,
setInternalColumnWidthPreferences,
setSelectedEntities,
sort: activeSort,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
const headerGroups = useMemo(() => table.getHeaderGroups(), [columnOrder]);
const resetLayoutPreferences = useCallback(() => {
onResetLayoutPreferences().then(() => {
setInternalAttributeColumnOrder(defaultColumnOrder);
setInternalColumnWidthPreferences({});
});
}, [defaultColumnOrder, onResetLayoutPreferences, setInternalAttributeColumnOrder, setInternalColumnWidthPreferences]);
return (
<MetaDataProvider<Meta> meta={meta}>
<SelectedEntitiesProvider<Entity>
table={table}
selectedEntities={selectedEntities}
isSomeRowsSelected={table.getIsSomeRowsSelected()}
isAllRowsSelected={table.getIsAllRowsSelected()}>
<ActiveSliceColContext.Provider value={activeSliceCol}>
<ExpandedSectionsProvider>
<ActionsRow>
<div>{displayBulkAction && <BulkActionsRow bulkActions={actions} />}</div>
{noColumnReordering && noPageSizeSelect ? null : (
<LayoutConfigRow>
Show
<ButtonGroup>
{displayPageSizeSelect && !noPageSizeSelect && (
<PageSizeSelect pageSize={pageSize} showLabel={false} onChange={onPageSizeChange} />
)}
{!noColumnReordering && (
<ColumnsVisibilitySelect<Entity>
table={table}
onResetLayoutPreferences={resetLayoutPreferences}
/>
)}
</ButtonGroup>
</LayoutConfigRow>
)}
</ActionsRow>
<TableDndProvider table={table}>
<DndStylesContext.Consumer>
{({ activeColId, columnTransform }) => (
<ScrollContainer
id="scroll-container"
ref={scrollContainerRef}
$actionsHeaderWidth={actionsColMinWidth}
$activeColId={activeColId}
$columnTransform={columnTransform}
$columnWidths={columnWidths}
$canScrollRight={scrolledToRight && tableIsCompressed}
$scrollContainerWidth={scrollContainerWidth}>
<InnerContainer>
<Table<Entity>
expandedSectionRenderers={expandedSectionRenderers}
headerGroups={headerGroups}
rowOverride={rowOverride}
rows={table.getRowModel().rows}
/>
<ScrollRightIndicator ref={scrolledToRightIndicator} />
</InnerContainer>
</ScrollContainer>
)}
</DndStylesContext.Consumer>
</TableDndProvider>
</ExpandedSectionsProvider>
</ActiveSliceColContext.Provider>
</SelectedEntitiesProvider>
</MetaDataProvider>
);
};
export default EntityDataTable;