@teselagen/ui 0.7.35 → 0.7.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/isBeingCalledExcessively.js +1 -0
  2. package/package.json +1 -1
  3. package/DataTable/utils/filterLocalEntitiesToHasura.d.ts +0 -5
  4. package/DataTable/utils/initializeHasuraWhereAndFilter.d.ts +0 -2
  5. package/DataTable/utils/tableQueryParamsToHasuraClauses.d.ts +0 -26
  6. package/src/AdvancedOptions.js +0 -33
  7. package/src/AdvancedOptions.spec.js +0 -26
  8. package/src/AssignDefaultsModeContext.js +0 -22
  9. package/src/AsyncValidateFieldSpinner/index.js +0 -12
  10. package/src/BlueprintError/index.js +0 -14
  11. package/src/BounceLoader/index.js +0 -16
  12. package/src/BounceLoader/style.css +0 -45
  13. package/src/CollapsibleCard/index.js +0 -68
  14. package/src/CollapsibleCard/style.css +0 -23
  15. package/src/DNALoader/index.js +0 -20
  16. package/src/DNALoader/style.css +0 -251
  17. package/src/DataTable/CellDragHandle.js +0 -132
  18. package/src/DataTable/ColumnFilterMenu.js +0 -62
  19. package/src/DataTable/Columns.js +0 -979
  20. package/src/DataTable/DisabledLoadingComponent.js +0 -15
  21. package/src/DataTable/DisplayOptions.js +0 -199
  22. package/src/DataTable/DropdownCell.js +0 -61
  23. package/src/DataTable/EditableCell.js +0 -44
  24. package/src/DataTable/FilterAndSortMenu.js +0 -388
  25. package/src/DataTable/PagingTool.js +0 -225
  26. package/src/DataTable/RenderCell.js +0 -191
  27. package/src/DataTable/SearchBar.js +0 -69
  28. package/src/DataTable/SortableColumns.js +0 -100
  29. package/src/DataTable/TableFormTrackerContext.js +0 -10
  30. package/src/DataTable/ThComponent.js +0 -44
  31. package/src/DataTable/dataTableEnhancer.js +0 -41
  32. package/src/DataTable/defaultFormatters.js +0 -32
  33. package/src/DataTable/defaultValidators.js +0 -40
  34. package/src/DataTable/editCellHelper.js +0 -44
  35. package/src/DataTable/getCellVal.js +0 -20
  36. package/src/DataTable/getVals.js +0 -8
  37. package/src/DataTable/index.js +0 -3209
  38. package/src/DataTable/isTruthy.js +0 -12
  39. package/src/DataTable/isValueEmpty.js +0 -3
  40. package/src/DataTable/style.css +0 -608
  41. package/src/DataTable/utils/convertSchema.js +0 -69
  42. package/src/DataTable/utils/filterLocalEntitiesToHasura.js +0 -236
  43. package/src/DataTable/utils/filterLocalEntitiesToHasura.test.js +0 -587
  44. package/src/DataTable/utils/formatPasteData.js +0 -16
  45. package/src/DataTable/utils/getAllRows.js +0 -11
  46. package/src/DataTable/utils/getCellCopyText.js +0 -7
  47. package/src/DataTable/utils/getCellInfo.js +0 -36
  48. package/src/DataTable/utils/getFieldPathToField.js +0 -7
  49. package/src/DataTable/utils/getIdOrCodeOrIndex.js +0 -9
  50. package/src/DataTable/utils/getLastSelectedEntity.js +0 -11
  51. package/src/DataTable/utils/getNewEntToSelect.js +0 -25
  52. package/src/DataTable/utils/getRowCopyText.js +0 -28
  53. package/src/DataTable/utils/getTableConfigFromStorage.js +0 -5
  54. package/src/DataTable/utils/handleCopyColumn.js +0 -21
  55. package/src/DataTable/utils/handleCopyHelper.js +0 -15
  56. package/src/DataTable/utils/handleCopyRows.js +0 -23
  57. package/src/DataTable/utils/handleCopyTable.js +0 -16
  58. package/src/DataTable/utils/index.js +0 -55
  59. package/src/DataTable/utils/initializeHasuraWhereAndFilter.js +0 -26
  60. package/src/DataTable/utils/isBottomRightCornerOfRectangle.js +0 -20
  61. package/src/DataTable/utils/isEntityClean.js +0 -15
  62. package/src/DataTable/utils/primarySelectedValue.js +0 -1
  63. package/src/DataTable/utils/queryParams.js +0 -350
  64. package/src/DataTable/utils/removeCleanRows.js +0 -22
  65. package/src/DataTable/utils/rowClick.js +0 -181
  66. package/src/DataTable/utils/selection.js +0 -8
  67. package/src/DataTable/utils/tableQueryParamsToHasuraClauses.js +0 -253
  68. package/src/DataTable/utils/tableQueryParamsToHasuraClauses.test.js +0 -206
  69. package/src/DataTable/utils/useTableEntities.js +0 -38
  70. package/src/DataTable/utils/utils.js +0 -37
  71. package/src/DataTable/utils/withSelectedEntities.js +0 -65
  72. package/src/DataTable/utils/withTableParams.js +0 -288
  73. package/src/DataTable/validateTableWideErrors.js +0 -160
  74. package/src/DataTable/viewColumn.js +0 -97
  75. package/src/DialogFooter/index.js +0 -86
  76. package/src/DialogFooter/style.css +0 -9
  77. package/src/DropdownButton.js +0 -36
  78. package/src/FillWindow.css +0 -6
  79. package/src/FillWindow.js +0 -69
  80. package/src/FormComponents/FormSeparator.js +0 -9
  81. package/src/FormComponents/LoadingDots.js +0 -14
  82. package/src/FormComponents/Uploader.js +0 -1278
  83. package/src/FormComponents/getNewName.js +0 -31
  84. package/src/FormComponents/index.js +0 -1266
  85. package/src/FormComponents/itemUpload.js +0 -84
  86. package/src/FormComponents/sortify.js +0 -73
  87. package/src/FormComponents/style.css +0 -275
  88. package/src/FormComponents/tryToMatchSchemas.js +0 -264
  89. package/src/FormComponents/utils.js +0 -6
  90. package/src/HotkeysDialog/index.js +0 -79
  91. package/src/HotkeysDialog/style.css +0 -54
  92. package/src/InfoHelper/index.js +0 -78
  93. package/src/InfoHelper/style.css +0 -7
  94. package/src/IntentText/index.js +0 -18
  95. package/src/Loading/index.js +0 -70
  96. package/src/Loading/style.css +0 -4
  97. package/src/MatchHeaders.js +0 -234
  98. package/src/MenuBar/index.js +0 -423
  99. package/src/MenuBar/style.css +0 -45
  100. package/src/PromptUnsavedChanges/index.js +0 -38
  101. package/src/ResizableDraggableDialog/index.js +0 -141
  102. package/src/ResizableDraggableDialog/style.css +0 -42
  103. package/src/ScrollToTop/index.js +0 -72
  104. package/src/SimpleStepViz.js +0 -22
  105. package/src/Tag.js +0 -112
  106. package/src/TagSelect/index.js +0 -69
  107. package/src/TagSelect/style.css +0 -13
  108. package/src/TgHtmlSelect/index.js +0 -20
  109. package/src/TgSelect/index.js +0 -537
  110. package/src/TgSelect/style.css +0 -61
  111. package/src/TgSuggest/index.js +0 -124
  112. package/src/Timeline/TimelineEvent.js +0 -31
  113. package/src/Timeline/index.js +0 -15
  114. package/src/Timeline/style.css +0 -29
  115. package/src/UploadCsvWizard.css +0 -4
  116. package/src/UploadCsvWizard.js +0 -719
  117. package/src/autoTooltip.js +0 -201
  118. package/src/constants.js +0 -1
  119. package/src/customIcons.js +0 -361
  120. package/src/enhancers/withDialog/index.js +0 -196
  121. package/src/enhancers/withDialog/tg_modalState.js +0 -47
  122. package/src/enhancers/withField.js +0 -20
  123. package/src/enhancers/withFields.js +0 -11
  124. package/src/enhancers/withLocalStorage.js +0 -11
  125. package/src/index.js +0 -88
  126. package/src/rerenderOnWindowResize.js +0 -26
  127. package/src/showAppSpinner.js +0 -12
  128. package/src/showConfirmationDialog/index.js +0 -148
  129. package/src/showDialogOnDocBody.js +0 -33
  130. package/src/style.css +0 -265
  131. package/src/throwFormError.js +0 -16
  132. package/src/toastr.js +0 -148
  133. package/src/typeToCommonType.js +0 -6
  134. package/src/useDialog.js +0 -63
  135. package/src/utils/adHoc.js +0 -10
  136. package/src/utils/basicHandleActionsWithFullState.js +0 -14
  137. package/src/utils/browserUtils.js +0 -3
  138. package/src/utils/combineReducersWithFullState.js +0 -14
  139. package/src/utils/commandControls.js +0 -82
  140. package/src/utils/commandUtils.js +0 -112
  141. package/src/utils/determineBlackOrWhiteTextColor.js +0 -4
  142. package/src/utils/getDayjsFormatter.js +0 -35
  143. package/src/utils/getTextFromEl.js +0 -28
  144. package/src/utils/handlerHelpers.js +0 -24
  145. package/src/utils/hooks/index.js +0 -1
  146. package/src/utils/hooks/useDeepEqualMemo.js +0 -15
  147. package/src/utils/hooks/useStableReference.js +0 -9
  148. package/src/utils/hotkeyUtils.js +0 -131
  149. package/src/utils/isBeingCalledExcessively.js +0 -24
  150. package/src/utils/menuUtils.js +0 -433
  151. package/src/utils/popoverOverflowModifiers.js +0 -11
  152. package/src/utils/pureNoFunc.js +0 -31
  153. package/src/utils/renderOnDoc.js +0 -32
  154. package/src/utils/showProgressToast.js +0 -22
  155. package/src/utils/tagUtils.js +0 -45
  156. package/src/utils/tgFormValues.js +0 -35
  157. package/src/utils/useTraceUpdate.js +0 -19
  158. package/src/utils/withSelectTableRecords.js +0 -43
  159. package/src/utils/withStore.js +0 -10
  160. package/src/wrapDialog.js +0 -116
@@ -1,3209 +0,0 @@
1
- import React, {
2
- useEffect,
3
- useRef,
4
- useMemo,
5
- useState,
6
- useCallback,
7
- useContext
8
- } from "react";
9
- import {
10
- invert,
11
- toNumber,
12
- isEmpty,
13
- min,
14
- max,
15
- camelCase,
16
- startCase,
17
- noop,
18
- cloneDeep,
19
- keyBy,
20
- omit,
21
- forEach,
22
- lowerCase,
23
- get,
24
- omitBy,
25
- times,
26
- toArray,
27
- isFunction,
28
- isEqual,
29
- every,
30
- some
31
- } from "lodash-es";
32
- import {
33
- Button,
34
- Menu,
35
- MenuItem,
36
- ContextMenu,
37
- Icon,
38
- Intent,
39
- Callout,
40
- Tooltip,
41
- useHotkeys
42
- } from "@blueprintjs/core";
43
- import { arrayMove } from "@dnd-kit/sortable";
44
- import classNames from "classnames";
45
- import scrollIntoView from "dom-scroll-into-view";
46
- import ReactTable from "@teselagen/react-table";
47
- import immer, { produceWithPatches, enablePatches, applyPatches } from "immer";
48
- import papaparse from "papaparse";
49
- import { useDispatch, useSelector } from "react-redux";
50
- import { ThComponent } from "./ThComponent";
51
- import {
52
- defaultParsePaste,
53
- formatPasteData,
54
- getAllRows,
55
- getCellCopyText,
56
- getCellInfo,
57
- getEntityIdToEntity,
58
- getFieldPathToIndex,
59
- getIdOrCodeOrIndex,
60
- getLastSelectedEntity,
61
- getNewEntToSelect,
62
- getRecordsFromIdMap,
63
- getRowCopyText,
64
- handleCopyColumn,
65
- handleCopyHelper,
66
- handleCopyRows,
67
- handleCopyTable,
68
- isEntityClean,
69
- PRIMARY_SELECTED_VAL,
70
- removeCleanRows
71
- } from "./utils";
72
- import { useDeepEqualMemo } from "../utils/hooks";
73
- import rowClick, {
74
- changeSelectedEntities,
75
- finalizeSelection
76
- } from "./utils/rowClick";
77
- import PagingTool from "./PagingTool";
78
- import SearchBar from "./SearchBar";
79
- import DisplayOptions from "./DisplayOptions";
80
- import DisabledLoadingComponent from "./DisabledLoadingComponent";
81
- import SortableColumns from "./SortableColumns";
82
- import dataTableEnhancer from "./dataTableEnhancer";
83
- import "../toastr";
84
- import "@teselagen/react-table/react-table.css";
85
- import "./style.css";
86
- import { nanoid } from "nanoid";
87
- import { SwitchField } from "../FormComponents";
88
- import { validateTableWideErrors } from "./validateTableWideErrors";
89
- import { editCellHelper } from "./editCellHelper";
90
- import getTableConfigFromStorage from "./utils/getTableConfigFromStorage";
91
- import { viewColumn, openColumn, multiViewColumn } from "./viewColumn";
92
- import convertSchema from "./utils/convertSchema";
93
- import TableFormTrackerContext from "./TableFormTrackerContext";
94
- import {
95
- getCurrentParamsFromUrl,
96
- getQueryParams,
97
- makeDataTableHandlers,
98
- setCurrentParamsOnUrl
99
- } from "./utils/queryParams";
100
- import { useColumns } from "./Columns";
101
- import { formValueSelector, change as _change } from "redux-form";
102
- import { throwFormError } from "../throwFormError";
103
- import { isObservableArray, toJS } from "mobx";
104
- import { isBeingCalledExcessively } from "../utils/isBeingCalledExcessively";
105
- import { getCCDisplayName } from "./utils/tableQueryParamsToHasuraClauses";
106
-
107
- enablePatches();
108
- const IS_LINUX = window.navigator.platform.toLowerCase().search("linux") > -1;
109
-
110
- const itemSizeEstimators = {
111
- compact: () => 25.34,
112
- normal: () => 33.34,
113
- comfortable: () => 41.34
114
- };
115
-
116
- const DataTable = ({
117
- controlled_pageSize,
118
- formName = "tgDataTable",
119
- history,
120
- isSimple,
121
- isLocalCall = true,
122
- isTableParamsConnected,
123
- noForm,
124
- orderByFirstColumn,
125
- schema: _schema,
126
- showEmptyColumnsByDefault,
127
- tableParams: _tableParams,
128
- anyTouched,
129
- blur,
130
- ...ownProps
131
- }) => {
132
- if (isTableParamsConnected && _tableParams && !_tableParams.entities) {
133
- throw new Error(
134
- `No entities array detected in tableParams object (<DataTable {...tableParams}/>). You need to call withQuery() after withTableParams() like: compose(withTableParams(), withQuery(something)).`
135
- );
136
- }
137
- const dispatch = useDispatch();
138
- const change = useCallback(
139
- (...args) => dispatch(_change(formName, ...args)),
140
- [dispatch, formName]
141
- );
142
- const tableRef = useRef();
143
- const alreadySelected = useRef(false);
144
- const [onlyShowRowsWErrors, setOnlyShowRowsWErrors] = useState(false);
145
- const [entitiesUndoRedoStack, setEntitiesUndoRedoStack] = useState({
146
- currentVersion: 0
147
- });
148
- const [selectedCells, setSelectedCells] = useState({});
149
- const _tableConfig = getTableConfigFromStorage(formName);
150
- // make user set page size persist
151
- const userSetPageSize =
152
- _tableConfig?.userSetPageSize && parseInt(_tableConfig.userSetPageSize, 10);
153
-
154
- const formTracker = useContext(TableFormTrackerContext);
155
- useEffect(() => {
156
- if (formTracker.isActive && !formTracker.formNames.includes(formName)) {
157
- formTracker.pushFormName(formName);
158
- }
159
- }, [formTracker, formName]);
160
-
161
- const [showForcedHiddenColumns, setShowForcedHidden] = useState(() => {
162
- if (showEmptyColumnsByDefault) {
163
- return true;
164
- }
165
- return false;
166
- });
167
-
168
- const {
169
- reduxFormCellValidation: _reduxFormCellValidation,
170
- reduxFormEditingCell,
171
- reduxFormEntities,
172
- reduxFormQueryParams: _reduxFormQueryParams = {},
173
- reduxFormSelectedEntityIdMap: _reduxFormSelectedEntityIdMap = {}
174
- } = useSelector(state =>
175
- formValueSelector(formName)(
176
- state,
177
- "reduxFormCellValidation",
178
- "reduxFormEntities",
179
- "reduxFormQueryParams",
180
- "reduxFormSelectedEntityIdMap"
181
- )
182
- );
183
-
184
- // We want to make sure we don't rerender everything unnecessary
185
- // with redux-forms we tend to do unnecessary renders
186
- const reduxFormCellValidation = useDeepEqualMemo(_reduxFormCellValidation);
187
- const reduxFormQueryParams = useDeepEqualMemo(_reduxFormQueryParams);
188
- const reduxFormSelectedEntityIdMap = useDeepEqualMemo(
189
- _reduxFormSelectedEntityIdMap
190
- );
191
-
192
- let props = ownProps;
193
- if (!isTableParamsConnected) {
194
- // When using mobx values we need to transform it to a js array instead of a proxy so the next hooks get the right values
195
- const normalizedEntities = isObservableArray(ownProps.entities)
196
- ? toJS(ownProps.entities)
197
- : ownProps.entities;
198
- //this is the case where we're hooking up to withTableParams locally, so we need to take the tableParams off the props
199
- props = {
200
- ...ownProps,
201
- ..._tableParams,
202
- entities: normalizedEntities
203
- };
204
- }
205
-
206
- const convertedSchema = useMemo(() => convertSchema(_schema), [_schema]);
207
-
208
- if (isLocalCall) {
209
- if (!noForm && (!formName || formName === "tgDataTable")) {
210
- throw new Error(
211
- "Please pass a unique 'formName' prop to the locally connected <DataTable/> component with schema: ",
212
- _schema
213
- );
214
- }
215
- } else {
216
- //in user instantiated withTableParams() call
217
- if (!formName || formName === "tgDataTable") {
218
- throw new Error(
219
- "Please pass a unique 'formName' prop to the withTableParams() with schema: ",
220
- _schema
221
- );
222
- }
223
- }
224
-
225
- const { withPaging = !isSimple } = props;
226
- const {
227
- doNotCoercePageSize,
228
- isInfinite = isSimple && !withPaging,
229
- syncDisplayOptionsToDb,
230
- urlConnected,
231
- withSelectedEntities
232
- } = props;
233
-
234
- const defaults = useMemo(() => {
235
- const _defaults = {
236
- pageSize: controlled_pageSize || 25,
237
- order: [], // ["-name", "statusCode"] //an array of camelCase display names with - sign to denote reverse
238
- searchTerm: "",
239
- page: 1,
240
- filters: [
241
- // filters look like this:
242
- // {
243
- // selectedFilter: 'textContains', //camel case
244
- // filterOn: ccDisplayName, //camel case display name
245
- // filterValue: 'thomas',
246
- // }
247
- ],
248
- ...(props.defaults || {})
249
- };
250
- if (isLocalCall && orderByFirstColumn && !_defaults?.order?.length) {
251
- const r = [getCCDisplayName(convertedSchema.fields[0])];
252
- _defaults.order = r;
253
- }
254
-
255
- if (!syncDisplayOptionsToDb && userSetPageSize) {
256
- _defaults.pageSize = userSetPageSize;
257
- }
258
-
259
- return _defaults;
260
- }, [
261
- controlled_pageSize,
262
- convertedSchema.fields,
263
- isLocalCall,
264
- orderByFirstColumn,
265
- props.defaults,
266
- syncDisplayOptionsToDb,
267
- userSetPageSize
268
- ]);
269
-
270
- const selectedEntities = withSelectedEntities
271
- ? getRecordsFromIdMap(reduxFormSelectedEntityIdMap)
272
- : undefined;
273
-
274
- props = {
275
- ...props,
276
- ...(withSelectedEntities &&
277
- typeof withSelectedEntities === "string" && {
278
- [withSelectedEntities]: selectedEntities
279
- })
280
- };
281
-
282
- const _currentParams = useMemo(() => {
283
- const tmp =
284
- (urlConnected
285
- ? getCurrentParamsFromUrl(history.location) //important to use history location and not ownProps.location because for some reason the location path lags one render behind!!
286
- : reduxFormQueryParams) || {};
287
- return tmp;
288
- }, [history, reduxFormQueryParams, urlConnected]);
289
-
290
- const currentParams = useDeepEqualMemo(_currentParams);
291
-
292
- const tableParams = useMemo(() => {
293
- if (!isTableParamsConnected) {
294
- const setNewParams = newParams => {
295
- // we always will update the redux params as a workaround for withRouter not always working
296
- // if inside a redux-connected container https://github.com/ReactTraining/react-router/issues/5037
297
- change("reduxFormQueryParams", prev => {
298
- let tmp = newParams;
299
- if (typeof tmp === "function") tmp = newParams(prev);
300
- urlConnected && setCurrentParamsOnUrl(tmp, history?.replace);
301
- return tmp;
302
- });
303
- };
304
-
305
- const dispatchProps = makeDataTableHandlers({
306
- setNewParams,
307
- defaults,
308
- onlyOneFilter: props.onlyOneFilter
309
- });
310
-
311
- const changeFormValue = (...args) => change(...args);
312
-
313
- return {
314
- changeFormValue,
315
- selectedEntities,
316
- ..._tableParams,
317
- ...dispatchProps,
318
- isTableParamsConnected: true //let the table know not to do local sorting/filtering etc.
319
- };
320
- }
321
- return _tableParams;
322
- }, [
323
- _tableParams,
324
- change,
325
- defaults,
326
- history?.replace,
327
- isTableParamsConnected,
328
- props.onlyOneFilter,
329
- selectedEntities,
330
- urlConnected
331
- ]);
332
-
333
- props = {
334
- ...props,
335
- ...tableParams
336
- };
337
-
338
- const queryParams = useMemo(() => {
339
- if (!isTableParamsConnected) {
340
- return getQueryParams({
341
- doNotCoercePageSize,
342
- currentParams,
343
- entities: props.entities, // for local table
344
- urlConnected,
345
- defaults,
346
- schema: convertedSchema,
347
- isInfinite,
348
- isLocalCall,
349
- additionalFilter: props.additionalFilter,
350
- noOrderError: props.noOrderError,
351
- isCodeModel: props.isCodeModel,
352
- ownProps: props
353
- });
354
- }
355
- return {};
356
- // eslint-disable-next-line react-hooks/exhaustive-deps
357
- }, [
358
- props.entities,
359
- props.noOrderError,
360
- props.isCodeModel,
361
- convertedSchema,
362
- currentParams,
363
- doNotCoercePageSize,
364
- isInfinite,
365
- isLocalCall,
366
- isTableParamsConnected,
367
- urlConnected
368
- ]);
369
-
370
- props = {
371
- ...props,
372
- ...queryParams
373
- };
374
-
375
- const {
376
- addFilters = noop,
377
- additionalFilters,
378
- additionalFooterButtons,
379
- autoFocusSearch,
380
- cellRenderer,
381
- children,
382
- className = "",
383
- clearFilters = noop,
384
- compact: _compact = true,
385
- compactPaging,
386
- contextMenu = noop,
387
- controlled_hasNextPage,
388
- controlled_onRefresh,
389
- controlled_page,
390
- controlled_setPage,
391
- controlled_setPageSize,
392
- controlled_total,
393
- currentUser,
394
- deleteTableConfiguration,
395
- disabled = false,
396
- disableSetPageSize,
397
- doNotShowEmptyRows,
398
- doNotValidateUntouchedRows,
399
- editingCellSelectAll,
400
- entities: _origEntities = [],
401
- entitiesAcrossPages: _entitiesAcrossPages,
402
- entityCount,
403
- errorParsingUrlString,
404
- expandAllByDefault,
405
- extraClasses = "",
406
- extraCompact: _extraCompact,
407
- filters = [],
408
- fragment,
409
- getCellHoverText,
410
- getRowClassName,
411
- helperProp,
412
- hideColumnHeader,
413
- hideDisplayOptionsIcon,
414
- hidePageSizeWhenPossible = isSimple ? !withPaging : false,
415
- hideSelectedCount = isSimple,
416
- hideSetPageSize,
417
- hideTotalPages,
418
- selectedIds,
419
- isCellEditable,
420
- isCopyable = true,
421
- isEntityDisabled = noop,
422
- isLoading = false,
423
- isOpenable,
424
- isSingleSelect = false,
425
- isViewable,
426
- recordIdToIsVisibleMap,
427
- setRecordIdToIsVisibleMap,
428
- keepSelectionOnPageChange,
429
- leftOfSearchBarItems,
430
- maxHeight = 600,
431
- minimalStyle,
432
- mustClickCheckboxToSelect,
433
- noDeselectAll,
434
- noFooter = isSimple ? !withPaging : false,
435
- noFullscreenButton = isSimple,
436
- noHeader = false,
437
- noPadding = isSimple,
438
- noRowsFoundMessage,
439
- noSelect = false,
440
- noUserSelect,
441
- onDeselect = noop,
442
- onDoubleClick,
443
- onMultiRowSelect = noop,
444
- onRefresh,
445
- onRowClick = noop,
446
- onRowSelect = noop,
447
- onSingleRowSelect = noop,
448
- order,
449
- page = 1,
450
- pageSize: _pageSize = 10,
451
- pagingDisabled,
452
- removeSingleFilter,
453
- ReactTableProps = {},
454
- safeQuery,
455
- searchMenuButton,
456
- searchTerm,
457
- selectAllByDefault,
458
- setNewParams,
459
- setOrder,
460
- setPage = noop,
461
- setPageSize = noop,
462
- setSearchTerm = noop,
463
- shouldShowSubComponent,
464
- showCount = false,
465
- style = {},
466
- SubComponent,
467
- subHeader,
468
- tableConfigurations,
469
- tableName,
470
- topLeftItems,
471
- upsertFieldOption,
472
- upsertTableConfiguration,
473
- variables,
474
- withCheckboxes = false,
475
- withDisplayOptions,
476
- withExpandAndCollapseAllButton,
477
- withFilter,
478
- withSearch = !isSimple,
479
- withSelectAll,
480
- withSort,
481
- withTitle = !isSimple,
482
- noExcessiveCheck
483
- } = props;
484
-
485
- const _entities = useMemo(
486
- () => (reduxFormEntities?.length ? reduxFormEntities : _origEntities) || [],
487
- [_origEntities, reduxFormEntities]
488
- );
489
-
490
- const entities = useDeepEqualMemo(_entities);
491
-
492
- const entitiesAcrossPages = useDeepEqualMemo(_entitiesAcrossPages);
493
-
494
- // This is because we need to maintain the reduxFormSelectedEntityIdMap and
495
- // allOrderedEntities updated
496
- useEffect(() => {
497
- !noExcessiveCheck &&
498
- isBeingCalledExcessively({ uniqName: `dt_entities_${formName}` });
499
- change("allOrderedEntities", entitiesAcrossPages);
500
- if (entities.length === 0 || isEmpty(reduxFormSelectedEntityIdMap)) return;
501
- changeSelectedEntities({
502
- idMap: reduxFormSelectedEntityIdMap,
503
- entities,
504
- change
505
- });
506
- // eslint-disable-next-line react-hooks/exhaustive-deps
507
- }, [
508
- entitiesAcrossPages,
509
- reduxFormSelectedEntityIdMap,
510
- change,
511
- noExcessiveCheck
512
- ]);
513
-
514
- const [tableConfig, setTableConfig] = useState({ fieldOptions: [] });
515
-
516
- useEffect(() => {
517
- if (withDisplayOptions) {
518
- let newTableConfig = {};
519
- if (syncDisplayOptionsToDb) {
520
- newTableConfig = tableConfigurations && tableConfigurations[0];
521
- } else {
522
- newTableConfig = getTableConfigFromStorage(formName);
523
- }
524
- !noExcessiveCheck &&
525
- isBeingCalledExcessively({ uniqName: `dt_setTableConfig_${formName}` });
526
- // if the tableConfig is the same as the newTableConfig, don't update
527
- setTableConfig(prev => {
528
- if (!newTableConfig) {
529
- newTableConfig = {
530
- fieldOptions: []
531
- };
532
- if (isEqual(prev, newTableConfig)) {
533
- return prev;
534
- } else {
535
- return newTableConfig;
536
- }
537
- } else {
538
- return newTableConfig;
539
- }
540
- });
541
- }
542
- }, [
543
- convertedSchema, // If the schema changes we want to take into account the synced tableConfig again
544
- formName,
545
- syncDisplayOptionsToDb,
546
- tableConfigurations,
547
- withDisplayOptions,
548
- noExcessiveCheck
549
- ]);
550
-
551
- const schema = useMemo(() => {
552
- const schema = { ...convertedSchema };
553
- if (isViewable) {
554
- schema.fields = [viewColumn, ...schema.fields];
555
- }
556
- if (recordIdToIsVisibleMap) {
557
- schema.fields = [multiViewColumn, ...schema.fields];
558
- }
559
- if (isOpenable) {
560
- schema.fields = [
561
- openColumn({ onDoubleClick, history }),
562
- ...schema.fields
563
- ];
564
- }
565
- // this must come before handling orderings.
566
- schema.fields = schema.fields.map(field => {
567
- if (field.placementPath) {
568
- return {
569
- ...field,
570
- sortDisabled:
571
- field.sortDisabled ||
572
- (typeof field.path === "string" && field.path.includes(".")),
573
- path: field.placementPath
574
- };
575
- } else {
576
- return field;
577
- }
578
- });
579
-
580
- if (withDisplayOptions) {
581
- const fieldOptsByPath = keyBy(tableConfig.fieldOptions, "path");
582
- schema.fields = schema.fields.map(field => {
583
- const fieldOpt = fieldOptsByPath[field.path];
584
- let noValsForField = false;
585
- // only add this hidden column ability if no paging
586
- if (
587
- !showForcedHiddenColumns &&
588
- withDisplayOptions &&
589
- (isSimple || isInfinite)
590
- ) {
591
- noValsForField = entities.every(e => {
592
- const val = get(e, field.path);
593
- return field.render
594
- ? !field.render(val, e, undefined, {
595
- currentParams,
596
- setNewParams
597
- })
598
- : cellRenderer?.[field.path]
599
- ? !cellRenderer[field.path](val, e, undefined, {
600
- currentParams,
601
- setNewParams
602
- })
603
- : !val;
604
- });
605
- }
606
- if (noValsForField && entities.length) {
607
- return {
608
- ...field,
609
- isHidden: true,
610
- isForcedHidden: true
611
- };
612
- } else if (fieldOpt) {
613
- return {
614
- ...field,
615
- isHidden: fieldOpt.isHidden
616
- };
617
- } else {
618
- return field;
619
- }
620
- });
621
-
622
- const columnOrderings = tableConfig.columnOrderings;
623
- if (columnOrderings) {
624
- const fieldsWithOrders = [];
625
- const fieldsWithoutOrder = [];
626
- // if a new field has been added since the orderings were set then we want
627
- // it to be at the end instead of the beginning
628
- schema.fields.forEach(field => {
629
- if (columnOrderings.indexOf(field.path) > -1) {
630
- fieldsWithOrders.push(field);
631
- } else {
632
- fieldsWithoutOrder.push(field);
633
- }
634
- });
635
- schema.fields = fieldsWithOrders
636
- .sort(({ path: path1 }, { path: path2 }) => {
637
- return (
638
- columnOrderings.indexOf(path1) - columnOrderings.indexOf(path2)
639
- );
640
- })
641
- .concat(fieldsWithoutOrder);
642
- // We shouldn't need to update the columnOrderings here, this could lead
643
- // to unnecessary updates. TableConfig and schema have circular
644
- // dependencies, which is bad at the moment of updating.
645
- if (
646
- !isEqual(
647
- schema.fields.map(f => f.path),
648
- columnOrderings
649
- )
650
- ) {
651
- setTableConfig(prev => ({
652
- ...prev,
653
- columnOrderings: schema.fields.map(f => f.path)
654
- }));
655
- }
656
- }
657
- }
658
- return schema;
659
- }, [
660
- cellRenderer,
661
- convertedSchema,
662
- currentParams,
663
- entities,
664
- history,
665
- isInfinite,
666
- isOpenable,
667
- isSimple,
668
- isViewable,
669
- onDoubleClick,
670
- setNewParams,
671
- showForcedHiddenColumns,
672
- tableConfig.columnOrderings,
673
- tableConfig.fieldOptions,
674
- withDisplayOptions,
675
- recordIdToIsVisibleMap
676
- ]);
677
-
678
- const {
679
- moveColumnPersist,
680
- persistPageSize,
681
- resetDefaultVisibility,
682
- resizePersist,
683
- updateColumnVisibility,
684
- updateTableDisplayDensity
685
- } = useMemo(() => {
686
- let resetDefaultVisibility;
687
- let updateColumnVisibility;
688
- let updateTableDisplayDensity;
689
- let persistPageSize;
690
- let moveColumnPersist;
691
- let resizePersist = noop;
692
-
693
- if (withDisplayOptions) {
694
- const fieldOptsByPath = keyBy(tableConfig.fieldOptions, "path");
695
- if (syncDisplayOptionsToDb) {
696
- // sync up to db
697
- // There must be a better way to set this variable...
698
- let tableConfigurationId;
699
- resetDefaultVisibility = function () {
700
- tableConfigurationId = tableConfig.id;
701
- if (tableConfigurationId) {
702
- deleteTableConfiguration(tableConfigurationId);
703
- }
704
- };
705
- updateColumnVisibility = function ({ shouldShow, path }) {
706
- if (tableConfigurationId) {
707
- const existingFieldOpt = fieldOptsByPath[path] || {};
708
- upsertFieldOption({
709
- id: existingFieldOpt.id,
710
- path,
711
- isHidden: !shouldShow,
712
- tableConfigurationId
713
- });
714
- } else {
715
- upsertTableConfiguration({
716
- userId: currentUser.user.id,
717
- formName,
718
- fieldOptions: [
719
- {
720
- path,
721
- isHidden: !shouldShow
722
- }
723
- ]
724
- });
725
- }
726
- };
727
- } else {
728
- const syncStorage = newTableConfig => {
729
- setTableConfig(newTableConfig);
730
- window.localStorage.setItem(formName, JSON.stringify(newTableConfig));
731
- };
732
-
733
- //sync display options with localstorage
734
- resetDefaultVisibility = function () {
735
- setTableConfig({ fieldOptions: [] });
736
- window.localStorage.removeItem(formName);
737
- };
738
- updateColumnVisibility = function ({ path, paths, shouldShow }) {
739
- const newFieldOpts = {
740
- ...fieldOptsByPath
741
- };
742
- const pathsToUse = paths ? paths : [path];
743
- pathsToUse.forEach(path => {
744
- newFieldOpts[path] = { path, isHidden: !shouldShow };
745
- });
746
- syncStorage({ ...tableConfig, fieldOptions: toArray(newFieldOpts) });
747
- };
748
- updateTableDisplayDensity = function (density) {
749
- syncStorage({ ...tableConfig, density: density });
750
- };
751
- persistPageSize = function (pageSize) {
752
- syncStorage({ ...tableConfig, userSetPageSize: pageSize });
753
- };
754
- moveColumnPersist = function ({ oldIndex, newIndex }) {
755
- // we might already have an array of the fields [path1, path2, ..etc]
756
- const columnOrderings =
757
- tableConfig.columnOrderings ||
758
- schema.fields.map(({ path }) => path); // columnOrderings is [path1, path2, ..etc]
759
- syncStorage({
760
- ...tableConfig,
761
- columnOrderings: arrayMove(columnOrderings, oldIndex, newIndex)
762
- });
763
- };
764
- resizePersist = function (newResized) {
765
- syncStorage({ ...tableConfig, resized: newResized });
766
- };
767
- }
768
- }
769
- return {
770
- moveColumnPersist,
771
- persistPageSize,
772
- resetDefaultVisibility,
773
- resizePersist,
774
- updateColumnVisibility,
775
- updateTableDisplayDensity
776
- };
777
- }, [
778
- currentUser?.user?.id,
779
- deleteTableConfiguration,
780
- formName,
781
- schema.fields,
782
- syncDisplayOptionsToDb,
783
- tableConfig,
784
- upsertFieldOption,
785
- upsertTableConfiguration,
786
- withDisplayOptions
787
- ]);
788
-
789
- let compact = _compact;
790
- let extraCompact = _extraCompact;
791
-
792
- if (withDisplayOptions && tableConfig.density) {
793
- compact = tableConfig.density === "compact";
794
- extraCompact = tableConfig.density === "extraCompact";
795
- }
796
-
797
- const resized = useMemo(
798
- () => tableConfig.resized || [],
799
- [tableConfig?.resized]
800
- );
801
-
802
- const pageSize = controlled_pageSize || _pageSize;
803
-
804
- const [expandedEntityIdMap, setExpandedEntityIdMap] = useState(() => {
805
- const initialExpandedEntityIdMap = {};
806
- if (expandAllByDefault) {
807
- entities.forEach(entity => {
808
- initialExpandedEntityIdMap[entity.id || entity.code] = true;
809
- });
810
- }
811
- return initialExpandedEntityIdMap;
812
- });
813
-
814
- const updateValidation = useCallback(
815
- (entities, newCellValidate) => {
816
- const tableWideErr = validateTableWideErrors({
817
- entities,
818
- schema,
819
- newCellValidate
820
- });
821
- change("reduxFormCellValidation", tableWideErr);
822
- },
823
- [schema, change]
824
- );
825
-
826
- const updateEntitiesHelper = useCallback(
827
- (ents, fn) => {
828
- const [nextState, patches, inversePatches] = produceWithPatches(ents, fn);
829
- if (!inversePatches.length) return;
830
- const thatNewNew = [...nextState];
831
- thatNewNew.isDirty = true;
832
- change("reduxFormEntities", thatNewNew);
833
- setEntitiesUndoRedoStack(prev => ({
834
- ...omitBy(prev, (v, k) => {
835
- return toNumber(k) > prev.currentVersion + 1;
836
- }),
837
- currentVersion: prev.currentVersion + 1,
838
- [prev.currentVersion + 1]: {
839
- inversePatches,
840
- patches
841
- }
842
- }));
843
- },
844
- [change]
845
- );
846
-
847
- const formatAndValidateEntities = useCallback(
848
- (entities, { useDefaultValues, indexToStartAt } = {}) => {
849
- const editableFields = schema.fields.filter(f => !f.isNotEditable);
850
- const validationErrors = {};
851
-
852
- const newEnts = immer(entities, entities => {
853
- entities.forEach((e, index) => {
854
- editableFields.forEach(columnSchema => {
855
- if (useDefaultValues) {
856
- if (e[columnSchema.path] === undefined) {
857
- if (isFunction(columnSchema.defaultValue)) {
858
- e[columnSchema.path] = columnSchema.defaultValue(
859
- index + indexToStartAt,
860
- e
861
- );
862
- } else e[columnSchema.path] = columnSchema.defaultValue;
863
- }
864
- }
865
- //mutative
866
- const { error } = editCellHelper({
867
- entity: e,
868
- columnSchema,
869
- newVal: e[columnSchema.path]
870
- });
871
- if (error) {
872
- const rowId = getIdOrCodeOrIndex(e, index);
873
- validationErrors[`${rowId}:${columnSchema.path}`] = error;
874
- }
875
- });
876
- });
877
- });
878
- return {
879
- newEnts,
880
- validationErrors
881
- };
882
- },
883
- [schema.fields]
884
- );
885
-
886
- const updateValidationHelper = useCallback(() => {
887
- updateValidation(entities, reduxFormCellValidation);
888
- }, [entities, reduxFormCellValidation, updateValidation]);
889
-
890
- const addEditableTableEntities = useCallback(
891
- incomingEnts => {
892
- updateEntitiesHelper(entities, entities => {
893
- const newEntities = incomingEnts.map(e => ({
894
- ...e,
895
- id: e.id || nanoid(),
896
- _isClean: false
897
- }));
898
-
899
- const { newEnts, validationErrors } = formatAndValidateEntities(
900
- newEntities,
901
- {
902
- useDefaultValues: true,
903
- indexToStartAt: entities.length
904
- }
905
- );
906
- if (every(entities, "_isClean")) {
907
- forEach(newEnts, (e, i) => {
908
- entities[i] = e;
909
- });
910
- } else {
911
- entities.splice(entities.length, 0, ...newEnts);
912
- }
913
-
914
- updateValidation(entities, {
915
- ...reduxFormCellValidation,
916
- ...validationErrors
917
- });
918
- });
919
- },
920
- [
921
- entities,
922
- formatAndValidateEntities,
923
- reduxFormCellValidation,
924
- updateEntitiesHelper,
925
- updateValidation
926
- ]
927
- );
928
-
929
- const getEditableTableInfoAndThrowFormError = useCallback(() => {
930
- const { entsToUse, validationToUse } = removeCleanRows(
931
- reduxFormEntities,
932
- reduxFormCellValidation
933
- );
934
- const validationWTableErrs = validateTableWideErrors({
935
- entities: entsToUse,
936
- schema,
937
- newCellValidate: validationToUse
938
- });
939
-
940
- if (!entsToUse?.length) {
941
- throwFormError(
942
- "Please add at least one row to the table before submitting."
943
- );
944
- }
945
- const invalid =
946
- isEmpty(validationWTableErrs) || !some(validationWTableErrs, v => v)
947
- ? undefined
948
- : validationWTableErrs;
949
-
950
- if (invalid) {
951
- throwFormError("Please fix the errors in the table before submitting.");
952
- }
953
-
954
- return entsToUse;
955
- }, [reduxFormCellValidation, reduxFormEntities, schema]);
956
-
957
- useEffect(() => {
958
- // This is bad practice, we shouldn't be assigning value to an
959
- // external variable
960
- if (helperProp) {
961
- helperProp.updateValidationHelper = updateValidationHelper;
962
- helperProp.addEditableTableEntities = addEditableTableEntities;
963
- helperProp.getEditableTableInfoAndThrowFormError =
964
- getEditableTableInfoAndThrowFormError;
965
- }
966
- }, [
967
- addEditableTableEntities,
968
- getEditableTableInfoAndThrowFormError,
969
- helperProp,
970
- updateValidationHelper
971
- ]);
972
-
973
- const handleRowMove = useCallback(
974
- (type, shiftHeld) => e => {
975
- e.preventDefault();
976
- e.stopPropagation();
977
- let newIdMap = {};
978
- const lastSelectedEnt = getLastSelectedEntity(
979
- reduxFormSelectedEntityIdMap
980
- );
981
-
982
- if (noSelect) return;
983
- if (lastSelectedEnt) {
984
- let lastSelectedIndex = entities.findIndex(
985
- ent => ent === lastSelectedEnt
986
- );
987
- if (lastSelectedIndex === -1) {
988
- if (lastSelectedEnt.id !== undefined) {
989
- lastSelectedIndex = entities.findIndex(
990
- ent => ent.id === lastSelectedEnt.id
991
- );
992
- } else if (lastSelectedEnt.code !== undefined) {
993
- lastSelectedIndex = entities.findIndex(
994
- ent => ent.code === lastSelectedEnt.code
995
- );
996
- }
997
- }
998
- if (lastSelectedIndex === -1) {
999
- return;
1000
- }
1001
- const newEntToSelect = getNewEntToSelect({
1002
- type,
1003
- lastSelectedIndex,
1004
- entities,
1005
- isEntityDisabled
1006
- });
1007
-
1008
- if (!newEntToSelect) return;
1009
- if (shiftHeld && !isSingleSelect) {
1010
- if (
1011
- reduxFormSelectedEntityIdMap[
1012
- newEntToSelect.id || newEntToSelect.code
1013
- ]
1014
- ) {
1015
- //the entity being moved to has already been selected
1016
- newIdMap = omit(reduxFormSelectedEntityIdMap, [
1017
- lastSelectedEnt.id || lastSelectedEnt.code
1018
- ]);
1019
- newIdMap[newEntToSelect.id || newEntToSelect.code].time =
1020
- Date.now() + 1;
1021
- } else {
1022
- //the entity being moved to has NOT been selected yet
1023
- newIdMap = {
1024
- ...reduxFormSelectedEntityIdMap,
1025
- [newEntToSelect.id || newEntToSelect.code]: {
1026
- entity: newEntToSelect,
1027
- time: Date.now()
1028
- }
1029
- };
1030
- }
1031
- } else {
1032
- //no shiftHeld
1033
- newIdMap[newEntToSelect.id || newEntToSelect.code] = {
1034
- entity: newEntToSelect,
1035
- time: Date.now()
1036
- };
1037
- }
1038
- }
1039
-
1040
- finalizeSelection({
1041
- idMap: newIdMap,
1042
- entities,
1043
- props: {
1044
- onDeselect,
1045
- onSingleRowSelect,
1046
- onMultiRowSelect,
1047
- noDeselectAll,
1048
- onRowSelect,
1049
- noSelect,
1050
- change
1051
- }
1052
- });
1053
- },
1054
- [
1055
- change,
1056
- entities,
1057
- isEntityDisabled,
1058
- isSingleSelect,
1059
- noDeselectAll,
1060
- noSelect,
1061
- onDeselect,
1062
- onMultiRowSelect,
1063
- onRowSelect,
1064
- onSingleRowSelect,
1065
- reduxFormSelectedEntityIdMap
1066
- ]
1067
- );
1068
-
1069
- const primarySelectedCellId = useMemo(() => {
1070
- for (const k of Object.keys(selectedCells)) {
1071
- if (selectedCells[k] === PRIMARY_SELECTED_VAL) {
1072
- return k;
1073
- }
1074
- }
1075
- }, [selectedCells]);
1076
-
1077
- const startCellEdit = useCallback(
1078
- (cellId, initialValue) => {
1079
- // This initial value is not needed if the event is propagated accordingly.
1080
- // This is directly connected to the RenderCell component, which does set
1081
- // the initial value.
1082
- change("reduxFormInitialValue", initialValue);
1083
- change("reduxFormEditingCell", prev => {
1084
- //check if the cell is already selected and editing and if so, don't change it
1085
- if (prev === cellId) return cellId;
1086
- setSelectedCells(prev => {
1087
- if (prev[cellId] === PRIMARY_SELECTED_VAL) {
1088
- return prev;
1089
- }
1090
- return { ...prev, [cellId]: PRIMARY_SELECTED_VAL };
1091
- });
1092
- return cellId;
1093
- });
1094
- },
1095
- [change]
1096
- );
1097
-
1098
- const handleEnterStartCellEdit = useCallback(
1099
- e => {
1100
- e.stopPropagation();
1101
- startCellEdit(primarySelectedCellId);
1102
- },
1103
- [primarySelectedCellId, startCellEdit]
1104
- );
1105
-
1106
- const handleDeleteCell = useCallback(() => {
1107
- const newCellValidate = {
1108
- ...reduxFormCellValidation
1109
- };
1110
- if (isEmpty(selectedCells)) return;
1111
- const rowIds = [];
1112
- updateEntitiesHelper(entities, entities => {
1113
- const entityIdToEntity = getEntityIdToEntity(entities);
1114
- Object.keys(selectedCells).forEach(cellId => {
1115
- const [rowId, path] = cellId.split(":");
1116
- rowIds.push(rowId);
1117
- const entity = entityIdToEntity[rowId].e;
1118
- delete entity._isClean;
1119
- const { error } = editCellHelper({
1120
- entity,
1121
- path,
1122
- schema,
1123
- newVal: ""
1124
- });
1125
- if (error) {
1126
- newCellValidate[cellId] = error;
1127
- } else {
1128
- delete newCellValidate[cellId];
1129
- }
1130
- });
1131
- updateValidation(entities, newCellValidate);
1132
- });
1133
- }, [
1134
- entities,
1135
- reduxFormCellValidation,
1136
- schema,
1137
- selectedCells,
1138
- updateEntitiesHelper,
1139
- updateValidation
1140
- ]);
1141
-
1142
- const handleCopySelectedCells = useCallback(
1143
- e => {
1144
- // if the current selection is consecutive cells then copy with
1145
- // tabs between. if not then just select primary selected cell
1146
- if (isEmpty(selectedCells)) return;
1147
- const pathToIndex = getFieldPathToIndex(schema);
1148
- const entityIdToEntity = getEntityIdToEntity(entities);
1149
- const selectionGrid = [];
1150
- let firstRowIndex;
1151
- let firstCellIndex;
1152
- Object.keys(selectedCells).forEach(key => {
1153
- const [rowId, path] = key.split(":");
1154
- const eInfo = entityIdToEntity[rowId];
1155
- if (eInfo) {
1156
- if (firstRowIndex === undefined || eInfo.i < firstRowIndex) {
1157
- firstRowIndex = eInfo.i;
1158
- }
1159
- if (!selectionGrid[eInfo.i]) {
1160
- selectionGrid[eInfo.i] = [];
1161
- }
1162
- const cellIndex = pathToIndex[path];
1163
- if (firstCellIndex === undefined || cellIndex < firstCellIndex) {
1164
- firstCellIndex = cellIndex;
1165
- }
1166
- selectionGrid[eInfo.i][cellIndex] = true;
1167
- }
1168
- });
1169
- if (firstRowIndex === undefined) return;
1170
- const allRows = getAllRows(e);
1171
- let fullCellText = "";
1172
- const fullJson = [];
1173
- times(selectionGrid.length, i => {
1174
- const row = selectionGrid[i];
1175
- if (fullCellText) {
1176
- fullCellText += "\n";
1177
- }
1178
- if (!row) {
1179
- return;
1180
- } else {
1181
- const jsonRow = [];
1182
- // ignore header
1183
- let [rowCopyText, json] = getRowCopyText(allRows[i + 1]);
1184
- rowCopyText = rowCopyText.split("\t");
1185
- times(row.length, i => {
1186
- const cell = row[i];
1187
- if (cell) {
1188
- fullCellText += rowCopyText[i];
1189
- jsonRow.push(json[i]);
1190
- }
1191
- if (i !== row.length - 1 && i >= firstCellIndex)
1192
- fullCellText += "\t";
1193
- });
1194
- fullJson.push(jsonRow);
1195
- }
1196
- });
1197
- if (!fullCellText) return window.toastr.warning("No text to copy");
1198
-
1199
- handleCopyHelper(fullCellText, fullJson, "Selected cells copied");
1200
- },
1201
- [entities, selectedCells, schema]
1202
- );
1203
-
1204
- const handleCopySelectedRows = useCallback(
1205
- (selectedRecords, e) => {
1206
- const idToIndex = entities.reduce((acc, e, i) => {
1207
- acc[e.id || e.code] = i;
1208
- return acc;
1209
- }, {});
1210
-
1211
- //index 0 of the table is the column titles
1212
- //must add 1 to rowNum
1213
- const rowNumbersToCopy = selectedRecords
1214
- .map(rec => idToIndex[rec.id || rec.code] + 1)
1215
- .sort();
1216
-
1217
- if (!rowNumbersToCopy.length) return;
1218
- rowNumbersToCopy.unshift(0); //add in the header row
1219
- try {
1220
- const allRowEls = getAllRows(e);
1221
- if (!allRowEls) return;
1222
- const rowEls = rowNumbersToCopy.map(i => allRowEls[i]);
1223
-
1224
- handleCopyRows(rowEls, {
1225
- onFinishMsg: "Selected rows copied"
1226
- });
1227
- } catch (error) {
1228
- console.error(`error:`, error);
1229
- window.toastr.error("Error copying rows.");
1230
- }
1231
- },
1232
- [entities]
1233
- );
1234
-
1235
- const handleCopyHotkey = useCallback(
1236
- e => {
1237
- if (isCellEditable) {
1238
- handleCopySelectedCells(e);
1239
- } else {
1240
- handleCopySelectedRows(
1241
- getRecordsFromIdMap(reduxFormSelectedEntityIdMap),
1242
- e
1243
- );
1244
- }
1245
- },
1246
- [
1247
- handleCopySelectedCells,
1248
- handleCopySelectedRows,
1249
- isCellEditable,
1250
- reduxFormSelectedEntityIdMap
1251
- ]
1252
- );
1253
-
1254
- const handleCut = useCallback(
1255
- e => {
1256
- handleDeleteCell();
1257
- handleCopyHotkey(e);
1258
- },
1259
- [handleCopyHotkey, handleDeleteCell]
1260
- );
1261
-
1262
- const flashTableBorder = () => {
1263
- try {
1264
- const table = tableRef.current.tableRef;
1265
- table.classList.add("tgBorderBlue");
1266
- setTimeout(() => {
1267
- table.classList.remove("tgBorderBlue");
1268
- }, 300);
1269
- } catch (e) {
1270
- console.error(`err when flashing table border:`, e);
1271
- }
1272
- };
1273
-
1274
- const handleUndo = useCallback(() => {
1275
- if (entitiesUndoRedoStack.currentVersion > 0) {
1276
- flashTableBorder();
1277
- const nextState = applyPatches(
1278
- entities,
1279
- entitiesUndoRedoStack[entitiesUndoRedoStack.currentVersion]
1280
- .inversePatches
1281
- );
1282
- const { newEnts, validationErrors } =
1283
- formatAndValidateEntities(nextState);
1284
- setEntitiesUndoRedoStack(prev => ({
1285
- ...prev,
1286
- currentVersion: prev.currentVersion - 1
1287
- }));
1288
- updateValidation(newEnts, validationErrors);
1289
- change("reduxFormEntities", newEnts);
1290
- }
1291
- }, [
1292
- change,
1293
- entities,
1294
- formatAndValidateEntities,
1295
- entitiesUndoRedoStack,
1296
- updateValidation
1297
- ]);
1298
-
1299
- const handleRedo = useCallback(() => {
1300
- const nextV = entitiesUndoRedoStack.currentVersion + 1;
1301
- if (entitiesUndoRedoStack[nextV]) {
1302
- flashTableBorder();
1303
- const nextState = applyPatches(
1304
- entities,
1305
- entitiesUndoRedoStack[nextV].patches
1306
- );
1307
- const { newEnts, validationErrors } =
1308
- formatAndValidateEntities(nextState);
1309
- change("reduxFormEntities", newEnts);
1310
- updateValidation(newEnts, validationErrors);
1311
- setEntitiesUndoRedoStack(prev => ({
1312
- ...prev,
1313
- currentVersion: nextV
1314
- }));
1315
- }
1316
- }, [
1317
- change,
1318
- entities,
1319
- formatAndValidateEntities,
1320
- entitiesUndoRedoStack,
1321
- updateValidation
1322
- ]);
1323
-
1324
- const handleSelectAllRows = useCallback(
1325
- e => {
1326
- if (isSingleSelect) return;
1327
- e.preventDefault();
1328
-
1329
- if (isCellEditable) {
1330
- const schemaPaths = schema.fields.map(f => f.path);
1331
- const newSelectedCells = {};
1332
- entities.forEach((entity, i) => {
1333
- if (isEntityDisabled(entity)) return;
1334
- const entityId = getIdOrCodeOrIndex(entity, i);
1335
- schemaPaths.forEach(p => {
1336
- newSelectedCells[`${entityId}:${p}`] = true;
1337
- });
1338
- });
1339
- setSelectedCells(newSelectedCells);
1340
- } else {
1341
- const newIdMap = {};
1342
-
1343
- entities.forEach((entity, i) => {
1344
- if (isEntityDisabled(entity)) return;
1345
- const entityId = getIdOrCodeOrIndex(entity, i);
1346
- newIdMap[entityId] = { entity };
1347
- });
1348
- finalizeSelection({
1349
- idMap: newIdMap,
1350
- entities,
1351
- props: {
1352
- onDeselect,
1353
- onSingleRowSelect,
1354
- onMultiRowSelect,
1355
- noDeselectAll,
1356
- onRowSelect,
1357
- noSelect,
1358
- change
1359
- }
1360
- });
1361
- }
1362
- },
1363
- [
1364
- change,
1365
- entities,
1366
- isCellEditable,
1367
- isEntityDisabled,
1368
- isSingleSelect,
1369
- noDeselectAll,
1370
- noSelect,
1371
- onDeselect,
1372
- onMultiRowSelect,
1373
- onRowSelect,
1374
- onSingleRowSelect,
1375
- schema.fields
1376
- ]
1377
- );
1378
-
1379
- const hotKeys = useMemo(
1380
- () => [
1381
- {
1382
- global: false,
1383
- combo: "up",
1384
- label: "Move Up a Row",
1385
- onKeyDown: handleRowMove("up")
1386
- },
1387
- {
1388
- global: false,
1389
- combo: "down",
1390
- label: "Move Down a Row",
1391
- onKeyDown: handleRowMove("down")
1392
- },
1393
- {
1394
- global: false,
1395
- combo: "up+shift",
1396
- label: "Move Up a Row",
1397
- onKeyDown: handleRowMove("up", true)
1398
- },
1399
- ...(isCellEditable
1400
- ? [
1401
- {
1402
- global: false,
1403
- combo: "enter",
1404
- label: "Enter -> Start Cell Edit",
1405
- onKeyDown: handleEnterStartCellEdit
1406
- },
1407
- {
1408
- global: false,
1409
- combo: "mod+x",
1410
- label: "Cut",
1411
- onKeyDown: handleCut
1412
- },
1413
- {
1414
- global: false,
1415
- combo: IS_LINUX ? "alt+z" : "mod+z",
1416
- label: "Undo",
1417
- onKeyDown: handleUndo
1418
- },
1419
- {
1420
- global: false,
1421
- combo: IS_LINUX ? "alt+shift+z" : "mod+shift+z",
1422
- label: "Redo",
1423
- onKeyDown: handleRedo
1424
- },
1425
- {
1426
- global: false,
1427
- combo: "backspace",
1428
- label: "Delete Cell",
1429
- onKeyDown: handleDeleteCell
1430
- }
1431
- ]
1432
- : []),
1433
- {
1434
- global: false,
1435
- combo: "down+shift",
1436
- label: "Move Down a Row",
1437
- onKeyDown: handleRowMove("down", true)
1438
- },
1439
- {
1440
- global: false,
1441
- combo: "mod + c",
1442
- label: "Copy rows",
1443
- onKeyDown: handleCopyHotkey
1444
- },
1445
- {
1446
- global: false,
1447
- combo: "mod + a",
1448
- label: "Select rows",
1449
- onKeyDown: handleSelectAllRows
1450
- }
1451
- ],
1452
- [
1453
- handleCopyHotkey,
1454
- handleCut,
1455
- handleDeleteCell,
1456
- handleEnterStartCellEdit,
1457
- handleRedo,
1458
- handleRowMove,
1459
- handleSelectAllRows,
1460
- handleUndo,
1461
- isCellEditable
1462
- ]
1463
- );
1464
-
1465
- const { handleKeyDown, handleKeyUp } = useHotkeys(hotKeys);
1466
- const [columns, setColumns] = useState([]);
1467
- const [fullscreen, setFullscreen] = useState(false);
1468
- const [selectingAll, setSelectingAll] = useState(false);
1469
-
1470
- // format in the schema shouldn't be something that changes the value
1471
- // everytime, it produces weird behavior since it keeps rerendering,
1472
- // we should make enforce the user set the format as something that
1473
- // "formats", not "changes".
1474
- useEffect(() => {
1475
- const formatAndValidateTableInitial = () => {
1476
- const { newEnts, validationErrors } = formatAndValidateEntities(entities);
1477
- const toKeep = {};
1478
- //on the initial load we want to keep any async table wide errors
1479
- forEach(reduxFormCellValidation, (v, k) => {
1480
- if (v && v._isTableAsyncWideError) {
1481
- toKeep[k] = v;
1482
- }
1483
- });
1484
- change("reduxFormEntities", prev => {
1485
- if (!isEqual(prev, newEnts)) {
1486
- return newEnts;
1487
- }
1488
- return prev;
1489
- });
1490
- updateValidation(newEnts, {
1491
- ...toKeep,
1492
- ...validationErrors
1493
- });
1494
- };
1495
- isCellEditable && formatAndValidateTableInitial();
1496
- }, [
1497
- change,
1498
- entities,
1499
- formatAndValidateEntities,
1500
- isCellEditable,
1501
- reduxFormCellValidation,
1502
- updateValidation
1503
- ]);
1504
-
1505
- const handlePaste = useCallback(
1506
- e => {
1507
- if (isCellEditable) {
1508
- if (isEmpty(selectedCells)) return;
1509
- try {
1510
- let pasteData = [];
1511
- let toPaste;
1512
- if (window.clipboardData && window.clipboardData.getData) {
1513
- // IE
1514
- toPaste = window.clipboardData.getData("Text");
1515
- } else if (e.clipboardData && e.clipboardData.getData) {
1516
- toPaste = e.clipboardData.getData("text/plain");
1517
- }
1518
- const jsonToPaste = e.clipboardData.getData("application/json");
1519
- try {
1520
- const pastedJson = [];
1521
- JSON.parse(jsonToPaste).forEach(row => {
1522
- const newRow = [];
1523
- Object.values(row).forEach(cell => {
1524
- const cellVal = JSON.parse(cell);
1525
- newRow.push(cellVal);
1526
- });
1527
- pastedJson.push(newRow);
1528
- });
1529
- pasteData = pastedJson;
1530
- // try to remove the header row if it exists
1531
- if (
1532
- pasteData[0] &&
1533
- pasteData[0][0] &&
1534
- pasteData[0][0].__isHeaderCell
1535
- ) {
1536
- pasteData = pasteData.slice(1);
1537
- }
1538
- } catch (e) {
1539
- if (toPaste.includes(",")) {
1540
- //try papaparsing it out as a csv if it contains commas
1541
- try {
1542
- const { data, errors } = papaparse.parse(toPaste, {
1543
- header: false
1544
- });
1545
- if (data?.length && !errors?.length) {
1546
- pasteData = data;
1547
- }
1548
- } catch (error) {
1549
- console.error(`error p982qhgpf9qh`, error);
1550
- }
1551
- }
1552
- }
1553
- pasteData = pasteData.length ? pasteData : defaultParsePaste(toPaste);
1554
-
1555
- if (!pasteData || !pasteData.length) return;
1556
-
1557
- if (pasteData.length === 1 && pasteData[0].length === 1) {
1558
- const newCellValidate = {
1559
- ...reduxFormCellValidation
1560
- };
1561
- // single paste value, fill all cells with value
1562
- const newVal = pasteData[0][0];
1563
- updateEntitiesHelper(entities, entities => {
1564
- const entityIdToEntity = getEntityIdToEntity(entities);
1565
- Object.keys(selectedCells).forEach(cellId => {
1566
- const [rowId, path] = cellId.split(":");
1567
-
1568
- const entity = entityIdToEntity[rowId].e;
1569
- delete entity._isClean;
1570
- const { error } = editCellHelper({
1571
- entity,
1572
- path,
1573
- schema,
1574
- newVal: formatPasteData({ newVal, path, schema })
1575
- });
1576
- if (error) {
1577
- newCellValidate[cellId] = error;
1578
- } else {
1579
- delete newCellValidate[cellId];
1580
- }
1581
- });
1582
- updateValidation(entities, newCellValidate);
1583
- });
1584
- } else {
1585
- // handle paste in same format
1586
- if (primarySelectedCellId) {
1587
- const newCellValidate = {
1588
- ...reduxFormCellValidation
1589
- };
1590
-
1591
- const newSelectedCells = { ...selectedCells };
1592
- updateEntitiesHelper(entities, entities => {
1593
- const entityIdToEntity = getEntityIdToEntity(entities);
1594
- const [rowId, primaryCellPath] =
1595
- primarySelectedCellId.split(":");
1596
- const primaryEntityInfo = entityIdToEntity[rowId];
1597
- const startIndex = primaryEntityInfo.i;
1598
- const endIndex = primaryEntityInfo.i + pasteData.length;
1599
- for (let i = startIndex; i < endIndex; i++) {
1600
- if (!entities[i]) {
1601
- entities[i] = { id: nanoid() };
1602
- }
1603
- }
1604
- const entitiesToManipulate = entities.slice(
1605
- startIndex,
1606
- endIndex
1607
- );
1608
- const pathToIndex = getFieldPathToIndex(schema);
1609
- const indexToPath = invert(pathToIndex);
1610
- const startCellIndex = pathToIndex[primaryCellPath];
1611
- pasteData.forEach((row, i) => {
1612
- row.forEach((newVal, j) => {
1613
- if (newVal) {
1614
- const cellIndexToChange = startCellIndex + j;
1615
- const entity = entitiesToManipulate[i];
1616
- if (entity) {
1617
- delete entity._isClean;
1618
- const path = indexToPath[cellIndexToChange];
1619
- if (path) {
1620
- const { error } = editCellHelper({
1621
- entity,
1622
- path,
1623
- schema,
1624
- newVal: formatPasteData({
1625
- newVal,
1626
- path,
1627
- schema
1628
- })
1629
- });
1630
- const cellId = `${getIdOrCodeOrIndex(entity)}:${path}`;
1631
- if (!newSelectedCells[cellId]) {
1632
- newSelectedCells[cellId] = true;
1633
- }
1634
- if (error) {
1635
- newCellValidate[cellId] = error;
1636
- } else {
1637
- delete newCellValidate[cellId];
1638
- }
1639
- }
1640
- }
1641
- }
1642
- });
1643
- });
1644
- updateValidation(entities, newCellValidate);
1645
- });
1646
- setSelectedCells(newSelectedCells);
1647
- }
1648
- }
1649
- } catch (error) {
1650
- console.error(`error:`, error);
1651
- }
1652
- }
1653
- },
1654
- [
1655
- entities,
1656
- isCellEditable,
1657
- primarySelectedCellId,
1658
- reduxFormCellValidation,
1659
- schema,
1660
- selectedCells,
1661
- updateEntitiesHelper,
1662
- updateValidation
1663
- ]
1664
- );
1665
-
1666
- useEffect(() => {
1667
- document.addEventListener("paste", handlePaste);
1668
- return () => {
1669
- document.removeEventListener("paste", handlePaste);
1670
- };
1671
- }, [handlePaste]);
1672
-
1673
- useEffect(() => {
1674
- addFilters(additionalFilters);
1675
- // eslint-disable-next-line react-hooks/exhaustive-deps
1676
- }, [additionalFilters]);
1677
-
1678
- useEffect(() => {
1679
- setColumns(
1680
- schema.fields
1681
- ? schema.fields.reduce((col, field, i) => {
1682
- if (field.isHidden) {
1683
- return col;
1684
- }
1685
- return col.concat({
1686
- ...field,
1687
- columnIndex: i
1688
- });
1689
- }, [])
1690
- : []
1691
- );
1692
- }, [schema?.fields]);
1693
-
1694
- const setSelectedIds = useCallback(
1695
- (selectedIds, scrollToFirst) => {
1696
- const idArray = Array.isArray(selectedIds) ? selectedIds : [selectedIds];
1697
- const selectedEntities = entities.filter(
1698
- e => idArray.indexOf(getIdOrCodeOrIndex(e)) > -1 && !isEntityDisabled(e)
1699
- );
1700
- const newIdMap = selectedEntities.reduce((acc, entity) => {
1701
- acc[getIdOrCodeOrIndex(entity)] = { entity };
1702
- return acc;
1703
- }, {});
1704
- setExpandedEntityIdMap(newIdMap);
1705
- finalizeSelection({
1706
- idMap: newIdMap,
1707
- entities,
1708
- props: {
1709
- onDeselect,
1710
- onSingleRowSelect,
1711
- onMultiRowSelect,
1712
- noDeselectAll,
1713
- onRowSelect,
1714
- noSelect,
1715
- change
1716
- }
1717
- });
1718
- // This option could be eliminated, keeping it because it was prior in the
1719
- // code, but it is a fuctionality not needed
1720
- if (scrollToFirst) {
1721
- const idToScrollTo = idArray[0];
1722
- if (!idToScrollTo && idToScrollTo !== 0) return;
1723
- const entityIndexToScrollTo = entities.findIndex(
1724
- e => e.id === idToScrollTo || e.code === idToScrollTo
1725
- );
1726
- if (entityIndexToScrollTo === -1 || !tableRef.current) return;
1727
- const tableBody = tableRef.current.tableRef.querySelector(".rt-tbody");
1728
- if (!tableBody) return;
1729
- const rowEl =
1730
- tableBody.getElementsByClassName("rt-tr-group")[
1731
- entityIndexToScrollTo
1732
- ];
1733
- if (!rowEl) return;
1734
- setTimeout(() => {
1735
- //we need to delay for a teeny bit to make sure the table has drawn
1736
- rowEl &&
1737
- tableBody &&
1738
- scrollIntoView(rowEl, tableBody, {
1739
- alignWithTop: true
1740
- });
1741
- }, 0);
1742
- }
1743
- },
1744
- [
1745
- change,
1746
- entities,
1747
- isEntityDisabled,
1748
- noDeselectAll,
1749
- noSelect,
1750
- onDeselect,
1751
- onMultiRowSelect,
1752
- onRowSelect,
1753
- onSingleRowSelect
1754
- ]
1755
- );
1756
-
1757
- // We need to make sure this only runs at the beggining
1758
- useEffect(() => {
1759
- if (selectedIds) {
1760
- setSelectedIds(selectedIds);
1761
- }
1762
- if (selectAllByDefault && entities && entities.length) {
1763
- if (alreadySelected.current) return;
1764
- setSelectedIds(entities.map(getIdOrCodeOrIndex));
1765
- alreadySelected.current = true;
1766
- }
1767
- }, [entities, selectedIds, selectAllByDefault, setSelectedIds]);
1768
-
1769
- const TheadComponent = useCallback(
1770
- ({ className, style, children }) => {
1771
- const moveColumn = ({ oldIndex, newIndex }) => {
1772
- let oldStateColumnIndex, newStateColumnIndex;
1773
- columns.forEach((column, i) => {
1774
- if (oldIndex === column.columnIndex) oldStateColumnIndex = i;
1775
- if (newIndex === column.columnIndex) newStateColumnIndex = i;
1776
- });
1777
- // because it is all handled in state we need
1778
- // to perform the move and update the columnIndices
1779
- // because they are used for the sortable columns
1780
- const newColumns = arrayMove(
1781
- columns,
1782
- oldStateColumnIndex,
1783
- newStateColumnIndex
1784
- ).map((column, i) => {
1785
- return {
1786
- ...column,
1787
- columnIndex: i
1788
- };
1789
- });
1790
- setColumns(newColumns);
1791
- };
1792
- return (
1793
- <SortableColumns
1794
- className={className}
1795
- style={style}
1796
- moveColumn={moveColumnPersist || moveColumn}
1797
- >
1798
- {children}
1799
- </SortableColumns>
1800
- );
1801
- },
1802
- [columns, moveColumnPersist]
1803
- );
1804
-
1805
- const addEntitiesToSelection = entities => {
1806
- const idMap = reduxFormSelectedEntityIdMap || {};
1807
- const newIdMap = cloneDeep(idMap) || {};
1808
- entities.forEach((entity, i) => {
1809
- if (isEntityDisabled(entity)) return;
1810
- const entityId = getIdOrCodeOrIndex(entity, i);
1811
- newIdMap[entityId] = { entity };
1812
- });
1813
- finalizeSelection({
1814
- idMap: newIdMap,
1815
- entities,
1816
- props: {
1817
- onDeselect,
1818
- onSingleRowSelect,
1819
- onMultiRowSelect,
1820
- noDeselectAll,
1821
- onRowSelect,
1822
- noSelect,
1823
- change
1824
- }
1825
- });
1826
- };
1827
-
1828
- const refocusTable = useCallback(() => {
1829
- const table = tableRef.current?.tableRef?.closest(
1830
- ".data-table-container>div"
1831
- );
1832
- table?.focus();
1833
- }, []);
1834
-
1835
- const isSelectionARectangle = useCallback(() => {
1836
- if (selectedCells && Object.keys(selectedCells).length > 1) {
1837
- const pathToIndex = getFieldPathToIndex(schema);
1838
- const entityMap = getEntityIdToEntity(entities);
1839
- let selectionGrid = [];
1840
- let firstCellIndex;
1841
- let lastCellIndex;
1842
- let lastRowIndex;
1843
- let firstRowIndex;
1844
- const selectedPaths = [];
1845
- Object.keys(selectedCells).forEach(key => {
1846
- // if (reduxFormSelectedCells[key] === PRIMARY_SELECTED_VAL) {
1847
- // primaryCellId = key;
1848
- // }
1849
- const [rowId, cellPath] = key.split(":");
1850
- if (!selectedPaths.includes(cellPath)) selectedPaths.push(cellPath);
1851
- const cellIndex = pathToIndex[cellPath];
1852
- const ent = entityMap[rowId];
1853
- if (!ent) return;
1854
- const { i } = ent;
1855
- if (firstRowIndex === undefined || i < firstRowIndex) {
1856
- firstRowIndex = i;
1857
- }
1858
- if (lastRowIndex === undefined || i > lastRowIndex) {
1859
- lastRowIndex = i;
1860
- }
1861
- if (!selectionGrid[i]) selectionGrid[i] = [];
1862
- selectionGrid[i][cellIndex] = { cellId: key, rowIndex: i, cellIndex };
1863
- if (firstCellIndex === undefined || cellIndex < firstCellIndex) {
1864
- firstCellIndex = cellIndex;
1865
- }
1866
- if (lastCellIndex === undefined || cellIndex > lastCellIndex) {
1867
- lastCellIndex = cellIndex;
1868
- }
1869
- });
1870
- selectionGrid = selectionGrid.slice(firstRowIndex);
1871
- let isRectangle = true;
1872
- for (let i = 0; i < selectionGrid.length; i++) {
1873
- const row = selectionGrid[i];
1874
- if (!row) {
1875
- isRectangle = false;
1876
- break;
1877
- } else {
1878
- for (let j = firstCellIndex; j < row.length; j++) {
1879
- if (!row[j]) {
1880
- isRectangle = false;
1881
- break;
1882
- }
1883
- }
1884
- }
1885
- }
1886
- if (isRectangle) {
1887
- return {
1888
- entityMap,
1889
- firstCellIndex,
1890
- firstRowIndex,
1891
- isRect: true,
1892
- lastCellIndex,
1893
- lastRowIndex,
1894
- selectedPaths,
1895
- selectionGrid,
1896
- pathToIndex
1897
- };
1898
- } else {
1899
- return {};
1900
- }
1901
- }
1902
- return {};
1903
- }, [entities, schema, selectedCells]);
1904
-
1905
- const handleCellClick = useCallback(
1906
- ({ event, cellId }) => {
1907
- if (!cellId) return;
1908
- const [rowId, cellPath] = cellId.split(":");
1909
- const entityMap = getEntityIdToEntity(entities);
1910
- const { e: entity, i: rowIndex } = entityMap[rowId];
1911
- const pathToIndex = getFieldPathToIndex(schema);
1912
- const columnIndex = pathToIndex[cellPath];
1913
- const rowDisabled = isEntityDisabled(entity);
1914
-
1915
- if (rowDisabled) return;
1916
- let newSelectedCells = {
1917
- ...selectedCells
1918
- };
1919
- if (newSelectedCells[cellId] && !event.shiftKey) {
1920
- // don't deselect if editing
1921
- if (reduxFormEditingCell === cellId) return;
1922
- if (event.metaKey) {
1923
- delete newSelectedCells[cellId];
1924
- } else {
1925
- newSelectedCells = {};
1926
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1927
- }
1928
- } else {
1929
- if (event.metaKey) {
1930
- if (isEmpty(newSelectedCells)) {
1931
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1932
- } else {
1933
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1934
- if (primarySelectedCellId)
1935
- newSelectedCells[primarySelectedCellId] = true;
1936
- }
1937
- } else if (event.shiftKey) {
1938
- if (primarySelectedCellId) {
1939
- const [rowId, colPath] = primarySelectedCellId.split(":");
1940
- const primaryRowIndex = entities.findIndex((e, i) => {
1941
- return getIdOrCodeOrIndex(e, i) === rowId;
1942
- });
1943
- const fieldToIndex = getFieldPathToIndex(schema);
1944
- const primaryColIndex = fieldToIndex[colPath];
1945
-
1946
- if (primaryRowIndex === -1 || primaryColIndex === -1) {
1947
- newSelectedCells = {};
1948
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1949
- } else {
1950
- const minRowIndex = min([primaryRowIndex, rowIndex]);
1951
- const minColIndex = min([primaryColIndex, columnIndex]);
1952
- const maxRowIndex = max([primaryRowIndex, rowIndex]);
1953
- const maxColIndex = max([primaryColIndex, columnIndex]);
1954
- const entitiesBetweenRows = entities.slice(
1955
- minRowIndex,
1956
- maxRowIndex + 1
1957
- );
1958
- const fieldsBetweenCols = schema.fields.slice(
1959
- minColIndex,
1960
- maxColIndex + 1
1961
- );
1962
- newSelectedCells = {
1963
- [primarySelectedCellId]: PRIMARY_SELECTED_VAL
1964
- };
1965
- entitiesBetweenRows.forEach(e => {
1966
- const rowId = getIdOrCodeOrIndex(e, entities.indexOf(e));
1967
- fieldsBetweenCols.forEach(f => {
1968
- const cellId = `${rowId}:${f.path}`;
1969
- if (!newSelectedCells[cellId])
1970
- newSelectedCells[cellId] = true;
1971
- });
1972
- });
1973
- // newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1974
- // newSelectedCells[primarySelectedCellId] = true;
1975
- }
1976
- } else {
1977
- newSelectedCells = {};
1978
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1979
- }
1980
- } else {
1981
- newSelectedCells = {};
1982
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
1983
- }
1984
- }
1985
-
1986
- setSelectedCells(newSelectedCells);
1987
- },
1988
- [
1989
- entities,
1990
- isEntityDisabled,
1991
- primarySelectedCellId,
1992
- reduxFormEditingCell,
1993
- schema,
1994
- selectedCells
1995
- ]
1996
- );
1997
-
1998
- const insertRows = useCallback(
1999
- ({ above, numRows = 1, appendToBottom } = {}) => {
2000
- const [rowId] = primarySelectedCellId?.split(":") || [];
2001
- updateEntitiesHelper(entities, entities => {
2002
- const newEntities = times(numRows).map(() => ({ id: nanoid() }));
2003
-
2004
- const indexToInsert = entities.findIndex((e, i) => {
2005
- return getIdOrCodeOrIndex(e, i) === rowId;
2006
- });
2007
- const insertIndex = above ? indexToInsert : indexToInsert + 1;
2008
- const insertIndexToUse = appendToBottom ? entities.length : insertIndex;
2009
- let { newEnts, validationErrors } = formatAndValidateEntities(
2010
- newEntities,
2011
- {
2012
- useDefaultValues: true,
2013
- indexToStartAt: insertIndexToUse
2014
- }
2015
- );
2016
-
2017
- newEnts = newEnts.map(e => ({
2018
- ...e,
2019
- _isClean: true
2020
- }));
2021
- updateValidation(entities, {
2022
- ...reduxFormCellValidation,
2023
- ...validationErrors
2024
- });
2025
-
2026
- entities.splice(insertIndexToUse, 0, ...newEnts);
2027
- });
2028
- refocusTable();
2029
- },
2030
- [
2031
- entities,
2032
- formatAndValidateEntities,
2033
- primarySelectedCellId,
2034
- reduxFormCellValidation,
2035
- refocusTable,
2036
- updateEntitiesHelper,
2037
- updateValidation
2038
- ]
2039
- );
2040
-
2041
- const showContextMenu = useCallback(
2042
- (e, { idMap, selectedCells } = {}) => {
2043
- let selectedRecords;
2044
- if (isCellEditable) {
2045
- const rowIds = {};
2046
- Object.keys(selectedCells).forEach(cellKey => {
2047
- const [rowId] = cellKey.split(":");
2048
- rowIds[rowId] = true;
2049
- });
2050
- selectedRecords = entities.filter(
2051
- ent => rowIds[getIdOrCodeOrIndex(ent)]
2052
- );
2053
- } else {
2054
- selectedRecords = getRecordsFromIdMap(idMap);
2055
- }
2056
-
2057
- const itemsToRender = contextMenu({
2058
- selectedRecords,
2059
- history
2060
- });
2061
- if (!itemsToRender && !isCopyable) return null;
2062
- const copyMenuItems = [];
2063
-
2064
- e.persist();
2065
- if (isCopyable) {
2066
- //compute the cellWrapper here so we don't lose access to it
2067
- const cellWrapper =
2068
- e.target.querySelector(".tg-cell-wrapper") ||
2069
- e.target.closest(".tg-cell-wrapper");
2070
- if (cellWrapper) {
2071
- copyMenuItems.push(
2072
- <MenuItem
2073
- key="copyCell"
2074
- onClick={() => {
2075
- //TODOCOPY: we need to make sure that the cell copy is being used by the row copy.. right now we have 2 different things going on
2076
- //do we need to be able to copy hidden cells? It seems like it should just copy what's on the page..?
2077
- const specificColumn = cellWrapper.getAttribute("data-test");
2078
- handleCopyRows([cellWrapper.closest(".rt-tr")], {
2079
- specificColumn,
2080
- onFinishMsg: "Cell copied"
2081
- });
2082
- const [text, jsonText] = getCellCopyText(cellWrapper);
2083
- handleCopyHelper(text, jsonText);
2084
- }}
2085
- text="Cell"
2086
- />
2087
- );
2088
-
2089
- copyMenuItems.push(
2090
- <MenuItem
2091
- key="copyColumn"
2092
- onClick={() => {
2093
- handleCopyColumn(e, cellWrapper);
2094
- }}
2095
- text="Column"
2096
- />
2097
- );
2098
- if (selectedRecords.length > 1) {
2099
- copyMenuItems.push(
2100
- <MenuItem
2101
- key="copyColumnSelected"
2102
- onClick={() => {
2103
- handleCopyColumn(e, cellWrapper, selectedRecords);
2104
- }}
2105
- text="Column (Selected)"
2106
- />
2107
- );
2108
- }
2109
- }
2110
- if (selectedRecords.length === 0 || selectedRecords.length === 1) {
2111
- //compute the row here so we don't lose access to it
2112
- const cell =
2113
- e.target.querySelector(".tg-cell-wrapper") ||
2114
- e.target.closest(".tg-cell-wrapper") ||
2115
- e.target.closest(".rt-td");
2116
- const row = cell.closest(".rt-tr");
2117
- copyMenuItems.push(
2118
- <MenuItem
2119
- key="copySelectedRows"
2120
- onClick={() => {
2121
- handleCopyRows([row]);
2122
- // loop through each cell in the row
2123
- }}
2124
- text="Row"
2125
- />
2126
- );
2127
- } else if (selectedRecords.length > 1) {
2128
- copyMenuItems.push(
2129
- <MenuItem
2130
- key="copySelectedRows"
2131
- onClick={() => {
2132
- handleCopySelectedRows(selectedRecords, e);
2133
- // loop through each cell in the row
2134
- }}
2135
- text="Rows"
2136
- />
2137
- );
2138
- }
2139
- copyMenuItems.push(
2140
- <MenuItem
2141
- key="copyFullTableRows"
2142
- onClick={() => {
2143
- handleCopyTable(e);
2144
- // loop through each cell in the row
2145
- }}
2146
- text="Table"
2147
- />
2148
- );
2149
- }
2150
- const selectedRowIds = Object.keys(selectedCells).map(cellId => {
2151
- const [rowId] = cellId.split(":");
2152
- return rowId;
2153
- });
2154
-
2155
- const menu = (
2156
- <Menu>
2157
- {itemsToRender}
2158
- {copyMenuItems.length && (
2159
- <MenuItem icon="clipboard" key="copyOpts" text="Copy">
2160
- {copyMenuItems}
2161
- </MenuItem>
2162
- )}
2163
- {isCellEditable && (
2164
- <>
2165
- <MenuItem
2166
- icon="add-row-top"
2167
- text="Add Row Above"
2168
- key="addRowAbove"
2169
- onClick={() => {
2170
- insertRows({ above: true });
2171
- }}
2172
- />
2173
- <MenuItem
2174
- icon="add-row-top"
2175
- text="Add Row Below"
2176
- key="addRowBelow"
2177
- onClick={() => {
2178
- insertRows({});
2179
- }}
2180
- />
2181
- <MenuItem
2182
- icon="remove"
2183
- text={`Remove Row${selectedRowIds.length > 1 ? "s" : ""}`}
2184
- key="removeRow"
2185
- onClick={() => {
2186
- const selectedRowIds = Object.keys(selectedCells).map(
2187
- cellId => {
2188
- const [rowId] = cellId.split(":");
2189
- return rowId;
2190
- }
2191
- );
2192
- updateEntitiesHelper(entities, entities => {
2193
- const ents = entities.filter(
2194
- (e, i) =>
2195
- !selectedRowIds.includes(getIdOrCodeOrIndex(e, i))
2196
- );
2197
- updateValidation(
2198
- ents,
2199
- omitBy(reduxFormCellValidation, (v, cellId) =>
2200
- selectedRowIds.includes(cellId.split(":")[0])
2201
- )
2202
- );
2203
- return ents;
2204
- });
2205
- refocusTable();
2206
- }}
2207
- />
2208
- </>
2209
- )}
2210
- </Menu>
2211
- );
2212
- ContextMenu.show(menu, { left: e.clientX, top: e.clientY });
2213
- },
2214
- [
2215
- contextMenu,
2216
- entities,
2217
- handleCopySelectedRows,
2218
- history,
2219
- insertRows,
2220
- isCellEditable,
2221
- isCopyable,
2222
- reduxFormCellValidation,
2223
- refocusTable,
2224
- updateEntitiesHelper,
2225
- updateValidation
2226
- ]
2227
- );
2228
-
2229
- const getTableRowProps = useCallback(
2230
- (state, rowInfo) => {
2231
- if (!rowInfo) {
2232
- return {
2233
- className: "no-row-data"
2234
- };
2235
- }
2236
- const entity = rowInfo.original;
2237
- const rowId = getIdOrCodeOrIndex(entity, rowInfo.index);
2238
- const rowSelected = reduxFormSelectedEntityIdMap[rowId];
2239
- const isExpanded = expandedEntityIdMap[rowId];
2240
- const rowDisabled = isEntityDisabled(entity);
2241
- const dataId = entity.id || entity.code;
2242
- return {
2243
- onClick: e => {
2244
- if (isCellEditable) return;
2245
- // if checkboxes are activated or row expander is clicked don't select row
2246
- if (e.target.matches(".tg-expander, .tg-expander *")) {
2247
- setExpandedEntityIdMap(prev => ({ ...prev, [rowId]: !isExpanded }));
2248
- return;
2249
- } else if (
2250
- e.target.closest(".tg-react-table-checkbox-cell-container")
2251
- ) {
2252
- return;
2253
- } else if (mustClickCheckboxToSelect) {
2254
- return;
2255
- }
2256
- if (e.detail > 1) {
2257
- return; //cancel multiple quick clicks
2258
- }
2259
- rowClick(e, rowInfo, entities, {
2260
- reduxFormSelectedEntityIdMap,
2261
- isSingleSelect,
2262
- noSelect,
2263
- onRowClick,
2264
- isEntityDisabled,
2265
- withCheckboxes,
2266
- onDeselect,
2267
- onSingleRowSelect,
2268
- onMultiRowSelect,
2269
- noDeselectAll,
2270
- onRowSelect,
2271
- change
2272
- });
2273
- },
2274
- //row right click
2275
- onContextMenu: e => {
2276
- e.preventDefault();
2277
- if (rowId === undefined || rowDisabled || isCellEditable) return;
2278
- const oldIdMap = cloneDeep(reduxFormSelectedEntityIdMap) || {};
2279
- let newIdMap;
2280
- if (withCheckboxes) {
2281
- newIdMap = oldIdMap;
2282
- } else {
2283
- // if we are not using checkboxes we need to make sure
2284
- // that the id of the record gets added to the id map
2285
- newIdMap = oldIdMap[rowId] ? oldIdMap : { [rowId]: { entity } };
2286
-
2287
- // tgreen: this will refresh the selection with fresh data. The entities in redux might not be up to date
2288
- const keyedEntities = keyBy(entities, getIdOrCodeOrIndex);
2289
- forEach(newIdMap, (val, key) => {
2290
- const freshEntity = keyedEntities[key];
2291
- if (freshEntity) {
2292
- newIdMap[key] = { ...newIdMap[key], entity: freshEntity };
2293
- }
2294
- });
2295
- finalizeSelection({
2296
- idMap: newIdMap,
2297
- entities,
2298
- props: {
2299
- onDeselect,
2300
- onSingleRowSelect,
2301
- onMultiRowSelect,
2302
- noDeselectAll,
2303
- onRowSelect,
2304
- noSelect,
2305
- change
2306
- }
2307
- });
2308
- }
2309
- showContextMenu(e, { idMap: newIdMap, selectedCells });
2310
- },
2311
- className: classNames(
2312
- "with-row-data",
2313
- getRowClassName && getRowClassName(rowInfo, state),
2314
- {
2315
- disabled: rowDisabled,
2316
- selected: rowSelected && !withCheckboxes,
2317
- "rt-tr-last-row": rowInfo.index === entities.length - 1
2318
- }
2319
- ),
2320
- "data-test-id": dataId === undefined ? rowInfo.index : dataId,
2321
- "data-index": rowInfo.index,
2322
- "data-tip": typeof rowDisabled === "string" ? rowDisabled : undefined,
2323
- onDoubleClick: e => {
2324
- if (rowDisabled) return;
2325
- onDoubleClick &&
2326
- onDoubleClick(rowInfo.original, rowInfo.index, history, e);
2327
- }
2328
- };
2329
- },
2330
- [
2331
- change,
2332
- entities,
2333
- expandedEntityIdMap,
2334
- getRowClassName,
2335
- history,
2336
- isCellEditable,
2337
- isEntityDisabled,
2338
- isSingleSelect,
2339
- mustClickCheckboxToSelect,
2340
- noDeselectAll,
2341
- noSelect,
2342
- onDeselect,
2343
- onDoubleClick,
2344
- onMultiRowSelect,
2345
- onRowClick,
2346
- onRowSelect,
2347
- onSingleRowSelect,
2348
- reduxFormSelectedEntityIdMap,
2349
- selectedCells,
2350
- showContextMenu,
2351
- withCheckboxes
2352
- ]
2353
- );
2354
-
2355
- const getTableCellProps = useCallback(
2356
- (state, rowInfo, column) => {
2357
- if (!isCellEditable) return {}; //only allow cell selection to do stuff here
2358
- if (!rowInfo) return {};
2359
- if (!reduxFormCellValidation) return {};
2360
- const entity = rowInfo.original;
2361
- const rowIndex = rowInfo.index;
2362
- const rowId = getIdOrCodeOrIndex(entity, rowIndex);
2363
- const {
2364
- cellId,
2365
- cellIdAbove,
2366
- cellIdToRight,
2367
- cellIdBelow,
2368
- cellIdToLeft,
2369
- rowDisabled,
2370
- columnIndex
2371
- } = getCellInfo({
2372
- columnIndex: column.index,
2373
- columnPath: column.path,
2374
- rowId,
2375
- schema,
2376
- entities,
2377
- rowIndex,
2378
- isEntityDisabled,
2379
- entity
2380
- });
2381
-
2382
- const _isClean =
2383
- (entity._isClean && doNotValidateUntouchedRows) ||
2384
- isEntityClean(entity);
2385
-
2386
- const err = !_isClean && reduxFormCellValidation[cellId];
2387
- let selectedTopBorder,
2388
- selectedRightBorder,
2389
- selectedBottomBorder,
2390
- selectedLeftBorder;
2391
- if (selectedCells[cellId]) {
2392
- selectedTopBorder = !selectedCells[cellIdAbove];
2393
- selectedRightBorder = !selectedCells[cellIdToRight];
2394
- selectedBottomBorder = !selectedCells[cellIdBelow];
2395
- selectedLeftBorder = !selectedCells[cellIdToLeft];
2396
- }
2397
- const isPrimarySelected = selectedCells[cellId] === PRIMARY_SELECTED_VAL;
2398
- const className = classNames({
2399
- isSelectedCell: selectedCells[cellId],
2400
- isPrimarySelected,
2401
- isSecondarySelected: selectedCells[cellId] === true,
2402
- noSelectedTopBorder: !selectedTopBorder,
2403
- isCleanRow: _isClean,
2404
- noSelectedRightBorder: !selectedRightBorder,
2405
- noSelectedBottomBorder: !selectedBottomBorder,
2406
- noSelectedLeftBorder: !selectedLeftBorder,
2407
- isDropdownCell: column.type === "dropdown",
2408
- isEditingCell: reduxFormEditingCell === cellId,
2409
- hasCellError: !!err,
2410
- "no-data-tip": selectedCells[cellId]
2411
- });
2412
- return {
2413
- onDoubleClick: () => {
2414
- // cell double click
2415
- if (rowDisabled) return;
2416
- startCellEdit(cellId);
2417
- },
2418
- ...(err && {
2419
- "data-tip": err?.message || err,
2420
- "data-no-child-data-tip": true
2421
- }),
2422
- onContextMenu: e => {
2423
- const newSelectedCells = { ...selectedCells };
2424
- if (!isPrimarySelected) {
2425
- if (primarySelectedCellId) {
2426
- newSelectedCells[primarySelectedCellId] = true;
2427
- }
2428
- newSelectedCells[cellId] = PRIMARY_SELECTED_VAL;
2429
- setSelectedCells(newSelectedCells);
2430
- }
2431
- showContextMenu(e, { selectedCells: newSelectedCells });
2432
- },
2433
- onClick: event => {
2434
- handleCellClick({
2435
- event,
2436
- cellId,
2437
- rowDisabled,
2438
- rowIndex,
2439
- columnIndex
2440
- });
2441
- },
2442
- className
2443
- };
2444
- },
2445
- [
2446
- doNotValidateUntouchedRows,
2447
- entities,
2448
- handleCellClick,
2449
- isCellEditable,
2450
- isEntityDisabled,
2451
- primarySelectedCellId,
2452
- reduxFormCellValidation,
2453
- reduxFormEditingCell,
2454
- schema,
2455
- selectedCells,
2456
- showContextMenu,
2457
- startCellEdit
2458
- ]
2459
- );
2460
-
2461
- if (withSelectAll && !safeQuery) {
2462
- throw new Error("safeQuery is needed for selecting all table records");
2463
- }
2464
-
2465
- let compactClassName = "";
2466
- if (compactPaging) {
2467
- compactClassName += " tg-compact-paging";
2468
- }
2469
- compactClassName += extraCompact
2470
- ? " tg-extra-compact-table"
2471
- : compact
2472
- ? " tg-compact-table"
2473
- : "";
2474
-
2475
- const hasFilters =
2476
- filters.length ||
2477
- searchTerm ||
2478
- schema.fields.some(
2479
- field => field.filterIsActive && field.filterIsActive(currentParams)
2480
- );
2481
-
2482
- const additionalFilterKeys = schema.fields.reduce((acc, field) => {
2483
- if (field.filterKey) acc.push(field.filterKey);
2484
- return acc;
2485
- }, []);
2486
-
2487
- const filtersOnNonDisplayedFields = useMemo(() => {
2488
- const _filtersOnNonDisplayedFields = [];
2489
- if (filters && filters.length) {
2490
- schema.fields.forEach(field => {
2491
- const ccDisplayName = getCCDisplayName(field);
2492
- if (field.isHidden) {
2493
- filters.forEach(filter => {
2494
- if (filter.filterOn === ccDisplayName) {
2495
- _filtersOnNonDisplayedFields.push({
2496
- ...filter,
2497
- displayName: field.displayName
2498
- });
2499
- }
2500
- });
2501
- }
2502
- });
2503
- }
2504
- return _filtersOnNonDisplayedFields;
2505
- }, [filters, schema.fields]);
2506
-
2507
- const numRows = isInfinite ? entities.length : pageSize;
2508
- const idMap = useMemo(
2509
- () => reduxFormSelectedEntityIdMap || {},
2510
- [reduxFormSelectedEntityIdMap]
2511
- );
2512
- const selectedRowCount = Object.keys(idMap).filter(key => idMap[key]).length;
2513
-
2514
- let rowsToShow = doNotShowEmptyRows
2515
- ? Math.min(numRows, entities.length)
2516
- : numRows;
2517
- // if there are no entities then provide enough space to show
2518
- // no rows found message
2519
- if (entities.length === 0 && rowsToShow < 3) rowsToShow = 3;
2520
- const expandedRows = entities.reduce((acc, row, index) => {
2521
- const rowId = getIdOrCodeOrIndex(row, index);
2522
- acc[index] = expandedEntityIdMap[rowId];
2523
- return acc;
2524
- }, {});
2525
-
2526
- const showHeader = (withTitle || withSearch || children) && !noHeader;
2527
- const toggleFullscreenButton = (
2528
- <Button
2529
- icon="fullscreen"
2530
- active={fullscreen}
2531
- minimal
2532
- onClick={() => setFullscreen(prev => !prev)}
2533
- />
2534
- );
2535
-
2536
- const { showSelectAll, showClearAll } = useMemo(() => {
2537
- let _showSelectAll = false;
2538
- let _showClearAll = false;
2539
- // we want to show select all if every row on the current page is selected
2540
- // and not every row across all pages are already selected.
2541
- if (!isInfinite) {
2542
- const canShowSelectAll =
2543
- withSelectAll ||
2544
- (entitiesAcrossPages && numRows < entitiesAcrossPages.length);
2545
- if (canShowSelectAll) {
2546
- // could all be disabled
2547
- let atLeastOneRowOnCurrentPageSelected = false;
2548
- const allRowsOnCurrentPageSelected = entities.every(e => {
2549
- const rowId = getIdOrCodeOrIndex(e);
2550
- const selected = idMap[rowId] || isEntityDisabled(e);
2551
- if (selected) atLeastOneRowOnCurrentPageSelected = true;
2552
- return selected;
2553
- });
2554
- if (
2555
- atLeastOneRowOnCurrentPageSelected &&
2556
- allRowsOnCurrentPageSelected
2557
- ) {
2558
- let everyEntitySelected;
2559
- if (isLocalCall) {
2560
- everyEntitySelected = entitiesAcrossPages.every(e => {
2561
- const rowId = getIdOrCodeOrIndex(e);
2562
- return idMap[rowId] || isEntityDisabled(e);
2563
- });
2564
- } else {
2565
- everyEntitySelected = entityCount <= selectedRowCount;
2566
- }
2567
- if (everyEntitySelected) {
2568
- _showClearAll = selectedRowCount;
2569
- }
2570
- // only show if not all selected
2571
- _showSelectAll = !everyEntitySelected;
2572
- }
2573
- }
2574
- }
2575
- return { showSelectAll: _showSelectAll, showClearAll: _showClearAll };
2576
- }, [
2577
- entities,
2578
- entitiesAcrossPages,
2579
- entityCount,
2580
- idMap,
2581
- isEntityDisabled,
2582
- isInfinite,
2583
- isLocalCall,
2584
- numRows,
2585
- selectedRowCount,
2586
- withSelectAll
2587
- ]);
2588
-
2589
- const showNumSelected = !noSelect && !isSingleSelect && !hideSelectedCount;
2590
- const selectedAndTotalMessage = useMemo(() => {
2591
- let _selectedAndTotalMessage = "";
2592
- if (showNumSelected) {
2593
- _selectedAndTotalMessage += `${selectedRowCount} Selected `;
2594
- }
2595
- if (showCount && showNumSelected) {
2596
- _selectedAndTotalMessage += `/ `;
2597
- }
2598
- if (showCount) {
2599
- _selectedAndTotalMessage += `${entityCount || 0} Total`;
2600
- }
2601
- if (_selectedAndTotalMessage) {
2602
- _selectedAndTotalMessage = <div>{_selectedAndTotalMessage}</div>;
2603
- }
2604
- return _selectedAndTotalMessage;
2605
- }, [entityCount, selectedRowCount, showCount, showNumSelected]);
2606
-
2607
- const shouldShowPaging =
2608
- !isInfinite &&
2609
- withPaging &&
2610
- (hidePageSizeWhenPossible ? entityCount > pageSize : true);
2611
-
2612
- const SubComponentToUse = useMemo(() => {
2613
- if (SubComponent) {
2614
- return row => {
2615
- let shouldShow = true;
2616
- if (shouldShowSubComponent) {
2617
- shouldShow = shouldShowSubComponent(row.original);
2618
- }
2619
- if (shouldShow) {
2620
- return SubComponent(row);
2621
- }
2622
- };
2623
- }
2624
- return;
2625
- }, [SubComponent, shouldShowSubComponent]);
2626
-
2627
- const nonDisplayedFilterComp = useMemo(() => {
2628
- if (filtersOnNonDisplayedFields.length) {
2629
- const content = filtersOnNonDisplayedFields.map(
2630
- ({ displayName, path, selectedFilter, filterValue }) => {
2631
- let filterValToDisplay = filterValue;
2632
- if (selectedFilter === "inList") {
2633
- filterValToDisplay = Array.isArray(filterValToDisplay)
2634
- ? filterValToDisplay
2635
- : filterValToDisplay && filterValToDisplay.split(";");
2636
- }
2637
- if (Array.isArray(filterValToDisplay)) {
2638
- filterValToDisplay = filterValToDisplay.join(", ");
2639
- }
2640
- return (
2641
- <div
2642
- key={displayName || startCase(camelCase(path))}
2643
- className="tg-filter-on-non-displayed-field"
2644
- >
2645
- {displayName || startCase(camelCase(path))}{" "}
2646
- {lowerCase(selectedFilter)} {filterValToDisplay}
2647
- </div>
2648
- );
2649
- }
2650
- );
2651
- return (
2652
- <div style={{ marginRight: 5, marginLeft: "auto" }}>
2653
- <Tooltip
2654
- content={
2655
- <div>
2656
- Active filters on hidden columns:
2657
- <br />
2658
- <br />
2659
- {content}
2660
- </div>
2661
- }
2662
- >
2663
- <Icon icon="filter-list" />
2664
- </Tooltip>
2665
- </div>
2666
- );
2667
- }
2668
- return null;
2669
- }, [filtersOnNonDisplayedFields]);
2670
-
2671
- const filteredEnts = useMemo(() => {
2672
- if (onlyShowRowsWErrors) {
2673
- const rowToErrorMap = {};
2674
- forEach(reduxFormCellValidation, (err, cellId) => {
2675
- if (err) {
2676
- const [rowId] = cellId.split(":");
2677
- rowToErrorMap[rowId] = true;
2678
- }
2679
- });
2680
- return entities.filter(e => {
2681
- return rowToErrorMap[e.id];
2682
- });
2683
- }
2684
- return entities;
2685
- }, [entities, onlyShowRowsWErrors, reduxFormCellValidation]);
2686
-
2687
- const renderColumns = useColumns({
2688
- addFilters,
2689
- cellRenderer,
2690
- columns,
2691
- currentParams,
2692
- compact,
2693
- editingCellSelectAll,
2694
- entities,
2695
- expandedEntityIdMap,
2696
- extraCompact,
2697
- filters,
2698
- formName,
2699
- getCellHoverText,
2700
- isCellEditable,
2701
- isEntityDisabled,
2702
- isLocalCall,
2703
- isSimple,
2704
- isSingleSelect,
2705
- isSelectionARectangle,
2706
- noDeselectAll,
2707
- noSelect,
2708
- noUserSelect,
2709
- onDeselect,
2710
- onMultiRowSelect,
2711
- onRowClick,
2712
- onRowSelect,
2713
- onSingleRowSelect,
2714
- order,
2715
- primarySelectedCellId,
2716
- reduxFormCellValidation,
2717
- reduxFormSelectedEntityIdMap,
2718
- refocusTable,
2719
- removeSingleFilter,
2720
- schema,
2721
- selectedCells,
2722
- setExpandedEntityIdMap,
2723
- setNewParams,
2724
- setOrder,
2725
- setSelectedCells,
2726
- shouldShowSubComponent,
2727
- startCellEdit,
2728
- SubComponent,
2729
- tableRef,
2730
- updateEntitiesHelper,
2731
- updateValidation,
2732
- withCheckboxes,
2733
- withExpandAndCollapseAllButton,
2734
- withFilter,
2735
- withSort,
2736
- recordIdToIsVisibleMap,
2737
- setRecordIdToIsVisibleMap
2738
- });
2739
-
2740
- const scrollToTop = useCallback(
2741
- () =>
2742
- tableRef.current?.tableRef?.children?.[0]?.children?.[0]?.scrollIntoView(),
2743
- []
2744
- );
2745
-
2746
- const reactTable = useMemo(
2747
- () => (
2748
- <ReactTable
2749
- data={filteredEnts}
2750
- ref={tableRef}
2751
- className={classNames({
2752
- isCellEditable,
2753
- "tg-table-loading": isLoading,
2754
- "tg-table-disabled": disabled
2755
- })}
2756
- itemSizeEstimator={
2757
- extraCompact
2758
- ? itemSizeEstimators.compact
2759
- : compact
2760
- ? itemSizeEstimators.normal
2761
- : itemSizeEstimators.comfortable
2762
- }
2763
- TfootComponent={() => {
2764
- return <button>hasdfasdf</button>;
2765
- }}
2766
- // We should try to not give all the props to the render column
2767
- columns={renderColumns}
2768
- pageSize={rowsToShow}
2769
- expanded={expandedRows}
2770
- showPagination={false}
2771
- sortable={false}
2772
- loading={isLoading || disabled}
2773
- defaultResized={resized}
2774
- onResizedChange={(newResized = []) => {
2775
- const resizedToUse = newResized.map(column => {
2776
- // have a min width of 50 so that columns don't disappear
2777
- if (column.value < 50) {
2778
- return {
2779
- ...column,
2780
- value: 50
2781
- };
2782
- } else {
2783
- return column;
2784
- }
2785
- });
2786
- resizePersist(resizedToUse);
2787
- }}
2788
- TheadComponent={TheadComponent}
2789
- ThComponent={ThComponent}
2790
- getTrGroupProps={getTableRowProps}
2791
- getTdProps={getTableCellProps}
2792
- NoDataComponent={({ children }) =>
2793
- isLoading ? null : (
2794
- <div className="rt-noData">{noRowsFoundMessage || children}</div>
2795
- )
2796
- }
2797
- LoadingComponent={({ loadingText, loading }) => (
2798
- <DisabledLoadingComponent
2799
- loading={loading}
2800
- loadingText={loadingText}
2801
- disabled={disabled}
2802
- />
2803
- )}
2804
- style={{
2805
- maxHeight,
2806
- minHeight: 150,
2807
- ...style
2808
- }}
2809
- SubComponent={SubComponentToUse}
2810
- {...ReactTableProps}
2811
- />
2812
- ),
2813
- [
2814
- ReactTableProps,
2815
- SubComponentToUse,
2816
- TheadComponent,
2817
- compact,
2818
- disabled,
2819
- expandedRows,
2820
- extraCompact,
2821
- filteredEnts,
2822
- getTableCellProps,
2823
- getTableRowProps,
2824
- isCellEditable,
2825
- isLoading,
2826
- maxHeight,
2827
- noRowsFoundMessage,
2828
- renderColumns,
2829
- resizePersist,
2830
- resized,
2831
- rowsToShow,
2832
- style
2833
- ]
2834
- );
2835
-
2836
- return (
2837
- <div tabIndex="1" onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}>
2838
- <div
2839
- className={classNames(
2840
- "data-table-container",
2841
- extraClasses,
2842
- className,
2843
- compactClassName,
2844
- {
2845
- fullscreen,
2846
- in_cypress_test: window.Cypress, //tnr: this is a hack to make cypress be able to correctly click the table without the sticky header getting in the way. remove me once https://github.com/cypress-io/cypress/issues/871 is fixed
2847
- "dt-isViewable": isViewable,
2848
- "dt-minimalStyle": minimalStyle,
2849
- "no-padding": noPadding,
2850
- "hide-column-header": hideColumnHeader
2851
- }
2852
- )}
2853
- >
2854
- <div
2855
- className="data-table-container-inner"
2856
- {...(isCellEditable && {
2857
- tabIndex: -1,
2858
- onKeyDown: e => {
2859
- const isTabKey = e.key === "Tab";
2860
- const isArrowKey = e.key.startsWith("Arrow");
2861
- if ((isArrowKey && e.target?.tagName !== "INPUT") || isTabKey) {
2862
- const left = e.key === "ArrowLeft";
2863
- const up = e.key === "ArrowUp";
2864
- const down = e.key === "ArrowDown" || e.key === "Enter";
2865
- let cellIdToUse = primarySelectedCellId;
2866
- const pathToIndex = getFieldPathToIndex(schema);
2867
- const entityMap = getEntityIdToEntity(entities);
2868
- if (!cellIdToUse) return;
2869
- const {
2870
- isRect,
2871
- firstCellIndex,
2872
- lastCellIndex,
2873
- lastRowIndex,
2874
- firstRowIndex
2875
- } = isSelectionARectangle();
2876
-
2877
- if (isRect) {
2878
- const [rowId, columnPath] = cellIdToUse.split(":");
2879
-
2880
- const columnIndex = pathToIndex[columnPath];
2881
- const indexToPath = invert(pathToIndex);
2882
- // we want to grab the cell opposite to the primary selected cell
2883
- if (
2884
- firstCellIndex === columnIndex &&
2885
- firstRowIndex === entityMap[rowId]?.i
2886
- ) {
2887
- cellIdToUse = `${entities[lastRowIndex].id}:${indexToPath[lastCellIndex]}`;
2888
- } else if (
2889
- firstCellIndex === columnIndex &&
2890
- lastRowIndex === entityMap[rowId]?.i
2891
- ) {
2892
- cellIdToUse = `${entities[firstRowIndex].id}:${indexToPath[lastCellIndex]}`;
2893
- } else if (
2894
- lastCellIndex === columnIndex &&
2895
- firstRowIndex === entityMap[rowId]?.i
2896
- ) {
2897
- cellIdToUse = `${entities[lastRowIndex].id}:${indexToPath[firstCellIndex]}`;
2898
- } else {
2899
- cellIdToUse = `${entities[firstRowIndex].id}:${indexToPath[firstCellIndex]}`;
2900
- }
2901
- }
2902
- if (!cellIdToUse) return;
2903
- const [rowId, columnPath] = cellIdToUse.split(":");
2904
- const columnIndex = pathToIndex[columnPath];
2905
-
2906
- const { i: rowIndex } = entityMap[rowId];
2907
-
2908
- const {
2909
- cellIdAbove,
2910
- cellIdToRight,
2911
- cellIdBelow,
2912
- cellIdToLeft
2913
- } = getCellInfo({
2914
- columnIndex,
2915
- columnPath,
2916
- rowId,
2917
- schema,
2918
- entities,
2919
- rowIndex,
2920
- isEntityDisabled,
2921
- entity: entityMap[rowId].e
2922
- });
2923
- const nextCellId = up
2924
- ? cellIdAbove
2925
- : down
2926
- ? cellIdBelow
2927
- : left
2928
- ? cellIdToLeft
2929
- : cellIdToRight;
2930
-
2931
- e.stopPropagation();
2932
- e.preventDefault();
2933
- if (!nextCellId) return;
2934
- // this.handleCellBlur();
2935
- // this.finishCellEdit
2936
- if (
2937
- document.activeElement?.parentElement?.classList.contains(
2938
- "rt-td"
2939
- )
2940
- ) {
2941
- document.activeElement.blur();
2942
- }
2943
- handleCellClick({
2944
- event: e,
2945
- cellId: nextCellId
2946
- });
2947
- }
2948
- if (e.metaKey || e.ctrlKey || e.altKey) return;
2949
- if (!primarySelectedCellId) return;
2950
- const entityIdToEntity = getEntityIdToEntity(entities);
2951
- const [rowId] = primarySelectedCellId.split(":");
2952
- if (!rowId) return;
2953
- const entity = entityIdToEntity[rowId].e;
2954
- if (!entity) return;
2955
- const rowDisabled = isEntityDisabled(entity);
2956
- const isNum = e.code?.startsWith("Digit");
2957
- const isLetter = e.code?.startsWith("Key");
2958
- if (!isNum && !isLetter) {
2959
- return;
2960
- }
2961
- if (rowDisabled) return;
2962
- e.stopPropagation();
2963
- startCellEdit(primarySelectedCellId, e.key);
2964
- }
2965
- })}
2966
- >
2967
- {isCellEditable && entities.length > 50 && (
2968
- // test for this!!
2969
- <SwitchField
2970
- name="onlyShowRowsWErrors"
2971
- inlineLabel={true}
2972
- label="Only Show Rows With Errors"
2973
- onChange={e => {
2974
- setOnlyShowRowsWErrors(e.target.value);
2975
- }}
2976
- />
2977
- )}
2978
- {showHeader && (
2979
- <div className="data-table-header">
2980
- <div className="data-table-title-and-buttons">
2981
- {tableName && withTitle && (
2982
- <span className="data-table-title">{tableName}</span>
2983
- )}
2984
- {children}
2985
- {topLeftItems}
2986
- </div>
2987
- {errorParsingUrlString && (
2988
- <Callout
2989
- icon="error"
2990
- style={{
2991
- width: "unset"
2992
- }}
2993
- intent={Intent.WARNING}
2994
- >
2995
- Error parsing URL
2996
- </Callout>
2997
- )}
2998
- {nonDisplayedFilterComp}
2999
- {withSearch && (
3000
- <div className="data-table-search-and-clear-filter-container">
3001
- {leftOfSearchBarItems}
3002
- {hasFilters ? (
3003
- <Tooltip content="Clear Filters">
3004
- <Button
3005
- minimal
3006
- intent="danger"
3007
- icon="filter-remove"
3008
- disabled={disabled}
3009
- className="data-table-clear-filters"
3010
- onClick={() => {
3011
- clearFilters(additionalFilterKeys);
3012
- }}
3013
- />
3014
- </Tooltip>
3015
- ) : (
3016
- ""
3017
- )}
3018
- <SearchBar
3019
- noForm={noForm}
3020
- searchInput={currentParams.searchTerm}
3021
- setSearchTerm={setSearchTerm}
3022
- loading={isLoading}
3023
- searchMenuButton={searchMenuButton}
3024
- disabled={disabled}
3025
- autoFocusSearch={autoFocusSearch}
3026
- />
3027
- </div>
3028
- )}
3029
- </div>
3030
- )}
3031
- {subHeader}
3032
- {showSelectAll && !isSingleSelect && (
3033
- <div
3034
- style={{
3035
- marginTop: 5,
3036
- marginBottom: 5,
3037
- display: "flex",
3038
- alignItems: "center"
3039
- }}
3040
- >
3041
- All items on this page are selected.{" "}
3042
- <Button
3043
- small
3044
- minimal
3045
- intent="primary"
3046
- text={`Select all ${
3047
- entityCount || entitiesAcrossPages.length
3048
- } items`}
3049
- loading={selectingAll}
3050
- onClick={async () => {
3051
- if (withSelectAll) {
3052
- // this will be by querying for everything
3053
- setSelectingAll(true);
3054
- try {
3055
- const allEntities = await safeQuery(fragment, {
3056
- variables: {
3057
- filter: variables.filter,
3058
- sort: variables.sort
3059
- },
3060
- canCancel: true
3061
- });
3062
- addEntitiesToSelection(allEntities);
3063
- } catch (error) {
3064
- console.error(`error:`, error);
3065
- window.toastr.error("Error selecting all constructs");
3066
- }
3067
- setSelectingAll(false);
3068
- } else {
3069
- addEntitiesToSelection(entitiesAcrossPages);
3070
- }
3071
- }}
3072
- />
3073
- </div>
3074
- )}
3075
- {showClearAll > 0 && (
3076
- <div
3077
- style={{
3078
- marginTop: 5,
3079
- marginBottom: 5,
3080
- display: "flex",
3081
- alignItems: "center"
3082
- }}
3083
- >
3084
- All {showClearAll} items are selected.
3085
- <Button
3086
- small
3087
- minimal
3088
- intent="primary"
3089
- text="Clear Selection"
3090
- onClick={() => {
3091
- finalizeSelection({
3092
- idMap: {},
3093
- entities,
3094
- props: {
3095
- onDeselect,
3096
- onSingleRowSelect,
3097
- onMultiRowSelect,
3098
- noDeselectAll,
3099
- onRowSelect,
3100
- noSelect,
3101
- change
3102
- }
3103
- });
3104
- }}
3105
- />
3106
- </div>
3107
- )}
3108
- {reactTable}
3109
- {isCellEditable && (
3110
- <div style={{ display: "flex" }}>
3111
- <div
3112
- style={{
3113
- width: "100%",
3114
- display: "flex",
3115
- justifyContent: "center"
3116
- }}
3117
- >
3118
- {!onlyShowRowsWErrors && (
3119
- <Button
3120
- icon="add"
3121
- onClick={() => {
3122
- insertRows({ numRows: 10, appendToBottom: true });
3123
- }}
3124
- minimal
3125
- >
3126
- Add 10 Rows
3127
- </Button>
3128
- )}
3129
- </div>
3130
- <Button
3131
- onClick={e => {
3132
- handleCopyTable(e, { isDownload: true });
3133
- }}
3134
- data-tip="Download Table as CSV"
3135
- minimal
3136
- icon="download"
3137
- />
3138
- </div>
3139
- )}
3140
- {!noFooter && (
3141
- <div
3142
- className="data-table-footer"
3143
- style={{
3144
- justifyContent:
3145
- !showNumSelected && !showCount ? "flex-end" : "space-between"
3146
- }}
3147
- >
3148
- {selectedAndTotalMessage}
3149
- <div style={{ display: "flex", flexWrap: "wrap" }}>
3150
- {additionalFooterButtons}
3151
- {!noFullscreenButton && toggleFullscreenButton}
3152
- {withDisplayOptions && (
3153
- <DisplayOptions
3154
- compact={compact}
3155
- extraCompact={extraCompact}
3156
- disabled={disabled}
3157
- hideDisplayOptionsIcon={hideDisplayOptionsIcon}
3158
- resetDefaultVisibility={resetDefaultVisibility}
3159
- updateColumnVisibility={updateColumnVisibility}
3160
- updateTableDisplayDensity={updateTableDisplayDensity}
3161
- showForcedHiddenColumns={showForcedHiddenColumns}
3162
- setShowForcedHidden={setShowForcedHidden}
3163
- hasOptionForForcedHidden={
3164
- withDisplayOptions && (isSimple || isInfinite)
3165
- }
3166
- schema={schema}
3167
- />
3168
- )}
3169
- {shouldShowPaging && (
3170
- <PagingTool
3171
- controlled_hasNextPage={controlled_hasNextPage}
3172
- controlled_onRefresh={controlled_onRefresh}
3173
- controlled_page={controlled_page}
3174
- controlled_setPage={controlled_setPage}
3175
- controlled_setPageSize={controlled_setPageSize}
3176
- controlled_total={controlled_total}
3177
- disabled={disabled}
3178
- disableSetPageSize={disableSetPageSize}
3179
- entities={entities}
3180
- entityCount={entityCount}
3181
- hideSetPageSize={hideSetPageSize}
3182
- hideTotalPages={hideTotalPages}
3183
- keepSelectionOnPageChange={keepSelectionOnPageChange}
3184
- onRefresh={onRefresh}
3185
- page={page}
3186
- pageSize={pageSize}
3187
- pagingDisabled={pagingDisabled}
3188
- persistPageSize={persistPageSize}
3189
- setPage={setPage}
3190
- setPageSize={setPageSize}
3191
- setSelectedEntityIdMap={newIdMap => {
3192
- change("reduxFormSelectedEntityIdMap", newIdMap);
3193
- }}
3194
- scrollToTop={scrollToTop}
3195
- />
3196
- )}
3197
- </div>
3198
- </div>
3199
- )}
3200
- </div>
3201
- </div>
3202
- </div>
3203
- );
3204
- };
3205
-
3206
- const WrappedDT = dataTableEnhancer(DataTable);
3207
- export default WrappedDT;
3208
- const ConnectedPagingTool = dataTableEnhancer(PagingTool);
3209
- export { ConnectedPagingTool };