@teselagen/ui 0.7.36 → 0.8.1

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