@teselagen/ui 0.8.6-beta.22 → 0.8.6-beta.24

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 (39) hide show
  1. package/DataTable/EditabelCell.d.ts +7 -0
  2. package/DataTable/defaultProps.d.ts +43 -0
  3. package/DataTable/utils/computePresets.d.ts +1 -0
  4. package/DataTable/utils/convertSchema.d.ts +22 -2
  5. package/DataTable/utils/getAllRows.d.ts +1 -1
  6. package/DataTable/utils/handleCopyColumn.d.ts +1 -1
  7. package/DataTable/utils/handleCopyTable.d.ts +1 -1
  8. package/DataTable/utils/isBottomRightCornerOfRectangle.d.ts +10 -8
  9. package/DataTable/utils/isEntityClean.d.ts +3 -1
  10. package/DataTable/utils/primarySelectedValue.d.ts +1 -1
  11. package/DataTable/utils/removeCleanRows.d.ts +11 -3
  12. package/DataTable/utils/selection.d.ts +3 -1
  13. package/DataTable/utils/useDeepEqualMemo.d.ts +1 -0
  14. package/DataTable/utils/useTableEntities.d.ts +17 -4
  15. package/DataTable/utils/useTableParams.d.ts +49 -0
  16. package/index.cjs.js +125 -109
  17. package/index.es.js +125 -109
  18. package/package.json +2 -2
  19. package/src/DataTable/Columns.jsx +945 -0
  20. package/src/DataTable/EditabelCell.js +44 -0
  21. package/src/DataTable/EditabelCell.jsx +44 -0
  22. package/src/DataTable/RenderCell.jsx +191 -0
  23. package/src/DataTable/defaultProps.js +45 -0
  24. package/src/DataTable/index.js +96 -68
  25. package/src/DataTable/utils/computePresets.js +42 -0
  26. package/src/DataTable/utils/convertSchema.ts +79 -0
  27. package/src/DataTable/utils/getAllRows.js +2 -6
  28. package/src/DataTable/utils/handleCopyColumn.js +2 -2
  29. package/src/DataTable/utils/handleCopyTable.js +2 -2
  30. package/src/DataTable/utils/isBottomRightCornerOfRectangle.ts +27 -0
  31. package/src/DataTable/utils/isEntityClean.ts +15 -0
  32. package/src/DataTable/utils/primarySelectedValue.ts +1 -0
  33. package/src/DataTable/utils/queryParams.js +1 -1
  34. package/src/DataTable/utils/removeCleanRows.ts +25 -0
  35. package/src/DataTable/utils/selection.ts +11 -0
  36. package/src/DataTable/utils/useDeepEqualMemo.js +10 -0
  37. package/src/DataTable/utils/useTableEntities.ts +60 -0
  38. package/src/DataTable/utils/useTableParams.js +361 -0
  39. package/style.css +10537 -0
@@ -1,9 +1,5 @@
1
- export const getAllRows = e => {
2
- const el = e.target.querySelector(".data-table-container")
3
- ? e.target.querySelector(".data-table-container")
4
- : e.target.closest(".data-table-container");
5
-
6
- const allRowEls = el.querySelectorAll(".rt-tr");
1
+ export const getAllRows = tableRef => {
2
+ const allRowEls = tableRef.current?.tableRef?.querySelectorAll(".rt-tr");
7
3
  if (!allRowEls || !allRowEls.length) {
8
4
  return;
9
5
  }
@@ -2,9 +2,9 @@ import { getAllRows } from "./getAllRows";
2
2
  import { getIdOrCodeOrIndex } from "./getIdOrCodeOrIndex";
3
3
  import { handleCopyRows } from "./handleCopyRows";
4
4
 
5
- export const handleCopyColumn = (e, cellWrapper, selectedRecords) => {
5
+ export const handleCopyColumn = (tableRef, cellWrapper, selectedRecords) => {
6
6
  const specificColumn = cellWrapper.getAttribute("data-test");
7
- let rowElsToCopy = getAllRows(e);
7
+ let rowElsToCopy = getAllRows(tableRef);
8
8
  if (!rowElsToCopy) return;
9
9
  if (selectedRecords) {
10
10
  const ids = selectedRecords.map(e => getIdOrCodeOrIndex(e)?.toString());
@@ -1,9 +1,9 @@
1
1
  import { getAllRows } from "./getAllRows";
2
2
  import { handleCopyRows } from "./handleCopyRows";
3
3
 
4
- export const handleCopyTable = (e, opts) => {
4
+ export const handleCopyTable = (tableRef, opts) => {
5
5
  try {
6
- const allRowEls = getAllRows(e);
6
+ const allRowEls = getAllRows(tableRef);
7
7
  if (!allRowEls) return;
8
8
  handleCopyRows(allRowEls, {
9
9
  ...opts,
@@ -0,0 +1,27 @@
1
+ export const isBottomRightCornerOfRectangle = ({
2
+ cellId,
3
+ selectionGrid,
4
+ lastRowIndex,
5
+ lastCellIndex,
6
+ entityMap,
7
+ pathToIndex
8
+ }: {
9
+ cellId: string;
10
+ selectionGrid: (string | undefined)[][];
11
+ lastRowIndex: number;
12
+ lastCellIndex: number;
13
+ entityMap: Record<string, { i: number }>;
14
+ pathToIndex: Record<string, number>;
15
+ }) => {
16
+ selectionGrid.forEach(row => {
17
+ // remove undefineds from start of row
18
+ while (row[0] === undefined && row.length) row.shift();
19
+ });
20
+ const [rowId, cellPath] = cellId.split(":");
21
+ const ent = entityMap[rowId];
22
+ if (!ent) return;
23
+ const { i } = ent;
24
+ const cellIndex = pathToIndex[cellPath];
25
+ const isBottomRight = i === lastRowIndex && cellIndex === lastCellIndex;
26
+ return isBottomRight;
27
+ };
@@ -0,0 +1,15 @@
1
+ export function isEntityClean(e: { [key: string]: unknown } | null): boolean {
2
+ if (typeof e !== "object" || e === null) {
3
+ return true; // or return false depending on what you want for non-object inputs
4
+ }
5
+ let isClean = true;
6
+ for (const [key, val] of Object.entries(e)) {
7
+ if (key === "id") continue;
8
+ if (key === "_isClean") continue;
9
+ if (val) {
10
+ isClean = false;
11
+ break;
12
+ }
13
+ }
14
+ return isClean;
15
+ }
@@ -0,0 +1 @@
1
+ export const PRIMARY_SELECTED_VAL = "main_cell";
@@ -381,7 +381,7 @@ export function getQueryParams({
381
381
  // in case entries that have the same value in the column being sorted on
382
382
  // fall back to id as a secondary sort to make sure ordering happens correctly
383
383
  order_by.push(
384
- isCodeModel ? { code: "desc" } : { [window.__sortId || "id"]: "desc" }
384
+ isCodeModel ? { code: "asc" } : { [window.__sortId || "id"]: "asc" }
385
385
  );
386
386
 
387
387
  return {
@@ -0,0 +1,25 @@
1
+ import { isEntityClean } from "./isEntityClean";
2
+ import { getIdOrCodeOrIndex } from "./getIdOrCodeOrIndex";
3
+
4
+ export const removeCleanRows = (
5
+ entities: ({ [key: string]: unknown } & { _isClean?: boolean })[],
6
+ cellValidation: Record<string, unknown>
7
+ ) => {
8
+ const toFilterOut: Record<string, boolean> = {};
9
+ const entsToUse = (entities || []).filter(e => {
10
+ if (!(e._isClean || isEntityClean(e))) return true;
11
+ else {
12
+ toFilterOut[getIdOrCodeOrIndex(e)] = true;
13
+ return false;
14
+ }
15
+ });
16
+
17
+ const validationToUse: Record<string, unknown> = {};
18
+ Object.entries(cellValidation || {}).forEach(([k, v]) => {
19
+ const [rowId] = k.split(":");
20
+ if (!toFilterOut[rowId]) {
21
+ validationToUse[k] = v;
22
+ }
23
+ });
24
+ return { entsToUse, validationToUse };
25
+ };
@@ -0,0 +1,11 @@
1
+ import { getIdOrCodeOrIndex } from "./getIdOrCodeOrIndex";
2
+
3
+ export const getSelectedRowsFromEntities = (
4
+ entities: { [key: string]: unknown }[],
5
+ idMap: Record<string, boolean>
6
+ ) => {
7
+ if (!idMap) return [];
8
+ return entities.reduce((acc: number[], entity, i) => {
9
+ return idMap[getIdOrCodeOrIndex(entity, i)] ? acc.concat([i]) : acc;
10
+ }, []);
11
+ };
@@ -0,0 +1,10 @@
1
+ import { isEqual } from "lodash-es";
2
+ import { useRef } from "react";
3
+
4
+ export const useDeepEqualMemo = value => {
5
+ const ref = useRef();
6
+ if (!isEqual(value, ref.current)) {
7
+ ref.current = value;
8
+ }
9
+ return ref.current;
10
+ };
@@ -0,0 +1,60 @@
1
+ import { useCallback } from "react";
2
+ import { useDispatch, useSelector } from "react-redux";
3
+ import { change, initialize } from "redux-form";
4
+
5
+ type _Entity = { [key: string]: unknown } & { id: string };
6
+
7
+ type SelectedEntityIdMap<Entity extends _Entity> = Record<
8
+ string,
9
+ { entity: Entity; time: number; index?: number }
10
+ >;
11
+
12
+ export const useTableEntities = <Entity extends _Entity>(
13
+ tableFormName: string
14
+ ) => {
15
+ const dispatch = useDispatch();
16
+ const selectTableEntities = useCallback(
17
+ (entities: { id: string }[] = []) => {
18
+ initialize(tableFormName, {}, true, {
19
+ keepDirty: true,
20
+ updateUnregisteredFields: true,
21
+ keepValues: true
22
+ });
23
+ const selectedEntityIdMap: SelectedEntityIdMap<{ id: string }> = {};
24
+ entities.forEach(entity => {
25
+ selectedEntityIdMap[entity.id] = {
26
+ entity,
27
+ time: Date.now()
28
+ };
29
+ });
30
+ dispatch(
31
+ change(
32
+ tableFormName,
33
+ "reduxFormSelectedEntityIdMap",
34
+ selectedEntityIdMap
35
+ )
36
+ );
37
+ },
38
+ [dispatch, tableFormName]
39
+ );
40
+
41
+ const { allOrderedEntities, selectedEntities } = useSelector(
42
+ (state: {
43
+ form: Record<
44
+ string,
45
+ {
46
+ values?: {
47
+ allOrderedEntities?: Entity[];
48
+ reduxFormSelectedEntityIdMap?: SelectedEntityIdMap<Entity>;
49
+ };
50
+ }
51
+ >;
52
+ }) => ({
53
+ allOrderedEntities:
54
+ state.form?.[tableFormName]?.values?.allOrderedEntities,
55
+ selectedEntities:
56
+ state.form?.[tableFormName]?.values?.reduxFormSelectedEntityIdMap
57
+ })
58
+ );
59
+ return { selectTableEntities, allOrderedEntities, selectedEntities };
60
+ };
@@ -0,0 +1,361 @@
1
+ import { useContext, useEffect, useMemo, useState } from "react";
2
+ import { change } from "redux-form";
3
+ import { useDispatch, useSelector } from "react-redux";
4
+ import { isFunction, keyBy, get } from "lodash-es";
5
+ import TableFormTrackerContext from "../TableFormTrackerContext";
6
+ import { viewColumn, openColumn } from "./viewColumn";
7
+ import convertSchema from "./convertSchema";
8
+ import { getRecordsFromIdMap } from "./withSelectedEntities";
9
+ import {
10
+ makeDataTableHandlers,
11
+ getQueryParams,
12
+ setCurrentParamsOnUrl,
13
+ getCurrentParamsFromUrl,
14
+ getCCDisplayName
15
+ } from "./queryParams";
16
+ import getTableConfigFromStorage from "./getTableConfigFromStorage";
17
+
18
+ /*
19
+ NOTE:
20
+ This haven't been tested yet. It is the first version of what we should replace withTableParams
21
+ and also the first bit of the DataTable.
22
+ */
23
+
24
+ /**
25
+ * Note all these options can be passed at Design Time or at Runtime (like reduxForm())
26
+ *
27
+ * @export
28
+ *
29
+ * @param {compOrOpts} compOrOpts
30
+ * @typedef {object} compOrOpts
31
+ * @property {*string} formName - required unique identifier for the table
32
+ * @property {Object | Function} schema - The data table schema or a function returning it. The function wll be called with props as the argument.
33
+ * @property {boolean} urlConnected - whether the table should connect to/update the URL
34
+ * @property {boolean} withSelectedEntities - whether or not to pass the selected entities
35
+ * @property {boolean} isCodeModel - whether the model is keyed by code instead of id in the db
36
+ * @property {object} defaults - tableParam defaults such as pageSize, filter, etc
37
+ * @property {boolean} noOrderError - won't console an error if an order is not found on schema
38
+ */
39
+ export default function useTableParams(
40
+ props // This should be the same as the spread above
41
+ ) {
42
+ const {
43
+ formName,
44
+ isTableParamsConnected,
45
+ urlConnected,
46
+ onlyOneFilter,
47
+ defaults = {},
48
+ // WE NEED THIS HOOK TO BE WRAPPED IN A WITHROUTER OR MOVE TO REACT-ROUTER-DOM 5
49
+ // BEST SOLUTION IS TO ASSUME IT IS GOING TO BE RECEIVED
50
+ history,
51
+ withSelectedEntities,
52
+ tableParams: _tableParams,
53
+ schema: __schema,
54
+ noForm,
55
+ orderByFirstColumn,
56
+ withDisplayOptions,
57
+ syncDisplayOptionsToDb,
58
+ tableConfigurations,
59
+ isViewable,
60
+ isOpenable,
61
+ showEmptyColumnsByDefault,
62
+ isSimple,
63
+ entities: _origEntities = [],
64
+ cellRenderer,
65
+ additionalFilter,
66
+ additionalOrFilter,
67
+ doNotCoercePageSize,
68
+ isLocalCall
69
+ } = props;
70
+ const isInfinite = props.isInfinite || isSimple || !props.withPaging;
71
+ const additionalFilterToUse =
72
+ typeof additionalFilter === "function"
73
+ ? additionalFilter.bind(this, props)
74
+ : () => additionalFilter;
75
+
76
+ const additionalOrFilterToUse =
77
+ typeof additionalOrFilter === "function"
78
+ ? additionalOrFilter.bind(this, props)
79
+ : () => additionalOrFilter;
80
+
81
+ let _schema;
82
+ if (isFunction(__schema)) _schema = __schema(props);
83
+ else _schema = __schema;
84
+ const convertedSchema = convertSchema(_schema);
85
+
86
+ if (isLocalCall) {
87
+ if (!noForm && (!formName || formName === "tgDataTable")) {
88
+ throw new Error(
89
+ "Please pass a unique 'formName' prop to the locally connected <DataTable/> component with schema: ",
90
+ _schema
91
+ );
92
+ }
93
+ if (orderByFirstColumn && !defaults?.order?.length) {
94
+ const r = [getCCDisplayName(convertedSchema.fields[0])];
95
+ defaults.order = r;
96
+ }
97
+ } else {
98
+ //in user instantiated withTableParams() call
99
+ if (!formName || formName === "tgDataTable") {
100
+ throw new Error(
101
+ "Please pass a unique 'formName' prop to the withTableParams() with schema: ",
102
+ _schema
103
+ );
104
+ }
105
+ }
106
+
107
+ const [showForcedHiddenColumns, setShowForcedHidden] = useState(() => {
108
+ if (showEmptyColumnsByDefault) {
109
+ return true;
110
+ }
111
+ return false;
112
+ });
113
+
114
+ const [tableConfig, setTableConfig] = useState({ fieldOptions: [] });
115
+
116
+ useEffect(() => {
117
+ let newTableConfig = {};
118
+ if (withDisplayOptions) {
119
+ if (syncDisplayOptionsToDb) {
120
+ newTableConfig = tableConfigurations && tableConfigurations[0];
121
+ } else {
122
+ newTableConfig = getTableConfigFromStorage(formName);
123
+ }
124
+ if (!newTableConfig) {
125
+ newTableConfig = {
126
+ fieldOptions: []
127
+ };
128
+ }
129
+ }
130
+ setTableConfig(newTableConfig);
131
+ }, [
132
+ formName,
133
+ syncDisplayOptionsToDb,
134
+ tableConfigurations,
135
+ withDisplayOptions
136
+ ]);
137
+
138
+ // make user set page size persist
139
+ const userSetPageSize =
140
+ tableConfig?.userSetPageSize && parseInt(tableConfig.userSetPageSize, 10);
141
+ if (!syncDisplayOptionsToDb && userSetPageSize) {
142
+ defaults.pageSize = userSetPageSize;
143
+ }
144
+
145
+ const {
146
+ reduxFormSearchInput = "",
147
+ onlyShowRowsWErrors,
148
+ reduxFormCellValidation,
149
+ reduxFormEntities,
150
+ reduxFormSelectedCells = {},
151
+ reduxFormSelectedEntityIdMap = {},
152
+ reduxFormQueryParams = {}
153
+ } = useSelector(state => {
154
+ if (!state.form[formName]) return {};
155
+ return state.form[formName].values || {};
156
+ });
157
+
158
+ const entities = reduxFormEntities || _origEntities;
159
+
160
+ const { schema } = useMemo(() => {
161
+ const schema = convertSchema(_schema);
162
+ if (isViewable) {
163
+ schema.fields = [viewColumn, ...schema.fields];
164
+ }
165
+ if (isOpenable) {
166
+ schema.fields = [openColumn, ...schema.fields];
167
+ }
168
+ // this must come before handling orderings.
169
+ schema.fields = schema.fields.map(field => {
170
+ if (field.placementPath) {
171
+ return {
172
+ ...field,
173
+ sortDisabled:
174
+ field.sortDisabled ||
175
+ (typeof field.path === "string" && field.path.includes(".")),
176
+ path: field.placementPath
177
+ };
178
+ } else {
179
+ return field;
180
+ }
181
+ });
182
+
183
+ if (withDisplayOptions) {
184
+ const fieldOptsByPath = keyBy(tableConfig.fieldOptions, "path");
185
+ schema.fields = schema.fields.map(field => {
186
+ const fieldOpt = fieldOptsByPath[field.path];
187
+ let noValsForField = false;
188
+ // only add this hidden column ability if no paging
189
+ if (
190
+ !showForcedHiddenColumns &&
191
+ withDisplayOptions &&
192
+ (isSimple || isInfinite)
193
+ ) {
194
+ noValsForField = entities.every(e => {
195
+ const val = get(e, field.path);
196
+ return field.render
197
+ ? !field.render(val, e)
198
+ : cellRenderer[field.path]
199
+ ? !cellRenderer[field.path](val, e)
200
+ : !val;
201
+ });
202
+ }
203
+ if (noValsForField) {
204
+ return {
205
+ ...field,
206
+ isHidden: true,
207
+ isForcedHidden: true
208
+ };
209
+ } else if (fieldOpt) {
210
+ return {
211
+ ...field,
212
+ isHidden: fieldOpt.isHidden
213
+ };
214
+ } else {
215
+ return field;
216
+ }
217
+ });
218
+
219
+ const columnOrderings = tableConfig.columnOrderings;
220
+ if (columnOrderings) {
221
+ const fieldsWithOrders = [];
222
+ const fieldsWithoutOrder = [];
223
+ // if a new field has been added since the orderings were set then we want
224
+ // it to be at the end instead of the beginning
225
+ schema.fields.forEach(field => {
226
+ if (columnOrderings.indexOf(field.path) > -1) {
227
+ fieldsWithOrders.push(field);
228
+ } else {
229
+ fieldsWithoutOrder.push(field);
230
+ }
231
+ });
232
+ schema.fields = fieldsWithOrders
233
+ .sort(({ path: path1 }, { path: path2 }) => {
234
+ return (
235
+ columnOrderings.indexOf(path1) - columnOrderings.indexOf(path2)
236
+ );
237
+ })
238
+ .concat(fieldsWithoutOrder);
239
+ setTableConfig(prev => ({
240
+ ...prev,
241
+ columnOrderings: schema.fields.map(f => f.path)
242
+ }));
243
+ }
244
+ }
245
+ return { schema };
246
+ }, [
247
+ _schema,
248
+ cellRenderer,
249
+ entities,
250
+ isInfinite,
251
+ isOpenable,
252
+ isSimple,
253
+ isViewable,
254
+ showForcedHiddenColumns,
255
+ tableConfig,
256
+ withDisplayOptions
257
+ ]);
258
+
259
+ const selectedEntities = withSelectedEntities
260
+ ? getRecordsFromIdMap(reduxFormSelectedEntityIdMap)
261
+ : undefined;
262
+
263
+ const currentParams = urlConnected
264
+ ? getCurrentParamsFromUrl(history.location) //important to use history location and not ownProps.location because for some reason the location path lags one render behind!!
265
+ : reduxFormQueryParams;
266
+
267
+ currentParams.searchTerm = reduxFormSearchInput;
268
+
269
+ props = {
270
+ ...props,
271
+ ...getQueryParams({
272
+ doNotCoercePageSize,
273
+ currentParams,
274
+ entities: props.entities, // for local table
275
+ urlConnected,
276
+ defaults: props.defaults,
277
+ schema: convertedSchema,
278
+ isInfinite,
279
+ isLocalCall,
280
+ additionalFilter: additionalFilterToUse,
281
+ additionalOrFilter: additionalOrFilterToUse,
282
+ noOrderError: props.noOrderError,
283
+ isCodeModel: props.isCodeModel,
284
+ ownProps: props
285
+ })
286
+ };
287
+
288
+ const dispatch = useDispatch();
289
+ let tableParams;
290
+ if (!isTableParamsConnected) {
291
+ const updateSearch = val => {
292
+ setTimeout(() => {
293
+ dispatch(change(formName, "reduxFormSearchInput", val || ""));
294
+ });
295
+ };
296
+
297
+ let setNewParams;
298
+ if (urlConnected) {
299
+ setNewParams = newParams => {
300
+ setCurrentParamsOnUrl(newParams, history.replace);
301
+ dispatch(change(formName, "reduxFormQueryParams", newParams)); //we always will update the redux params as a workaround for withRouter not always working if inside a redux-connected container https://github.com/ReactTraining/react-router/issues/5037
302
+ };
303
+ } else {
304
+ setNewParams = function (newParams) {
305
+ dispatch(change(formName, "reduxFormQueryParams", newParams));
306
+ };
307
+ }
308
+
309
+ const bindThese = makeDataTableHandlers({
310
+ setNewParams,
311
+ updateSearch,
312
+ defaults,
313
+ onlyOneFilter
314
+ });
315
+
316
+ const boundDispatchProps = {};
317
+ //bind currentParams to actions
318
+ Object.keys(bindThese).forEach(function (key) {
319
+ const action = bindThese[key];
320
+ boundDispatchProps[key] = function (...args) {
321
+ action(...args, currentParams);
322
+ };
323
+ });
324
+
325
+ const changeFormValue = (...args) => dispatch(change(formName, ...args));
326
+
327
+ tableParams = {
328
+ changeFormValue,
329
+ selectedEntities,
330
+ ..._tableParams,
331
+ ...props,
332
+ ...boundDispatchProps,
333
+ form: formName, //this will override the default redux form name
334
+ isTableParamsConnected: true //let the table know not to do local sorting/filtering etc.
335
+ };
336
+ }
337
+
338
+ const formTracker = useContext(TableFormTrackerContext);
339
+ useEffect(() => {
340
+ if (formTracker.isActive && !formTracker.formNames.includes(formName)) {
341
+ formTracker.pushFormName(formName);
342
+ }
343
+ }, [formTracker, formName]);
344
+
345
+ return {
346
+ ...props,
347
+ selectedEntities,
348
+ tableParams,
349
+ currentParams,
350
+ schema,
351
+ entities,
352
+ reduxFormSearchInput,
353
+ onlyShowRowsWErrors,
354
+ reduxFormCellValidation,
355
+ reduxFormSelectedCells,
356
+ reduxFormSelectedEntityIdMap,
357
+ reduxFormQueryParams,
358
+ showForcedHiddenColumns,
359
+ setShowForcedHidden
360
+ };
361
+ }