@macrostrat/data-sheet 4.7.0 → 4.9.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 (125) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +60 -19
  3. package/dist/actions/context.cjs +10 -1
  4. package/dist/actions/context.cjs.map +1 -1
  5. package/dist/actions/context.js +10 -1
  6. package/dist/actions/context.js.map +1 -1
  7. package/dist/actions/types.d.ts +4 -0
  8. package/dist/components/data-editor.cjs +527 -0
  9. package/dist/components/data-editor.cjs.map +1 -0
  10. package/dist/components/data-editor.d.ts +142 -0
  11. package/dist/components/data-editor.js +524 -0
  12. package/dist/components/data-editor.js.map +1 -0
  13. package/dist/components/editor-actions.cjs +167 -0
  14. package/dist/components/editor-actions.cjs.map +1 -0
  15. package/dist/components/editor-actions.d.ts +37 -0
  16. package/dist/components/editor-actions.js +165 -0
  17. package/dist/components/editor-actions.js.map +1 -0
  18. package/dist/components/editor-popup.cjs +11 -1
  19. package/dist/components/editor-popup.cjs.map +1 -1
  20. package/dist/components/editor-popup.js +11 -1
  21. package/dist/components/editor-popup.js.map +1 -1
  22. package/dist/components/index.d.ts +3 -0
  23. package/dist/components/indicators/selection.cjs +10 -4
  24. package/dist/components/indicators/selection.cjs.map +1 -1
  25. package/dist/components/indicators/selection.js +10 -4
  26. package/dist/components/indicators/selection.js.map +1 -1
  27. package/dist/components/row-editor.cjs +351 -0
  28. package/dist/components/row-editor.cjs.map +1 -0
  29. package/dist/components/row-editor.d.ts +181 -0
  30. package/dist/components/row-editor.js +349 -0
  31. package/dist/components/row-editor.js.map +1 -0
  32. package/dist/components/row-editor.module.sass.cjs +51 -0
  33. package/dist/components/row-editor.module.sass.cjs.map +1 -0
  34. package/dist/components/row-editor.module.sass.js +49 -0
  35. package/dist/components/row-editor.module.sass.js.map +1 -0
  36. package/dist/components/toolbars/actions-toolbar.cjs +1 -1
  37. package/dist/components/toolbars/actions-toolbar.cjs.map +1 -1
  38. package/dist/components/toolbars/actions-toolbar.js +1 -1
  39. package/dist/components/toolbars/actions-toolbar.js.map +1 -1
  40. package/dist/data-panel.cjs +36 -0
  41. package/dist/data-panel.cjs.map +1 -1
  42. package/dist/data-panel.d.ts +3 -2
  43. package/dist/data-panel.js +37 -1
  44. package/dist/data-panel.js.map +1 -1
  45. package/dist/data-panel.module.sass.cjs +28 -26
  46. package/dist/data-panel.module.sass.cjs.map +1 -1
  47. package/dist/data-panel.module.sass.js +28 -26
  48. package/dist/data-panel.module.sass.js.map +1 -1
  49. package/dist/data-sheet.css +267 -56
  50. package/dist/data-sheet.d.ts +2 -1
  51. package/dist/data-view.d.ts +1 -0
  52. package/dist/index.cjs +28 -0
  53. package/dist/index.cjs.map +1 -1
  54. package/dist/index.js +31 -3
  55. package/dist/index.js.map +1 -1
  56. package/dist/main.module.sass.cjs +14 -13
  57. package/dist/main.module.sass.cjs.map +1 -1
  58. package/dist/main.module.sass.js +14 -13
  59. package/dist/main.module.sass.js.map +1 -1
  60. package/dist/postgrest-table/data-loaders.cjs +8 -1
  61. package/dist/postgrest-table/data-loaders.cjs.map +1 -1
  62. package/dist/postgrest-table/data-loaders.js +9 -2
  63. package/dist/postgrest-table/data-loaders.js.map +1 -1
  64. package/dist/provider/column-spec.cjs +8 -1
  65. package/dist/provider/column-spec.cjs.map +1 -1
  66. package/dist/provider/column-spec.d.ts +105 -1
  67. package/dist/provider/column-spec.js +8 -1
  68. package/dist/provider/column-spec.js.map +1 -1
  69. package/dist/provider/core.cjs +32 -7
  70. package/dist/provider/core.cjs.map +1 -1
  71. package/dist/provider/core.d.ts +5 -1
  72. package/dist/provider/core.js +32 -7
  73. package/dist/provider/core.js.map +1 -1
  74. package/dist/provider/loader-state.cjs +11 -3
  75. package/dist/provider/loader-state.cjs.map +1 -1
  76. package/dist/provider/loader-state.d.ts +8 -1
  77. package/dist/provider/loader-state.js +12 -4
  78. package/dist/provider/loader-state.js.map +1 -1
  79. package/dist/provider/table-data.cjs +10 -1
  80. package/dist/provider/table-data.cjs.map +1 -1
  81. package/dist/provider/table-data.d.ts +10 -0
  82. package/dist/provider/table-data.js +11 -2
  83. package/dist/provider/table-data.js.map +1 -1
  84. package/dist/provider/types.cjs.map +1 -1
  85. package/dist/provider/types.d.ts +4 -1
  86. package/dist/provider/types.js.map +1 -1
  87. package/dist/provider/zustand-store.cjs +26 -13
  88. package/dist/provider/zustand-store.cjs.map +1 -1
  89. package/dist/provider/zustand-store.js +14 -1
  90. package/dist/provider/zustand-store.js.map +1 -1
  91. package/dist/renderers/cell-renderer.cjs +15 -4
  92. package/dist/renderers/cell-renderer.cjs.map +1 -1
  93. package/dist/renderers/cell-renderer.js +13 -4
  94. package/dist/renderers/cell-renderer.js.map +1 -1
  95. package/dist/renderers/column-header-cell.cjs +12 -1
  96. package/dist/renderers/column-header-cell.cjs.map +1 -1
  97. package/dist/renderers/column-header-cell.js +11 -1
  98. package/dist/renderers/column-header-cell.js.map +1 -1
  99. package/dist/types.cjs.map +1 -1
  100. package/dist/types.d.ts +30 -1
  101. package/dist/types.js.map +1 -1
  102. package/package.json +2 -2
  103. package/src/actions/context.ts +13 -2
  104. package/src/actions/types.ts +5 -0
  105. package/src/components/data-editor.ts +741 -0
  106. package/src/components/editor-actions.ts +228 -0
  107. package/src/components/editor-popup.ts +16 -3
  108. package/src/components/index.ts +3 -0
  109. package/src/components/indicators/selection.ts +12 -4
  110. package/src/components/row-editor.module.sass +161 -0
  111. package/src/components/row-editor.ts +620 -0
  112. package/src/components/toolbars/actions-toolbar.ts +3 -2
  113. package/src/data-panel.module.sass +25 -0
  114. package/src/data-panel.ts +50 -1
  115. package/src/main.module.sass +19 -0
  116. package/src/postgrest-table/data-loaders.ts +13 -0
  117. package/src/provider/column-spec.ts +94 -16
  118. package/src/provider/core.ts +41 -9
  119. package/src/provider/loader-state.ts +15 -2
  120. package/src/provider/table-data.ts +23 -1
  121. package/src/provider/types.ts +4 -1
  122. package/src/provider/zustand-store.ts +30 -1
  123. package/src/renderers/cell-renderer.ts +18 -3
  124. package/src/renderers/column-header-cell.ts +10 -0
  125. package/src/types.ts +31 -1
@@ -1 +1 @@
1
- {"version":3,"file":"data-loaders.js","sources":["../../src/postgrest-table/data-loaders.ts"],"sourcesContent":["/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n ClientServerOptions,\n PostgrestClient,\n PostgrestFilterBuilder,\n PostgrestQueryBuilder,\n} from \"@supabase/postgrest-js\";\nimport { adjustArraySize, RowRegion } from \"./loading-utils.ts\";\nimport {\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataFilter,\n tableDataAtom,\n TableDataProvider,\n useSelector,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { FetchDataOptions, FetchMode } from \"../types.ts\";\nimport {\n lazyLoaderCoreStateAtom,\n resolveInitialData,\n seededRows,\n type LazyLoaderStateCore,\n} from \"../provider/loader-state.ts\";\n\ninterface LazyLoaderState<T> extends LazyLoaderStateCore<T> {\n data: (T | null)[];\n visibleRegion: RowRegion;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\n/** Operators available for server-side column filtering via PostgREST.\n * `cs`/`ov` target array columns (contains / overlaps). */\nexport type PostgrestFilterOperator =\n | \"eq\"\n | \"neq\"\n | \"like\"\n | \"ilike\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"is\"\n | \"cs\"\n | \"ov\";\n\n/** A single column sort entry. */\nexport interface ColumnSortEntry {\n key: string;\n ascending: boolean;\n}\n\n/** A single column filter entry. */\nexport interface PostgrestColumnFilter {\n key: string;\n operator: PostgrestFilterOperator;\n value: string;\n}\n\nexport interface PostgrestFilter {\n id?: string;\n type: \"filter\";\n apply(\n req: PostgrestFilterBuilder<any, any, any, any>,\n ): PostgrestFilterBuilder<any, any, any, any>;\n}\n\nexport function standardizeFilter(\n columnFilter: PostgrestColumnFilter,\n): PostgrestFilter {\n return {\n type: \"filter\",\n apply(req) {\n return applyColumnFilters(req, [columnFilter]);\n },\n };\n}\n\nexport function applyColumnFilters(\n req: PostgrestFilterBuilder<any, any, any, any>,\n filters: PostgrestColumnFilter[],\n) {\n for (const cf of filters) {\n if (cf.value === \"\" || cf.value == null) continue;\n // Array-column operators need a list value and postgrest-js's dedicated\n // builders (which emit the `{…}` array literal), not a scalar `.filter`.\n if (cf.operator === \"cs\") {\n req = req.contains(cf.key, splitFilterList(cf.value));\n continue;\n }\n if (cf.operator === \"ov\") {\n req = req.overlaps(cf.key, splitFilterList(cf.value));\n continue;\n }\n const val =\n cf.operator === \"like\" || cf.operator === \"ilike\"\n ? `*${cf.value}*`\n : cf.value;\n req = req.filter(cf.key, cf.operator, val);\n }\n return req;\n}\n\n/** Split a comma-separated filter value into trimmed, non-empty tokens (the set\n * for `cs`/`ov`); a single value yields a one-element list. */\nfunction splitFilterList(value: any): string[] {\n return String(value)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | { type: \"seed\"; data: T[]; totalCount?: number | null }\n | {\n type: \"loaded\";\n data: T[];\n offset: number;\n totalSize: number;\n totalCount?: number | null;\n }\n | { type: \"error\"; error: Error }\n | { type: \"update-data\"; changes: Spec<T[]> }\n | { type: \"reset\" }\n | { type: \"configure\"; fetchMode: FetchMode; pageSize: number };\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes as any),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n const newData = action.data ?? [];\n const offset = action.offset ?? 0;\n data = [\n ...data.slice(0, offset),\n ...newData,\n ...data.slice(offset + newData.length),\n ];\n return {\n ...state,\n data,\n loading: false,\n totalCount:\n action.totalCount !== undefined\n ? action.totalCount\n : state.totalCount,\n };\n case \"configure\":\n return {\n ...state,\n fetchMode: action.fetchMode,\n pageSize: action.pageSize,\n };\n case \"reset\":\n // A view change (or initial load) re-fetches from scratch. Rather than\n // blanking the table (which reads as a jarring empty flash while the\n // request is in flight — very visible on sort/filter), pre-size to a page\n // of `null` ghost/skeleton rows so the body stays populated and the load\n // is legible. `loaded` then adjusts the array to the real size.\n return {\n visibleRegion: defaultVisibleRegion,\n data: new Array(Math.max(state.pageSize, 0)).fill(null),\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n case \"seed\": {\n // Rows the caller already had (a server render, say). Same shape as a\n // completed first fetch: pre-size to the reported total so the scrollbar\n // and counter are right immediately, and mark the loader `initialized` so\n // it neither refetches the seeded window nor flashes an empty state.\n const data = seededRows({\n rows: action.data ?? [],\n totalCount: action.totalCount,\n });\n return {\n visibleRegion: defaultVisibleRegion,\n data: data as T[],\n loading: false,\n error: null,\n initialized: true,\n totalCount: action.totalCount ?? null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n }\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ntype SortAndFilterOptions = {\n /** Column-level sort state, managed externally. When provided, overrides\n * the `order` prop for query building. */\n order?: PostgrestOrder<any>[];\n filters?: PostgrestFilter[];\n};\n\ninterface QueryConfig extends SortAndFilterOptions {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n identityKey: string;\n /** The identity column's default ordering (used when nothing in `order`\n * already sorts it). A string ⇒ ascending; pass a `PostgrestOrder` to set the\n * direction (e.g. `source_id` descending). */\n identityOrder?: PostgrestOrder<any>;\n lastLoadedRow?: any;\n lastLoadedRowIndex: number;\n}\n\n/** Format a value for a PostgREST logic-tree condition. Reserved characters\n * (`, . : ( )`), spaces, quotes, and backslashes require the value to be\n * double-quoted, with `\"` and `\\` backslash-escaped inside — otherwise a map\n * name containing a comma would break the `or=(...)` parse. */\nfunction formatKeysetValue(v: any): string {\n const s = String(v);\n if (s === \"\" || /[,.:()\"\\\\ ]/.test(s)) {\n return `\"${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n return s;\n}\n\n/** An equality condition for the cursor prefix (`col.eq.v`, or `col.is.null`). */\nfunction keysetEq(key: string, v: any): string {\n return v == null ? `${key}.is.null` : `${key}.eq.${formatKeysetValue(v)}`;\n}\n\n/**\n * Build the compound keyset predicate (the body of an `or=(...)`) selecting\n * rows strictly after `lastRow` under `clauses` (lexicographic, last clause is\n * the identity tiebreaker):\n *\n * (c1 OP1 v1)\n * OR (c1 = v1 AND c2 OP2 v2)\n * OR (c1 = v1 AND c2 = v2 AND c3 OP3 v3) …\n *\n * `OPi` is `gt` for an ascending clause, `lt` for descending. Nulls-last: a\n * null pivot value has no strictly-ordered non-null successor at its level, so\n * that term is skipped and the tie defers to deeper clauses (the identity key\n * is non-null, so at least its term is always emitted). Returns `null` if no\n * term applies. (Known limit: rows whose *sort* column is null aren't picked up\n * across the non-null→null boundary — an edge for nullable sort columns; the\n * non-null identity tiebreaker keeps pagination from stalling.)\n */\nfunction buildKeysetPredicate(\n clauses: PostgrestOrder<any>[],\n lastRow: any,\n): string | null {\n const terms: string[] = [];\n for (let i = 0; i < clauses.length; i++) {\n const v = lastRow[clauses[i].key];\n if (v == null) continue;\n const conds: string[] = [];\n for (let j = 0; j < i; j++) {\n conds.push(keysetEq(clauses[j].key, lastRow[clauses[j].key]));\n }\n const op = (clauses[i].ascending ?? true) ? \"gt\" : \"lt\";\n conds.push(`${clauses[i].key}.${op}.${formatKeysetValue(v)}`);\n terms.push(conds.length === 1 ? conds[0] : `and(${conds.join(\",\")})`);\n }\n return terms.length > 0 ? terms.join(\",\") : null;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<any, any, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count, lastLoadedRowIndex } = config;\n const opts = { count };\n\n let cols: string;\n if (Array.isArray(columns)) {\n cols = columns.join(\", \");\n } else {\n cols = columns ?? \"*\";\n }\n\n let query = client.select(cols, opts);\n\n const filters = config.filters ?? [];\n for (const filter of filters) {\n query = filter.apply(query);\n }\n\n const orderClauses = buildPostgrestOrderClauses(\n config.order ?? [],\n config.identityOrder ?? config.identityKey,\n );\n\n let hasOrdering = false;\n for (const clause of orderClauses) {\n query = query.order(clause.key, clause);\n hasOrdering = true;\n }\n\n // Keyset cursor: rows strictly after the last loaded row under the active\n // ordering. This MUST be a compound predicate, not an independent `gt`/`lt`\n // per column: with a leading low-cardinality sort (e.g. `state`), a plain\n // `state.gt.X AND source_id.lt.Y` drops every row sharing the cursor's\n // `state` (`state.gt.X` is false for them). The lexicographic form keeps the\n // tie broken by the next column, ending on the non-null identity key.\n if (config.lastLoadedRow != null && hasOrdering) {\n const pred = buildKeysetPredicate(orderClauses, config.lastLoadedRow);\n if (pred != null) query = query.or(pred);\n }\n\n let offset: number | null = null;\n if (!hasOrdering && lastLoadedRowIndex > 0) {\n // We need to load based on offsets\n offset = lastLoadedRowIndex + 1;\n }\n\n if (config.limit != null) {\n if (offset != null) {\n query = query.range(offset, offset + config.limit - 1);\n console.log(`Random seek from ${offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n\n return query;\n}\n\nconst defaultVisibleRegion: RowRegion = {\n rowIndexStart: 0,\n rowIndexEnd: 0,\n};\n\n/** Atom to house the current visible region of the table */\nconst visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);\n\n\n/** Current page index (0-based) for paged fetch mode. */\nexport const chunkPageAtom = atom(0);\n\n/** Footer state for the optional bottom-of-table indicator: rows loaded, the\n * source total when known, load status, and — in paged mode — the current\n * page and total pages. */\nexport interface TableFooterInfo {\n mode: FetchMode;\n loaded: number;\n total: number | null;\n loading: boolean;\n /** A fetch has been attempted since the last view reset — so `loaded === 0`\n * can be told apart from \"not loaded yet\" (avoids an empty-state flash). */\n initialized: boolean;\n error: Error | null;\n page: number;\n pageSize: number;\n totalPages: number | null;\n}\n\nexport const tableFooterAtom = atom<TableFooterInfo>((get) => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom) ?? [];\n let loaded = 0;\n let hasGaps = false;\n for (const row of data) {\n if (row != null) loaded++;\n else hasGaps = true;\n }\n // Total is known when the source reported it, or (scroll mode) when the array\n // is fully populated — otherwise it's still being discovered.\n const total = core.totalCount ?? (hasGaps ? null : data.length);\n const totalPages =\n core.totalCount != null ? Math.ceil(core.totalCount / core.pageSize) : null;\n return {\n mode: core.fetchMode,\n loaded,\n total,\n loading: core.loading,\n initialized: core.initialized,\n error: core.error,\n page: get(chunkPageAtom),\n pageSize: core.pageSize,\n totalPages,\n };\n});\n\n/** Auto-load this many pages per burst, then pause (null ⇒ unbounded). Set by\n * a consumer (e.g. `DataPanel`'s `autoLoadPages` prop). */\nexport const autoLoadPagesAtom = atom<number | null>(null);\n\n/** Row count at the last manual \"load more\" — the point auto-load resumes\n * counting a fresh burst from. */\nexport const resumeBaselineAtom = atom(0);\n\n/** Live loading controls, read from the store rather than passed down a\n * boundary contract. Any component inside the provider can call\n * `useLoadControls()` — a footer, a toolbar button, a status line — without the\n * renderer wiring a specific prop shape to it. */\nexport interface LoadControls {\n /** Load the next page and resume auto-loading (clears a paused state). */\n loadMore: () => void;\n /** A fetch is in flight. */\n loading: boolean;\n /** A fetch has been attempted since the last view reset (so an empty result\n * can be told apart from \"not loaded yet\"). */\n initialized: boolean;\n /** The most recent load error (cleared on the next successful load), else\n * `null` — so a footer/consumer can degrade gracefully instead of hanging. */\n error: Error | null;\n /** More rows remain to load. */\n hasMore: boolean;\n /** Rows loaded so far. */\n loaded: number;\n /** Source total when known, else `null`. */\n total: number | null;\n /** Auto-load is paused at the `autoLoadPages` checkpoint. */\n paused: boolean;\n /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —\n * used to gate an infinite-scroll sentinel. */\n canLoadMore: boolean;\n /** Advance one page *without* resuming a paused auto-load (the sentinel\n * uses this; `loadMore` is the manual, un-pausing variant). */\n advance: () => void;\n /** Rows per page. */\n pageSize: number;\n /** Current page index (0-based). Only meaningful in `\"paged\"` fetch mode —\n * scroll mode accumulates windows rather than sitting on a page. */\n page: number;\n /** Total pages when the source reported a total, else `null`. */\n totalPages: number | null;\n}\n\n/** Store-managed load controls (see `LoadControls`). Reads the loader's footer\n * state, the loaded rows, and the pause atoms; `loadMore`/`advance` set the\n * visible region so the loader fetches the next chunk. */\nexport function useLoadControls(): LoadControls {\n const footer = ctx.useValue(tableFooterAtom);\n const data = ctx.useValue(tableDataAtom) ?? [];\n const { isLocalProvider } = ctx.useValue(dataProviderAtom);\n const resumeBaseline = ctx.useValue(resumeBaselineAtom);\n const autoLoadPages = ctx.useValue(autoLoadPagesAtom);\n const setResumeBaseline = ctx.useSet(resumeBaselineAtom);\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n let loadedCount = 0;\n for (const row of data) if (row != null) loadedCount++;\n const pageSize = footer.pageSize || 100;\n const dataLength = data.length;\n const hasMore = !isLocalProvider && loadedCount < dataLength;\n const paused =\n autoLoadPages != null &&\n loadedCount - resumeBaseline >= autoLoadPages * pageSize;\n const canLoadMore = hasMore && !footer.loading && !paused;\n\n const advance = useCallback(() => {\n setVisibleRegion({\n rowIndexStart: 0,\n rowIndexEnd: Math.min(loadedCount + pageSize, dataLength),\n });\n }, [setVisibleRegion, loadedCount, pageSize, dataLength]);\n\n const loadMore = useCallback(() => {\n setResumeBaseline(loadedCount);\n advance();\n }, [setResumeBaseline, loadedCount, advance]);\n\n return {\n loadMore,\n loading: footer.loading,\n initialized: footer.initialized,\n error: footer.error,\n hasMore,\n loaded: footer.loaded,\n total: footer.total,\n paused,\n canLoadMore,\n advance,\n pageSize,\n page: footer.page,\n totalPages: footer.totalPages,\n // Page addressing is exposed so a footer can render a real link to the next\n // page, not just a button that calls `loadMore`. That's the difference\n // between a list a crawler (or a JS-less client) can follow and one it\n // can't — see the note on crawlable pagination in the Data list editors\n // feature doc.\n };\n}\n\nexport interface ViewInfo {\n visibleRegion: RowRegion;\n totalCount: number | null;\n loading: boolean;\n error: Error | null;\n}\n\nexport const viewInfoAtom = atom<ViewInfo>((get) => {\n const state = get(lazyLoaderStateAtom);\n return {\n visibleRegion: state.visibleRegion,\n loading: state.loading,\n error: state.error,\n totalCount: state.data.length,\n };\n});\n\n/** Temporary passthrough atom to allow visible region to be separated from the rest\n * of the lazy loader state\n */\nconst lazyLoaderStateAtom = atom(\n (get): LazyLoaderState<any> => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom);\n const visibleRegion = get(visibleRegionAtom);\n return {\n ...core,\n data,\n visibleRegion,\n };\n },\n (get, set, update: any) => {\n // Split the state between several places\n if (typeof update === \"function\") {\n update = update(get(lazyLoaderStateAtom));\n }\n const { visibleRegion, data, ...rest } = update;\n if (visibleRegion != null) {\n set(visibleRegionAtom, visibleRegion);\n }\n // Propagate the data array even when empty — a `reset` (view change) must\n // clear the stale rows so the re-fetch rebuilds a correctly-sized array\n // (otherwise a filtered/sorted result splices over a stale, larger array).\n if (data != null) {\n set(tableDataAtom, data);\n }\n if (Object.keys(rest).length > 1) {\n set(lazyLoaderCoreStateAtom, (v) => ({ ...v, ...rest }));\n }\n },\n);\n\nfunction useLazyLoaderReducer() {\n const [state, setState] = ctx.use(lazyLoaderStateAtom);\n const dispatch = useCallback(\n (action: LazyLoaderAction<any>) =>\n setState((prev) => lazyLoadingReducer(prev, action)),\n [setState],\n );\n return [state, dispatch] as const;\n}\n\nfunction buildPostgrestOrderClauses(\n sorts: (ColumnSortEntry | PostgrestOrder<any>)[],\n identityOrder: PostgrestOrder<any> | string,\n): PostgrestOrder<any>[] {\n // Build the ORDER BY for a PostgREST query. Two invariants:\n // 1. Each column appears at most once. Keyset pagination adds a `gt`/`lt`\n // cursor predicate per order clause, so a duplicated column (e.g. the\n // identity key present in both a base order and an active sort, with\n // opposite directions) would emit contradictory `col=lt.X&col=gt.X`\n // bounds that match nothing — an infinite empty-result reload. First\n // occurrence wins (active sorts should be passed ahead of base order).\n // 2. The identity key is ordered last (a stable tiebreaker for the cursor),\n // appended with its default direction only if no clause already sorts it.\n const identitySort =\n typeof identityOrder == \"string\"\n ? { key: identityOrder, ascending: true }\n : identityOrder;\n const identityKey = identitySort.key;\n\n const seen = new Set<string>();\n const clauses: PostgrestOrder<any>[] = [];\n for (const sort of sorts) {\n if (seen.has(sort.key)) continue;\n seen.add(sort.key);\n clauses.push({\n key: sort.key,\n ascending: sort.ascending,\n nullsFirst: \"nullsFirst\" in sort ? sort.nullsFirst : false,\n });\n }\n\n if (seen.has(identityKey)) {\n // Move the (already-deduped) identity clause to the end, keeping the\n // direction the active sort chose.\n const idx = clauses.findIndex((c) => c.key === identityKey);\n const [idClause] = clauses.splice(idx, 1);\n clauses.push(idClause);\n } else {\n clauses.push({\n key: identitySort.key,\n ascending: identitySort.ascending ?? true,\n nullsFirst: (identitySort as any).nullsFirst ?? false,\n });\n }\n return clauses;\n}\n\nexport function useScrollHandler() {\n /** A standardized approach to holding onto the scroll position for the table */\n // Reference to hold onto the scroll position\n const ref = useRef<RowRegion>(null);\n\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n return useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n setVisibleRegion(visibleCells);\n ref.current = visibleCells;\n }, 500),\n [setVisibleRegion],\n );\n}\n\n/**\n * A generic, backend-agnostic windowed data source. Give it a `fetchChunk`\n * function and it drives the sheet's lazy loading: it loads the chunk covering\n * the first unloaded visible row, pre-sizes the sparse array from `totalCount`,\n * threads the active sorts/filters through so the source can apply them\n * server-side, and re-fetches from scratch when the view state changes. This\n * is the unified seam that upstreams bespoke loaders (`fetchChunk` receives the\n * view state; there's no separate adapter object).\n *\n * Call it from a component rendered inside `DataSheet` (see `ChunkLoaderManager`).\n */\nexport function useDataLoader<T = any>(\n fetchChunk: FetchData<T>,\n options: FetchDataOptions<T> = {},\n) {\n const {\n pageSize = 100,\n fetchMode = \"scroll\",\n filterDebounce = 0,\n initialData,\n } = options;\n const [state, dispatch] = useLazyLoaderReducer();\n\n const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);\n\n const visibleRegion = ctx.useValue(visibleRegionAtom);\n const page = ctx.useValue(chunkPageAtom);\n const setPage = ctx.useSet(chunkPageAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n const columnSorts = useSelector((s) => s.columnSorts);\n const activeFilters = useSelector((s) => s.activeFilters);\n const abortRef = useRef<AbortController | null>(null);\n // Tracks the (page, viewKey) already loaded in paged mode, so the effect\n // doesn't re-fetch on unrelated re-renders.\n const loadedRef = useRef<{ page: number; viewKey: string }>({\n page: -1,\n viewKey: \"\",\n });\n\n const filters: FetchDataFilter[] = useMemo(\n () =>\n (Array.from(activeFilters.entries()) as [any, any][]).map(\n ([id, entry]) => ({\n id,\n columnKey: entry.filter?.columnKey,\n state: entry.state,\n predicate: entry.filter?.predicate,\n }),\n ),\n [activeFilters],\n );\n\n // Publish the windowing config so the footer/pager can read it.\n useEffect(() => {\n dispatch({ type: \"configure\", fetchMode, pageSize: pageSize });\n }, [fetchMode, pageSize]);\n\n // Reset (re-fetch from scratch) when sorts/filters change, or when the fetch\n // mode switches (paged holds a dense page; scroll needs to re-initialize and\n // pre-size) — so a table can flip between modes cleanly.\n const viewKey = useMemo(\n () => JSON.stringify({ sorts: columnSorts, filters }),\n [columnSorts, filters],\n );\n // Debounce the view-state → refetch: rapid changes (typing in a text filter)\n // otherwise reset + refetch on every keystroke, flashing the list. The store\n // (and so the filter input) still updates instantly; only the *fetch* waits\n // for the view to settle. Scroll paging is unaffected — it's driven by\n // `visibleRegion`/`data`, not this key. `filterDebounce: 0` (default) keeps\n // the immediate behavior.\n const debouncedViewKey = useDebouncedValue(viewKey, filterDebounce);\n // A caller-supplied first window (`initialData`) stands in for the mount-time\n // reset+fetch. It's consumed once: any later view change resets normally,\n // since the seed only describes the view it was fetched for.\n //\n // The store is normally created already seeded (`DataSheetStoreWrapper`), so\n // the rows are in the very first render — including a server render. The\n // dispatch below is the fallback for a store that wasn't.\n const seedRef = useRef(resolveInitialData(initialData));\n // Gate on the seed until it's actually in state (see the fetch effect).\n const awaitingSeedRef = useRef(seedRef.current != null);\n useEffect(() => {\n const seed = seedRef.current;\n seedRef.current = null;\n if (seed != null) {\n if (!state.initialized) {\n dispatch({\n type: \"seed\",\n data: seed.rows,\n totalCount: seed.totalCount,\n });\n }\n setPage(0);\n // Paged mode tracks which (page, view) it has in hand separately from the\n // array; record the seed there too, or it would immediately re-fetch the\n // page it was just handed.\n loadedRef.current = { page: 0, viewKey };\n return;\n }\n dispatch({ type: \"reset\" });\n setPage(0);\n }, [debouncedViewKey, fetchMode, refreshToken]);\n\n useAsyncEffect(async () => {\n if (state.loading) return;\n\n // A seed hasn't landed in state yet. Every effect in a commit sees the\n // render's snapshot, so this one runs *before* the seed it was mounted\n // alongside is visible — and would issue exactly the request the seed\n // exists to avoid. Skip until the seeded state arrives.\n if (awaitingSeedRef.current) {\n if (state.initialized) awaitingSeedRef.current = false;\n return;\n }\n\n // Determine the chunk offset to fetch, and (scroll mode) a keyset cursor:\n // the already-loaded row just before the chunk, so keyset sources can page\n // from it instead of a slow OFFSET.\n let offset: number;\n let cursor: { row: any; index: number } | null = null;\n if (fetchMode === \"paged\") {\n // Fetch the current page once; skip if already loaded for this view.\n if (\n loadedRef.current.page === page &&\n loadedRef.current.viewKey === viewKey\n ) {\n return;\n }\n offset = page * pageSize;\n } else {\n const rowIndex = indexOfFirstNullInRegion(state.data, visibleRegion);\n if (rowIndex == null && state.initialized) return;\n offset = Math.floor((rowIndex ?? 0) / pageSize) * pageSize;\n const prev = offset > 0 ? state.data[offset - 1] : null;\n if (prev != null) cursor = { row: prev, index: offset - 1 };\n }\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n dispatch({ type: \"start-loading\" });\n try {\n const result = await fetchChunk({\n offset,\n limit: pageSize,\n signal: controller.signal,\n sorts: columnSorts,\n filters,\n cursor,\n });\n if (controller.signal.aborted) return;\n const rows = result.rows ?? [];\n if (fetchMode === \"paged\") {\n loadedRef.current = { page, viewKey };\n // The sheet shows just this page's rows (dense, from index 0); the\n // real source length is tracked separately for the pager.\n dispatch({\n type: \"loaded\",\n data: rows,\n offset: 0,\n totalSize: rows.length,\n totalCount: result.totalCount ?? null,\n });\n } else {\n // Size the (sparse) array. With a known total, size to it. Without one\n // (keyset / infinite scroll), use the short-chunk heuristic: a chunk\n // smaller than the page size means we've hit the end — size exactly to\n // the loaded rows; otherwise pad one more page of nulls so scrolling\n // into them triggers the next fetch. So an unknown-length source never\n // needs a count — it grows a page at a time until a short chunk.\n const loadedEnd = offset + rows.length;\n let totalSize: number;\n if (result.totalCount != null) {\n totalSize = result.totalCount;\n } else {\n const reachedEnd = rows.length < pageSize;\n totalSize = reachedEnd ? loadedEnd : loadedEnd + pageSize;\n }\n dispatch({\n type: \"loaded\",\n data: rows,\n offset,\n totalSize,\n // Preserve a previously-known total when a chunk omits it (undefined):\n // keyset pages can't re-count (the cursor filter would skew it), so\n // only the initial cursorless fetch reports the total.\n totalCount: result.totalCount,\n });\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n dispatch({ type: \"error\", error: err as Error });\n }\n }\n }, [state.data, visibleRegion, debouncedViewKey, page, fetchMode]);\n\n return { data: state.data, loading: state.loading, error: state.error };\n}\n\n/** A value that trails `value` by `delay` ms of stability — the first value is\n * returned immediately, and `delay <= 0` disables debouncing entirely. */\nfunction useDebouncedValue<T>(value: T, delay: number): T {\n const [debounced, setDebounced] = useState(value);\n useEffect(() => {\n if (delay <= 0) {\n setDebounced(value);\n return;\n }\n const t = setTimeout(() => setDebounced(value), delay);\n return () => clearTimeout(t);\n }, [value, delay]);\n return debounced;\n}\n\n/**\n * Build a `fetchChunk` backed by a PostgREST endpoint, for use with\n * `useChunkLoader` / `ChunkLoaderManager`. It reuses `buildQuery`, so it pages\n * with **keyset pagination** (via the loader's `cursor`) whenever the query is\n * ordered — falling back to `OFFSET` only when it isn't — and threads the\n * active store sorts/filters into the query. The total count is requested only\n * on the initial (cursorless) fetch, since a keyset cursor filter would skew it.\n */\nexport function createPostgRESTFetchChunk<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (applied when no active\n * sort targets it). `false` ⇒ the table defaults to identity-descending\n * (e.g. newest `source_id` first) without a redundant `baseOrder` entry that\n * would otherwise collide with the identity tiebreaker. Defaults to `true`. */\n identityAscending?: boolean;\n columns?: string | string[];\n /** Order applied before the active column sorts (identity key appended last). */\n baseOrder?: PostgrestOrder<any>[];\n /** A transform over the query builder, applied as a base filter (the `filter` prop). */\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n /** Translate a stored filter entry to a `PostgrestFilter` (return `null` to\n * skip). Defaults to the `{ key, operator, value }` column-filter shape. */\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): FetchData<T> {\n const translate = config.translateFilter ?? standardColumnFilter;\n return async ({ limit, signal, sorts, filters, cursor }) => {\n const client = new PostgrestClient(config.endpoint).from(config.table);\n\n // Active sorts first so they win the by-key dedupe in\n // `buildPostgrestOrderClauses` (a user sort on the identity column\n // overrides its default direction rather than colliding with it).\n const order: PostgrestOrder<any>[] = [\n ...sorts.map((s) => ({ key: s.key, ascending: s.ascending })),\n ...(config.baseOrder ?? []),\n ];\n\n const pgFilters: PostgrestFilter[] = [];\n if (config.baseFilter != null) {\n const apply = config.baseFilter;\n pgFilters.push({ type: \"filter\", apply });\n }\n for (const f of filters) {\n const pf = translate(f);\n if (pf != null) pgFilters.push(pf);\n }\n\n const query = buildQuery(client, {\n columns: config.columns,\n // Only the initial (cursorless) fetch reports an accurate total.\n count: cursor == null ? \"exact\" : undefined,\n limit,\n identityKey: config.identityKey,\n identityOrder: {\n key: config.identityKey,\n ascending: config.identityAscending ?? true,\n },\n order,\n filters: pgFilters,\n lastLoadedRow: cursor?.row ?? null,\n lastLoadedRowIndex: cursor?.index ?? -1,\n });\n\n const res: any = await query;\n if (signal.aborted) return { rows: [] };\n if (res?.error != null) throw res.error;\n const rows = res?.data ?? [];\n return res?.count != null ? { rows, totalCount: res.count } : { rows };\n };\n}\n\n/**\n * A full PostgREST `TableDataProvider`: the read side (`fetchData` + row\n * `identity`) plus persistence — `saveRows` (upsert) and `deleteRows` (by\n * identity). Pass it to `DataSheet`'s `provider` prop. The mutation methods\n * throw on error so the Save action surfaces it.\n */\nexport function createPostgRESTProvider<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (see\n * `createPostgRESTFetchChunk`). `false` ⇒ identity-descending by default. */\n identityAscending?: boolean;\n columns?: string | string[];\n baseOrder?: PostgrestOrder<any>[];\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): TableDataProvider<T> {\n const from = () => new PostgrestClient(config.endpoint).from(config.table);\n return {\n fetchData: createPostgRESTFetchChunk<T>(config),\n identity: (row: any) => row?.[config.identityKey],\n async distinctValues(columnKey, options = {}) {\n // PostgREST derives a GROUP BY from a `select` that mixes a plain column\n // with an aggregate, so one small request returns the whole vocabulary\n // *with* frequencies — rather than paging the table and deduplicating\n // client-side. Ordered by the value so the picker's list is stable.\n //\n // `baseFilter` applies (it defines the rows this view is *about*), but the\n // *active* filters deliberately don't: a picker whose options disappear as\n // you narrow the view can't be used to widen it again.\n let req: any = from().select(`${columnKey},count()`);\n if (config.baseFilter != null) req = config.baseFilter(req);\n req = req.order(columnKey, { ascending: true, nullsFirst: false });\n if (options.limit != null) req = req.limit(options.limit);\n if (options.signal != null) req = req.abortSignal(options.signal);\n const { data, error } = await req;\n if (error != null) throw error;\n return (data ?? []).map((row: any) => ({\n value: row[columnKey],\n count: row.count,\n }));\n },\n async saveRows(rows) {\n const res: any = await from().upsert(rows as any[], {\n defaultToNull: false,\n });\n if (res?.error != null) throw res.error;\n },\n async deleteRows(ids) {\n const res: any = await from().delete().in(config.identityKey, ids);\n if (res?.error != null) throw res.error;\n },\n };\n}\n\n/** Default filter translation for the built-in operator `columnFilter`: its\n * column is `f.columnKey`, its state is `{ operator, value }`. (Also accepts a\n * `key` in state for hand-rolled filters.) */\nfunction standardColumnFilter(f: FetchDataFilter): PostgrestFilter | null {\n const s = f.state;\n if (s == null) return null;\n const key = f.columnKey ?? s.key;\n if (key != null && s.operator != null && s.value != null && s.value !== \"\") {\n return standardizeFilter({ key, operator: s.operator, value: s.value });\n }\n return null;\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n // Clamp to the array length: a visible region can outlast the data it was\n // set against (e.g. a keyset page hits the end of a filtered set and the\n // array shrinks below a region end set before the shrink). Scanning past\n // `data.length` reads `undefined` as a fillable null and re-fetches the same\n // now-out-of-range offset forever — the tail-of-filtered-set reload loop.\n const end = Math.min(region.rowIndexEnd, data.length);\n for (let i = region.rowIndexStart; i < end; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":["data","update"],"mappings":";;;;;;;;;;AA+EO,SAAS,kBACd,cACiB;AACjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AACT,aAAO,mBAAmB,KAAK,CAAC,YAAY,CAAC;AAAA,IAC/C;AAAA,EAAA;AAEJ;AAEO,SAAS,mBACd,KACA,SACA;AACA,aAAW,MAAM,SAAS;AACxB,QAAI,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,UAAU,YAAY,IAAI,YAAY,QAAQ,MAAM;AAChE,YAAM,EAAE,MAAM,MAAA,IAAU,MAAM;AAC9B,UAAI,SAAS,KAAM,OAAM;AACzB,cAAQ,QAAQ,CAAA,GAAI,IAAI,CAAC,SAAc;AAAA,QACrC,OAAO,IAAI,SAAS;AAAA,QACpB,OAAO,IAAI;AAAA,MAAA,EACX;AAAA,IACJ;AAAA,IACA,MAAM,SAAS,MAAM;AACnB,YAAM,MAAW,MAAM,OAAO,OAAO,MAAe;AAAA,QAClD,eAAe;AAAA,MAAA,CAChB;AACD,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,IACA,MAAM,WAAW,KAAK;AACpB,YAAM,MAAW,MAAM,OAAO,SAAS,GAAG,OAAO,aAAa,GAAG;AACjE,UAAI,KAAK,SAAS,KAAM,OAAM,IAAI;AAAA,IACpC;AAAA,EAAA;AAEJ;AAKA,SAAS,qBAAqB,GAA4C;AACxE,QAAM,IAAI,EAAE;AACZ,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,MAAM,EAAE,aAAa,EAAE;AAC7B,MAAI,OAAO,QAAQ,EAAE,YAAY,QAAQ,EAAE,SAAS,QAAQ,EAAE,UAAU,IAAI;AAC1E,WAAO,kBAAkB,EAAE,KAAK,UAAU,EAAE,UAAU,OAAO,EAAE,OAAO;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,yBACP,MACA,QACe;AAMf,QAAM,MAAM,KAAK,IAAI,OAAO,aAAa,KAAK,MAAM;AACpD,WAAS,IAAI,OAAO,eAAe,IAAI,KAAK,KAAK;AAC/C,QAAI,KAAK,CAAC,KAAK,MAAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"data-loaders.js","sources":["../../src/postgrest-table/data-loaders.ts"],"sourcesContent":["/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\nimport {\n ClientServerOptions,\n PostgrestClient,\n PostgrestFilterBuilder,\n PostgrestQueryBuilder,\n} from \"@supabase/postgrest-js\";\nimport { adjustArraySize, RowRegion } from \"./loading-utils.ts\";\nimport {\n ctx,\n dataProviderAtom,\n dataRefreshTokenAtom,\n FetchData,\n FetchDataFilter,\n tableDataAtom,\n TableDataProvider,\n useSelector,\n} from \"../provider\";\nimport { atom } from \"jotai\";\nimport { FetchDataOptions, FetchMode } from \"../types.ts\";\nimport {\n lazyLoaderCoreStateAtom,\n resolveInitialData,\n seededRows,\n startAfterAtom,\n type LazyLoaderStateCore,\n} from \"../provider/loader-state.ts\";\n\ninterface LazyLoaderState<T> extends LazyLoaderStateCore<T> {\n data: (T | null)[];\n visibleRegion: RowRegion;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\n/** Operators available for server-side column filtering via PostgREST.\n * `cs`/`ov` target array columns (contains / overlaps). */\nexport type PostgrestFilterOperator =\n | \"eq\"\n | \"neq\"\n | \"like\"\n | \"ilike\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"is\"\n | \"cs\"\n | \"ov\";\n\n/** A single column sort entry. */\nexport interface ColumnSortEntry {\n key: string;\n ascending: boolean;\n}\n\n/** A single column filter entry. */\nexport interface PostgrestColumnFilter {\n key: string;\n operator: PostgrestFilterOperator;\n value: string;\n}\n\nexport interface PostgrestFilter {\n id?: string;\n type: \"filter\";\n apply(\n req: PostgrestFilterBuilder<any, any, any, any>,\n ): PostgrestFilterBuilder<any, any, any, any>;\n}\n\nexport function standardizeFilter(\n columnFilter: PostgrestColumnFilter,\n): PostgrestFilter {\n return {\n type: \"filter\",\n apply(req) {\n return applyColumnFilters(req, [columnFilter]);\n },\n };\n}\n\nexport function applyColumnFilters(\n req: PostgrestFilterBuilder<any, any, any, any>,\n filters: PostgrestColumnFilter[],\n) {\n for (const cf of filters) {\n if (cf.value === \"\" || cf.value == null) continue;\n // Array-column operators need a list value and postgrest-js's dedicated\n // builders (which emit the `{…}` array literal), not a scalar `.filter`.\n if (cf.operator === \"cs\") {\n req = req.contains(cf.key, splitFilterList(cf.value));\n continue;\n }\n if (cf.operator === \"ov\") {\n req = req.overlaps(cf.key, splitFilterList(cf.value));\n continue;\n }\n const val =\n cf.operator === \"like\" || cf.operator === \"ilike\"\n ? `*${cf.value}*`\n : cf.value;\n req = req.filter(cf.key, cf.operator, val);\n }\n return req;\n}\n\n/** Split a comma-separated filter value into trimmed, non-empty tokens (the set\n * for `cs`/`ov`); a single value yields a one-element list. */\nfunction splitFilterList(value: any): string[] {\n return String(value)\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | { type: \"seed\"; data: T[]; totalCount?: number | null }\n | {\n type: \"loaded\";\n data: T[];\n offset: number;\n totalSize: number;\n totalCount?: number | null;\n }\n | { type: \"error\"; error: Error }\n | { type: \"update-data\"; changes: Spec<T[]> }\n | { type: \"reset\" }\n | { type: \"configure\"; fetchMode: FetchMode; pageSize: number };\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes as any),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n const newData = action.data ?? [];\n const offset = action.offset ?? 0;\n data = [\n ...data.slice(0, offset),\n ...newData,\n ...data.slice(offset + newData.length),\n ];\n return {\n ...state,\n data,\n loading: false,\n totalCount:\n action.totalCount !== undefined\n ? action.totalCount\n : state.totalCount,\n };\n case \"configure\":\n return {\n ...state,\n fetchMode: action.fetchMode,\n pageSize: action.pageSize,\n };\n case \"reset\":\n // A view change (or initial load) re-fetches from scratch. Rather than\n // blanking the table (which reads as a jarring empty flash while the\n // request is in flight — very visible on sort/filter), pre-size to a page\n // of `null` ghost/skeleton rows so the body stays populated and the load\n // is legible. `loaded` then adjusts the array to the real size.\n return {\n visibleRegion: defaultVisibleRegion,\n data: new Array(Math.max(state.pageSize, 0)).fill(null),\n loading: false,\n error: null,\n initialized: false,\n totalCount: null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n case \"seed\": {\n // Rows the caller already had (a server render, say). Same shape as a\n // completed first fetch: pre-size to the reported total so the scrollbar\n // and counter are right immediately, and mark the loader `initialized` so\n // it neither refetches the seeded window nor flashes an empty state.\n const data = seededRows({\n rows: action.data ?? [],\n totalCount: action.totalCount,\n });\n return {\n visibleRegion: defaultVisibleRegion,\n data: data as T[],\n loading: false,\n error: null,\n initialized: true,\n totalCount: action.totalCount ?? null,\n fetchMode: state.fetchMode,\n pageSize: state.pageSize,\n };\n }\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ntype SortAndFilterOptions = {\n /** Column-level sort state, managed externally. When provided, overrides\n * the `order` prop for query building. */\n order?: PostgrestOrder<any>[];\n filters?: PostgrestFilter[];\n};\n\ninterface QueryConfig extends SortAndFilterOptions {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n identityKey: string;\n /** The identity column's default ordering (used when nothing in `order`\n * already sorts it). A string ⇒ ascending; pass a `PostgrestOrder` to set the\n * direction (e.g. `source_id` descending). */\n identityOrder?: PostgrestOrder<any>;\n lastLoadedRow?: any;\n lastLoadedRowIndex: number;\n}\n\n/** Format a value for a PostgREST logic-tree condition. Reserved characters\n * (`, . : ( )`), spaces, quotes, and backslashes require the value to be\n * double-quoted, with `\"` and `\\` backslash-escaped inside — otherwise a map\n * name containing a comma would break the `or=(...)` parse. */\nfunction formatKeysetValue(v: any): string {\n const s = String(v);\n if (s === \"\" || /[,.:()\"\\\\ ]/.test(s)) {\n return `\"${s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n }\n return s;\n}\n\n/** An equality condition for the cursor prefix (`col.eq.v`, or `col.is.null`). */\nfunction keysetEq(key: string, v: any): string {\n return v == null ? `${key}.is.null` : `${key}.eq.${formatKeysetValue(v)}`;\n}\n\n/**\n * Build the compound keyset predicate (the body of an `or=(...)`) selecting\n * rows strictly after `lastRow` under `clauses` (lexicographic, last clause is\n * the identity tiebreaker):\n *\n * (c1 OP1 v1)\n * OR (c1 = v1 AND c2 OP2 v2)\n * OR (c1 = v1 AND c2 = v2 AND c3 OP3 v3) …\n *\n * `OPi` is `gt` for an ascending clause, `lt` for descending. Nulls-last: a\n * null pivot value has no strictly-ordered non-null successor at its level, so\n * that term is skipped and the tie defers to deeper clauses (the identity key\n * is non-null, so at least its term is always emitted). Returns `null` if no\n * term applies. (Known limit: rows whose *sort* column is null aren't picked up\n * across the non-null→null boundary — an edge for nullable sort columns; the\n * non-null identity tiebreaker keeps pagination from stalling.)\n */\nfunction buildKeysetPredicate(\n clauses: PostgrestOrder<any>[],\n lastRow: any,\n): string | null {\n const terms: string[] = [];\n for (let i = 0; i < clauses.length; i++) {\n const v = lastRow[clauses[i].key];\n if (v == null) continue;\n const conds: string[] = [];\n for (let j = 0; j < i; j++) {\n conds.push(keysetEq(clauses[j].key, lastRow[clauses[j].key]));\n }\n const op = (clauses[i].ascending ?? true) ? \"gt\" : \"lt\";\n conds.push(`${clauses[i].key}.${op}.${formatKeysetValue(v)}`);\n terms.push(conds.length === 1 ? conds[0] : `and(${conds.join(\",\")})`);\n }\n return terms.length > 0 ? terms.join(\",\") : null;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<any, any, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count, lastLoadedRowIndex } = config;\n const opts = { count };\n\n let cols: string;\n if (Array.isArray(columns)) {\n cols = columns.join(\", \");\n } else {\n cols = columns ?? \"*\";\n }\n\n let query = client.select(cols, opts);\n\n const filters = config.filters ?? [];\n for (const filter of filters) {\n query = filter.apply(query);\n }\n\n const orderClauses = buildPostgrestOrderClauses(\n config.order ?? [],\n config.identityOrder ?? config.identityKey,\n );\n\n let hasOrdering = false;\n for (const clause of orderClauses) {\n query = query.order(clause.key, clause);\n hasOrdering = true;\n }\n\n // Keyset cursor: rows strictly after the last loaded row under the active\n // ordering. This MUST be a compound predicate, not an independent `gt`/`lt`\n // per column: with a leading low-cardinality sort (e.g. `state`), a plain\n // `state.gt.X AND source_id.lt.Y` drops every row sharing the cursor's\n // `state` (`state.gt.X` is false for them). The lexicographic form keeps the\n // tie broken by the next column, ending on the non-null identity key.\n if (config.lastLoadedRow != null && hasOrdering) {\n const pred = buildKeysetPredicate(orderClauses, config.lastLoadedRow);\n if (pred != null) query = query.or(pred);\n }\n\n let offset: number | null = null;\n if (!hasOrdering && lastLoadedRowIndex > 0) {\n // We need to load based on offsets\n offset = lastLoadedRowIndex + 1;\n }\n\n if (config.limit != null) {\n if (offset != null) {\n query = query.range(offset, offset + config.limit - 1);\n console.log(`Random seek from ${offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n\n return query;\n}\n\nconst defaultVisibleRegion: RowRegion = {\n rowIndexStart: 0,\n rowIndexEnd: 0,\n};\n\n/** Atom to house the current visible region of the table */\nconst visibleRegionAtom = atom<RowRegion>(defaultVisibleRegion);\n\n\n/** Current page index (0-based) for paged fetch mode. */\nexport const chunkPageAtom = atom(0);\n\n/** Footer state for the optional bottom-of-table indicator: rows loaded, the\n * source total when known, load status, and — in paged mode — the current\n * page and total pages. */\nexport interface TableFooterInfo {\n mode: FetchMode;\n loaded: number;\n total: number | null;\n loading: boolean;\n /** A fetch has been attempted since the last view reset — so `loaded === 0`\n * can be told apart from \"not loaded yet\" (avoids an empty-state flash). */\n initialized: boolean;\n error: Error | null;\n page: number;\n pageSize: number;\n totalPages: number | null;\n}\n\nexport const tableFooterAtom = atom<TableFooterInfo>((get) => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom) ?? [];\n let loaded = 0;\n let hasGaps = false;\n for (const row of data) {\n if (row != null) loaded++;\n else hasGaps = true;\n }\n // Total is known when the source reported it, or (scroll mode) when the array\n // is fully populated — otherwise it's still being discovered.\n const total = core.totalCount ?? (hasGaps ? null : data.length);\n const totalPages =\n core.totalCount != null ? Math.ceil(core.totalCount / core.pageSize) : null;\n return {\n mode: core.fetchMode,\n loaded,\n total,\n loading: core.loading,\n initialized: core.initialized,\n error: core.error,\n page: get(chunkPageAtom),\n pageSize: core.pageSize,\n totalPages,\n };\n});\n\n/** Auto-load this many pages per burst, then pause (null ⇒ unbounded). Set by\n * a consumer (e.g. `DataPanel`'s `autoLoadPages` prop). */\nexport const autoLoadPagesAtom = atom<number | null>(null);\n\n/** Row count at the last manual \"load more\" — the point auto-load resumes\n * counting a fresh burst from. */\nexport const resumeBaselineAtom = atom(0);\n\n/** Live loading controls, read from the store rather than passed down a\n * boundary contract. Any component inside the provider can call\n * `useLoadControls()` — a footer, a toolbar button, a status line — without the\n * renderer wiring a specific prop shape to it. */\nexport interface LoadControls {\n /** Load the next page and resume auto-loading (clears a paused state). */\n loadMore: () => void;\n /** A fetch is in flight. */\n loading: boolean;\n /** A fetch has been attempted since the last view reset (so an empty result\n * can be told apart from \"not loaded yet\"). */\n initialized: boolean;\n /** The most recent load error (cleared on the next successful load), else\n * `null` — so a footer/consumer can degrade gracefully instead of hanging. */\n error: Error | null;\n /** More rows remain to load. */\n hasMore: boolean;\n /** Rows loaded so far. */\n loaded: number;\n /** Source total when known, else `null`. */\n total: number | null;\n /** Auto-load is paused at the `autoLoadPages` checkpoint. */\n paused: boolean;\n /** Auto-load is currently permitted (`hasMore && !loading && !paused`) —\n * used to gate an infinite-scroll sentinel. */\n canLoadMore: boolean;\n /** Advance one page *without* resuming a paused auto-load (the sentinel\n * uses this; `loadMore` is the manual, un-pausing variant). */\n advance: () => void;\n /** Rows per page. */\n pageSize: number;\n /** Current page index (0-based). Only meaningful in `\"paged\"` fetch mode —\n * scroll mode accumulates windows rather than sitting on a page. */\n page: number;\n /** Total pages when the source reported a total, else `null`. */\n totalPages: number | null;\n}\n\n/** Store-managed load controls (see `LoadControls`). Reads the loader's footer\n * state, the loaded rows, and the pause atoms; `loadMore`/`advance` set the\n * visible region so the loader fetches the next chunk. */\nexport function useLoadControls(): LoadControls {\n const footer = ctx.useValue(tableFooterAtom);\n const data = ctx.useValue(tableDataAtom) ?? [];\n const { isLocalProvider } = ctx.useValue(dataProviderAtom);\n const resumeBaseline = ctx.useValue(resumeBaselineAtom);\n const autoLoadPages = ctx.useValue(autoLoadPagesAtom);\n const setResumeBaseline = ctx.useSet(resumeBaselineAtom);\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n let loadedCount = 0;\n for (const row of data) if (row != null) loadedCount++;\n const pageSize = footer.pageSize || 100;\n const dataLength = data.length;\n const hasMore = !isLocalProvider && loadedCount < dataLength;\n const paused =\n autoLoadPages != null &&\n loadedCount - resumeBaseline >= autoLoadPages * pageSize;\n const canLoadMore = hasMore && !footer.loading && !paused;\n\n const advance = useCallback(() => {\n setVisibleRegion({\n rowIndexStart: 0,\n rowIndexEnd: Math.min(loadedCount + pageSize, dataLength),\n });\n }, [setVisibleRegion, loadedCount, pageSize, dataLength]);\n\n const loadMore = useCallback(() => {\n setResumeBaseline(loadedCount);\n advance();\n }, [setResumeBaseline, loadedCount, advance]);\n\n return {\n loadMore,\n loading: footer.loading,\n initialized: footer.initialized,\n error: footer.error,\n hasMore,\n loaded: footer.loaded,\n total: footer.total,\n paused,\n canLoadMore,\n advance,\n pageSize,\n page: footer.page,\n totalPages: footer.totalPages,\n // Page addressing is exposed so a footer can render a real link to the next\n // page, not just a button that calls `loadMore`. That's the difference\n // between a list a crawler (or a JS-less client) can follow and one it\n // can't — see the note on crawlable pagination in the Data list editors\n // feature doc.\n };\n}\n\nexport interface ViewInfo {\n visibleRegion: RowRegion;\n totalCount: number | null;\n loading: boolean;\n error: Error | null;\n}\n\nexport const viewInfoAtom = atom<ViewInfo>((get) => {\n const state = get(lazyLoaderStateAtom);\n return {\n visibleRegion: state.visibleRegion,\n loading: state.loading,\n error: state.error,\n totalCount: state.data.length,\n };\n});\n\n/** Temporary passthrough atom to allow visible region to be separated from the rest\n * of the lazy loader state\n */\nconst lazyLoaderStateAtom = atom(\n (get): LazyLoaderState<any> => {\n const core = get(lazyLoaderCoreStateAtom);\n const data = get(tableDataAtom);\n const visibleRegion = get(visibleRegionAtom);\n return {\n ...core,\n data,\n visibleRegion,\n };\n },\n (get, set, update: any) => {\n // Split the state between several places\n if (typeof update === \"function\") {\n update = update(get(lazyLoaderStateAtom));\n }\n const { visibleRegion, data, ...rest } = update;\n if (visibleRegion != null) {\n set(visibleRegionAtom, visibleRegion);\n }\n // Propagate the data array even when empty — a `reset` (view change) must\n // clear the stale rows so the re-fetch rebuilds a correctly-sized array\n // (otherwise a filtered/sorted result splices over a stale, larger array).\n if (data != null) {\n set(tableDataAtom, data);\n }\n if (Object.keys(rest).length > 1) {\n set(lazyLoaderCoreStateAtom, (v) => ({ ...v, ...rest }));\n }\n },\n);\n\nfunction useLazyLoaderReducer() {\n const [state, setState] = ctx.use(lazyLoaderStateAtom);\n const dispatch = useCallback(\n (action: LazyLoaderAction<any>) =>\n setState((prev) => lazyLoadingReducer(prev, action)),\n [setState],\n );\n return [state, dispatch] as const;\n}\n\nfunction buildPostgrestOrderClauses(\n sorts: (ColumnSortEntry | PostgrestOrder<any>)[],\n identityOrder: PostgrestOrder<any> | string,\n): PostgrestOrder<any>[] {\n // Build the ORDER BY for a PostgREST query. Two invariants:\n // 1. Each column appears at most once. Keyset pagination adds a `gt`/`lt`\n // cursor predicate per order clause, so a duplicated column (e.g. the\n // identity key present in both a base order and an active sort, with\n // opposite directions) would emit contradictory `col=lt.X&col=gt.X`\n // bounds that match nothing — an infinite empty-result reload. First\n // occurrence wins (active sorts should be passed ahead of base order).\n // 2. The identity key is ordered last (a stable tiebreaker for the cursor),\n // appended with its default direction only if no clause already sorts it.\n const identitySort =\n typeof identityOrder == \"string\"\n ? { key: identityOrder, ascending: true }\n : identityOrder;\n const identityKey = identitySort.key;\n\n const seen = new Set<string>();\n const clauses: PostgrestOrder<any>[] = [];\n for (const sort of sorts) {\n if (seen.has(sort.key)) continue;\n seen.add(sort.key);\n clauses.push({\n key: sort.key,\n ascending: sort.ascending,\n nullsFirst: \"nullsFirst\" in sort ? sort.nullsFirst : false,\n });\n }\n\n if (seen.has(identityKey)) {\n // Move the (already-deduped) identity clause to the end, keeping the\n // direction the active sort chose.\n const idx = clauses.findIndex((c) => c.key === identityKey);\n const [idClause] = clauses.splice(idx, 1);\n clauses.push(idClause);\n } else {\n clauses.push({\n key: identitySort.key,\n ascending: identitySort.ascending ?? true,\n nullsFirst: (identitySort as any).nullsFirst ?? false,\n });\n }\n return clauses;\n}\n\nexport function useScrollHandler() {\n /** A standardized approach to holding onto the scroll position for the table */\n // Reference to hold onto the scroll position\n const ref = useRef<RowRegion>(null);\n\n const setVisibleRegion = ctx.useSet(visibleRegionAtom);\n\n return useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n setVisibleRegion(visibleCells);\n ref.current = visibleCells;\n }, 500),\n [setVisibleRegion],\n );\n}\n\n/**\n * A generic, backend-agnostic windowed data source. Give it a `fetchChunk`\n * function and it drives the sheet's lazy loading: it loads the chunk covering\n * the first unloaded visible row, pre-sizes the sparse array from `totalCount`,\n * threads the active sorts/filters through so the source can apply them\n * server-side, and re-fetches from scratch when the view state changes. This\n * is the unified seam that upstreams bespoke loaders (`fetchChunk` receives the\n * view state; there's no separate adapter object).\n *\n * Call it from a component rendered inside `DataSheet` (see `ChunkLoaderManager`).\n */\nexport function useDataLoader<T = any>(\n fetchChunk: FetchData<T>,\n options: FetchDataOptions<T> = {},\n) {\n const {\n pageSize = 100,\n fetchMode = \"scroll\",\n filterDebounce = 0,\n initialData,\n } = options;\n const [state, dispatch] = useLazyLoaderReducer();\n\n const { isLocalProvider, provider } = ctx.useValue(dataProviderAtom);\n\n const visibleRegion = ctx.useValue(visibleRegionAtom);\n const page = ctx.useValue(chunkPageAtom);\n const setPage = ctx.useSet(chunkPageAtom);\n const refreshToken = ctx.useValue(dataRefreshTokenAtom);\n // The keyset cursor of a view that starts mid-list. Seeded at store creation\n // (`startAfter`); cleared below on the first view change, since it describes\n // only the view it arrived with.\n const [startAfter, setStartAfter] = ctx.use(startAfterAtom);\n const columnSorts = useSelector((s) => s.columnSorts);\n const activeFilters = useSelector((s) => s.activeFilters);\n const abortRef = useRef<AbortController | null>(null);\n // Tracks the (page, viewKey) already loaded in paged mode, so the effect\n // doesn't re-fetch on unrelated re-renders.\n const loadedRef = useRef<{ page: number; viewKey: string }>({\n page: -1,\n viewKey: \"\",\n });\n\n const filters: FetchDataFilter[] = useMemo(\n () =>\n (Array.from(activeFilters.entries()) as [any, any][]).map(\n ([id, entry]) => ({\n id,\n columnKey: entry.filter?.columnKey,\n state: entry.state,\n predicate: entry.filter?.predicate,\n }),\n ),\n [activeFilters],\n );\n\n // Publish the windowing config so the footer/pager can read it.\n useEffect(() => {\n dispatch({ type: \"configure\", fetchMode, pageSize: pageSize });\n }, [fetchMode, pageSize]);\n\n // Reset (re-fetch from scratch) when sorts/filters change, or when the fetch\n // mode switches (paged holds a dense page; scroll needs to re-initialize and\n // pre-size) — so a table can flip between modes cleanly.\n const viewKey = useMemo(\n () => JSON.stringify({ sorts: columnSorts, filters }),\n [columnSorts, filters],\n );\n // Debounce the view-state → refetch: rapid changes (typing in a text filter)\n // otherwise reset + refetch on every keystroke, flashing the list. The store\n // (and so the filter input) still updates instantly; only the *fetch* waits\n // for the view to settle. Scroll paging is unaffected — it's driven by\n // `visibleRegion`/`data`, not this key. `filterDebounce: 0` (default) keeps\n // the immediate behavior.\n const debouncedViewKey = useDebouncedValue(viewKey, filterDebounce);\n // A caller-supplied first window (`initialData`) stands in for the mount-time\n // reset+fetch. It's consumed once: any later view change resets normally,\n // since the seed only describes the view it was fetched for.\n //\n // The store is normally created already seeded (`DataSheetStoreWrapper`), so\n // the rows are in the very first render — including a server render. The\n // dispatch below is the fallback for a store that wasn't.\n const seedRef = useRef(resolveInitialData(initialData));\n // Gate on the seed until it's actually in state (see the fetch effect).\n const awaitingSeedRef = useRef(seedRef.current != null);\n const firstResetRef = useRef(true);\n useEffect(() => {\n const seed = seedRef.current;\n seedRef.current = null;\n // A view change (not the mount) ends a mid-list start: the cursor only\n // described the view it arrived with.\n if (!firstResetRef.current) {\n setStartAfter(null);\n }\n firstResetRef.current = false;\n if (seed != null) {\n if (!state.initialized) {\n dispatch({\n type: \"seed\",\n data: seed.rows,\n totalCount: seed.totalCount,\n });\n }\n setPage(0);\n // Paged mode tracks which (page, view) it has in hand separately from the\n // array; record the seed there too, or it would immediately re-fetch the\n // page it was just handed.\n loadedRef.current = { page: 0, viewKey };\n return;\n }\n dispatch({ type: \"reset\" });\n setPage(0);\n }, [debouncedViewKey, fetchMode, refreshToken]);\n\n useAsyncEffect(async () => {\n if (state.loading) return;\n\n // A seed hasn't landed in state yet. Every effect in a commit sees the\n // render's snapshot, so this one runs *before* the seed it was mounted\n // alongside is visible — and would issue exactly the request the seed\n // exists to avoid. Skip until the seeded state arrives.\n if (awaitingSeedRef.current) {\n if (state.initialized) awaitingSeedRef.current = false;\n return;\n }\n\n // Determine the chunk offset to fetch, and (scroll mode) a keyset cursor:\n // the already-loaded row just before the chunk, so keyset sources can page\n // from it instead of a slow OFFSET.\n let offset: number;\n let cursor: { row: any; index: number } | null = null;\n if (fetchMode === \"paged\") {\n // Fetch the current page once; skip if already loaded for this view.\n if (\n loadedRef.current.page === page &&\n loadedRef.current.viewKey === viewKey\n ) {\n return;\n }\n offset = page * pageSize;\n } else {\n const rowIndex = indexOfFirstNullInRegion(state.data, visibleRegion);\n if (rowIndex == null && state.initialized) return;\n offset = Math.floor((rowIndex ?? 0) / pageSize) * pageSize;\n const prev = offset > 0 ? state.data[offset - 1] : null;\n if (prev != null) cursor = { row: prev, index: offset - 1 };\n }\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n dispatch({ type: \"start-loading\" });\n try {\n const result = await fetchChunk({\n offset,\n limit: pageSize,\n signal: controller.signal,\n sorts: columnSorts,\n filters,\n cursor,\n after: startAfter,\n });\n if (controller.signal.aborted) return;\n const rows = result.rows ?? [];\n if (fetchMode === \"paged\") {\n loadedRef.current = { page, viewKey };\n // The sheet shows just this page's rows (dense, from index 0); the\n // real source length is tracked separately for the pager.\n dispatch({\n type: \"loaded\",\n data: rows,\n offset: 0,\n totalSize: rows.length,\n totalCount: result.totalCount ?? null,\n });\n } else {\n // Size the (sparse) array. With a known total, size to it. Without one\n // (keyset / infinite scroll), use the short-chunk heuristic: a chunk\n // smaller than the page size means we've hit the end — size exactly to\n // the loaded rows; otherwise pad one more page of nulls so scrolling\n // into them triggers the next fetch. So an unknown-length source never\n // needs a count — it grows a page at a time until a short chunk.\n const loadedEnd = offset + rows.length;\n let totalSize: number;\n if (result.totalCount != null) {\n totalSize = result.totalCount;\n } else {\n const reachedEnd = rows.length < pageSize;\n totalSize = reachedEnd ? loadedEnd : loadedEnd + pageSize;\n }\n dispatch({\n type: \"loaded\",\n data: rows,\n offset,\n totalSize,\n // Preserve a previously-known total when a chunk omits it (undefined):\n // keyset pages can't re-count (the cursor filter would skew it), so\n // only the initial cursorless fetch reports the total.\n totalCount: result.totalCount,\n });\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n dispatch({ type: \"error\", error: err as Error });\n }\n }\n }, [state.data, visibleRegion, debouncedViewKey, page, fetchMode]);\n\n return { data: state.data, loading: state.loading, error: state.error };\n}\n\n/** A value that trails `value` by `delay` ms of stability — the first value is\n * returned immediately, and `delay <= 0` disables debouncing entirely. */\nfunction useDebouncedValue<T>(value: T, delay: number): T {\n const [debounced, setDebounced] = useState(value);\n useEffect(() => {\n if (delay <= 0) {\n setDebounced(value);\n return;\n }\n const t = setTimeout(() => setDebounced(value), delay);\n return () => clearTimeout(t);\n }, [value, delay]);\n return debounced;\n}\n\n/**\n * Build a `fetchChunk` backed by a PostgREST endpoint, for use with\n * `useChunkLoader` / `ChunkLoaderManager`. It reuses `buildQuery`, so it pages\n * with **keyset pagination** (via the loader's `cursor`) whenever the query is\n * ordered — falling back to `OFFSET` only when it isn't — and threads the\n * active store sorts/filters into the query. The total count is requested only\n * on the initial (cursorless) fetch, since a keyset cursor filter would skew it.\n */\nexport function createPostgRESTFetchChunk<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (applied when no active\n * sort targets it). `false` ⇒ the table defaults to identity-descending\n * (e.g. newest `source_id` first) without a redundant `baseOrder` entry that\n * would otherwise collide with the identity tiebreaker. Defaults to `true`. */\n identityAscending?: boolean;\n columns?: string | string[];\n /** Order applied before the active column sorts (identity key appended last). */\n baseOrder?: PostgrestOrder<any>[];\n /** A transform over the query builder, applied as a base filter (the `filter` prop). */\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n /** Translate a stored filter entry to a `PostgrestFilter` (return `null` to\n * skip). Defaults to the `{ key, operator, value }` column-filter shape. */\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): FetchData<T> {\n const translate = config.translateFilter ?? standardColumnFilter;\n return async ({ limit, signal, sorts, filters, cursor }) => {\n const client = new PostgrestClient(config.endpoint).from(config.table);\n\n // Active sorts first so they win the by-key dedupe in\n // `buildPostgrestOrderClauses` (a user sort on the identity column\n // overrides its default direction rather than colliding with it).\n const order: PostgrestOrder<any>[] = [\n ...sorts.map((s) => ({ key: s.key, ascending: s.ascending })),\n ...(config.baseOrder ?? []),\n ];\n\n const pgFilters: PostgrestFilter[] = [];\n if (config.baseFilter != null) {\n const apply = config.baseFilter;\n pgFilters.push({ type: \"filter\", apply });\n }\n for (const f of filters) {\n const pf = translate(f);\n if (pf != null) pgFilters.push(pf);\n }\n\n const query = buildQuery(client, {\n columns: config.columns,\n // Only the initial (cursorless) fetch reports an accurate total.\n count: cursor == null ? \"exact\" : undefined,\n limit,\n identityKey: config.identityKey,\n identityOrder: {\n key: config.identityKey,\n ascending: config.identityAscending ?? true,\n },\n order,\n filters: pgFilters,\n lastLoadedRow: cursor?.row ?? null,\n lastLoadedRowIndex: cursor?.index ?? -1,\n });\n\n const res: any = await query;\n if (signal.aborted) return { rows: [] };\n if (res?.error != null) throw res.error;\n const rows = res?.data ?? [];\n return res?.count != null ? { rows, totalCount: res.count } : { rows };\n };\n}\n\n/**\n * A full PostgREST `TableDataProvider`: the read side (`fetchData` + row\n * `identity`) plus persistence — `saveRows` (upsert) and `deleteRows` (by\n * identity). Pass it to `DataSheet`'s `provider` prop. The mutation methods\n * throw on error so the Save action surfaces it.\n */\nexport function createPostgRESTProvider<T = any>(config: {\n endpoint: string;\n table: string;\n identityKey: string;\n /** Default ordering direction of the identity key (see\n * `createPostgRESTFetchChunk`). `false` ⇒ identity-descending by default. */\n identityAscending?: boolean;\n columns?: string | string[];\n baseOrder?: PostgrestOrder<any>[];\n baseFilter?: (\n q: PostgrestFilterBuilder<any, any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any, any>;\n translateFilter?: (f: FetchDataFilter) => PostgrestFilter | null;\n}): TableDataProvider<T> {\n const from = () => new PostgrestClient(config.endpoint).from(config.table);\n return {\n fetchData: createPostgRESTFetchChunk<T>(config),\n identity: (row: any) => row?.[config.identityKey],\n async distinctValues(columnKey, options = {}) {\n // PostgREST derives a GROUP BY from a `select` that mixes a plain column\n // with an aggregate, so one small request returns the whole vocabulary\n // *with* frequencies — rather than paging the table and deduplicating\n // client-side. Ordered by the value so the picker's list is stable.\n //\n // `baseFilter` applies (it defines the rows this view is *about*), but the\n // *active* filters deliberately don't: a picker whose options disappear as\n // you narrow the view can't be used to widen it again.\n let req: any = from().select(`${columnKey},count()`);\n if (config.baseFilter != null) req = config.baseFilter(req);\n req = req.order(columnKey, { ascending: true, nullsFirst: false });\n if (options.limit != null) req = req.limit(options.limit);\n if (options.signal != null) req = req.abortSignal(options.signal);\n const { data, error } = await req;\n if (error != null) throw error;\n return (data ?? []).map((row: any) => ({\n value: row[columnKey],\n count: row.count,\n }));\n },\n async saveRows(rows) {\n const res: any = await from().upsert(rows as any[], {\n defaultToNull: false,\n });\n if (res?.error != null) throw res.error;\n },\n async deleteRows(ids) {\n const res: any = await from().delete().in(config.identityKey, ids);\n if (res?.error != null) throw res.error;\n },\n };\n}\n\n/** Default filter translation for the built-in operator `columnFilter`: its\n * column is `f.columnKey`, its state is `{ operator, value }`. (Also accepts a\n * `key` in state for hand-rolled filters.) */\nfunction standardColumnFilter(f: FetchDataFilter): PostgrestFilter | null {\n const s = f.state;\n if (s == null) return null;\n const key = f.columnKey ?? s.key;\n if (key != null && s.operator != null && s.value != null && s.value !== \"\") {\n return standardizeFilter({ key, operator: s.operator, value: s.value });\n }\n return null;\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n // Clamp to the array length: a visible region can outlast the data it was\n // set against (e.g. a keyset page hits the end of a filtered set and the\n // array shrinks below a region end set before the shrink). Scanning past\n // `data.length` reads `undefined` as a fillable null and re-fetches the same\n // now-out-of-range offset forever — the tail-of-filtered-set reload loop.\n const end = Math.min(region.rowIndexEnd, data.length);\n for (let i = region.rowIndexStart; i < end; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":["data","update"],"mappings":";;;;;;;;;;AAgFO,SAAS,kBACd,cACiB;AACjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AACT,aAAO,mBAAmB,KAAK,CAAC,YAAY,CAAC;AAAA,IAC/C;AAAA,EAAA;AAEJ;AAEO,SAAS,mBACd,KACA,SACA;AACA,aAAW,MAAM,SA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AAM;AACnB,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
@@ -105,7 +105,7 @@ function generateColumnSpec(data, options = {}) {
105
105
  return postprocessColumnSpec(improvedSpec);
106
106
  }
107
107
  function postprocessColumnSpec(columnSpec) {
108
- return columnSpec.map((col) => {
108
+ return columnSpec.filter((col) => !col.hidden).map((col) => {
109
109
  return {
110
110
  ...col,
111
111
  filters: postprocessColumnFilters(col),
@@ -113,6 +113,12 @@ function postprocessColumnSpec(columnSpec) {
113
113
  };
114
114
  });
115
115
  }
116
+ function isColumnWritable(col, tableEditable = true) {
117
+ if (col == null) return false;
118
+ if (!tableEditable) return false;
119
+ if (col.derived) return false;
120
+ return col.editable !== false;
121
+ }
116
122
  function postprocessColumnFilters(col) {
117
123
  const { filterable = true, filters = [] } = col;
118
124
  if (!filterable) {
@@ -122,5 +128,6 @@ function postprocessColumnFilters(col) {
122
128
  }
123
129
  exports.generateColumnSpec = generateColumnSpec;
124
130
  exports.generateDefaultColumnSpec = generateDefaultColumnSpec;
131
+ exports.isColumnWritable = isColumnWritable;
125
132
  exports.postprocessColumnSpec = postprocessColumnSpec;
126
133
  //# sourceMappingURL=column-spec.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"column-spec.cjs","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n | \"text\"\n | \"string\"\n | \"number\"\n | \"integer\"\n | \"boolean\"\n | \"object\"\n | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /** Commit a new value for this cell. */\n onChange: (value: any) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc.\n */\n return columnSpec.map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":["enhanceColumnFilter"],"mappings":";;;AAGA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,IAAI;AAC5B;AAQA,MAAM,uBAAuB,CAAC,QAAQ,OAAO,GAAG,EAAE,SAAS;AAyKpD,SAAS,0BACd,MACA,UAAqC,IACvB;AAEd,MAAI,QAAQ,KAAM,QAAO,CAAA;AAGzB,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EAAA,IACjB;AAEJ,QAAM,2BAAW,IAAA;AACjB,QAAM,4BAAY,IAAA;AAElB,QAAM,mCAAmB,IAAA;AAEzB,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,KAAM;AACjB,eAAW,O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S,yBAAyB,KAA4C;AAC5E,QAAM,EAAE,aAAa,MAAM,UAAU,CAAA,MAAO;AAC5C,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,IAAI,CAAC,MAAMA,aAAAA,oBAAoB,KAAK,CAAC,CAAC;AACvD;;;;"}
1
+ {"version":3,"file":"column-spec.cjs","sources":["../../src/provider/column-spec.ts"],"sourcesContent":["import React from \"react\";\nimport type { Placement } from \"@blueprintjs/core\";\nimport { enhanceColumnFilter, TableFilter } from \"../actions\";\n\nconst defaultRenderers = {\n string: (d) => d,\n number: (d) => d?.toFixed(2),\n boolean: (d) => (d ? \"T\" : \"F\"),\n object: (d) => JSON.stringify(d),\n integer: (d) => d?.toFixed(0),\n array: (d) => d?.join(\", \"),\n};\n\ninterface ColumnSpecGenerateOptions {\n calculateWidths?: boolean;\n defaultWidth?: number;\n getWidthForValue?: (value: any) => number;\n}\n\nconst defaultWidthForValue = (val) => String(val).length * 8;\n\n/** Inferred data type of a column, used to select appropriate\n * sort/filter operators. */\nexport type ColumnDataType =\n \"text\" | \"string\" | \"number\" | \"integer\" | \"boolean\" | \"object\" | \"array\";\n\n/** Severity of a cell validation result. `warning` is soft (flagged, doesn't\n * block saving); `error` is hard (blocks saving). */\nexport type ValidationSeverity = \"warning\" | \"error\";\n\n/** The result of validating a cell. `null` means valid. */\nexport interface CellValidation {\n severity: ValidationSeverity;\n message?: string;\n}\n\n/**\n * Context handed to per-cell renderers (`valueRenderer`, and — as the\n * `cellContext` prop — a custom `cellComponent`). It lets a renderer draw\n * based on the row/column position and the cell's edit status, and, combined\n * with the editing API, write edits back for a specific cell.\n *\n * `rowIndex` is the underlying **data-row index** (the value edit methods\n * expect), so it stays stable when a sort or filter reorders the view.\n */\nexport interface CellRenderContext<T = any> {\n /** The cell's current value (the edited value if present, else the base). */\n value: any;\n /** Underlying data-row index — stable under sort/filter. */\n rowIndex: number;\n /** Column index within the active column spec. */\n colIndex: number;\n /** The full column spec for this cell's column. */\n column: ColumnSpec;\n /** The full row object backing this cell (may be undefined while loading). */\n row: T | null | undefined;\n /** Whether this cell has an uncommitted edit. */\n isEdited: boolean;\n /** Whether this cell's row is marked for deletion. */\n isDeleted: boolean;\n /** The row's status value (`RowStatusValue`) — `\"deleted\"` / `\"added\"` or a\n * consumer-defined status (e.g. `\"omitted\"`), or `undefined` for a normal\n * row. Lets a renderer style by arbitrary status, not just deletion. */\n status: string | undefined;\n /** Validation result for this cell, or `null` when valid. Orthogonal to the\n * edit status — a cell can be both edited and invalid. */\n validation: CellValidation | null;\n}\n\n/**\n * The editor configuration for a cell. Mirrors the static `dataEditor` /\n * `inlineEditor` column fields so a per-cell resolver (`editorForCell`) can\n * override either one for an individual cell.\n */\nexport interface CellEditors {\n dataEditor?: any;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n}\n\n/**\n * Context for a cell's detail surface (`cellDetail`). Extends the render\n * context with the edit affordances and controls a surface needs, so one\n * component can act as an editor (when `editable`) or a read-only viewer\n * (otherwise). This is the write side of the read/write contract, per-cell.\n */\nexport interface CellDetailContext<T = any> extends CellRenderContext<T> {\n /** Whether this cell is editable (column × table × not-deleted). */\n editable: boolean;\n /**\n * When the surface stands for several cells at once (the row editor over a\n * multi-row selection), the cells it stands for. `value` is then the value\n * they share, or `undefined` when they differ (`mixed`), and `onChange`\n * writes every one of them. Only offered to a column that declares\n * `multiCell`; absent for a single cell.\n */\n cells?: CellSelectionEntry<T>[];\n /** True when `cells` hold differing values. */\n mixed?: boolean;\n /** Where the surface is drawn: `\"cell\"`, the grid's own popover, modal or\n * in-cell surface; `\"row-editor\"`, a field of the sheet's row editor; or\n * `\"editor\"`, a field of a standalone `DataEditor` — so a surface can lay\n * itself out to suit (a picker nesting its own popovers only where it has\n * room). */\n surface?: \"cell\" | \"row-editor\" | \"editor\";\n /** Commit a new value for this cell — for every cell, when the surface\n * stands for several. */\n onChange: (value: any) => void;\n /** With `cells`, commit a value for each cell, aligned with them — for a\n * surface that changes each cell's own value (adding a tag to every row's\n * list) rather than setting them all to one. */\n onChangeCells?: (values: any[]) => void;\n /** Reset this cell (and selection) to its base value. */\n resetValue: () => void;\n /** Close the surface and return focus to the table. */\n close: () => void;\n}\n\n/** One of the cells a multi-cell surface stands for. */\nexport interface CellSelectionEntry<T = any> {\n rowIndex: number;\n row: T | null | undefined;\n value: any;\n}\n\n/** How a cell's detail surface is presented. Orthogonal to what it renders. */\nexport type DetailPresentation = \"popover\" | \"modal\" | \"inline\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n /** When true, an empty value is an error (sugar over `validate`). */\n required?: boolean;\n /** Validate a cell's value. Return a `{ severity, message }` for a\n * warning/error, or `null` when valid. Runs after the `required` check.\n * `warning` flags the cell but allows saving; `error` blocks saving. */\n validate?: (\n value: any,\n row: any,\n ctx: { rowIndex: number },\n ) => CellValidation | null;\n /** @deprecated Prefer `validate`, which carries severity + a message.\n * A falsy result maps to an `error`. */\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any, ctx?: CellRenderContext) => string | React.ReactNode;\n headerRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\n /**\n * Choose the editor for an individual cell from its render context,\n * overriding the static `dataEditor` / `inlineEditor` for that cell. Return\n * `undefined` (or omit a key) to fall back to the static configuration —\n * e.g. show a textarea only for cells whose value is long. A returned key is\n * respected even when its value is `false`/`null` (i.e. \"no editor here\").\n */\n editorForCell?: (ctx: CellRenderContext) => CellEditors | undefined;\n /**\n * Render a read-only detail panel for a cell. When set, selecting the cell\n * opens a popover with this content (following the table's `cellInteraction`\n * mode). The panel never takes keyboard focus, so arrow keys keep navigating\n * the table; Escape closes it. Mutually distinct from `dataEditor` — use this\n * for non-editable surfaces (previews, summaries, links).\n *\n * @deprecated Prefer `cellDetail`, which unifies editor and viewer.\n */\n detailRenderer?: (ctx: CellRenderContext) => React.ReactNode;\n /**\n * The unified cell surface (Workstream A): one renderer that acts as an\n * editor when `ctx.editable` and a read-only viewer otherwise, superseding\n * `dataEditor` / `detailRenderer` / `editorForCell`. Presentation is chosen\n * separately via `detailPresentation` (popover / modal / inline), so the\n * same component works in any container.\n */\n cellDetail?: (ctx: CellDetailContext) => React.ReactNode;\n /**\n * Whether this column's `cellDetail` can stand for several cells at once —\n * read the shared value (or `ctx.mixed`) and write every cell in\n * `ctx.cells` through one `onChange`. A surface that doesn't declare this\n * is shown read-only over a multi-row selection, with \"Multiple values\"\n * where they differ. The default editors (an input by `dataType`) always\n * can, since setting one value on every cell is what they do.\n */\n multiCell?: boolean;\n /** How `cellDetail` is presented. Defaults to `\"popover\"`. */\n detailPresentation?: DetailPresentation;\n /** What one cell of the column is called, for the selection indicator\n * (\"1 lithology\", \"3 lithologies\"). Defaults to the column's name. */\n cellLabel?: string;\n /** Where a popover `cellDetail` opens against its cell. Defaults to\n * `\"right-start\"`; a wide surface (a tag picker) reads better below, at\n * `\"bottom-start\"`. */\n detailPlacement?: Placement;\n cellComponent?: any;\n category?: string;\n editable?: boolean;\n /**\n * A **derived** column holds values computed from other data — a total, an\n * age that follows from an interval and a proportion — rather than values\n * anyone types. It is never writable, whatever `editable` or the table\n * says, and every write path (inline editing, fill, paste, the row editor)\n * leaves it alone; it is drawn dimmed so a reader can tell what is a record\n * and what is a restatement of one. Use it instead of `editable: false` when\n * the read-only-ness is a property of the *data* rather than of the view.\n */\n derived?: boolean;\n /**\n * A **hidden** column stays in the spec but is left out of the working\n * spec the table is built from: it isn't rendered, isn't part of a\n * selection, and isn't written by a fill or a paste. A consumer keeps one\n * spec and toggles this flag (\"show absolute ages\", \"show generated ids\")\n * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.\n */\n hidden?: boolean;\n inlineEditor?: boolean | React.ComponentType<any> | string | null;\n style?: React.CSSProperties;\n width?: number;\n /** Column-specific table actions (TableAction[]). These appear in the\n * actions toolbar when this column is part of the current selection. */\n actions?: any[];\n /** Column-specific table filters (TableFilter[]). These appear in the\n * filter bar and apply to this column's values. */\n filters?: any[];\n /** Whether this column supports server-side sorting. */\n sortable?: boolean;\n /** Whether this column supports server-side filtering.\n * Set to `true` for default operators, or provide a config object\n * with a custom set of operators. */\n filterable?: boolean | { operators?: string[] };\n /** Inferred data type, used to select context-appropriate filter\n * operators when `filterable` is `true` without explicit operators. */\n dataType?: ColumnDataType;\n /** Whether this column may be drag-reordered. Defaults to `true`; set\n * `false` to pin a fixed/system column in place. Applied by the default\n * header renderer (requires table-level `enableColumnReordering`). */\n reorderable?: boolean;\n}\n\nexport interface ColumnSpecOptions<T> {\n overrides: Record<string, Partial<ColumnSpec> | string>;\n data?: T[]; // Data to use for type inference\n nRows?: number; // Number of rows to use for type inference\n omitColumns?: string[]; // Columns to omit. Takes precedence over includeColumns.\n includeColumns?: string[]; // Columns to include.\n}\n\nexport function generateDefaultColumnSpec<T>(\n data: Array<T>,\n options: ColumnSpecGenerateOptions = {},\n): ColumnSpec[] {\n /** Build a default column spec from a dataset based on the first n rows */\n if (data == null) return [];\n // Get the keys\n\n const {\n defaultWidth = 150,\n calculateWidths = true,\n getWidthForValue = defaultWidthForValue,\n } = options;\n\n const keys = new Set<string>();\n const types = new Map();\n\n const columnWidths = new Map<string, number>();\n\n for (const row of data) {\n if (row == null) continue;\n for (const key of Object.keys(row)) {\n const val = row[key];\n keys.add(key);\n\n if (val == null) continue;\n\n if (calculateWidths) {\n let width = getWidthForValue(val);\n if (width != null && width >= 0) {\n columnWidths.set(key, Math.max(width, columnWidths.get(key) ?? 0));\n }\n }\n\n let type: string = typeof val;\n // Special 'type' for integers\n if (Number.isInteger(val)) {\n type = \"integer\";\n }\n\n // Special 'type' for arrays of simple values\n if (\n Array.isArray(val) &&\n val.every((d) => typeof d === \"string\" || typeof d === \"number\")\n ) {\n type = \"array\";\n }\n\n // Check if it is strictly a string, if so, we can explicitly mark it as text\n if (type === \"string\") {\n type = \"text\";\n }\n\n if (types.has(key)) {\n if (types.get(key) !== type) {\n if (type === \"number\" && types.get(key) === \"integer\") {\n types.set(key, \"number\");\n }\n if (type === \"object\" && types.get(key) === \"array\") {\n types.set(key, \"object\");\n }\n\n types.set(key, \"string\");\n }\n } else {\n types.set(key, type);\n }\n }\n }\n\n // Build a column spec\n const spec: ColumnSpec[] = [];\n for (const key of keys) {\n let width: number | undefined = undefined;\n if (calculateWidths) {\n // If we are calculating widths, use the value lengths\n width = Math.min(\n Math.max(defaultWidth / 2, columnWidths.get(key) ?? defaultWidth),\n defaultWidth * 1.5,\n );\n }\n\n const dataType = (types.get(key) ?? \"string\") as ColumnDataType;\n\n // Auto-infer sortable/filterable based on data type.\n // Scalar types (string, number, integer, boolean) get sort/filter;\n // complex types (object, array) do not.\n const isScalar =\n dataType === \"text\" ||\n dataType === \"string\" ||\n dataType === \"number\" ||\n dataType === \"integer\" ||\n dataType === \"boolean\";\n\n spec.push({\n name: key,\n key,\n valueRenderer: defaultRenderers[types.get(key)],\n width,\n dataType,\n sortable: isScalar,\n filterable: isScalar,\n });\n }\n return spec;\n}\n\nexport function generateColumnSpec<T>(\n data: T[],\n options: Partial<ColumnSpecOptions<T>> = {},\n): ColumnSpec[] {\n /** Generate a column spec from a dataset */\n const { overrides = {}, nRows = 10, omitColumns, includeColumns } = options;\n\n if (data == null) return [];\n\n const _nRows = Math.min(nRows, data.length);\n\n let columnSpec = generateDefaultColumnSpec(data.slice(0, _nRows));\n let filteredSpec = columnSpec.filter((col) => {\n if (omitColumns != null && omitColumns.includes(col.key)) {\n return false;\n }\n if (includeColumns != null && !includeColumns.includes(col.key)) {\n return false;\n }\n return true;\n });\n\n // Apply overrides\n const improvedSpec = filteredSpec.map((col) => {\n let ovr = overrides[col.key];\n if (ovr == null) return col;\n if (typeof ovr === \"string\") {\n return { ...col, name: ovr };\n }\n return { ...col, ...ovr };\n });\n return postprocessColumnSpec(improvedSpec);\n}\n\nexport function postprocessColumnSpec(columnSpec: ColumnSpec[]) {\n /** Postprocess column spec to make sure that, e.g., column filters are\n * properly established, etc. Hidden columns are dropped here, so everything\n * downstream — the renderer, the selection, the edit paths — works with the\n * visible columns only and indexes into one array.\n */\n return columnSpec\n .filter((col) => !col.hidden)\n .map((col) => {\n return {\n ...col,\n filters: postprocessColumnFilters(col),\n actions: col.actions ?? [],\n };\n });\n}\n\n/**\n * Whether a column takes writes at all: the table is editable, the column\n * isn't locked (`editable: false`) and it isn't `derived`. This is the one\n * rule every write path consults — the inline editor, `onSelectionEdited`,\n * fill, clear, clipboard paste and the row editor — so a locked column is\n * locked however the edit arrives, not only when it is typed into.\n */\nexport function isColumnWritable(\n col: ColumnSpec | null | undefined,\n tableEditable: boolean = true,\n): boolean {\n if (col == null) return false;\n if (!tableEditable) return false;\n if (col.derived) return false;\n return col.editable !== false;\n}\n\nfunction postprocessColumnFilters(col: ColumnSpec): TableFilter[] | undefined {\n const { filterable = true, filters = [] } = col;\n if (!filterable) {\n return undefined;\n }\n return filters.map((f) => enhanceColumnFilter(col, f));\n}\n"],"names":["enhanceColumnFilter"],"mappings":";;;AAIA,MAAM,mBAAmB;AAAA,EACvB,QAAQ,CAAC,MAAM;AAAA,EACf,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC3B,SAAS,CAAC,MAAO,IAAI,MAAM;AAAA,EAC3B,QAAQ,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/B,SAAS,CAAC,MAAM,GAAG,QAAQ,CAAC;AAAA,EAC5B,OAAO,CAAC,MAAM,GAAG,KAAK,IAAI;AAC5B;AAQA,MAAM,uBAAuB,CAAC,QAAQ,OAAO,GAAG,EAAE,SAAS;AAiOpD,SAAS,0BACd,MACA,UAAqC,IACvB;AAEd,MAAI,QAAQ,KAAM,QAAO,CAAA;AAGzB,QAAM;AAAA,IACJ,eAAe;AAAA,IACf,kBAAkB;AAAA,IAClB,mBAAmB;AAAA,EAAA,IACjB;AAEJ,QAAM,2BAAW,IAAA;AACjB,QAAM,4BAAY,IAAA;AAElB,QAAM,mCAAmB,IAAA;AAEzB,aAAW,OAAO,MAAM;AACtB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MACrC,SAAS,IAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAE7B,CAAC;AACL;AASO,SAAS,iBACd,KACA,gBAAyB,MAChB;AACT,MAAI,OAAO,KAAM,QAAO;AACxB,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,IAAI,QAAS,QAAO;AACxB,SAAO,IAAI,aAAa;AAC1B;AAEA,SAAS,yBAAyB,KAA4C;AAC5E,QAAM,EAAE,aAAa,MAAM,UAAU,CAAA,MAAO;AAC5C,MAAI,CAAC,YAAY;AACf,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,IAAI,CAAC,MAAMA,aAAAA,oBAAoB,KAAK,CAAC,CAAC;AACvD;;;;;"}
@@ -1,4 +1,5 @@
1
1
  import { default as React } from 'react';
2
+ import { Placement } from '@blueprintjs/core';
2
3
  import { TableFilter } from '../actions';
3
4
  interface ColumnSpecGenerateOptions {
4
5
  calculateWidths?: boolean;
@@ -66,13 +67,40 @@ export interface CellEditors {
66
67
  export interface CellDetailContext<T = any> extends CellRenderContext<T> {
67
68
  /** Whether this cell is editable (column × table × not-deleted). */
68
69
  editable: boolean;
69
- /** Commit a new value for this cell. */
70
+ /**
71
+ * When the surface stands for several cells at once (the row editor over a
72
+ * multi-row selection), the cells it stands for. `value` is then the value
73
+ * they share, or `undefined` when they differ (`mixed`), and `onChange`
74
+ * writes every one of them. Only offered to a column that declares
75
+ * `multiCell`; absent for a single cell.
76
+ */
77
+ cells?: CellSelectionEntry<T>[];
78
+ /** True when `cells` hold differing values. */
79
+ mixed?: boolean;
80
+ /** Where the surface is drawn: `"cell"`, the grid's own popover, modal or
81
+ * in-cell surface; `"row-editor"`, a field of the sheet's row editor; or
82
+ * `"editor"`, a field of a standalone `DataEditor` — so a surface can lay
83
+ * itself out to suit (a picker nesting its own popovers only where it has
84
+ * room). */
85
+ surface?: "cell" | "row-editor" | "editor";
86
+ /** Commit a new value for this cell — for every cell, when the surface
87
+ * stands for several. */
70
88
  onChange: (value: any) => void;
89
+ /** With `cells`, commit a value for each cell, aligned with them — for a
90
+ * surface that changes each cell's own value (adding a tag to every row's
91
+ * list) rather than setting them all to one. */
92
+ onChangeCells?: (values: any[]) => void;
71
93
  /** Reset this cell (and selection) to its base value. */
72
94
  resetValue: () => void;
73
95
  /** Close the surface and return focus to the table. */
74
96
  close: () => void;
75
97
  }
98
+ /** One of the cells a multi-cell surface stands for. */
99
+ export interface CellSelectionEntry<T = any> {
100
+ rowIndex: number;
101
+ row: T | null | undefined;
102
+ value: any;
103
+ }
76
104
  /** How a cell's detail surface is presented. Orthogonal to what it renders. */
77
105
  export type DetailPresentation = "popover" | "modal" | "inline";
78
106
  export interface ColumnSpec {
@@ -119,11 +147,45 @@ export interface ColumnSpec {
119
147
  * same component works in any container.
120
148
  */
121
149
  cellDetail?: (ctx: CellDetailContext) => React.ReactNode;
150
+ /**
151
+ * Whether this column's `cellDetail` can stand for several cells at once —
152
+ * read the shared value (or `ctx.mixed`) and write every cell in
153
+ * `ctx.cells` through one `onChange`. A surface that doesn't declare this
154
+ * is shown read-only over a multi-row selection, with "Multiple values"
155
+ * where they differ. The default editors (an input by `dataType`) always
156
+ * can, since setting one value on every cell is what they do.
157
+ */
158
+ multiCell?: boolean;
122
159
  /** How `cellDetail` is presented. Defaults to `"popover"`. */
123
160
  detailPresentation?: DetailPresentation;
161
+ /** What one cell of the column is called, for the selection indicator
162
+ * ("1 lithology", "3 lithologies"). Defaults to the column's name. */
163
+ cellLabel?: string;
164
+ /** Where a popover `cellDetail` opens against its cell. Defaults to
165
+ * `"right-start"`; a wide surface (a tag picker) reads better below, at
166
+ * `"bottom-start"`. */
167
+ detailPlacement?: Placement;
124
168
  cellComponent?: any;
125
169
  category?: string;
126
170
  editable?: boolean;
171
+ /**
172
+ * A **derived** column holds values computed from other data — a total, an
173
+ * age that follows from an interval and a proportion — rather than values
174
+ * anyone types. It is never writable, whatever `editable` or the table
175
+ * says, and every write path (inline editing, fill, paste, the row editor)
176
+ * leaves it alone; it is drawn dimmed so a reader can tell what is a record
177
+ * and what is a restatement of one. Use it instead of `editable: false` when
178
+ * the read-only-ness is a property of the *data* rather than of the view.
179
+ */
180
+ derived?: boolean;
181
+ /**
182
+ * A **hidden** column stays in the spec but is left out of the working
183
+ * spec the table is built from: it isn't rendered, isn't part of a
184
+ * selection, and isn't written by a fill or a paste. A consumer keeps one
185
+ * spec and toggles this flag ("show absolute ages", "show generated ids")
186
+ * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.
187
+ */
188
+ hidden?: boolean;
127
189
  inlineEditor?: boolean | React.ComponentType<any> | string | null;
128
190
  style?: React.CSSProperties;
129
191
  width?: number;
@@ -204,11 +266,45 @@ export declare function postprocessColumnSpec(columnSpec: ColumnSpec[]): {
204
266
  * same component works in any container.
205
267
  */
206
268
  cellDetail?: (ctx: CellDetailContext) => React.ReactNode;
269
+ /**
270
+ * Whether this column's `cellDetail` can stand for several cells at once —
271
+ * read the shared value (or `ctx.mixed`) and write every cell in
272
+ * `ctx.cells` through one `onChange`. A surface that doesn't declare this
273
+ * is shown read-only over a multi-row selection, with "Multiple values"
274
+ * where they differ. The default editors (an input by `dataType`) always
275
+ * can, since setting one value on every cell is what they do.
276
+ */
277
+ multiCell?: boolean;
207
278
  /** How `cellDetail` is presented. Defaults to `"popover"`. */
208
279
  detailPresentation?: DetailPresentation;
280
+ /** What one cell of the column is called, for the selection indicator
281
+ * ("1 lithology", "3 lithologies"). Defaults to the column's name. */
282
+ cellLabel?: string;
283
+ /** Where a popover `cellDetail` opens against its cell. Defaults to
284
+ * `"right-start"`; a wide surface (a tag picker) reads better below, at
285
+ * `"bottom-start"`. */
286
+ detailPlacement?: Placement;
209
287
  cellComponent?: any;
210
288
  category?: string;
211
289
  editable?: boolean;
290
+ /**
291
+ * A **derived** column holds values computed from other data — a total, an
292
+ * age that follows from an interval and a proportion — rather than values
293
+ * anyone types. It is never writable, whatever `editable` or the table
294
+ * says, and every write path (inline editing, fill, paste, the row editor)
295
+ * leaves it alone; it is drawn dimmed so a reader can tell what is a record
296
+ * and what is a restatement of one. Use it instead of `editable: false` when
297
+ * the read-only-ness is a property of the *data* rather than of the view.
298
+ */
299
+ derived?: boolean;
300
+ /**
301
+ * A **hidden** column stays in the spec but is left out of the working
302
+ * spec the table is built from: it isn't rendered, isn't part of a
303
+ * selection, and isn't written by a fill or a paste. A consumer keeps one
304
+ * spec and toggles this flag ("show absolute ages", "show generated ids")
305
+ * rather than maintaining two arrays. Resolved by `postprocessColumnSpec`.
306
+ */
307
+ hidden?: boolean;
212
308
  inlineEditor?: boolean | React.ComponentType<any> | string | null;
213
309
  style?: React.CSSProperties;
214
310
  width?: number;
@@ -228,4 +324,12 @@ export declare function postprocessColumnSpec(columnSpec: ColumnSpec[]): {
228
324
  * header renderer (requires table-level `enableColumnReordering`). */
229
325
  reorderable?: boolean;
230
326
  }[];
327
+ /**
328
+ * Whether a column takes writes at all: the table is editable, the column
329
+ * isn't locked (`editable: false`) and it isn't `derived`. This is the one
330
+ * rule every write path consults — the inline editor, `onSelectionEdited`,
331
+ * fill, clear, clipboard paste and the row editor — so a locked column is
332
+ * locked however the edit arrives, not only when it is typed into.
333
+ */
334
+ export declare function isColumnWritable(col: ColumnSpec | null | undefined, tableEditable?: boolean): boolean;
231
335
  export {};
@@ -103,7 +103,7 @@ function generateColumnSpec(data, options = {}) {
103
103
  return postprocessColumnSpec(improvedSpec);
104
104
  }
105
105
  function postprocessColumnSpec(columnSpec) {
106
- return columnSpec.map((col) => {
106
+ return columnSpec.filter((col) => !col.hidden).map((col) => {
107
107
  return {
108
108
  ...col,
109
109
  filters: postprocessColumnFilters(col),
@@ -111,6 +111,12 @@ function postprocessColumnSpec(columnSpec) {
111
111
  };
112
112
  });
113
113
  }
114
+ function isColumnWritable(col, tableEditable = true) {
115
+ if (col == null) return false;
116
+ if (!tableEditable) return false;
117
+ if (col.derived) return false;
118
+ return col.editable !== false;
119
+ }
114
120
  function postprocessColumnFilters(col) {
115
121
  const { filterable = true, filters = [] } = col;
116
122
  if (!filterable) {
@@ -121,6 +127,7 @@ function postprocessColumnFilters(col) {
121
127
  export {
122
128
  generateColumnSpec,
123
129
  generateDefaultColumnSpec,
130
+ isColumnWritable,
124
131
  postprocessColumnSpec
125
132
  };
126
133
  //# sourceMappingURL=column-spec.js.map