@macrostrat/data-sheet 4.1.0 → 4.2.0

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 (302) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/actions/builtin.cjs +1 -1
  3. package/dist/actions/builtin.cjs.map +1 -1
  4. package/dist/actions/builtin.d.ts +0 -2
  5. package/dist/actions/builtin.js +1 -1
  6. package/dist/actions/builtin.js.map +1 -1
  7. package/dist/actions/clipboard.cjs +1 -1
  8. package/dist/actions/clipboard.cjs.map +1 -1
  9. package/dist/actions/clipboard.d.ts +3 -2
  10. package/dist/actions/clipboard.js +1 -1
  11. package/dist/actions/clipboard.js.map +1 -1
  12. package/dist/actions/column-controls.cjs +7 -184
  13. package/dist/actions/column-controls.cjs.map +1 -1
  14. package/dist/actions/column-controls.d.ts +1 -1
  15. package/dist/actions/column-controls.js +5 -182
  16. package/dist/actions/column-controls.js.map +1 -1
  17. package/dist/actions/column-filter.cjs +24 -50
  18. package/dist/actions/column-filter.cjs.map +1 -1
  19. package/dist/actions/column-filter.d.ts +6 -4
  20. package/dist/actions/column-filter.js +25 -51
  21. package/dist/actions/column-filter.js.map +1 -1
  22. package/dist/actions/context.cjs +147 -0
  23. package/dist/actions/context.cjs.map +1 -0
  24. package/dist/actions/context.d.ts +93 -0
  25. package/dist/actions/context.js +145 -0
  26. package/dist/actions/context.js.map +1 -0
  27. package/dist/actions/edit-actions.cjs.map +1 -1
  28. package/dist/actions/edit-actions.d.ts +3 -1
  29. package/dist/actions/edit-actions.js.map +1 -1
  30. package/dist/actions/index.d.ts +2 -3
  31. package/dist/actions/selection.cjs +70 -115
  32. package/dist/actions/selection.cjs.map +1 -1
  33. package/dist/actions/selection.d.ts +22 -12
  34. package/dist/actions/selection.js +71 -114
  35. package/dist/actions/selection.js.map +1 -1
  36. package/dist/actions/{table-controls.cjs → table-actions.cjs} +7 -24
  37. package/dist/actions/table-actions.cjs.map +1 -0
  38. package/dist/actions/{table-controls.d.ts → table-actions.d.ts} +0 -4
  39. package/dist/actions/{table-controls.js → table-actions.js} +2 -19
  40. package/dist/actions/table-actions.js.map +1 -0
  41. package/dist/actions/types.d.ts +11 -89
  42. package/dist/components/cell-detail.cjs +6 -6
  43. package/dist/components/cell-detail.cjs.map +1 -1
  44. package/dist/components/cell-detail.js +1 -1
  45. package/dist/components/colors.cjs.map +1 -1
  46. package/dist/components/colors.js.map +1 -1
  47. package/dist/components/editor-popup.cjs +7 -7
  48. package/dist/components/editor-popup.cjs.map +1 -1
  49. package/dist/components/editor-popup.js +1 -1
  50. package/dist/components/index.d.ts +2 -1
  51. package/dist/components/indicators/filter-and-sort.cjs +378 -0
  52. package/dist/components/indicators/filter-and-sort.cjs.map +1 -0
  53. package/dist/components/indicators/filter-and-sort.d.ts +59 -0
  54. package/dist/components/indicators/filter-and-sort.js +376 -0
  55. package/dist/components/indicators/filter-and-sort.js.map +1 -0
  56. package/dist/components/indicators/filter-and-sort.module.sass.cjs +16 -0
  57. package/dist/components/indicators/filter-and-sort.module.sass.cjs.map +1 -0
  58. package/dist/components/indicators/filter-and-sort.module.sass.js +14 -0
  59. package/dist/components/indicators/filter-and-sort.module.sass.js.map +1 -0
  60. package/dist/components/indicators/index.d.ts +4 -0
  61. package/dist/components/indicators/selection.cjs +113 -0
  62. package/dist/components/indicators/selection.cjs.map +1 -0
  63. package/dist/components/indicators/selection.d.ts +3 -0
  64. package/dist/components/indicators/selection.js +111 -0
  65. package/dist/components/indicators/selection.js.map +1 -0
  66. package/dist/components/indicators/selection.module.sass.cjs +19 -0
  67. package/dist/components/indicators/selection.module.sass.cjs.map +1 -0
  68. package/dist/components/indicators/selection.module.sass.js +17 -0
  69. package/dist/components/indicators/selection.module.sass.js.map +1 -0
  70. package/dist/components/indicators/unified-filters.cjs +130 -0
  71. package/dist/components/indicators/unified-filters.cjs.map +1 -0
  72. package/dist/components/indicators/unified-filters.d.ts +10 -0
  73. package/dist/components/indicators/unified-filters.js +130 -0
  74. package/dist/components/indicators/unified-filters.js.map +1 -0
  75. package/dist/components/indicators/view-info.cjs +59 -0
  76. package/dist/components/indicators/view-info.cjs.map +1 -0
  77. package/dist/components/{view-info.d.ts → indicators/view-info.d.ts} +1 -0
  78. package/dist/components/{view-info.js → indicators/view-info.js} +17 -13
  79. package/dist/components/indicators/view-info.js.map +1 -0
  80. package/dist/components/text-areas.cjs +5 -5
  81. package/dist/components/text-areas.cjs.map +1 -1
  82. package/dist/components/text-areas.js +1 -1
  83. package/dist/components/toolbars/actions-toolbar.cjs +185 -0
  84. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -0
  85. package/dist/{actions/toolbar.d.ts → components/toolbars/actions-toolbar.d.ts} +9 -5
  86. package/dist/{actions/toolbar.js → components/toolbars/actions-toolbar.js} +36 -97
  87. package/dist/components/toolbars/actions-toolbar.js.map +1 -0
  88. package/dist/components/toolbars/actions-toolbar.module.sass.cjs +29 -0
  89. package/dist/components/toolbars/actions-toolbar.module.sass.cjs.map +1 -0
  90. package/dist/components/toolbars/actions-toolbar.module.sass.js +27 -0
  91. package/dist/components/toolbars/actions-toolbar.module.sass.js.map +1 -0
  92. package/dist/components/toolbars/active-filters.cjs +120 -0
  93. package/dist/components/toolbars/active-filters.cjs.map +1 -0
  94. package/dist/{actions/filters.d.ts → components/toolbars/active-filters.d.ts} +3 -3
  95. package/dist/components/toolbars/active-filters.js +120 -0
  96. package/dist/components/toolbars/active-filters.js.map +1 -0
  97. package/dist/components/toolbars/index.d.ts +2 -0
  98. package/dist/data-panel.cjs +291 -0
  99. package/dist/data-panel.cjs.map +1 -0
  100. package/dist/data-panel.d.ts +110 -0
  101. package/dist/data-panel.js +289 -0
  102. package/dist/data-panel.js.map +1 -0
  103. package/dist/data-panel.module.sass.cjs +40 -0
  104. package/dist/data-panel.module.sass.cjs.map +1 -0
  105. package/dist/data-panel.module.sass.js +38 -0
  106. package/dist/data-panel.module.sass.js.map +1 -0
  107. package/dist/{core.cjs → data-sheet.cjs} +123 -181
  108. package/dist/data-sheet.cjs.map +1 -0
  109. package/dist/data-sheet.css +241 -13
  110. package/dist/data-sheet.d.ts +16 -0
  111. package/dist/{core.js → data-sheet.js} +92 -150
  112. package/dist/data-sheet.js.map +1 -0
  113. package/dist/data-view.cjs +47 -0
  114. package/dist/data-view.cjs.map +1 -0
  115. package/dist/data-view.d.ts +15 -0
  116. package/dist/data-view.js +45 -0
  117. package/dist/data-view.js.map +1 -0
  118. package/dist/filters/operators.cjs +21 -4
  119. package/dist/filters/operators.cjs.map +1 -1
  120. package/dist/filters/operators.d.ts +5 -4
  121. package/dist/filters/operators.js +21 -4
  122. package/dist/filters/operators.js.map +1 -1
  123. package/dist/index.cjs +106 -47
  124. package/dist/index.cjs.map +1 -1
  125. package/dist/index.d.ts +4 -3
  126. package/dist/index.js +76 -17
  127. package/dist/index.js.map +1 -1
  128. package/dist/notifications.cjs +4 -4
  129. package/dist/notifications.cjs.map +1 -1
  130. package/dist/notifications.js +1 -1
  131. package/dist/postgrest-table/data-loaders.cjs +129 -103
  132. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  133. package/dist/postgrest-table/data-loaders.d.ts +52 -82
  134. package/dist/postgrest-table/data-loaders.js +110 -84
  135. package/dist/postgrest-table/data-loaders.js.map +1 -1
  136. package/dist/postgrest-table/index.cjs +18 -17
  137. package/dist/postgrest-table/index.cjs.map +1 -1
  138. package/dist/postgrest-table/index.d.ts +4 -3
  139. package/dist/postgrest-table/index.js +9 -8
  140. package/dist/postgrest-table/index.js.map +1 -1
  141. package/dist/{utils → provider}/column-spec.cjs +23 -9
  142. package/dist/provider/column-spec.cjs.map +1 -0
  143. package/dist/{utils → provider}/column-spec.d.ts +77 -2
  144. package/dist/{utils → provider}/column-spec.js +24 -10
  145. package/dist/provider/column-spec.js.map +1 -0
  146. package/dist/provider/core.cjs +382 -0
  147. package/dist/provider/core.cjs.map +1 -0
  148. package/dist/provider/core.d.ts +74 -0
  149. package/dist/provider/core.js +380 -0
  150. package/dist/provider/core.js.map +1 -0
  151. package/dist/provider/index.d.ts +7 -0
  152. package/dist/provider/interactions.cjs +128 -0
  153. package/dist/provider/interactions.cjs.map +1 -0
  154. package/dist/provider/interactions.d.ts +39 -0
  155. package/dist/provider/interactions.js +128 -0
  156. package/dist/provider/interactions.js.map +1 -0
  157. package/dist/provider/selection.cjs +29 -0
  158. package/dist/provider/selection.cjs.map +1 -0
  159. package/dist/provider/selection.d.ts +9 -0
  160. package/dist/provider/selection.js +29 -0
  161. package/dist/provider/selection.js.map +1 -0
  162. package/dist/provider/table-data.cjs +92 -0
  163. package/dist/provider/table-data.cjs.map +1 -0
  164. package/dist/provider/table-data.d.ts +81 -0
  165. package/dist/provider/table-data.js +92 -0
  166. package/dist/provider/table-data.js.map +1 -0
  167. package/dist/provider/types.cjs +22 -0
  168. package/dist/provider/types.cjs.map +1 -0
  169. package/dist/provider/types.d.ts +256 -0
  170. package/dist/provider/types.js +22 -0
  171. package/dist/provider/types.js.map +1 -0
  172. package/dist/{zustand-store.cjs → provider/zustand-store.cjs} +37 -23
  173. package/dist/provider/zustand-store.cjs.map +1 -0
  174. package/dist/{zustand-store.js → provider/zustand-store.js} +22 -8
  175. package/dist/provider/zustand-store.js.map +1 -0
  176. package/dist/{cell-renderer.cjs → renderers/cell-renderer.cjs} +68 -35
  177. package/dist/renderers/cell-renderer.cjs.map +1 -0
  178. package/dist/{cell-renderer.d.ts → renderers/cell-renderer.d.ts} +1 -2
  179. package/dist/{cell-renderer.js → renderers/cell-renderer.js} +66 -33
  180. package/dist/renderers/cell-renderer.js.map +1 -0
  181. package/dist/renderers/column-header-cell.cjs +40 -17
  182. package/dist/renderers/column-header-cell.cjs.map +1 -1
  183. package/dist/renderers/column-header-cell.d.ts +2 -2
  184. package/dist/renderers/column-header-cell.js +40 -17
  185. package/dist/renderers/column-header-cell.js.map +1 -1
  186. package/dist/renderers/index.d.ts +1 -0
  187. package/dist/types.cjs +7 -19
  188. package/dist/types.cjs.map +1 -1
  189. package/dist/types.d.ts +123 -226
  190. package/dist/types.js +7 -19
  191. package/dist/types.js.map +1 -1
  192. package/dist/utils/atoms.cjs +24 -0
  193. package/dist/utils/atoms.cjs.map +1 -0
  194. package/dist/utils/atoms.d.ts +4 -0
  195. package/dist/utils/atoms.js +24 -0
  196. package/dist/utils/atoms.js.map +1 -0
  197. package/dist/utils/debug-overlay.cjs.map +1 -1
  198. package/dist/utils/debug-overlay.js.map +1 -1
  199. package/dist/utils/index.d.ts +2 -3
  200. package/dist/utils/key-handling.cjs +140 -139
  201. package/dist/utils/key-handling.cjs.map +1 -1
  202. package/dist/utils/key-handling.d.ts +4 -2
  203. package/dist/utils/key-handling.js +136 -135
  204. package/dist/utils/key-handling.js.map +1 -1
  205. package/dist/utils/validation.cjs +6 -1
  206. package/dist/utils/validation.cjs.map +1 -1
  207. package/dist/utils/validation.d.ts +1 -1
  208. package/dist/utils/validation.js +6 -1
  209. package/dist/utils/validation.js.map +1 -1
  210. package/package.json +4 -3
  211. package/src/actions/builtin.ts +1 -4
  212. package/src/actions/clipboard.ts +4 -3
  213. package/src/actions/column-controls.ts +12 -228
  214. package/src/actions/column-filter.ts +28 -63
  215. package/src/actions/context.ts +299 -0
  216. package/src/actions/edit-actions.ts +3 -1
  217. package/src/actions/index.ts +2 -3
  218. package/src/actions/selection.ts +109 -156
  219. package/src/actions/{table-controls.ts → table-actions.ts} +0 -20
  220. package/src/actions/types.ts +17 -101
  221. package/src/components/colors.ts +1 -1
  222. package/src/components/index.ts +2 -1
  223. package/src/components/indicators/filter-and-sort.module.sass +13 -0
  224. package/src/components/indicators/filter-and-sort.ts +478 -0
  225. package/src/components/indicators/index.ts +4 -0
  226. package/src/components/indicators/selection.module.sass +22 -0
  227. package/src/components/indicators/selection.ts +141 -0
  228. package/src/components/indicators/unified-filters.ts +161 -0
  229. package/src/components/{view-info.ts → indicators/view-info.ts} +16 -27
  230. package/src/{actions/toolbar.module.sass → components/toolbars/actions-toolbar.module.sass} +17 -4
  231. package/src/{actions/toolbar.ts → components/toolbars/actions-toolbar.ts} +53 -126
  232. package/src/components/toolbars/active-filters.ts +150 -0
  233. package/src/components/toolbars/index.ts +2 -0
  234. package/src/data-panel.module.sass +185 -0
  235. package/src/data-panel.ts +556 -0
  236. package/src/{core.ts → data-sheet.ts} +144 -306
  237. package/src/data-view.ts +70 -0
  238. package/src/filters/operators.ts +38 -6
  239. package/src/index.ts +4 -3
  240. package/src/postgrest-table/data-loaders.ts +250 -181
  241. package/src/postgrest-table/index.ts +10 -9
  242. package/src/{utils → provider}/column-spec.ts +34 -15
  243. package/src/provider/core.ts +585 -0
  244. package/src/provider/index.ts +7 -0
  245. package/src/provider/interactions.ts +161 -0
  246. package/src/provider/selection.ts +31 -0
  247. package/src/provider/table-data.ts +178 -0
  248. package/src/provider/types.ts +273 -0
  249. package/src/{zustand-store.ts → provider/zustand-store.ts} +36 -14
  250. package/src/{cell-renderer.ts → renderers/cell-renderer.ts} +146 -58
  251. package/src/renderers/column-header-cell.ts +51 -17
  252. package/src/renderers/index.ts +1 -0
  253. package/src/types.ts +143 -236
  254. package/src/utils/atoms.ts +28 -0
  255. package/src/utils/debug-overlay.ts +1 -1
  256. package/src/utils/index.ts +2 -8
  257. package/src/utils/key-handling.ts +170 -164
  258. package/src/utils/validation.ts +7 -2
  259. package/dist/actions/filters.cjs +0 -139
  260. package/dist/actions/filters.cjs.map +0 -1
  261. package/dist/actions/filters.js +0 -139
  262. package/dist/actions/filters.js.map +0 -1
  263. package/dist/actions/table-controls.cjs.map +0 -1
  264. package/dist/actions/table-controls.js.map +0 -1
  265. package/dist/actions/toolbar.cjs +0 -246
  266. package/dist/actions/toolbar.cjs.map +0 -1
  267. package/dist/actions/toolbar.js.map +0 -1
  268. package/dist/actions/toolbar.module.sass.cjs +0 -27
  269. package/dist/actions/toolbar.module.sass.cjs.map +0 -1
  270. package/dist/actions/toolbar.module.sass.js +0 -25
  271. package/dist/actions/toolbar.module.sass.js.map +0 -1
  272. package/dist/cell-renderer.cjs.map +0 -1
  273. package/dist/cell-renderer.js.map +0 -1
  274. package/dist/components/view-info.cjs +0 -55
  275. package/dist/components/view-info.cjs.map +0 -1
  276. package/dist/components/view-info.js.map +0 -1
  277. package/dist/core.cjs.map +0 -1
  278. package/dist/core.d.ts +0 -113
  279. package/dist/core.js.map +0 -1
  280. package/dist/provider.cjs +0 -191
  281. package/dist/provider.cjs.map +0 -1
  282. package/dist/provider.d.ts +0 -25
  283. package/dist/provider.js +0 -189
  284. package/dist/provider.js.map +0 -1
  285. package/dist/table-updates/data-parameter.d.ts +0 -14
  286. package/dist/table-updates/filter.d.ts +0 -16
  287. package/dist/table-updates/index.d.ts +0 -19
  288. package/dist/utils/column-spec.cjs.map +0 -1
  289. package/dist/utils/column-spec.js.map +0 -1
  290. package/dist/utils/index.cjs +0 -9
  291. package/dist/utils/index.cjs.map +0 -1
  292. package/dist/utils/index.js +0 -9
  293. package/dist/utils/index.js.map +0 -1
  294. package/dist/zustand-store.cjs.map +0 -1
  295. package/dist/zustand-store.js.map +0 -1
  296. package/src/actions/filters.ts +0 -176
  297. package/src/components/actions.module.sass +0 -8
  298. package/src/provider.ts +0 -250
  299. package/src/table-updates/data-parameter.ts +0 -44
  300. package/src/table-updates/filter.ts +0 -124
  301. package/src/table-updates/index.ts +0 -239
  302. /package/dist/{zustand-store.d.ts → provider/zustand-store.d.ts} +0 -0
@@ -1,4 +1,5 @@
1
1
  import React from "react";
2
+ import { enhanceColumnFilter, TableFilter } from "../actions";
2
3
 
3
4
  const defaultRenderers = {
4
5
  string: (d) => d,
@@ -57,7 +58,7 @@ export interface CellRenderContext<T = any> {
57
58
  /** The full column spec for this cell's column. */
58
59
  column: ColumnSpec;
59
60
  /** The full row object backing this cell (may be undefined while loading). */
60
- row: T | undefined;
61
+ row: T | null | undefined;
61
62
  /** Whether this cell has an uncommitted edit. */
62
63
  isEdited: boolean;
63
64
  /** Whether this cell's row is marked for deletion. */
@@ -118,10 +119,7 @@ export interface ColumnSpec {
118
119
  * A falsy result maps to an `error`. */
119
120
  isValid?: (d: any) => boolean;
120
121
  transformValue?: (d: any) => any;
121
- valueRenderer?: (
122
- d: any,
123
- ctx?: CellRenderContext,
124
- ) => string | React.ReactNode;
122
+ valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;
125
123
  headerRenderer?: (d: any) => string | React.ReactNode;
126
124
  dataEditor?: any;
127
125
  /**
@@ -173,6 +171,10 @@ export interface ColumnSpec {
173
171
  /** Inferred data type, used to select context-appropriate filter
174
172
  * operators when `filterable` is `true` without explicit operators. */
175
173
  dataType?: ColumnDataType;
174
+ /** Whether this column may be drag-reordered. Defaults to `true`; set
175
+ * `false` to pin a fixed/system column in place. Applied by the default
176
+ * header renderer (requires table-level `enableColumnReordering`). */
177
+ reorderable?: boolean;
176
178
  }
177
179
 
178
180
  export interface ColumnSpecOptions<T> {
@@ -254,9 +256,9 @@ export function generateDefaultColumnSpec<T>(
254
256
  }
255
257
 
256
258
  // Build a column spec
257
- const spec = [];
259
+ const spec: ColumnSpec[] = [];
258
260
  for (const key of keys) {
259
- let width = null;
261
+ let width: number | undefined = undefined;
260
262
  if (calculateWidths) {
261
263
  // If we are calculating widths, use the value lengths
262
264
  width = Math.min(
@@ -292,15 +294,10 @@ export function generateDefaultColumnSpec<T>(
292
294
 
293
295
  export function generateColumnSpec<T>(
294
296
  data: T[],
295
- options: ColumnSpecOptions<T>,
297
+ options: Partial<ColumnSpecOptions<T>> = {},
296
298
  ): ColumnSpec[] {
297
299
  /** Generate a column spec from a dataset */
298
- const {
299
- overrides = {},
300
- nRows = 10,
301
- omitColumns,
302
- includeColumns,
303
- } = options ?? {};
300
+ const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;
304
301
 
305
302
  if (data == null) return [];
306
303
 
@@ -318,7 +315,7 @@ export function generateColumnSpec<T>(
318
315
  });
319
316
 
320
317
  // Apply overrides
321
- return filteredSpec.map((col) => {
318
+ const improvedSpec = filteredSpec.map((col) => {
322
319
  let ovr = overrides[col.key];
323
320
  if (ovr == null) return col;
324
321
  if (typeof ovr === "string") {
@@ -326,4 +323,26 @@ export function generateColumnSpec<T>(
326
323
  }
327
324
  return { ...col, ...ovr };
328
325
  });
326
+ return postprocessColumnSpec(improvedSpec);
327
+ }
328
+
329
+ export function postprocessColumnSpec(columnSpec: ColumnSpec[]) {
330
+ /** Postprocess column spec to make sure that, e.g., column filters are
331
+ * properly established, etc.
332
+ */
333
+ return columnSpec.map((col) => {
334
+ return {
335
+ ...col,
336
+ filters: postprocessColumnFilters(col),
337
+ actions: col.actions ?? [],
338
+ };
339
+ });
340
+ }
341
+
342
+ function postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {
343
+ const { filterable = true, filters = [] } = col;
344
+ if (!filterable) {
345
+ return undefined;
346
+ }
347
+ return filters.map((f) => enhanceColumnFilter(col, f));
329
348
  }
@@ -0,0 +1,585 @@
1
+ import { SetStateAction, useEffect, useMemo, useRef, useState } from "react";
2
+ import h from "@macrostrat/hyper";
3
+ import { createStore, StoreApi, useStore } from "zustand";
4
+ import { Table } from "@blueprintjs/table";
5
+ import {
6
+ type ColumnSpec,
7
+ generateColumnSpec,
8
+ postprocessColumnSpec,
9
+ } from "./column-spec.ts";
10
+ import { splitProps } from "../utils";
11
+ import { createScopedStore } from "@macrostrat/data-components";
12
+ import {
13
+ DataSheetProviderProps,
14
+ DataSheetState,
15
+ DataSheetStore,
16
+ DS_ROW_ID,
17
+ TableElementStatus,
18
+ } from "./types.ts";
19
+ import { createZustandStore } from "./zustand-store.ts";
20
+ import { atomWithStore } from "jotai-zustand";
21
+ import { toasterAtom } from "../notifications.ts";
22
+ import { TableAction } from "../actions";
23
+ import { atom } from "jotai";
24
+ import {
25
+ createLocalProvider,
26
+ dataRefreshTokenAtom,
27
+ FetchData,
28
+ TableDataProvider,
29
+ } from "./table-data.ts";
30
+ import { ErrorBoundary, ToasterContext } from "@macrostrat/ui-components";
31
+ import {
32
+ DataViewRendererType,
33
+ InteractionOptions,
34
+ interactionOptionsAtom,
35
+ interactionOptionsKeys,
36
+ resolveInteractionOptions,
37
+ } from "./interactions.ts";
38
+ import { DataViewProps } from "../data-view.ts";
39
+ import { DataSheetProps } from "../types.ts";
40
+ import { DataPanelProps } from "../data-panel.ts";
41
+
42
+ /** Create a Jotai scoped store */
43
+ export const ctx = createScopedStore();
44
+
45
+ export const storeAPIAtom = atom<StoreApi<DataSheetStore<any>>>();
46
+
47
+ const storeWrapperAtom = atom((get) => {
48
+ const _storeAPIAtom = get(storeAPIAtom);
49
+ if (_storeAPIAtom == null) {
50
+ return undefined;
51
+ }
52
+ return atomWithStore(_storeAPIAtom);
53
+ });
54
+
55
+ /** This is the basis for all other atoms that manipulate the store. */
56
+ export const storeAtom = atom(
57
+ (get) => {
58
+ const storeWrapper = get(storeWrapperAtom);
59
+ if (storeWrapper == null) {
60
+ return undefined;
61
+ }
62
+ return get(storeWrapper);
63
+ },
64
+ (get, set, action: SetStateAction<any>) => {
65
+ const storeWrapper = get(storeWrapperAtom);
66
+ if (storeWrapper == null) {
67
+ throw new Error("Missing DataSheetProvider");
68
+ }
69
+ return set(storeWrapper, action);
70
+ },
71
+ );
72
+
73
+ /** Stable empty spec so a function `columnSpec` yields a constant init value
74
+ * (see `DataSheetProviderInner`). */
75
+ const EMPTY_SPEC: ColumnSpec[] = [];
76
+
77
+ const initializeStoreAtom = atom(
78
+ null,
79
+ (get, set, payload: Partial<DataSheetStore<any>>) => {
80
+ set(storeAtom, (state) => {
81
+ return {
82
+ ...state,
83
+ ...payload,
84
+ };
85
+ });
86
+ },
87
+ );
88
+
89
+ export const tableActionsAtom = atom<TableAction[]>([]);
90
+
91
+ /** The resolved data source for the table, held in the provider layer (next to
92
+ * the store) rather than resolved inside the render loop. `provider` is the
93
+ * unified `TableDataProvider` (explicit, loose-`fetchData`-wrapped, or a local
94
+ * in-memory provider); `isLocalProvider` distinguishes the in-memory case (it
95
+ * loads the whole array at once and shows no load progress). `isExplicitProvider`
96
+ * distinguishes an explicit `provider` object from a loose `fetchData`/`data`
97
+ * source — only an explicit provider without `deleteRows` disables row
98
+ * deletion; loose sources keep the local delete overlay. */
99
+ export interface ResolvedDataProvider {
100
+ provider: TableDataProvider<any> | null;
101
+ isLocalProvider: boolean;
102
+ isExplicitProvider: boolean;
103
+ /** Row count of an in-memory (local) source, so a renderer can size the
104
+ * loader's page to "all of it" without also receiving the `data` prop. `0`
105
+ * for non-local sources. */
106
+ localCount: number;
107
+ }
108
+
109
+ const DEFAULT_DATA_PROVIDER: ResolvedDataProvider = {
110
+ provider: null,
111
+ isLocalProvider: true,
112
+ isExplicitProvider: false,
113
+ localCount: 0,
114
+ };
115
+
116
+ export const dataProviderAtom = atom<ResolvedDataProvider>(
117
+ DEFAULT_DATA_PROVIDER,
118
+ );
119
+
120
+ const EMPTY_ARRAY: any[] = [];
121
+
122
+ /** Resolve a table's data source from the loose `provider` / `fetchData` /
123
+ * `data` props (an explicit `provider` wins; else a loose `fetchData` (+
124
+ * `identity`) is wrapped as one; else in-memory `data` becomes a local
125
+ * provider). Shared by `DataSheet`, `DataPanel`, and `DataView` so all three
126
+ * resolve identically. */
127
+ export function useResolvedProvider<T>(props: {
128
+ provider?: TableDataProvider<T>;
129
+ fetchData?: FetchData<T>;
130
+ data?: T[];
131
+ identity?: (row: T) => string | number | null | undefined;
132
+ }): {
133
+ data: T[];
134
+ isLocalProvider: boolean;
135
+ activeProvider: TableDataProvider<any> | null;
136
+ dataProvider: ResolvedDataProvider;
137
+ } {
138
+ const _data = props.data ?? (EMPTY_ARRAY as T[]);
139
+ const isLocalProvider = props.provider == null && props.fetchData == null;
140
+ const isExplicitProvider = props.provider != null;
141
+ const activeProvider = useMemo<TableDataProvider<any> | null>(() => {
142
+ if (props.provider != null) return props.provider;
143
+ if (props.fetchData != null) {
144
+ return {
145
+ fetchData: props.fetchData,
146
+ identity: props.identity ?? ((r: any) => r?.id),
147
+ } as TableDataProvider<any>;
148
+ }
149
+ if (_data.length > 0) {
150
+ return createLocalProvider(
151
+ _data,
152
+ props.identity != null
153
+ ? { identity: props.identity as (row: any) => string | number }
154
+ : undefined,
155
+ );
156
+ }
157
+ return null;
158
+ // eslint-disable-next-line react-hooks/exhaustive-deps
159
+ }, [props.provider, props.fetchData, _data, props.identity]);
160
+ const localCount = isLocalProvider ? _data.length : 0;
161
+ const dataProvider = useMemo(
162
+ () => ({
163
+ provider: activeProvider,
164
+ isLocalProvider,
165
+ isExplicitProvider,
166
+ localCount,
167
+ }),
168
+ [activeProvider, isLocalProvider, isExplicitProvider, localCount],
169
+ );
170
+ return { data: _data, isLocalProvider, activeProvider, dataProvider };
171
+ }
172
+
173
+ function DataSheetStoreWrapper<T>(props: DataSheetProviderProps<T>) {
174
+ const { toaster, ...rest } = props;
175
+ const [store] = useState(() => {
176
+ return createStore<DataSheetStore<T>>(createZustandStore);
177
+ });
178
+ return h(
179
+ ctx.Provider,
180
+ {
181
+ atoms: [
182
+ [storeAPIAtom, store],
183
+ [toasterAtom, toaster],
184
+ ],
185
+ },
186
+ h(DataSheetProviderInner, rest),
187
+ );
188
+ }
189
+
190
+ const tableDataProviderKeys = new Set([
191
+ "provider",
192
+ "fetchData",
193
+ "data",
194
+ "identity",
195
+ ]);
196
+
197
+ const dataProviderKeys = new Set([
198
+ "columnSpec",
199
+ "columnSpecOptions",
200
+ "name",
201
+ "itemLabel",
202
+ "enableColumnReordering",
203
+ "defaultColumnWidth",
204
+ "refreshToken",
205
+ "identity",
206
+ "toaster",
207
+ "viewType",
208
+ "interactionOptions",
209
+ ]);
210
+
211
+ type AnyDataSheetProps<T> =
212
+ | DataViewProps<T>
213
+ | DataPanelProps<T>
214
+ | DataSheetProps<T>;
215
+
216
+ export function splitDataProviderProps<T>(props: AnyDataSheetProps<T>) {
217
+ /** Split provided props based on provider's needs */
218
+ return splitProps<AnyDataSheetProps<T>, DataSheetProviderProps<T>>(
219
+ props,
220
+ dataProviderKeys
221
+ .union(interactionOptionsKeys)
222
+ .union(tableDataProviderKeys) as Set<keyof DataSheetProviderProps<T>>,
223
+ );
224
+ }
225
+
226
+ export function DataSheetProvider<T>(
227
+ props: DataSheetProviderProps<T> & { children: React.ReactNode },
228
+ ) {
229
+ return h(
230
+ ToasterContext,
231
+ h(ErrorBoundary, h(DataSheetStoreWrapper<T>, props)),
232
+ );
233
+ }
234
+
235
+ type DataSheetProviderInnerProps<T> = DataSheetProviderProps<T> & {
236
+ dataProvider?: ResolvedDataProvider;
237
+ };
238
+
239
+ export function DataSheetProviderInner<T>(
240
+ props: DataSheetProviderInnerProps<T>,
241
+ ) {
242
+ const tableRef = useRef<Table>(null);
243
+
244
+ const [interactionOptionsProps, providerProps] = splitProps<
245
+ DataSheetProviderInnerProps<T>,
246
+ InteractionOptions
247
+ >(props, interactionOptionsKeys);
248
+ const interactionOptions = resolveInteractionOptions(
249
+ interactionOptionsProps,
250
+ props.viewType ?? DataViewRendererType.TABLE,
251
+ );
252
+
253
+ const {
254
+ children,
255
+ columnSpec,
256
+ columnSpecOptions,
257
+ name,
258
+ itemLabel,
259
+ enableColumnReordering,
260
+ defaultColumnWidth = 150,
261
+ refreshToken,
262
+ identity,
263
+ } = providerProps;
264
+
265
+ const { data, dataProvider } = useResolvedProvider<T>(providerProps);
266
+
267
+ const initializeStore = ctx.useSet(initializeStoreAtom);
268
+ const storeAPI = useStoreAPI<T>();
269
+
270
+ // The wrapper resolves the data source (see `DataSheet`); publish it into the
271
+ // scoped atom so the loader/store read it, rather than the inner render
272
+ // component resolving it each render. Kept updated as `data`/`provider`
273
+ // changes.
274
+
275
+ ctx.useSync(dataProviderAtom, dataProvider ?? DEFAULT_DATA_PROVIDER);
276
+ ctx.useSync(interactionOptionsAtom, interactionOptions);
277
+
278
+ const contentLabels = useMemo(() => {
279
+ return { tableName: name, itemLabel };
280
+ }, [name, itemLabel]);
281
+
282
+ ctx.useSync(contentLabelsAtom, contentLabels);
283
+
284
+ // A function `columnSpec` is derived from the loaded rows later (in
285
+ // `_DataSheet`), not here — start it empty. Crucially it's kept OUT of the
286
+ // init effect's deps: re-running init also resets `data`, so re-initializing
287
+ // when the function's identity changes (e.g. a consumer hiding a column)
288
+ // would wipe the loaded rows. `staticSpec` is a stable value in that case.
289
+ const isFnSpec = typeof columnSpec === "function";
290
+
291
+ const staticSpec = isFnSpec ? EMPTY_SPEC : columnSpec;
292
+ // Not sure how required this initialization is
293
+ const baseSpec = staticSpec ?? generateColumnSpec(data, columnSpecOptions);
294
+
295
+ useEffect(() => {
296
+ initializeStore({
297
+ columnSpec: postprocessColumnSpec(baseSpec),
298
+ // A function spec is derived from the loaded rows in `_DataSheet`; tell
299
+ // the loader not to auto-generate a plain spec from the first chunk.
300
+ deferColumnSpec: isFnSpec,
301
+ editable: interactionOptions.enableEditing,
302
+ enableColumnReordering,
303
+ data,
304
+ defaultColumnWidth,
305
+ tableRef,
306
+ });
307
+ }, [
308
+ data,
309
+ interactionOptions.enableEditing,
310
+ staticSpec,
311
+ isFnSpec,
312
+ columnSpecOptions,
313
+ enableColumnReordering,
314
+ ]);
315
+
316
+ // Function `columnSpec`: derive the spec from the loaded rows (no separate
317
+ // fetch of sample data), here at the provider level so BOTH renderers get it
318
+ // — the sheet's cell grid and the panel's `FacetControls` read the same
319
+ // derived spec. Derive once the first rows arrive, and re-derive when the
320
+ // function's identity changes (a consumer memoizes it over its own view state
321
+ // — hidden columns, order, overrides). Guarded by the function identity, so
322
+ // it never re-runs as more rows page in (which would clobber in-store column
323
+ // state on scroll).
324
+ const loadedData = useSelector<T, T[]>((s) => s.data ?? []);
325
+ const derivedSpecFor = useRef<unknown>(null);
326
+ useEffect(() => {
327
+ if (typeof columnSpec !== "function") return;
328
+ if (derivedSpecFor.current === columnSpec) return;
329
+ const rows = loadedData.filter((r) => r != null);
330
+ if (rows.length === 0) return;
331
+ derivedSpecFor.current = columnSpec;
332
+ storeAPI.setState({ columnSpec: columnSpec(rows) });
333
+ }, [columnSpec, loadedData, storeAPI]);
334
+
335
+ const bumpRefresh = ctx.useSet(dataRefreshTokenAtom);
336
+
337
+ // Imperative re-fetch: bump `refreshToken` to reload the provider (e.g.
338
+ // after a save). Skips the initial mount (the loader does its own first
339
+ // fetch). Shared by `_DataSheet` and `_DataPanel` — driven off this one
340
+ // provider-level `refreshToken`, whichever renderer is mounted.
341
+ const firstRefreshToken = useRef(true);
342
+ useEffect(() => {
343
+ if (firstRefreshToken.current) {
344
+ firstRefreshToken.current = false;
345
+ return;
346
+ }
347
+ bumpRefresh((v) => v + 1);
348
+ }, [refreshToken, bumpRefresh]);
349
+
350
+ // Provider-backed, auto-refreshing row mutations on the action context
351
+ // (`ctx.saveRows` / `deleteRows` / `insertRow`) — shared by `_DataSheet` and
352
+ // `_DataPanel` (the basis of a table/cards toggle) — so an immediate-edit
353
+ // action persists through the active provider and then re-fetches. Only the
354
+ // capabilities the provider supports are present.
355
+ useEffect(() => {
356
+ const p = dataProvider?.provider ?? null;
357
+ const refresh = () => bumpRefresh((v) => v + 1);
358
+ const withRefresh = <A extends any[]>(
359
+ fn?: (...args: A) => Promise<void>,
360
+ ) =>
361
+ fn == null
362
+ ? undefined
363
+ : async (...args: A) => {
364
+ await fn(...args);
365
+ refresh();
366
+ };
367
+ storeAPI.setState({
368
+ rowEditing: {
369
+ saveRows: withRefresh(p?.saveRows?.bind(p)),
370
+ deleteRows: withRefresh(p?.deleteRows?.bind(p)),
371
+ insertRow: withRefresh(p?.insertRow?.bind(p)),
372
+ refresh,
373
+ },
374
+ });
375
+ }, [storeAPI, dataProvider, bumpRefresh]);
376
+
377
+ // The active provider supplies the row identity for the edit overlay
378
+ // (`tableDataAtom`'s remap-by-identity), shared by `_DataSheet` and
379
+ // `_DataPanel` — falls back to the loose `identity` prop when the resolved
380
+ // provider doesn't carry its own (e.g. before the first row loads).
381
+ useEffect(() => {
382
+ const id = dataProvider?.provider?.identity ?? identity;
383
+ if (id != null) storeAPI.setState({ identity: id });
384
+ }, [storeAPI, dataProvider, identity]);
385
+
386
+ // Row deletion is a provider capability: an explicit `provider` (not a loose
387
+ // `fetchData`/`data` source) without `deleteRows` disables deletion
388
+ // entirely. Loose/local sources keep the in-table delete overlay. Shared by
389
+ // `_DataSheet` and `_DataPanel` — gates the delete action's disabled state
390
+ // read by the shared `ActionsToolbar`.
391
+ useEffect(() => {
392
+ const canDeleteRows =
393
+ !dataProvider?.isExplicitProvider ||
394
+ dataProvider.provider?.deleteRows != null;
395
+ storeAPI.setState({ canDeleteRows });
396
+ }, [storeAPI, dataProvider]);
397
+
398
+ return children;
399
+ }
400
+
401
+ export function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {
402
+ const store = ctx.useValue(storeAPIAtom);
403
+ if (!store) {
404
+ throw new Error("Missing DataSheetProvider");
405
+ }
406
+ return store;
407
+ }
408
+
409
+ export function useSelector<T = any, A = any>(
410
+ selector: (state: DataSheetStore<T>) => A,
411
+ ): A {
412
+ const store = useStoreAPI<T>();
413
+ return useStore(store, selector);
414
+ }
415
+ /** Atoms for efficient sub-selection of state */
416
+
417
+ export const columnSpecAtom = atom((get) => get(storeAtom)?.columnSpec ?? []);
418
+
419
+ export const tableDataAtom = atom(
420
+ (get) => {
421
+ return get(storeAtom)?.data ?? [];
422
+ },
423
+ (get, set, newData: any[]) => {
424
+ set(storeAtom, (state: DataSheetState<any>): DataSheetState<any> => {
425
+ let next: DataSheetState<any> = { ...state, data: newData };
426
+ // Auto-generate a plain column spec the first time real rows arrive — no
427
+ // spec yet and none deferred to a function (a function spec is derived
428
+ // separately). Keyed on "spec still empty + a non-null row present", NOT
429
+ // on `data.length == 0`: the loader pre-fills `data` with a page of `null`
430
+ // ghost rows on reset, so the array is non-empty before the first chunk.
431
+ if (state.columnSpec.length == 0 && !state.deferColumnSpec) {
432
+ const sample = newData.filter((row) => row != null);
433
+ if (sample.length > 0) {
434
+ next.columnSpec = generateColumnSpec(sample, state.columnSpecOptions);
435
+ }
436
+ }
437
+
438
+ // Re-attach the edit overlay by identity. The loader replaces `data` with
439
+ // re-ordered windows on sort/filter, so an index-keyed overlay would
440
+ // smear; keying by identity keeps edits (and deletes) on their rows, holds
441
+ // edits for not-yet-loaded rows, and re-appends locally-added rows (which
442
+ // aren't in the provider's data) after it. Skipped when the consumer
443
+ // controls the overlay (they own reconciliation).
444
+ if (!state.controlledOverlay) {
445
+ const remap = remapOverlayByIdentity(state, newData);
446
+ next.data = remap.data;
447
+ next.updatedData = remap.updatedData;
448
+ next.rowStatus = remap.rowStatus;
449
+ next.pendingOverlayById = remap.pending;
450
+ }
451
+
452
+ return next;
453
+ });
454
+ },
455
+ );
456
+
457
+ type OverlayEntry = { edit?: any; status?: any };
458
+
459
+ /** Row identity used by the overlay: an in-table-added row's synthetic id
460
+ * (stable across its edits), else the provider/consumer `identity`. */
461
+ function overlayIdentity(
462
+ state: DataSheetState<any>,
463
+ row: any,
464
+ ): string | number | null | undefined {
465
+ if (row == null) return undefined;
466
+ const added = row[DS_ROW_ID];
467
+ if (added != null) return added;
468
+ return state.identity(row);
469
+ }
470
+
471
+ /** Re-project the (index-keyed) edit overlay from the old `data` order onto a
472
+ * new one, matching rows by identity. Edits/statuses whose row is absent from
473
+ * `newData` are held in `pending` and re-applied when the row loads; rows added
474
+ * in-table (status `ADDED`) are re-appended after the provider data (they have
475
+ * no provider row). Starts from the prior pending set so edits survive multiple
476
+ * re-sorts. Returns the reconstructed data (provider rows + re-appended added
477
+ * rows) alongside the re-aligned overlay. */
478
+ function remapOverlayByIdentity(
479
+ state: DataSheetState<any>,
480
+ newData: any[],
481
+ ): {
482
+ data: any[];
483
+ updatedData: any[];
484
+ rowStatus: any[];
485
+ pending: Map<string | number, OverlayEntry>;
486
+ } {
487
+ const { data: oldData, updatedData, rowStatus } = state;
488
+
489
+ // Collect current overlay entries by identity, seeded with prior pending.
490
+ const byId = new Map<string | number, OverlayEntry>(state.pendingOverlayById);
491
+ const n = Math.max(
492
+ oldData.length,
493
+ updatedData?.length ?? 0,
494
+ rowStatus?.length ?? 0,
495
+ );
496
+ for (let i = 0; i < n; i++) {
497
+ const row = oldData[i];
498
+ if (row == null) continue;
499
+ const id = overlayIdentity(state, row);
500
+ if (id == null) continue;
501
+ const edit = updatedData?.[i];
502
+ const status = rowStatus?.[i];
503
+ if (edit != null || status != null) byId.set(id, { edit, status });
504
+ }
505
+
506
+ // Project onto the new data order.
507
+ const resultData = newData.slice();
508
+ const nextUpdated: any[] = [];
509
+ const nextStatus: any[] = [];
510
+ const attached = new Set<string | number>();
511
+ for (let j = 0; j < resultData.length; j++) {
512
+ const row = resultData[j];
513
+ if (row == null) continue;
514
+ const id = overlayIdentity(state, row);
515
+ if (id == null) continue;
516
+ const entry = byId.get(id);
517
+ if (entry == null) continue;
518
+ if (entry.edit != null) nextUpdated[j] = entry.edit;
519
+ if (entry.status != null) nextStatus[j] = entry.status;
520
+ attached.add(id);
521
+ }
522
+
523
+ // Re-append in-table-added rows (not present in the provider data), then hold
524
+ // anything still unattached (rows not currently loaded) as pending.
525
+ const pending = new Map<string | number, OverlayEntry>();
526
+ for (const [id, entry] of byId) {
527
+ if (attached.has(id)) continue;
528
+ if (entry.status === TableElementStatus.ADDED) {
529
+ const idx = resultData.length;
530
+ resultData.push(entry.edit ?? {});
531
+ nextUpdated[idx] = entry.edit;
532
+ nextStatus[idx] = entry.status;
533
+ } else {
534
+ pending.set(id, entry);
535
+ }
536
+ }
537
+
538
+ return {
539
+ data: resultData,
540
+ updatedData: nextUpdated,
541
+ rowStatus: nextStatus,
542
+ pending,
543
+ };
544
+ }
545
+
546
+ interface ContentLabels {
547
+ tableName: string | null | undefined;
548
+ itemLabel: string | null | undefined;
549
+ }
550
+
551
+ const contentLabelsAtom = atom<ContentLabels>({
552
+ tableName: null,
553
+ itemLabel: null,
554
+ });
555
+
556
+ export const itemLabelAtom = atom<string>((get) => {
557
+ return get(contentLabelsAtom).itemLabel ?? "row";
558
+ });
559
+ export const tableNameAtom = atom<string | null>((get) => {
560
+ let { tableName, itemLabel } = get(contentLabelsAtom);
561
+ if (tableName != null) return tableName;
562
+ if (itemLabel != null) capitalize(pluralize(itemLabel, 2));
563
+ return "Table";
564
+ });
565
+
566
+ export function useItemCount(n: number) {
567
+ const dataKind = ctx.useValue(itemLabelAtom);
568
+ return itemCount(n, dataKind ?? "row");
569
+ }
570
+
571
+ function itemCount(n: number, dataKind: string) {
572
+ const base = n == 0 ? "No" : `${n}`;
573
+ return base + " " + pluralize(dataKind, n);
574
+ }
575
+
576
+ export function pluralize(singularForm: string, n: number) {
577
+ const pluralForm = singularForm + "s";
578
+ if (n == 0) return `${pluralForm}`;
579
+ if (n == 1) return singularForm;
580
+ return pluralForm;
581
+ }
582
+
583
+ export function capitalize(s: string) {
584
+ return s.charAt(0).toUpperCase() + s.slice(1);
585
+ }
@@ -0,0 +1,7 @@
1
+ export * from "./core";
2
+ export * from "./table-data";
3
+ export * from "./types";
4
+ export * from "./zustand-store";
5
+ export * from "./interactions.ts";
6
+ export * from "./selection.ts";
7
+ export * from "./column-spec.ts";