@macrostrat/data-sheet 2.1.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"mappings":"A,M,2C,A,Q,iB,C,C,U,C,C,Y,C,C,a,C,C,c,C,K,O,A,Q,M,mB,A,Q,e,C,C,Y,C,K,S,A,Q,kB,C,K,kB,A,Q,M,qB,C,S,E,C,C,C,C,C,C,C,E,O,c,C,E,E,C,I,E,I,E,W,C,E,a,C,C,E,C,I,E,W,E,C,E,E,C,E,E,E,iB,A,O,I,A,C,E,S,C,E,G,K,E,O,C,C,E,C,O,C,G,K,E,C,I,E,C,C,E,A,Q,C,C,E,C,I,E,C,G,E,Q,C,C,E,O,C,C,E,C,E,E,I,C,E,O,C,E,E,O,E,E,O,A,C,I,E,A,M,uB,E,I,O,E,I,C,mB,C,C,E,Q,C,S,C,C,C,E,C,C,E,C,C,E,E,iB,C,G,E,Q,C,I,E,C,E,E,E,oB,I,G,E,E,oB,I,G,E,E,c,I,G,E,E,c,I,G,E,E,c,I,G,I,E,E,SCyFA,IAAM,EAAmB,AAAA,EAA6C,MAOhE,EAAW,AAAA,EACf,AAAC,GAAwD,CAAA,CACvD,WAAY,EAAM,WAAW,CAAC,MAAM,CAAG,GAAK,EAAM,WAAW,CAAC,IAAI,CAAG,CACvE,CAAA,GAGK,SAAS,EAAqB,CAAA,SACnC,CAAQ,CAAA,KACR,CAAI,CAAA,WACJ,CAAU,CAAA,kBACV,CAAiB,CAAA,SACjB,CAAQ,CAAA,uBACR,CAAsB,CACI,EAC1B,IAAM,EAAkB,AAAA,EAAqB,CAC3C,cAAe,EACf,YAAa,CACf,GAEM,EAAW,AAAA,EAAe,MAE1B,CAAC,EAAM,CAAG,AAAA,EAAS,IAChB,AAAA,EACL,EAAS,AAAC,GACD,CAAA,CACL,KAAA,EACA,WAAY,GAAc,AAAA,CAAA,EAAA,EAAA,kBAAiB,AAAjB,EAAmB,EAA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AAI,CAAA,KAAE,CAAI,CAAE,CAAG,SACvB,AAAY,MAAR,GAAgB,AAAQ,MAAR,GAChB,GAAwB,CAAA,CAAI,CAAC,EAAE,GAAK,CAAI,CAAC,EAAE,EAAI,CAAI,CAAC,EAAE,GAAK,CAAI,CAAC,EAAC,AAAD,EAD3B,KAGlC,CAAE,IAAK,CAAI,CAAC,EAAE,CAAE,IAAK,CAAI,CAAC,EAAE,CAAE,oBAAqB,CAAE,CAC9D,CA6BO,SAAS,EACd,CAAa,SAGb,AAAI,GAAK,SAAW,EAAU,KACvB,EAAY,EAAK,CAAA,EAC1B,Q,K,iB,C,K,iB,C,K,W,C,K,W,C,K,W","sources":["<anon>","packages/data-sheet/src/provider.ts"],"sourcesContent":["import \"./data-sheet.50d0742f.js\";\nimport {createContext as $lNLp4$createContext, useRef as $lNLp4$useRef, useState as $lNLp4$useState, useEffect as $lNLp4$useEffect, useContext as $lNLp4$useContext} from \"react\";\nimport $lNLp4$macrostrathyper from \"@macrostrat/hyper\";\nimport {createStore as $lNLp4$createStore, useStore as $lNLp4$useStore} from \"zustand\";\nimport {createComputed as $lNLp4$createComputed} from \"zustand-computed\";\nimport $lNLp4$immutabilityhelper from \"immutability-helper\";\n\n\nfunction $parcel$export(e, n, v, s) {\n Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});\n}\n\n var $parcel$global = globalThis;\n \nvar $parcel$modules = {};\nvar $parcel$inits = {};\n\nvar parcelRequire = $parcel$global[\"parcelRequirea149\"];\n\nif (parcelRequire == null) {\n parcelRequire = function(id) {\n if (id in $parcel$modules) {\n return $parcel$modules[id].exports;\n }\n if (id in $parcel$inits) {\n var init = $parcel$inits[id];\n delete $parcel$inits[id];\n var module = {id: id, exports: {}};\n $parcel$modules[id] = module;\n init.call(module.exports, module, module.exports);\n return module.exports;\n }\n var err = new Error(\"Cannot find module '\" + id + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n };\n\n parcelRequire.register = function register(id, init) {\n $parcel$inits[id] = init;\n };\n\n $parcel$global[\"parcelRequirea149\"] = parcelRequire;\n}\n\nvar parcelRegister = parcelRequire.register;\nvar $7e5384423bc0f425$exports = {};\n\n$parcel$export($7e5384423bc0f425$exports, \"DataSheetProvider\", () => $7e5384423bc0f425$export$135c527978291360);\n$parcel$export($7e5384423bc0f425$exports, \"singleFocusedCell\", () => $7e5384423bc0f425$export$de0bb697976d7dcb);\n$parcel$export($7e5384423bc0f425$exports, \"useStoreAPI\", () => $7e5384423bc0f425$export$54fc6f5c8f914926);\n$parcel$export($7e5384423bc0f425$exports, \"useSelector\", () => $7e5384423bc0f425$export$2105062e25df4afe);\n$parcel$export($7e5384423bc0f425$exports, \"topLeftCell\", () => $7e5384423bc0f425$export$88b0ba8661dc41b4);\n\n\n\n\n\nvar $50UEa = parcelRequire(\"50UEa\");\n\nconst $7e5384423bc0f425$var$DataSheetContext = (0, $lNLp4$createContext)(null);\nconst $7e5384423bc0f425$var$computed = (0, $lNLp4$createComputed)((state)=>({\n hasUpdates: state.updatedData.length > 0 || state.deletedRows.size > 0\n }));\nfunction $7e5384423bc0f425$export$135c527978291360({ children: children, data: data, columnSpec: columnSpec, columnSpecOptions: columnSpecOptions, editable: editable, enableColumnReordering: enableColumnReordering }) {\n const visibleCellsRef = (0, $lNLp4$useRef)({\n rowIndexStart: 0,\n rowIndexEnd: 0\n });\n const tableRef = (0, $lNLp4$useRef)(null);\n const [store] = (0, $lNLp4$useState)(()=>{\n return (0, $lNLp4$createStore)($7e5384423bc0f425$var$computed((set)=>{\n return {\n data: data,\n columnSpec: columnSpec ?? (0, $50UEa.generateColumnSpec)(data, columnSpecOptions),\n editable: editable,\n deletedRows: new Set(),\n selection: [],\n fillValueBaseCell: null,\n updatedData: [],\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: tableRef,\n // This is a placeholder\n enableColumnReordering: false,\n setSelection (selection) {\n set($7e5384423bc0f425$var$updateSelection(selection));\n },\n moveFocusedCell (direction) {\n set((state)=>{\n const { topLeftCell: topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col: col, row: row } = topLeftCell;\n switch(direction){\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(row + 1, Math.max(state.data.length, state.updatedData.length) - 1);\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region = {\n cols: [\n col,\n col\n ],\n rows: [\n row,\n row\n ]\n };\n return $7e5384423bc0f425$var$updateSelection([\n region\n ]);\n });\n },\n addRow (row = {}) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */ set((state)=>{\n const { updatedData: updatedData, data: data, selection: selection } = state;\n const lastRowIndex = $7e5384423bc0f425$var$getLastRowIndex(selection) ?? Math.max(data.length, updatedData.length) - 1;\n // If there is a selection, insert the new row after the last selected row\n const spec = {\n $splice: [\n [\n lastRowIndex + 1,\n 0,\n row\n ]\n ]\n };\n console.log(spec);\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n setUpdatedData (data) {\n if (Array.isArray(data)) set({\n updatedData: data\n });\n else set((state)=>{\n return {\n updatedData: data(state.updatedData)\n };\n });\n },\n deleteSelectedRows () {\n // Remove selected rows from the data and updatedData arrays\n set((state)=>{\n const { selection: selection, deletedRows: deletedRows } = state;\n const rowIndices = $7e5384423bc0f425$var$getRowIndices(selection);\n // Delete rows from both updatedData and data\n const newDeletedRows = new Set(deletedRows);\n for (const rowIndex of rowIndices)newDeletedRows.add(rowIndex);\n // Remove selected rows and reset selection\n return {\n deletedRows: newDeletedRows,\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n };\n });\n },\n resetChanges () {\n // Reset the updated data to the initial data\n set((state)=>({\n updatedData: [],\n deletedRows: new Set(),\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n }));\n },\n setVisibleCells (visibleCells) {\n // Visible cells are used for infinite scrolling\n // Right now we don't store this in the state\n visibleCellsRef.current = visibleCells;\n },\n onDragValue (cell) {\n set({\n fillValueBaseCell: cell\n });\n },\n onCellEdited (rowIndex, columnName, value) {\n set((state)=>{\n const { editable: editable, updatedData: updatedData, data: data } = state;\n if (!editable) return {};\n let rowSpec;\n // Check to see if the new value is the same as the old one\n if (value !== data[rowIndex]?.[columnName]) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = {\n [rowOp]: {\n [columnName]: value\n }\n };\n } else rowSpec = {\n $unset: [\n columnName\n ]\n };\n const spec = {\n [rowIndex]: rowSpec\n };\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n initialize (props) {\n set({\n ...props,\n initialized: true\n });\n },\n clearSelection () {\n set((state)=>{\n // Delete all selected cells\n const { selection: selection, updatedData: updatedData, columnSpec: columnSpec, data: data } = state;\n let spec = {};\n for (const region of selection){\n const { cols: cols, rows: rows } = region;\n const rowRange = (0, $50UEa.range)(rows ?? [\n 0,\n updatedData.length - 1\n ]);\n const colRange = (0, $50UEa.range)(cols ?? [\n 0,\n columnSpec.length - 1\n ]);\n for (const row of rowRange){\n let vals = {};\n for (const col of colRange){\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") vals[key] = \"\";\n }\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = {\n [op]: vals\n };\n }\n }\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n onSelection (selection) {\n set((state)=>{\n if ($7e5384423bc0f425$var$selectionEquals(selection, state.selection) && $7e5384423bc0f425$export$de0bb697976d7dcb(selection) == null // Only if we're in a multi-cell selection mode\n ) // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n };\n let spec = $7e5384423bc0f425$var$updateSelection(selection);\n if (state.fillValueBaseCell != null) spec.updatedData = $7e5384423bc0f425$var$fillValues(state, selection);\n return spec;\n });\n },\n onColumnsReordered (oldIndex, newIndex, length) {\n set((state)=>{\n if (!state.enableColumnReordering) return {};\n const { columnSpec: columnSpec } = state;\n const newSpec = [\n ...columnSpec\n ];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return {\n columnSpec: newSpec\n };\n });\n },\n scrollToRow (rowIndex) {\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [\n rowIndex,\n rowIndex\n ]\n });\n }\n };\n }));\n });\n // Not sure how required this initialization is\n (0, $lNLp4$useEffect)(()=>{\n const { initialize: initialize } = store.getState();\n initialize({\n data: data,\n columnSpec: columnSpec ?? (0, $50UEa.generateColumnSpec)(data, columnSpecOptions),\n editable: editable,\n enableColumnReordering: enableColumnReordering\n });\n }, [\n data,\n editable,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering\n ]);\n return (0, $lNLp4$macrostrathyper)($7e5384423bc0f425$var$DataSheetContext.Provider, {\n value: store\n }, children);\n}\nfunction $7e5384423bc0f425$export$54fc6f5c8f914926() {\n const store = (0, $lNLp4$useContext)($7e5384423bc0f425$var$DataSheetContext);\n if (!store) throw new Error(\"Missing DataSheetProvider\");\n return store;\n}\nfunction $7e5384423bc0f425$export$2105062e25df4afe(selector) {\n const store = $7e5384423bc0f425$export$54fc6f5c8f914926();\n return (0, $lNLp4$useStore)(store, selector);\n}\nfunction $7e5384423bc0f425$var$updateSelection(selection) {\n const focusedCell = $7e5384423bc0f425$export$de0bb697976d7dcb(selection);\n let spec = {\n selection: selection,\n focusedCell: focusedCell,\n topLeftCell: $7e5384423bc0f425$export$88b0ba8661dc41b4(selection)\n };\n if (focusedCell != null) spec.fillValueBaseCell = null;\n return spec;\n}\nfunction $7e5384423bc0f425$var$getLastRowIndex(regions) {\n /** Get the last row index from a selection of regions */ if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions){\n const { rows: rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) /** If no valid rows are found, return null */ return null;\n return lastRow;\n}\nfunction $7e5384423bc0f425$var$getRowIndices(regions) {\n /** Get the row indices from a selection of regions */ if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set();\n for (const region of regions){\n const { rows: rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for(let i = rows[0]; i <= rows[1]; i++)rowIndices.add(i);\n }\n return Array.from(rowIndices).sort((a, b)=>a - b);\n}\nfunction $7e5384423bc0f425$export$88b0ba8661dc41b4(regions, requireSolitaryCell = false) {\n /** Top left cell of a ranged selection */ if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols: cols, rows: rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1])) return null;\n return {\n col: cols[0],\n row: rows[0],\n focusSelectionIndex: 0\n };\n}\nfunction $7e5384423bc0f425$var$selectionEquals(a, b) {\n /** Check if two selections are equal */ if (a.length !== b.length) return false;\n for(let i = 0; i < a.length; i++){\n const regionA = a[i];\n const regionB = b[i];\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n if (colsA.length !== colsB.length || rowsA.length !== rowsB.length || colsA[0] !== colsB[0] || colsA[1] !== colsB[1] || rowsA[0] !== rowsB[0] || rowsA[1] !== rowsB[1]) return false;\n }\n return true;\n}\nfunction $7e5384423bc0f425$export$de0bb697976d7dcb(sel) {\n /** Derive a single focused cell from a selected region, if possible */ if (sel?.length !== 1) return null;\n return $7e5384423bc0f425$export$88b0ba8661dc41b4(sel, true);\n}\nfunction $7e5384423bc0f425$var$fillValues(state, selection) {\n const { updatedData: updatedData, columnSpec: columnSpec, editable: editable, fillValueBaseCell: fillValueBaseCell, data: data } = state;\n // Prepare regions by unnesting columns\n let regions = selection.map((region)=>{\n const { cols: cols, rows: rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols;\n return {\n cols: [\n col,\n col\n ],\n rows: rows\n };\n });\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col: col, row: row } = fillValueBaseCell;\n const key = columnSpec[col].key;\n const value = updatedData[row]?.[key] ?? data[row][key];\n const spec = {};\n for (const region of regions){\n const { cols: cols, rows: rows } = region;\n for (const row of (0, $50UEa.range)(rows)){\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = {\n [op]: {\n [key]: value\n }\n };\n }\n }\n return (0, $lNLp4$immutabilityhelper)(updatedData, spec);\n}\n\n\nexport {$7e5384423bc0f425$export$135c527978291360 as DataSheetProvider, $7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell, $7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI, $7e5384423bc0f425$export$2105062e25df4afe as useSelector, $7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};\n//# sourceMappingURL=data-sheet.52753d1d.js.map\n","import { createContext, useContext, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport { createComputed } from \"zustand-computed\";\nimport type {\n FocusedCellCoordinates,\n Region,\n Table2,\n} from \"@blueprintjs/table\";\nimport { generateColumnSpec } from \"./utils\";\nimport update, { Spec } from \"immutability-helper\";\nimport { range } from \"./utils\";\nimport React from \"react\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n required?: boolean;\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\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}\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 interface DataSheetCoreProps<T> {\n data: T[];\n columnSpec?: ColumnSpec[];\n editable?: boolean;\n enableColumnReordering?: boolean;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n deletedRows: Set<number>;\n // Sparse data structure for updated data\n updatedData: T[];\n initialized: boolean;\n}\n\nexport interface DataSheetComputedStore {\n hasUpdates: boolean;\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;\n\ntype StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStore<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(cell: FocusedCellCoordinates | null): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\"): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n initialize(props: DataSheetCoreProps<T>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n setVisibleCells(visibleCells: VisibleCells): void;\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2>;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n};\n\nconst DataSheetContext = createContext<StoreApi<DataSheetStore<any>>>(null);\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nconst computed = createComputed(\n (state: DataSheetStore<any>): DataSheetComputedStore => ({\n hasUpdates: state.updatedData.length > 0 || state.deletedRows.size > 0,\n }),\n) as any;\n\nexport function DataSheetProvider<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n}: DataSheetProviderProps<T>) {\n const visibleCellsRef = useRef<VisibleCells>({\n rowIndexStart: 0,\n rowIndexEnd: 0,\n });\n\n const tableRef = useRef<Table2>(null);\n\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(\n computed((set): DataSheetStore<T> => {\n return {\n data,\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n deletedRows: new Set<number>(),\n selection: [],\n fillValueBaseCell: null,\n updatedData: [],\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef,\n // This is a placeholder\n enableColumnReordering: false,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n return updateSelection([region]);\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n set((state) => {\n const { updatedData, data, selection } = state;\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // If there is a selection, insert the new row after the last selected row\n const spec: Spec<any> = {\n $splice: [[lastRowIndex + 1, 0, row]],\n };\n console.log(spec);\n\n return {\n updatedData: update(updatedData, spec),\n };\n });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Remove selected rows from the data and updatedData arrays\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n\n // Delete rows from both updatedData and data\n const newDeletedRows = new Set(deletedRows);\n for (const rowIndex of rowIndices) {\n newDeletedRows.add(rowIndex);\n }\n\n // Remove selected rows and reset selection\n return {\n deletedRows: newDeletedRows,\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n },\n resetChanges() {\n // Reset the updated data to the initial data\n set((state) => ({\n updatedData: [],\n deletedRows: new Set<number>(),\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n }));\n },\n setVisibleCells(visibleCells: VisibleCells) {\n // Visible cells are used for infinite scrolling\n // Right now we don't store this in the state\n visibleCellsRef.current = visibleCells;\n },\n onDragValue(cell: FocusedCellCoordinates | null) {\n set({ fillValueBaseCell: cell });\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n // Check to see if the new value is the same as the old one\n if (value !== data[rowIndex]?.[columnName]) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else {\n rowSpec = { $unset: [columnName] };\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n },\n initialize(props: DataSheetCoreProps<T>) {\n set({ ...props, initialized: true });\n },\n clearSelection() {\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, updatedData.length - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const row of rowRange) {\n let vals = {};\n for (const col of colRange) {\n const key = columnSpec[col].key;\n const currentValue =\n updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n }\n }\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n },\n onSelection(selection: Region[]) {\n set((state) => {\n if (\n selectionEquals(selection, state.selection) &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillValues(state, selection);\n }\n return spec;\n });\n },\n onColumnsReordered(\n oldIndex: number,\n newIndex: number,\n length: number,\n ) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n };\n }),\n );\n });\n\n // Not sure how required this initialization is\n useEffect(() => {\n const { initialize } = store.getState();\n initialize({\n data,\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n enableColumnReordering,\n });\n }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);\n\n return h(DataSheetContext.Provider, { value: store }, children);\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = useContext(DataSheetContext);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedStore) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n\nfunction updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n if (focusedCell != null) {\n spec.fillValueBaseCell = null;\n }\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\nfunction fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {\n const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;\n\n // Prepare regions by unnesting columns\n let regions = selection.map((region) => {\n const { cols, rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols;\n return { cols: [col, col], rows };\n });\n\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col, row } = fillValueBaseCell;\n const key = columnSpec[col].key;\n const value = updatedData[row]?.[key] ?? data[row][key];\n const spec = {};\n for (const region of regions) {\n const { cols, rows } = region;\n for (const row of range(rows)) {\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n }\n }\n return update(updatedData, spec);\n}\n"],"names":["createContext","$lNLp4$createContext","useRef","$lNLp4$useRef","useState","$lNLp4$useState","useEffect","$lNLp4$useEffect","useContext","$lNLp4$useContext","$lNLp4$macrostrathyper","createStore","$lNLp4$createStore","useStore","$lNLp4$useStore","createComputed","$lNLp4$createComputed","$lNLp4$immutabilityhelper","$parcel$export","e","n","v","s","Object","defineProperty","get","set","enumerable","configurable","$parcel$global","globalThis","$parcel$modules","$parcel$inits","parcelRequire","id","exports","init","module","call","err","Error","code","register","$7e5384423bc0f425$exports","$7e5384423bc0f425$export$135c527978291360","$7e5384423bc0f425$export$de0bb697976d7dcb","$7e5384423bc0f425$export$54fc6f5c8f914926","$7e5384423bc0f425$export$2105062e25df4afe","$7e5384423bc0f425$export$88b0ba8661dc41b4","$50UEa","$7e5384423bc0f425$var$DataSheetContext","$7e5384423bc0f425$var$computed","state","hasUpdates","updatedData","length","deletedRows","size","children","data","columnSpec","columnSpecOptions","editable","enableColumnReordering","visibleCellsRef","rowIndexStart","rowIndexEnd","tableRef","store","generateColumnSpec","Set","selection","fillValueBaseCell","focusedCell","topLeftCell","initialized","setSelection","$7e5384423bc0f425$var$updateSelection","moveFocusedCell","direction","col","row","Math","max","min","cols","rows","addRow","spec","$splice","lastRowIndex","$7e5384423bc0f425$var$getLastRowIndex","regions","lastRow","region","console","log","setUpdatedData","Array","isArray","deleteSelectedRows","rowIndices","$7e5384423bc0f425$var$getRowIndices","i","add","from","sort","a","b","newDeletedRows","rowIndex","resetChanges","setVisibleCells","visibleCells","current","onDragValue","cell","onCellEdited","columnName","value","rowSpec","$unset","initialize","props","clearSelection","rowRange","range","colRange","vals","key","currentValue","op","onSelection","$7e5384423bc0f425$var$selectionEquals","regionA","regionB","colsA","colsB","rowsA","rowsB","$7e5384423bc0f425$var$fillValues","map","onColumnsReordered","oldIndex","newIndex","newSpec","removed","splice","scrollToRow","scrollToRegion","getState","Provider","selector","requireSolitaryCell","focusSelectionIndex","sel","DataSheetProvider","singleFocusedCell","useStoreAPI","useSelector"],"version":3,"file":"data-sheet.52753d1d.js.map","sourceRoot":"../../../../"}
1
+ {"mappings":"A,M,2C,A,Q,iB,C,C,U,C,C,Y,C,C,a,C,C,c,C,K,O,A,Q,M,mB,A,Q,e,C,C,Y,C,K,S,A,Q,kB,C,K,kB,A,Q,M,qB,C,S,E,C,C,C,C,C,C,C,E,O,c,C,E,E,C,I,E,I,E,W,C,E,a,C,C,E,C,I,E,W,E,C,E,E,C,E,E,E,iB,A,O,I,A,C,E,S,C,E,G,K,E,O,C,C,E,C,O,C,G,K,E,C,I,E,C,C,E,A,Q,C,C,E,C,I,E,C,G,E,Q,C,C,E,O,C,C,E,C,E,E,I,C,E,O,C,E,E,O,E,E,O,A,C,I,E,A,M,uB,E,I,O,E,I,C,mB,C,C,E,Q,C,S,C,C,C,E,C,C,E,C,C,E,E,iB,C,G,E,Q,C,I,E,C,E,E,E,oB,I,G,E,E,oB,I,G,E,E,c,I,G,E,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QAAQ,CAAE,CAAE,MAAO,CAAM,EAAG,EACxD,CAEO,SAAS,IACd,IAAM,EAAQ,AAAA,EAAW,GACzB,GAAI,CAAC,EACH,MAAM,AAAI,MAAM,6BAElB,OAAO,CACT,CAEO,SAAS,EACd,CAAkE,EAGlE,OAAO,AAAA,EADO,IACS,EACzB,CAEA,SAAS,EAAmB,CAAmB,EAC7C,IAAM,EAAc,EAAkB,GAClC,EAAmC,CACrC,UAAA,EACA,YAAA,EACA,YAAa,EAAY,EAC3B,EAIA,OAHI,AAAe,MAAf,GACF,CAAA,EAAK,iBAAiB,CAAG,IAD3B,EAGO,CACT,CAgCO,SAAS,EACd,CAAiB,CACjB,EAA+B,CAAA,CAAK,EAGpC,GAAI,AAAW,MAAX,EAAiB,OAAO,KAC5B,GAAM,CAAC,EAAO,CAAG,EACjB,GAAI,AAAU,MAAV,EAAgB,OAAO,KAC3B,GAAM,CAAA,KAAE,CAAI,CAAA,KAAE,CAAI,CAAE,CAAG,SACvB,AAAY,MAAR,GAAgB,AAAQ,MAAR,GAChB,GAAwB,CAAA,CAAI,CAAC,EAAE,GAAK,CAAI,CAAC,EAAE,EAAI,CAAI,CAAC,EAAE,GAAK,CAAI,CAAC,EAAC,AAAD,EAD3B,KAGlC,CAAE,IAAK,CAAI,CAAC,EAAE,CAAE,IAAK,CAAI,CAAC,EAAE,CAAE,oBAAqB,CAAE,CAC9D,CA6BO,SAAS,EACd,CAAa,SAGb,AAAI,GAAK,SAAW,EAAU,KACvB,EAAY,EAAK,CAAA,EAC1B,Q,K,iB,C,K,iB,C,K,W,C,K,W,C,K,W","sources":["<anon>","packages/data-sheet/src/provider.ts"],"sourcesContent":["import \"./data-sheet.50d0742f.js\";\nimport {createContext as $lNLp4$createContext, useRef as $lNLp4$useRef, useState as $lNLp4$useState, useEffect as $lNLp4$useEffect, useContext as $lNLp4$useContext} from \"react\";\nimport $lNLp4$macrostrathyper from \"@macrostrat/hyper\";\nimport {createStore as $lNLp4$createStore, useStore as $lNLp4$useStore} from \"zustand\";\nimport {createComputed as $lNLp4$createComputed} from \"zustand-computed\";\nimport $lNLp4$immutabilityhelper from \"immutability-helper\";\n\n\nfunction $parcel$export(e, n, v, s) {\n Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});\n}\n\n var $parcel$global = globalThis;\n \nvar $parcel$modules = {};\nvar $parcel$inits = {};\n\nvar parcelRequire = $parcel$global[\"parcelRequirea149\"];\n\nif (parcelRequire == null) {\n parcelRequire = function(id) {\n if (id in $parcel$modules) {\n return $parcel$modules[id].exports;\n }\n if (id in $parcel$inits) {\n var init = $parcel$inits[id];\n delete $parcel$inits[id];\n var module = {id: id, exports: {}};\n $parcel$modules[id] = module;\n init.call(module.exports, module, module.exports);\n return module.exports;\n }\n var err = new Error(\"Cannot find module '\" + id + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n };\n\n parcelRequire.register = function register(id, init) {\n $parcel$inits[id] = init;\n };\n\n $parcel$global[\"parcelRequirea149\"] = parcelRequire;\n}\n\nvar parcelRegister = parcelRequire.register;\nvar $7e5384423bc0f425$exports = {};\n\n$parcel$export($7e5384423bc0f425$exports, \"DataSheetProvider\", () => $7e5384423bc0f425$export$135c527978291360);\n$parcel$export($7e5384423bc0f425$exports, \"singleFocusedCell\", () => $7e5384423bc0f425$export$de0bb697976d7dcb);\n$parcel$export($7e5384423bc0f425$exports, \"useStoreAPI\", () => $7e5384423bc0f425$export$54fc6f5c8f914926);\n$parcel$export($7e5384423bc0f425$exports, \"useSelector\", () => $7e5384423bc0f425$export$2105062e25df4afe);\n$parcel$export($7e5384423bc0f425$exports, \"topLeftCell\", () => $7e5384423bc0f425$export$88b0ba8661dc41b4);\n\n\n\n\n\nvar $50UEa = parcelRequire(\"50UEa\");\n\nconst $7e5384423bc0f425$var$DataSheetContext = (0, $lNLp4$createContext)(null);\nconst $7e5384423bc0f425$var$computed = (0, $lNLp4$createComputed)((state)=>({\n hasUpdates: state.updatedData.length > 0 || state.deletedRows.size > 0\n }));\nfunction $7e5384423bc0f425$export$135c527978291360({ children: children, data: data, columnSpec: columnSpec, columnSpecOptions: columnSpecOptions, editable: editable, enableColumnReordering: enableColumnReordering }) {\n const visibleCellsRef = (0, $lNLp4$useRef)({\n rowIndexStart: 0,\n rowIndexEnd: 0\n });\n const tableRef = (0, $lNLp4$useRef)(null);\n const [store] = (0, $lNLp4$useState)(()=>{\n return (0, $lNLp4$createStore)($7e5384423bc0f425$var$computed((set)=>{\n return {\n data: data,\n columnSpec: columnSpec ?? (0, $50UEa.generateColumnSpec)(data, columnSpecOptions),\n editable: editable,\n deletedRows: new Set(),\n selection: [],\n fillValueBaseCell: null,\n updatedData: [],\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef: tableRef,\n // This is a placeholder\n enableColumnReordering: false,\n setSelection (selection) {\n set($7e5384423bc0f425$var$updateSelection(selection));\n },\n moveFocusedCell (direction) {\n set((state)=>{\n const { topLeftCell: topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col: col, row: row } = topLeftCell;\n switch(direction){\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(row + 1, Math.max(state.data.length, state.updatedData.length) - 1);\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region = {\n cols: [\n col,\n col\n ],\n rows: [\n row,\n row\n ]\n };\n return $7e5384423bc0f425$var$updateSelection([\n region\n ]);\n });\n },\n addRow (row = {}) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */ set((state)=>{\n const { updatedData: updatedData, data: data, selection: selection } = state;\n const lastRowIndex = $7e5384423bc0f425$var$getLastRowIndex(selection) ?? Math.max(data.length, updatedData.length) - 1;\n // If there is a selection, insert the new row after the last selected row\n const spec = {\n $splice: [\n [\n lastRowIndex + 1,\n 0,\n row\n ]\n ]\n };\n console.log(spec);\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n setUpdatedData (data) {\n if (Array.isArray(data)) set({\n updatedData: data\n });\n else set((state)=>{\n return {\n updatedData: data(state.updatedData)\n };\n });\n },\n deleteSelectedRows () {\n // Remove selected rows from the data and updatedData arrays\n set((state)=>{\n const { selection: selection, deletedRows: deletedRows } = state;\n const rowIndices = $7e5384423bc0f425$var$getRowIndices(selection);\n // Delete rows from both updatedData and data\n const newDeletedRows = new Set(deletedRows);\n for (const rowIndex of rowIndices)newDeletedRows.add(rowIndex);\n // Remove selected rows and reset selection\n return {\n deletedRows: newDeletedRows,\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n };\n });\n },\n resetChanges () {\n // Reset the updated data to the initial data\n set((state)=>({\n updatedData: [],\n deletedRows: new Set(),\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n }));\n },\n setVisibleCells (visibleCells) {\n // Visible cells are used for infinite scrolling\n // Right now we don't store this in the state\n visibleCellsRef.current = visibleCells;\n },\n onDragValue (cell) {\n set({\n fillValueBaseCell: cell\n });\n },\n onCellEdited (rowIndex, columnName, value) {\n set((state)=>{\n const { editable: editable, updatedData: updatedData, data: data } = state;\n if (!editable) return {};\n let rowSpec;\n // Check to see if the new value is the same as the old one\n if (value !== data[rowIndex]?.[columnName]) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = {\n [rowOp]: {\n [columnName]: value\n }\n };\n } else rowSpec = {\n $unset: [\n columnName\n ]\n };\n const spec = {\n [rowIndex]: rowSpec\n };\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n initialize (props) {\n set({\n ...props,\n initialized: true\n });\n },\n clearSelection () {\n set((state)=>{\n // Delete all selected cells\n const { selection: selection, updatedData: updatedData, columnSpec: columnSpec, data: data } = state;\n let spec = {};\n for (const region of selection){\n const { cols: cols, rows: rows } = region;\n const rowRange = (0, $50UEa.range)(rows ?? [\n 0,\n updatedData.length - 1\n ]);\n const colRange = (0, $50UEa.range)(cols ?? [\n 0,\n columnSpec.length - 1\n ]);\n for (const row of rowRange){\n let vals = {};\n for (const col of colRange){\n const key = columnSpec[col].key;\n const currentValue = updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") vals[key] = \"\";\n }\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = {\n [op]: vals\n };\n }\n }\n return {\n updatedData: (0, $lNLp4$immutabilityhelper)(updatedData, spec)\n };\n });\n },\n onSelection (selection) {\n set((state)=>{\n if ($7e5384423bc0f425$var$selectionEquals(selection, state.selection) && $7e5384423bc0f425$export$de0bb697976d7dcb(selection) == null // Only if we're in a multi-cell selection mode\n ) // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null\n };\n let spec = $7e5384423bc0f425$var$updateSelection(selection);\n if (state.fillValueBaseCell != null) spec.updatedData = $7e5384423bc0f425$var$fillValues(state, selection);\n return spec;\n });\n },\n onColumnsReordered (oldIndex, newIndex, length) {\n set((state)=>{\n if (!state.enableColumnReordering) return {};\n const { columnSpec: columnSpec } = state;\n const newSpec = [\n ...columnSpec\n ];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return {\n columnSpec: newSpec\n };\n });\n },\n scrollToRow (rowIndex) {\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [\n rowIndex,\n rowIndex\n ]\n });\n }\n };\n }));\n });\n // Not sure how required this initialization is\n (0, $lNLp4$useEffect)(()=>{\n const { initialize: initialize } = store.getState();\n initialize({\n data: data,\n columnSpec: columnSpec ?? (0, $50UEa.generateColumnSpec)(data, columnSpecOptions),\n editable: editable,\n enableColumnReordering: enableColumnReordering\n });\n }, [\n data,\n editable,\n columnSpec,\n columnSpecOptions,\n enableColumnReordering\n ]);\n return (0, $lNLp4$macrostrathyper)($7e5384423bc0f425$var$DataSheetContext.Provider, {\n value: store\n }, children);\n}\nfunction $7e5384423bc0f425$export$54fc6f5c8f914926() {\n const store = (0, $lNLp4$useContext)($7e5384423bc0f425$var$DataSheetContext);\n if (!store) throw new Error(\"Missing DataSheetProvider\");\n return store;\n}\nfunction $7e5384423bc0f425$export$2105062e25df4afe(selector) {\n const store = $7e5384423bc0f425$export$54fc6f5c8f914926();\n return (0, $lNLp4$useStore)(store, selector);\n}\nfunction $7e5384423bc0f425$var$updateSelection(selection) {\n const focusedCell = $7e5384423bc0f425$export$de0bb697976d7dcb(selection);\n let spec = {\n selection: selection,\n focusedCell: focusedCell,\n topLeftCell: $7e5384423bc0f425$export$88b0ba8661dc41b4(selection)\n };\n if (focusedCell != null) spec.fillValueBaseCell = null;\n return spec;\n}\nfunction $7e5384423bc0f425$var$getLastRowIndex(regions) {\n /** Get the last row index from a selection of regions */ if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions){\n const { rows: rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) /** If no valid rows are found, return null */ return null;\n return lastRow;\n}\nfunction $7e5384423bc0f425$var$getRowIndices(regions) {\n /** Get the row indices from a selection of regions */ if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set();\n for (const region of regions){\n const { rows: rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for(let i = rows[0]; i <= rows[1]; i++)rowIndices.add(i);\n }\n return Array.from(rowIndices).sort((a, b)=>a - b);\n}\nfunction $7e5384423bc0f425$export$88b0ba8661dc41b4(regions, requireSolitaryCell = false) {\n /** Top left cell of a ranged selection */ if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols: cols, rows: rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1])) return null;\n return {\n col: cols[0],\n row: rows[0],\n focusSelectionIndex: 0\n };\n}\nfunction $7e5384423bc0f425$var$selectionEquals(a, b) {\n /** Check if two selections are equal */ if (a.length !== b.length) return false;\n for(let i = 0; i < a.length; i++){\n const regionA = a[i];\n const regionB = b[i];\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n if (colsA.length !== colsB.length || rowsA.length !== rowsB.length || colsA[0] !== colsB[0] || colsA[1] !== colsB[1] || rowsA[0] !== rowsB[0] || rowsA[1] !== rowsB[1]) return false;\n }\n return true;\n}\nfunction $7e5384423bc0f425$export$de0bb697976d7dcb(sel) {\n /** Derive a single focused cell from a selected region, if possible */ if (sel?.length !== 1) return null;\n return $7e5384423bc0f425$export$88b0ba8661dc41b4(sel, true);\n}\nfunction $7e5384423bc0f425$var$fillValues(state, selection) {\n const { updatedData: updatedData, columnSpec: columnSpec, editable: editable, fillValueBaseCell: fillValueBaseCell, data: data } = state;\n // Prepare regions by unnesting columns\n let regions = selection.map((region)=>{\n const { cols: cols, rows: rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols;\n return {\n cols: [\n col,\n col\n ],\n rows: rows\n };\n });\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col: col, row: row } = fillValueBaseCell;\n const key = columnSpec[col].key;\n const value = updatedData[row]?.[key] ?? data[row][key];\n const spec = {};\n for (const region of regions){\n const { cols: cols, rows: rows } = region;\n for (const row of (0, $50UEa.range)(rows)){\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = {\n [op]: {\n [key]: value\n }\n };\n }\n }\n return (0, $lNLp4$immutabilityhelper)(updatedData, spec);\n}\n\n\nexport {$7e5384423bc0f425$export$135c527978291360 as DataSheetProvider, $7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell, $7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI, $7e5384423bc0f425$export$2105062e25df4afe as useSelector, $7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};\n//# sourceMappingURL=data-sheet.52753d1d.js.map\n","import { createContext, useContext, useEffect, useRef, useState } from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport { createStore, StoreApi, useStore } from \"zustand\";\nimport { createComputed } from \"zustand-computed\";\nimport type {\n FocusedCellCoordinates,\n Region,\n Table2,\n} from \"@blueprintjs/table\";\nimport { generateColumnSpec, range } from \"./utils\";\nimport update, { Spec } from \"immutability-helper\";\nimport React from \"react\";\n\nexport interface ColumnSpec {\n name: string;\n key: string;\n required?: boolean;\n isValid?: (d: any) => boolean;\n transformValue?: (d: any) => any;\n valueRenderer?: (d: any) => string | React.ReactNode;\n dataEditor?: any;\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}\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 interface DataSheetCoreProps<T> {\n data: T[];\n columnSpec?: ColumnSpec[];\n editable?: boolean;\n enableColumnReordering?: boolean;\n}\n\nexport interface DataSheetState<T> {\n selection: Region[];\n columnSpec: ColumnSpec[];\n fillValueBaseCell: FocusedCellCoordinates | null;\n focusedCell: FocusedCellCoordinates | null;\n topLeftCell: FocusedCellCoordinates | null;\n deletedRows: Set<number>;\n // Sparse data structure for updated data\n updatedData: T[];\n initialized: boolean;\n}\n\nexport interface DataSheetComputedStore {\n hasUpdates: boolean;\n}\n\ntype DataSheetVals<T> = DataSheetState<T> & DataSheetCoreProps<T>;\n\ntype StateUpdater<T> = T[] | ((state: T[]) => T[]);\n\nexport interface DataSheetStore<T> extends DataSheetVals<T> {\n setSelection(selection: Region[]): void;\n onDragValue(cell: FocusedCellCoordinates | null): void;\n setUpdatedData(data: StateUpdater<T>): void;\n onCellEdited(rowIndex: number, columnName: string, value: any): void;\n onColumnsReordered(oldIndex: number, newIndex: number, length: number): void;\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\"): void;\n deleteSelectedRows(): void;\n clearSelection(): void;\n resetChanges(): void;\n addRow(): void;\n initialize(props: DataSheetCoreProps<T>): void;\n onSelection(selection: Region[]): void;\n // Internal method used for infinite scrolling\n setVisibleCells(visibleCells: VisibleCells): void;\n scrollToRow(rowIndex: number): void;\n tableRef: React.MutableRefObject<Table2>;\n}\n\nexport type DataSheetProviderProps<T> = DataSheetCoreProps<T> & {\n children: React.ReactNode;\n columnSpecOptions?: ColumnSpecOptions<T>;\n};\n\nconst DataSheetContext = createContext<StoreApi<DataSheetStore<any>>>(null);\n\nexport interface VisibleCells {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nconst computed = createComputed(\n (state: DataSheetStore<any>): DataSheetComputedStore => ({\n hasUpdates: state.updatedData.length > 0 || state.deletedRows.size > 0,\n }),\n) as any;\n\nexport function DataSheetProvider<T>({\n children,\n data,\n columnSpec,\n columnSpecOptions,\n editable,\n enableColumnReordering,\n}: DataSheetProviderProps<T>) {\n const visibleCellsRef = useRef<VisibleCells>({\n rowIndexStart: 0,\n rowIndexEnd: 0,\n });\n\n const tableRef = useRef<Table2>(null);\n\n const [store] = useState(() => {\n return createStore<DataSheetStore<T>>(\n computed((set): DataSheetStore<T> => {\n return {\n data,\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n deletedRows: new Set<number>(),\n selection: [],\n fillValueBaseCell: null,\n updatedData: [],\n focusedCell: null,\n topLeftCell: null,\n initialized: false,\n tableRef,\n // This is a placeholder\n enableColumnReordering: false,\n setSelection(selection: Region[]) {\n set(updateSelection(selection));\n },\n moveFocusedCell(direction: \"up\" | \"down\" | \"left\" | \"right\") {\n set((state) => {\n const { topLeftCell } = state;\n if (topLeftCell == null) return {};\n let { col, row } = topLeftCell;\n switch (direction) {\n case \"up\":\n row = Math.max(0, row - 1);\n break;\n case \"down\":\n row = Math.min(\n row + 1,\n Math.max(state.data.length, state.updatedData.length) - 1,\n );\n break;\n case \"left\":\n col = Math.max(0, col - 1);\n break;\n case \"right\":\n col = Math.min(col + 1, state.columnSpec.length - 1);\n break;\n }\n const region: Region = { cols: [col, col], rows: [row, row] };\n return updateSelection([region]);\n });\n },\n addRow(row: Partial<T> = {} as T) {\n /** Add a new row. If there is a selection, use the last row index to determine\n * where to insert the new row. Otherwise, append to the end of the data. */\n set((state) => {\n const { updatedData, data, selection } = state;\n const lastRowIndex =\n getLastRowIndex(selection) ??\n Math.max(data.length, updatedData.length) - 1;\n // If there is a selection, insert the new row after the last selected row\n const spec: Spec<any> = {\n $splice: [[lastRowIndex + 1, 0, row]],\n };\n console.log(spec);\n\n return {\n updatedData: update(updatedData, spec),\n };\n });\n },\n setUpdatedData(data: StateUpdater<T>) {\n if (Array.isArray(data)) {\n set({ updatedData: data });\n } else {\n set((state) => {\n return { updatedData: data(state.updatedData) };\n });\n }\n },\n deleteSelectedRows() {\n // Remove selected rows from the data and updatedData arrays\n set((state) => {\n const { selection, deletedRows } = state;\n const rowIndices = getRowIndices(selection);\n\n // Delete rows from both updatedData and data\n const newDeletedRows = new Set(deletedRows);\n for (const rowIndex of rowIndices) {\n newDeletedRows.add(rowIndex);\n }\n\n // Remove selected rows and reset selection\n return {\n deletedRows: newDeletedRows,\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n });\n },\n resetChanges() {\n // Reset the updated data to the initial data\n set((state) => ({\n updatedData: [],\n deletedRows: new Set<number>(),\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n }));\n },\n setVisibleCells(visibleCells: VisibleCells) {\n // Visible cells are used for infinite scrolling\n // Right now we don't store this in the state\n visibleCellsRef.current = visibleCells;\n },\n onDragValue(cell: FocusedCellCoordinates | null) {\n set({ fillValueBaseCell: cell });\n },\n onCellEdited(rowIndex: number, columnName: string, value: any) {\n set((state) => {\n const { editable, updatedData, data } = state;\n if (!editable) return {};\n let rowSpec: any;\n // Check to see if the new value is the same as the old one\n if (value !== data[rowIndex]?.[columnName]) {\n const rowOp = updatedData[rowIndex] != null ? \"$merge\" : \"$set\";\n rowSpec = { [rowOp]: { [columnName]: value } };\n } else {\n rowSpec = { $unset: [columnName] };\n }\n const spec: Spec<T[]> = { [rowIndex]: rowSpec };\n return { updatedData: update(updatedData, spec) };\n });\n },\n initialize(props: DataSheetCoreProps<T>) {\n set({ ...props, initialized: true });\n },\n clearSelection() {\n set((state) => {\n // Delete all selected cells\n const { selection, updatedData, columnSpec, data } = state;\n let spec = {};\n for (const region of selection) {\n const { cols, rows } = region;\n const rowRange = range(rows ?? [0, updatedData.length - 1]);\n const colRange = range(cols ?? [0, columnSpec.length - 1]);\n for (const row of rowRange) {\n let vals = {};\n for (const col of colRange) {\n const key = columnSpec[col].key;\n const currentValue =\n updatedData[row]?.[key] ?? data[row]?.[key];\n if (currentValue != null && currentValue !== \"\") {\n vals[key] = \"\";\n }\n }\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: vals };\n }\n }\n return {\n updatedData: update(updatedData, spec),\n };\n });\n },\n onSelection(selection: Region[]) {\n set((state) => {\n if (\n selectionEquals(selection, state.selection) &&\n singleFocusedCell(selection) == null // Only if we're in a multi-cell selection mode\n ) {\n // If the selection is the same as the current selection, remove the selection.\n // In practice this only happens for whole-row and whole-column selections\n return {\n selection: [],\n focusedCell: null,\n topLeftCell: null,\n fillValueBaseCell: null,\n };\n }\n\n let spec = updateSelection(selection);\n if (state.fillValueBaseCell != null) {\n spec.updatedData = fillValues(state, selection);\n }\n return spec;\n });\n },\n onColumnsReordered(\n oldIndex: number,\n newIndex: number,\n length: number,\n ) {\n set((state) => {\n if (!state.enableColumnReordering) return {};\n const { columnSpec } = state;\n const newSpec = [...columnSpec];\n const removed = newSpec.splice(oldIndex, length);\n newSpec.splice(newIndex, 0, ...removed);\n return { columnSpec: newSpec };\n });\n },\n scrollToRow(rowIndex: number) {\n if (tableRef.current == null) return;\n tableRef.current.scrollToRegion({\n rows: [rowIndex, rowIndex],\n });\n },\n };\n }),\n );\n });\n\n // Not sure how required this initialization is\n useEffect(() => {\n const { initialize } = store.getState();\n initialize({\n data,\n columnSpec: columnSpec ?? generateColumnSpec(data, columnSpecOptions),\n editable,\n enableColumnReordering,\n });\n }, [data, editable, columnSpec, columnSpecOptions, enableColumnReordering]);\n\n return h(DataSheetContext.Provider, { value: store }, children);\n}\n\nexport function useStoreAPI<T>(): StoreApi<DataSheetStore<T>> {\n const store = useContext(DataSheetContext);\n if (!store) {\n throw new Error(\"Missing DataSheetProvider\");\n }\n return store;\n}\n\nexport function useSelector<T = any, A = any>(\n selector: (state: DataSheetStore<T> & DataSheetComputedStore) => A,\n): A {\n const store = useStoreAPI<T>();\n return useStore(store, selector);\n}\n\nfunction updateSelection<T>(selection: Region[]) {\n const focusedCell = singleFocusedCell(selection);\n let spec: Partial<DataSheetState<T>> = {\n selection,\n focusedCell,\n topLeftCell: topLeftCell(selection),\n };\n if (focusedCell != null) {\n spec.fillValueBaseCell = null;\n }\n return spec;\n}\n\nfunction getLastRowIndex(regions: Region[]): number | null {\n /** Get the last row index from a selection of regions */\n if (regions == null || regions.length === 0) return null;\n let lastRow = -1;\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n lastRow = Math.max(lastRow, rows[1]);\n }\n if (lastRow < 0) {\n /** If no valid rows are found, return null */\n return null;\n }\n return lastRow;\n}\n\nfunction getRowIndices(regions: Region[]): number[] {\n /** Get the row indices from a selection of regions */\n if (regions == null || regions.length === 0) return [];\n const rowIndices = new Set<number>();\n for (const region of regions) {\n const { rows } = region;\n if (rows == null || rows.length !== 2) continue;\n for (let i = rows[0]; i <= rows[1]; i++) {\n rowIndices.add(i);\n }\n }\n return Array.from(rowIndices).sort((a, b) => a - b);\n}\n\nexport function topLeftCell(\n regions: Region[],\n requireSolitaryCell: boolean = false,\n): FocusedCellCoordinates | null {\n /** Top left cell of a ranged selection */\n if (regions == null) return null;\n const [region] = regions;\n if (region == null) return null;\n const { cols, rows } = region;\n if (cols == null || rows == null) return null;\n if (requireSolitaryCell && (cols[0] !== cols[1] || rows[0] !== rows[1]))\n return null;\n return { col: cols[0], row: rows[0], focusSelectionIndex: 0 };\n}\n\nfunction selectionEquals(a: Region[], b: Region[]): boolean {\n /** Check if two selections are equal */\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const regionA = a[i];\n const regionB = b[i];\n\n const colsA = regionA.cols ?? [];\n const colsB = regionB.cols ?? [];\n\n const rowsA = regionA.rows ?? [];\n const rowsB = regionB.rows ?? [];\n\n if (\n colsA.length !== colsB.length ||\n rowsA.length !== rowsB.length ||\n colsA[0] !== colsB[0] ||\n colsA[1] !== colsB[1] ||\n rowsA[0] !== rowsB[0] ||\n rowsA[1] !== rowsB[1]\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function singleFocusedCell(\n sel: Region[],\n): FocusedCellCoordinates | null {\n /** Derive a single focused cell from a selected region, if possible */\n if (sel?.length !== 1) return null;\n return topLeftCell(sel, true);\n}\n\nfunction fillValues<T>(state: DataSheetStore<T>, selection: Region[]) {\n const { updatedData, columnSpec, editable, fillValueBaseCell, data } = state;\n\n // Prepare regions by unnesting columns\n let regions = selection.map((region) => {\n const { cols, rows } = region;\n // Get the first column (maybe should be the last)\n const [col] = cols;\n return { cols: [col, col], rows };\n });\n\n // Fill values downwards\n if (!editable || fillValueBaseCell == null) return updatedData;\n const { col, row } = fillValueBaseCell;\n const key = columnSpec[col].key;\n const value = updatedData[row]?.[key] ?? data[row][key];\n const spec = {};\n for (const region of regions) {\n const { cols, rows } = region;\n for (const row of range(rows)) {\n let op = updatedData[row] == null ? \"$set\" : \"$merge\";\n spec[row] = { [op]: { [key]: value } };\n }\n }\n return update(updatedData, spec);\n}\n"],"names":["createContext","$lNLp4$createContext","useRef","$lNLp4$useRef","useState","$lNLp4$useState","useEffect","$lNLp4$useEffect","useContext","$lNLp4$useContext","$lNLp4$macrostrathyper","createStore","$lNLp4$createStore","useStore","$lNLp4$useStore","createComputed","$lNLp4$createComputed","$lNLp4$immutabilityhelper","$parcel$export","e","n","v","s","Object","defineProperty","get","set","enumerable","configurable","$parcel$global","globalThis","$parcel$modules","$parcel$inits","parcelRequire","id","exports","init","module","call","err","Error","code","register","$7e5384423bc0f425$exports","$7e5384423bc0f425$export$135c527978291360","$7e5384423bc0f425$export$de0bb697976d7dcb","$7e5384423bc0f425$export$54fc6f5c8f914926","$7e5384423bc0f425$export$2105062e25df4afe","$7e5384423bc0f425$export$88b0ba8661dc41b4","$50UEa","$7e5384423bc0f425$var$DataSheetContext","$7e5384423bc0f425$var$computed","state","hasUpdates","updatedData","length","deletedRows","size","children","data","columnSpec","columnSpecOptions","editable","enableColumnReordering","visibleCellsRef","rowIndexStart","rowIndexEnd","tableRef","store","generateColumnSpec","Set","selection","fillValueBaseCell","focusedCell","topLeftCell","initialized","setSelection","$7e5384423bc0f425$var$updateSelection","moveFocusedCell","direction","col","row","Math","max","min","cols","rows","addRow","spec","$splice","lastRowIndex","$7e5384423bc0f425$var$getLastRowIndex","regions","lastRow","region","console","log","setUpdatedData","Array","isArray","deleteSelectedRows","rowIndices","$7e5384423bc0f425$var$getRowIndices","i","add","from","sort","a","b","newDeletedRows","rowIndex","resetChanges","setVisibleCells","visibleCells","current","onDragValue","cell","onCellEdited","columnName","value","rowSpec","$unset","initialize","props","clearSelection","rowRange","range","colRange","vals","key","currentValue","op","onSelection","$7e5384423bc0f425$var$selectionEquals","regionA","regionB","colsA","colsB","rowsA","rowsB","$7e5384423bc0f425$var$fillValues","map","onColumnsReordered","oldIndex","newIndex","newSpec","removed","splice","scrollToRow","scrollToRegion","getState","Provider","selector","requireSolitaryCell","focusSelectionIndex","sel","DataSheetProvider","singleFocusedCell","useStoreAPI","useSelector"],"version":3,"file":"data-sheet.52753d1d.js.map","sourceRoot":"../../../../"}
@@ -0,0 +1,2 @@
1
+ import{useAsyncEffect as e}from"@macrostrat/ui-components";import{debounce as t}from"underscore";import{useMemo as r,useReducer as n,useRef as o,useCallback as l}from"react";import a from"immutability-helper";import{PostgrestClient as i}from"@supabase/postgrest-js";function s(e,t){switch(console.log(t),t.type){case"start-loading":return{...e,loading:!0,initialized:!0};case"set-visible":return{...e,visibleRegion:t.region};case"update-data":return{...e,loading:!1,data:a(e.data,t.changes)};case"loaded":var r,n;let o=(r=e.data,null==(n=t.totalSize)||r.length===n?r:(r.length>n&&(r=r.slice(0,n)),[...r,...Array(n-r.length).fill(null)]));return o=[...o.slice(0,t.offset),...t.data,...o.slice(t.offset+t.data.length)],{...e,data:o,loading:!1};case"reset":return{data:[],loading:!1,error:null,visibleRegion:{rowIndexStart:0,rowIndexEnd:0},initialized:!1};case"error":return{...e,error:t.error,loading:!1};default:return e}}Object.defineProperty({},"usePostgRESTLazyLoader",{get:()=>f,set:void 0,enumerable:!0,configurable:!0});var d,u=((d=u||{})[d.up=0]="up",d[d.down=1]="down",d);let c=t(function(e,t,r,n){let o=function(e,t){for(let r=t.rowIndexStart;r<t.rowIndexEnd;r++)if(null==e[r])return r;return null}(r.data,r.visibleRegion);if((r.loading||null==o)&&r.initialized)return;let{chunkSize:l=100,...a}=t,i=t.order?.key??"id",s={...a,limit:l,offset:null},d=!r.initialized;d&&(s.count="exact"),d||(s.after=r.data[o-1]?.[i],null==s.after&&(s.offset=o)),n({type:"start-loading"}),(function(e,t){let r,{columns:n="*",count:o}=t;console.log("config",t),r=Array.isArray(n)?n.join(", "):n??"*";let l=e.select(r,{count:o});if(t.filter&&(l=t.filter(l)),console.log("query",l.url.search),null!=t.order){let{key:e,...r}=t.order;l=l.order(e,r),null!=t.after&&(l=l[r.ascending??!0?"gt":"lt"](e,t.after))}return null!=t.limit&&(null!=t.offset?(l=l.range(t.offset,t.offset+t.limit-1),console.log(`Random seek from ${t.offset}, this will be slow`)):l=l.limit(t.limit)),l})(e,s).then(e=>{let{data:t,count:r}=e;n({type:"loaded",data:t,offset:o,totalSize:r})})},100);function f(a,d,u={}){let g=r(()=>new i(a).from(d),[a,d]),[m,b]=n(s,{data:[],loading:!1,error:null,visibleRegion:{rowIndexStart:0,rowIndexEnd:0},initialized:!1}),{data:p,loading:w}=m;e(async()=>{c(g,u,m,b)},[p,m.visibleRegion.rowIndexStart,m.visibleRegion.rowIndexEnd]);let y=o(null);return{data:p,loading:w,onScroll:l(t(e=>{(e.rowIndexEnd!=y.current?.rowIndexEnd||e.rowIndexStart!=y.current?.rowIndexStart)&&(console.log("Visible cells changed",e),b({type:"set-visible",region:e}),y.current=e)},500),[b]),dispatch:b,client:g}}export{f as usePostgRESTLazyLoader};
2
+ //# sourceMappingURL=data-sheet.846d5f8f.js.map
@@ -0,0 +1 @@
1
+ {"mappings":"A,O,kB,C,K,2B,A,Q,Y,C,K,Y,A,Q,W,C,C,c,C,C,U,C,C,e,C,K,O,A,Q,M,qB,A,Q,mB,C,K,wB,CCmDA,SAAS,EACP,CAAyB,CACzB,CAA2B,EAG3B,OADA,QAAQ,GAAG,CAAC,GACJ,EAAO,IAAI,EACjB,IAAK,gBACH,MAAO,CACL,GAAG,CAAK,CACR,QAAS,CAAA,EACT,YAAa,CAAA,CACf,CACF,KAAK,cACH,MAAO,CACL,GAAG,CAAK,CACR,cAAe,EAAO,MAAM,AAC9B,CACF,KAAK,cACH,MAAO,CACL,GAAG,CAAK,CACR,QAAS,CAAA,EACT,KAAM,AAAA,EAAO,EAAM,IAAI,CAAE,EAAO,OAAO,CACzC,CACF,KAAK,aAjCmB,EAAU,EAkChC,IAAI,GAlCkB,EAkCK,EAAM,IAAI,CAjCzC,AAAI,AAAW,OADqB,EAkCO,EAAO,SAAS,GAjCpC,EAAI,MAAM,GAAK,EAC7B,GACE,EAAI,MAAM,CAAG,GAEtB,CAAA,EAAM,EAAI,KAAK,CAAC,EAAG,EAAnB,EAEK,IAAI,KAAQ,MA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E,CAAI,CAAA,MAAE,CAAK,CAAE,CAAG,EACxB,EAAS,CACP,KAAM,SACN,KAAA,EACA,OAAQ,EACR,UAAW,CACb,EACF,EACF,EAG6C,KAUtC,SAAS,EACd,CAAgB,CAChB,CAAa,CACb,EAA4B,CAAC,CAAC,EAU9B,IAAM,EAAS,AAAA,EAAQ,IACd,IAAI,EAAgB,GAAU,IAAI,CAAC,GACzC,CAAC,EAAU,EAAM,EAEd,CAAC,EAAO,EAAS,CAAG,AAAA,EAAW,EAZM,CACzC,KAAM,EAAE,CACR,QAAS,CAAA,EACT,MAAO,KACP,cAAe,CAAE,cAAe,EAAG,YAAa,CAAE,EAClD,YAAa,CAAA,CACf,GAOM,CAAA,KAAE,CAAI,CAAA,QAAE,CAAO,CAAE,CAAG,EAE1B,AAAA,EAAe,UACb,EAAa,EAAQ,EAAQ,EAAO,EACtC,EAAG,CACD,EACA,EAAM,aAAa,CAAC,aAAa,CACjC,EAAM,aAAa,CAAC,WAAW,CAChC,EAGD,IAAM,EAAM,AAAA,EAAO,MAoBnB,MAAO,CACL,KAAA,EACA,QAAA,EACA,SArBe,AAAA,EACf,AAAA,EAAS,AAAC,IAEN,CAAA,EAAa,WAAW,EAAI,EAAI,OAAO,EAAE,aACzC,EAAa,aAAa,EAAI,EAAI,OAAO,EAAE,aAAA,IAI7C,QAAQ,GAAG,CAAC,wBAAyB,GACrC,EAAS,CACP,KAAM,cACN,OAAQ,CACV,GACA,EAAI,OAAO,CAAG,EAChB,EAAG,KACH,CAAC,EAAS,EAOV,SAAA,EACA,OAAA,CACF,CACF,Q,K,sB","sources":["<anon>","packages/data-sheet/src/postgrest-table/data-loaders.ts"],"sourcesContent":["import {useAsyncEffect as $iD4eM$useAsyncEffect} from \"@macrostrat/ui-components\";\nimport {debounce as $iD4eM$debounce} from \"underscore\";\nimport {useMemo as $iD4eM$useMemo, useReducer as $iD4eM$useReducer, useRef as $iD4eM$useRef, useCallback as $iD4eM$useCallback} from \"react\";\nimport $iD4eM$immutabilityhelper from \"immutability-helper\";\nimport {PostgrestClient as $iD4eM$PostgrestClient} from \"@supabase/postgrest-js\";\n\n\nfunction $parcel$export(e, n, v, s) {\n Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});\n}\nvar $07d30ec9100abcaa$exports = {};\n\n$parcel$export($07d30ec9100abcaa$exports, \"usePostgRESTLazyLoader\", () => $07d30ec9100abcaa$export$4dffb9bb65ef8b2);\n/** Lazy loading of data from a PostgREST endpoint */ \n\n\n\n\nfunction $07d30ec9100abcaa$var$adjustArraySize(arr, newSize) {\n if (newSize == null || arr.length === newSize) return arr;\n else if (arr.length > newSize) // Trim the array\n arr = arr.slice(0, newSize);\n return [\n ...arr,\n ...Array(newSize - arr.length).fill(null)\n ];\n}\nfunction $07d30ec9100abcaa$var$lazyLoadingReducer(state, action) {\n console.log(action);\n switch(action.type){\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true\n };\n case \"set-visible\":\n return {\n ...state,\n visibleRegion: action.region\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: (0, $iD4eM$immutabilityhelper)(state.data, action.changes)\n };\n case \"loaded\":\n let data = $07d30ec9100abcaa$var$adjustArraySize(state.data, action.totalSize);\n data = [\n ...data.slice(0, action.offset),\n ...action.data,\n ...data.slice(action.offset + action.data.length)\n ];\n return {\n ...state,\n data: data,\n loading: false\n };\n case \"reset\":\n return {\n data: [],\n loading: false,\n error: null,\n visibleRegion: {\n rowIndexStart: 0,\n rowIndexEnd: 0\n },\n initialized: false\n };\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false\n };\n default:\n return state;\n }\n}\nvar $07d30ec9100abcaa$var$LoadDirection = /*#__PURE__*/ function(LoadDirection) {\n LoadDirection[LoadDirection[\"up\"] = 0] = \"up\";\n LoadDirection[LoadDirection[\"down\"] = 1] = \"down\";\n return LoadDirection;\n}($07d30ec9100abcaa$var$LoadDirection || {});\nfunction $07d30ec9100abcaa$var$overlapsNulls(data, region) {\n for(let i = region.rowIndexStart; i < region.rowIndexEnd; i++){\n if (data[i] == null) return true;\n }\n return false;\n}\nfunction $07d30ec9100abcaa$var$distanceToNextNonEmptyRow(data, start, direction, limit) {\n let i = start;\n while(i < data.length && i > 0 && limit > 0){\n if (data[i] != null) return i;\n i += direction === 1 ? 1 : -1;\n limit -= 1;\n }\n return i;\n}\nfunction $07d30ec9100abcaa$var$buildQuery(client, config) {\n const { columns: columns = \"*\", count: count } = config;\n const opts = {\n count: count\n };\n console.log(\"config\", config);\n let cols;\n if (Array.isArray(columns)) cols = columns.join(\", \");\n else cols = columns ?? \"*\";\n let query = client.select(cols, opts);\n if (config.filter) query = config.filter(query);\n console.log(\"query\", query.url.search);\n if (config.order != null) {\n const { key: orderKey, ...rest } = config.order;\n query = query.order(orderKey, rest);\n if (config.after != null) {\n const op = rest.ascending ?? true ? \"gt\" : \"lt\";\n query = query[op](orderKey, config.after);\n }\n }\n if (config.limit != null) {\n if (config.offset != null) {\n query = query.range(config.offset, config.offset + config.limit - 1);\n console.log(`Random seek from ${config.offset}, this will be slow`);\n } else query = query.limit(config.limit);\n }\n return query;\n}\nfunction $07d30ec9100abcaa$var$_loadMoreData(client, config, state, dispatch) {\n const rowIndex = $07d30ec9100abcaa$var$indexOfFirstNullInRegion(state.data, state.visibleRegion);\n if (state.loading || rowIndex == null) {\n if (state.initialized) return;\n }\n const { chunkSize: chunkSize = 100, ...rest } = config;\n const sortKey = config.order?.key ?? \"id\";\n let cfg = {\n ...rest,\n limit: chunkSize,\n offset: null\n };\n // Allows random seeking\n const isInitialQuery = !state.initialized;\n if (isInitialQuery) cfg.count = \"exact\";\n // This only works for forward queries\n if (!isInitialQuery) {\n cfg.after = state.data[rowIndex - 1]?.[sortKey];\n if (cfg.after == null) cfg.offset = rowIndex;\n }\n dispatch({\n type: \"start-loading\"\n });\n const query = $07d30ec9100abcaa$var$buildQuery(client, cfg);\n query.then((res)=>{\n const { data: data, count: count } = res;\n dispatch({\n type: \"loaded\",\n data: data,\n offset: rowIndex,\n totalSize: count\n });\n });\n}\n// Ensure only one data load is in progress at a time\nconst $07d30ec9100abcaa$var$loadMoreData = (0, $iD4eM$debounce)($07d30ec9100abcaa$var$_loadMoreData, 100);\nfunction $07d30ec9100abcaa$export$4dffb9bb65ef8b2(endpoint, table, config = {}) {\n const initialState = {\n data: [],\n loading: false,\n error: null,\n visibleRegion: {\n rowIndexStart: 0,\n rowIndexEnd: 0\n },\n initialized: false\n };\n const client = (0, $iD4eM$useMemo)(()=>{\n return new (0, $iD4eM$PostgrestClient)(endpoint).from(table);\n }, [\n endpoint,\n table\n ]);\n const [state, dispatch] = (0, $iD4eM$useReducer)($07d30ec9100abcaa$var$lazyLoadingReducer, initialState);\n const { data: data, loading: loading } = state;\n (0, $iD4eM$useAsyncEffect)(async ()=>{\n $07d30ec9100abcaa$var$loadMoreData(client, config, state, dispatch);\n }, [\n data,\n state.visibleRegion.rowIndexStart,\n state.visibleRegion.rowIndexEnd\n ]);\n // Reference to hold onto the scroll position\n const ref = (0, $iD4eM$useRef)(null);\n const onScroll = (0, $iD4eM$useCallback)((0, $iD4eM$debounce)((visibleCells)=>{\n if (visibleCells.rowIndexEnd == ref.current?.rowIndexEnd && visibleCells.rowIndexStart == ref.current?.rowIndexStart) return;\n console.log(\"Visible cells changed\", visibleCells);\n dispatch({\n type: \"set-visible\",\n region: visibleCells\n });\n ref.current = visibleCells;\n }, 500), [\n dispatch\n ]);\n return {\n data: data,\n loading: loading,\n onScroll: onScroll,\n dispatch: dispatch,\n client: client\n };\n}\nfunction $07d30ec9100abcaa$var$getRowIndexToLoadFrom(data, visibleRegion, chunkSize) {\n return $07d30ec9100abcaa$var$indexOfFirstNullInRegion(data, visibleRegion);\n}\nfunction $07d30ec9100abcaa$var$indexOfFirstNullInRegion(data, region) {\n for(let i = region.rowIndexStart; i < region.rowIndexEnd; i++){\n if (data[i] == null) return i;\n }\n return null;\n}\n\n\nexport {$07d30ec9100abcaa$export$4dffb9bb65ef8b2 as usePostgRESTLazyLoader};\n//# sourceMappingURL=data-sheet.846d5f8f.js.map\n","/** Lazy loading of data from a PostgREST endpoint */\n\nimport { useAsyncEffect } from \"@macrostrat/ui-components\";\nimport { debounce } from \"underscore\";\nimport { useCallback, useMemo, useReducer, useRef, useEffect } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\n\ninterface ChunkIndex {\n startRow: number;\n endRow: number;\n lastValue: any;\n}\n\nimport {\n PostgrestClient,\n PostgrestQueryBuilder,\n PostgrestFilterBuilder,\n} from \"@supabase/postgrest-js\";\n\ninterface LazyLoaderState<T> {\n data: (T | null)[];\n loading: boolean;\n error: Error | null;\n visibleRegion: RowRegion;\n initialized: boolean;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | { type: \"loaded\"; data: T[]; offset: number; totalSize: number }\n | { type: \"error\"; error: Error }\n | { type: \"set-visible\"; region: RowRegion }\n | { type: \"update-data\"; changes: Spec<T[]> }\n | { type: \"reset\" };\n\nfunction adjustArraySize<T>(arr: T[], newSize: number) {\n if (newSize == null || arr.length === newSize) {\n return arr;\n } else if (arr.length > newSize) {\n // Trim the array\n arr = arr.slice(0, newSize);\n }\n return [...arr, ...Array(newSize - arr.length).fill(null)];\n}\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n console.log(action);\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"set-visible\":\n return {\n ...state,\n visibleRegion: action.region,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n data = [\n ...data.slice(0, action.offset),\n ...action.data,\n ...data.slice(action.offset + action.data.length),\n ];\n\n return {\n ...state,\n data,\n loading: false,\n };\n\n case \"reset\":\n return {\n data: [],\n loading: false,\n error: null,\n visibleRegion: { rowIndexStart: 0, rowIndexEnd: 0 },\n initialized: false,\n };\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ninterface RowRegion {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nenum LoadDirection {\n \"up\",\n \"down\",\n}\n\nfunction overlapsNulls(data: any[], region: RowRegion) {\n for (let i = region.rowIndexStart; i < region.rowIndexEnd; i++) {\n if (data[i] == null) {\n return true;\n }\n }\n return false;\n}\n\nfunction distanceToNextNonEmptyRow(\n data: any[],\n start: number,\n direction: LoadDirection,\n limit: number,\n): number {\n let i = start;\n while (i < data.length && i > 0 && limit > 0) {\n if (data[i] != null) {\n return i;\n }\n i += direction === LoadDirection.down ? 1 : -1;\n limit -= 1;\n }\n return i;\n}\n\ninterface QueryConfig {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n offset?: number;\n order?: PostgrestOrder<any>;\n after?: any;\n fullTextSearch?: string;\n filter?: (\n query: PostgrestFilterBuilder<any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any>;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<T, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count } = config;\n const opts = { count };\n\n console.log(\"config\", config);\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 if (config.filter) {\n query = config.filter(query);\n }\n console.log(\"query\", query.url.search);\n\n if (config.order != null) {\n const { key: orderKey, ...rest } = config.order;\n query = query.order(orderKey, rest);\n if (config.after != null) {\n const op = (rest.ascending ?? true) ? \"gt\" : \"lt\";\n query = query[op](orderKey, config.after);\n }\n }\n if (config.limit != null) {\n if (config.offset != null) {\n query = query.range(config.offset, config.offset + config.limit - 1);\n console.log(`Random seek from ${config.offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n return query;\n}\n\nfunction _loadMoreData<T>(\n client: PostgrestQueryBuilder<T, any>,\n config: QueryConfig & { chunkSize: number },\n state: LazyLoaderState<T>,\n dispatch: any,\n) {\n const rowIndex = indexOfFirstNullInRegion(state.data, state.visibleRegion);\n if (state.loading || rowIndex == null) {\n if (state.initialized) {\n return;\n }\n }\n\n const { chunkSize = 100, ...rest } = config;\n\n const sortKey = config.order?.key ?? \"id\";\n\n let cfg: QueryConfig = {\n ...rest,\n limit: chunkSize,\n offset: null,\n };\n\n // Allows random seeking\n const isInitialQuery = !state.initialized;\n if (isInitialQuery) {\n cfg.count = \"exact\";\n }\n\n // This only works for forward queries\n if (!isInitialQuery) {\n cfg.after = state.data[rowIndex - 1]?.[sortKey];\n if (cfg.after == null) {\n cfg.offset = rowIndex;\n }\n }\n\n dispatch({ type: \"start-loading\" });\n\n const query = buildQuery(client, cfg);\n\n query.then((res) => {\n const { data, count } = res;\n dispatch({\n type: \"loaded\",\n data,\n offset: rowIndex,\n totalSize: count,\n });\n });\n}\n\n// Ensure only one data load is in progress at a time\nconst loadMoreData = debounce(_loadMoreData, 100);\n\ntype LazyLoaderOptions = Omit<QueryConfig, \"count\" | \"offset\" | \"limit\"> & {\n chunkSize?: number;\n sortKey?: string;\n filter?: (\n query: PostgrestFilterBuilder<any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any>;\n};\n\nexport function usePostgRESTLazyLoader(\n endpoint: string,\n table: string,\n config: LazyLoaderOptions = {},\n) {\n const initialState: LazyLoaderState<any> = {\n data: [],\n loading: false,\n error: null,\n visibleRegion: { rowIndexStart: 0, rowIndexEnd: 0 },\n initialized: false,\n };\n\n const client = useMemo(() => {\n return new PostgrestClient(endpoint).from(table);\n }, [endpoint, table]);\n\n const [state, dispatch] = useReducer(lazyLoadingReducer, initialState);\n const { data, loading } = state;\n\n useAsyncEffect(async () => {\n loadMoreData(client, config, state, dispatch);\n }, [\n data,\n state.visibleRegion.rowIndexStart,\n state.visibleRegion.rowIndexEnd,\n ]);\n\n // Reference to hold onto the scroll position\n const ref = useRef(null);\n\n const onScroll = useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n console.log(\"Visible cells changed\", visibleCells);\n dispatch({\n type: \"set-visible\",\n region: visibleCells,\n });\n ref.current = visibleCells;\n }, 500),\n [dispatch],\n );\n\n return {\n data,\n loading,\n onScroll,\n dispatch,\n client,\n };\n}\n\nfunction getRowIndexToLoadFrom<T>(\n data: (T | null)[],\n visibleRegion: RowRegion,\n chunkSize: number,\n) {\n return indexOfFirstNullInRegion(data, visibleRegion);\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n for (let i = region.rowIndexStart; i < region.rowIndexEnd; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":["useAsyncEffect","$iD4eM$useAsyncEffect","debounce","$iD4eM$debounce","useMemo","$iD4eM$useMemo","useReducer","$iD4eM$useReducer","useRef","$iD4eM$useRef","useCallback","$iD4eM$useCallback","$iD4eM$immutabilityhelper","PostgrestClient","$iD4eM$PostgrestClient","$07d30ec9100abcaa$var$lazyLoadingReducer","state","action","console","log","type","loading","initialized","visibleRegion","region","data","changes","arr","newSize","totalSize","length","slice","Array","fill","offset","error","rowIndexStart","rowIndexEnd","Object","defineProperty","get","$07d30ec9100abcaa$export$4dffb9bb65ef8b2","set","s","enumerable","configurable","LoadDirection","$07d30ec9100abcaa$var$LoadDirection","$07d30ec9100abcaa$var$loadMoreData","client","config","dispatch","rowIndex","$07d30ec9100abcaa$var$indexOfFirstNullInRegion","i","chunkSize","rest","sortKey","order","key","cfg","limit","isInitialQuery","count","after","query","$07d30ec9100abcaa$var$buildQuery","cols","columns","isArray","join","select","filter","url","search","orderKey","ascending","range","then","res","endpoint","table","from","ref","onScroll","visibleCells","current","usePostgRESTLazyLoader"],"version":3,"file":"data-sheet.846d5f8f.js.map","sourceRoot":"../../../../"}
@@ -1,2 +1,2 @@
1
- import"./data-sheet.820e5bc3.js";import"./data-sheet.ef1661d7.js";import"./data-sheet.86550c41.js";import"./data-sheet.52753d1d.js";function e(e,a){return Object.keys(a).forEach(function(t){"default"===t||"__esModule"===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return a[t]}})}),e}var a=globalThis,t={},r={},o=a.parcelRequirea149;null==o&&((o=function(e){if(e in t)return t[e].exports;if(e in r){var a=r[e];delete r[e];var o={id:e,exports:{}};return t[e]=o,a.call(o.exports,o,o.exports),o.exports}var $=Error("Cannot find module '"+e+"'");throw $.code="MODULE_NOT_FOUND",$}).register=function(e,a){r[e]=a},a.parcelRequirea149=o),o.register;var $={},d=o("1ehpN"),b=o("gxLKL"),c=o("gZfn5"),f=o("kib2Q");e($,d),e($,b),e($,c),e($,f);export{$963b78d65282413b$export$b556effaa3ad7d4a as DataSheetDensity,$963b78d65282413b$export$dea56b0125f0282d as DataSheet,$963b78d65282413b$export$222fa1b971ddc36 as getRowsToDelete,$963b78d65282413b$export$41ad0bbfa4755cac as BaseCell,$963b78d65282413b$export$e7db3202e96fc463 as ScrollToRowControl,$963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea as Cell,$4d256d31a726a84a$export$34ce2a614f5dd320 as PostgRESTTableView,$4d256d31a726a84a$export$2022c252b5885348 as wrapWithErrorHandling,$4d256d31a726a84a$export$48a1a02e95eff0a2 as notifyOnError,$4d256d31a726a84a$export$85a23c82145eafdb as LongTextViewer,$4d256d31a726a84a$export$8d4d3113a9b124d2 as IntervalCell,$4d256d31a726a84a$export$2ad73a796d2d3eb as lithologyRenderer,$4d256d31a726a84a$export$5da000845ac52c4f as ExpandedLithologies,$07d30ec9100abcaa$export$4dffb9bb65ef8b2 as usePostgRESTLazyLoader,$36eead336b938625$export$2a7e60c8443c1751 as EditorPopup,$827916362b958415$export$24aecfe8a925020d as ColorCell,$827916362b958415$export$e5f546a5ba915f1c as colorSwatchRenderer,$827916362b958415$export$9feb1bc2e5f1ccb3 as ColorPicker,$1b3be825da79eb57$export$b8e68c321a6269f1 as EditableTextArea,$1b3be825da79eb57$export$52c8c5a1aad17e2a as handleSpecialKeys,$bec5b73cd6722b6b$export$b215fe4466d8f847 as DataSheetActionsRow,$bec5b73cd6722b6b$export$c2c7070a9fc246e1 as DataSheetAction,$7e5384423bc0f425$export$135c527978291360 as DataSheetProvider,$7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell,$7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI,$7e5384423bc0f425$export$2105062e25df4afe as useSelector,$7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};
1
+ import"./data-sheet.820e5bc3.js";import"./data-sheet.22cde343.js";import"./data-sheet.86550c41.js";import"./data-sheet.52753d1d.js";function e(e,a){return Object.keys(a).forEach(function(t){"default"===t||"__esModule"===t||Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:function(){return a[t]}})}),e}var a=globalThis,t={},r={},o=a.parcelRequirea149;null==o&&((o=function(e){if(e in t)return t[e].exports;if(e in r){var a=r[e];delete r[e];var o={id:e,exports:{}};return t[e]=o,a.call(o.exports,o,o.exports),o.exports}var $=Error("Cannot find module '"+e+"'");throw $.code="MODULE_NOT_FOUND",$}).register=function(e,a){r[e]=a},a.parcelRequirea149=o),o.register;var $={},d=o("1ehpN"),b=o("gxLKL"),c=o("gZfn5"),f=o("kib2Q");e($,d),e($,b),e($,c),e($,f);export{$963b78d65282413b$export$b556effaa3ad7d4a as DataSheetDensity,$963b78d65282413b$export$dea56b0125f0282d as DataSheet,$963b78d65282413b$export$222fa1b971ddc36 as getRowsToDelete,$963b78d65282413b$export$41ad0bbfa4755cac as BaseCell,$963b78d65282413b$export$e7db3202e96fc463 as ScrollToRowControl,$963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea as Cell,$4d256d31a726a84a$export$34ce2a614f5dd320 as PostgRESTTableView,$4d256d31a726a84a$export$2022c252b5885348 as wrapWithErrorHandling,$4d256d31a726a84a$export$a346ab8a0cc01d91 as SearchAction,$4d256d31a726a84a$export$48a1a02e95eff0a2 as notifyOnError,$4d256d31a726a84a$export$85a23c82145eafdb as LongTextViewer,$4d256d31a726a84a$export$8d4d3113a9b124d2 as IntervalCell,$4d256d31a726a84a$export$2ad73a796d2d3eb as lithologyRenderer,$4d256d31a726a84a$export$5da000845ac52c4f as ExpandedLithologies,$07d30ec9100abcaa$export$4dffb9bb65ef8b2 as usePostgRESTLazyLoader,$36eead336b938625$export$2a7e60c8443c1751 as EditorPopup,$827916362b958415$export$24aecfe8a925020d as ColorCell,$827916362b958415$export$e5f546a5ba915f1c as colorSwatchRenderer,$827916362b958415$export$9feb1bc2e5f1ccb3 as ColorPicker,$1b3be825da79eb57$export$b8e68c321a6269f1 as EditableTextArea,$1b3be825da79eb57$export$52c8c5a1aad17e2a as handleSpecialKeys,$bec5b73cd6722b6b$export$b215fe4466d8f847 as DataSheetActionsRow,$bec5b73cd6722b6b$export$c2c7070a9fc246e1 as DataSheetAction,$7e5384423bc0f425$export$135c527978291360 as DataSheetProvider,$7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell,$7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI,$7e5384423bc0f425$export$2105062e25df4afe as useSelector,$7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"mappings":"A,M,2C,A,O,2C,A,O,2C,A,O,2C,C,S,E,C,C,C,E,O,O,I,C,G,O,C,S,C,E,Y,G,A,e,G,O,S,C,c,C,I,C,E,I,O,c,C,E,E,C,W,C,E,I,W,O,C,C,E,A,C,E,G,C,C,I,E,W,E,C,E,E,C,E,E,E,iB,A,O,I,A,C,E,S,C,E,G,K,E,O,C,C,E,C,O,C,G,K,E,C,I,E,C,C,E,A,Q,C,C,E,C,I,E,C,G,E,Q,C,C,E,O,C,C,E,C,E,E,I,C,E,O,C,E,E,O,E,E,O,A,C,I,E,A,M,uB,E,I,O,E,I,C,mB,C,C,E,Q,C,S,C,C,C,E,C,C,E,C,C,E,E,iB,C,G,E,Q,C,I,E,C,E,E,E,S,E,E,S,E,E,S,E,E,S,E,E,G,E,E,G,E,E,G,E,E,U,6C,gB,C,6C,S,C,4C,e,C,6C,Q,C,6C,kB,C,8D,I,C,6C,kB,C,6C,qB,C,6C,a,C,6C,c,C,6C,Y,C,4C,iB,C,6C,mB,C,4C,sB,C,6C,W,C,6C,S,C,6C,mB,C,6C,W,C,6C,gB,C,6C,iB,C,6C,mB,C,6C,e,C,6C,iB,C,6C,iB,C,6C,W,C,6C,W,C,6C,W","sources":["<anon>","packages/data-sheet/src/index.ts"],"sourcesContent":["import \"./data-sheet.820e5bc3.js\";\nimport \"./data-sheet.ef1661d7.js\";\nimport \"./data-sheet.86550c41.js\";\nimport \"./data-sheet.52753d1d.js\";\n\n\nfunction $parcel$exportWildcard(dest, source) {\n Object.keys(source).forEach(function(key) {\n if (key === 'default' || key === '__esModule' || Object.prototype.hasOwnProperty.call(dest, key)) {\n return;\n }\n\n Object.defineProperty(dest, key, {\n enumerable: true,\n get: function get() {\n return source[key];\n }\n });\n });\n\n return dest;\n}\n\n var $parcel$global = globalThis;\n \nvar $parcel$modules = {};\nvar $parcel$inits = {};\n\nvar parcelRequire = $parcel$global[\"parcelRequirea149\"];\n\nif (parcelRequire == null) {\n parcelRequire = function(id) {\n if (id in $parcel$modules) {\n return $parcel$modules[id].exports;\n }\n if (id in $parcel$inits) {\n var init = $parcel$inits[id];\n delete $parcel$inits[id];\n var module = {id: id, exports: {}};\n $parcel$modules[id] = module;\n init.call(module.exports, module, module.exports);\n return module.exports;\n }\n var err = new Error(\"Cannot find module '\" + id + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n };\n\n parcelRequire.register = function register(id, init) {\n $parcel$inits[id] = init;\n };\n\n $parcel$global[\"parcelRequirea149\"] = parcelRequire;\n}\n\nvar parcelRegister = parcelRequire.register;\nvar $c65828dbe869c24d$exports = {};\n\nvar $1ehpN = parcelRequire(\"1ehpN\");\n\nvar $gxLKL = parcelRequire(\"gxLKL\");\n\nvar $gZfn5 = parcelRequire(\"gZfn5\");\n\nvar $kib2Q = parcelRequire(\"kib2Q\");\n$parcel$exportWildcard($c65828dbe869c24d$exports, $1ehpN);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $gxLKL);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $gZfn5);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $kib2Q);\n\n\nexport {$963b78d65282413b$export$b556effaa3ad7d4a as DataSheetDensity, $963b78d65282413b$export$dea56b0125f0282d as DataSheet, $963b78d65282413b$export$222fa1b971ddc36 as getRowsToDelete, $963b78d65282413b$export$41ad0bbfa4755cac as BaseCell, $963b78d65282413b$export$e7db3202e96fc463 as ScrollToRowControl, $963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea as Cell, $4d256d31a726a84a$export$34ce2a614f5dd320 as PostgRESTTableView, $4d256d31a726a84a$export$2022c252b5885348 as wrapWithErrorHandling, $4d256d31a726a84a$export$48a1a02e95eff0a2 as notifyOnError, $4d256d31a726a84a$export$85a23c82145eafdb as LongTextViewer, $4d256d31a726a84a$export$8d4d3113a9b124d2 as IntervalCell, $4d256d31a726a84a$export$2ad73a796d2d3eb as lithologyRenderer, $4d256d31a726a84a$export$5da000845ac52c4f as ExpandedLithologies, $07d30ec9100abcaa$export$4dffb9bb65ef8b2 as usePostgRESTLazyLoader, $36eead336b938625$export$2a7e60c8443c1751 as EditorPopup, $827916362b958415$export$24aecfe8a925020d as ColorCell, $827916362b958415$export$e5f546a5ba915f1c as colorSwatchRenderer, $827916362b958415$export$9feb1bc2e5f1ccb3 as ColorPicker, $1b3be825da79eb57$export$b8e68c321a6269f1 as EditableTextArea, $1b3be825da79eb57$export$52c8c5a1aad17e2a as handleSpecialKeys, $bec5b73cd6722b6b$export$b215fe4466d8f847 as DataSheetActionsRow, $bec5b73cd6722b6b$export$c2c7070a9fc246e1 as DataSheetAction, $7e5384423bc0f425$export$135c527978291360 as DataSheetProvider, $7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell, $7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI, $7e5384423bc0f425$export$2105062e25df4afe as useSelector, $7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};\n//# sourceMappingURL=index.js.map\n","export * from \"./core\";\nexport * from \"./postgrest-table\";\nexport * from \"./components\";\nexport * from \"./provider\";\n"],"names":["$parcel$exportWildcard","dest","source","Object","keys","forEach","key","prototype","hasOwnProperty","call","defineProperty","enumerable","get","$parcel$global","globalThis","$parcel$modules","$parcel$inits","parcelRequire","id","exports","init","module","err","Error","code","register","$c65828dbe869c24d$exports","$1ehpN","$gxLKL","$gZfn5","$kib2Q","$963b78d65282413b$export$b556effaa3ad7d4a","DataSheetDensity","$963b78d65282413b$export$dea56b0125f0282d","DataSheet","$963b78d65282413b$export$222fa1b971ddc36","getRowsToDelete","$963b78d65282413b$export$41ad0bbfa4755cac","BaseCell","$963b78d65282413b$export$e7db3202e96fc463","ScrollToRowControl","$963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea","Cell","$4d256d31a726a84a$export$34ce2a614f5dd320","PostgRESTTableView","$4d256d31a726a84a$export$2022c252b5885348","wrapWithErrorHandling","$4d256d31a726a84a$export$48a1a02e95eff0a2","notifyOnError","$4d256d31a726a84a$export$85a23c82145eafdb","LongTextViewer","$4d256d31a726a84a$export$8d4d3113a9b124d2","IntervalCell","$4d256d31a726a84a$export$2ad73a796d2d3eb","lithologyRenderer","$4d256d31a726a84a$export$5da000845ac52c4f","ExpandedLithologies","$07d30ec9100abcaa$export$4dffb9bb65ef8b2","usePostgRESTLazyLoader","$36eead336b938625$export$2a7e60c8443c1751","EditorPopup","$827916362b958415$export$24aecfe8a925020d","ColorCell","$827916362b958415$export$e5f546a5ba915f1c","colorSwatchRenderer","$827916362b958415$export$9feb1bc2e5f1ccb3","ColorPicker","$1b3be825da79eb57$export$b8e68c321a6269f1","EditableTextArea","$1b3be825da79eb57$export$52c8c5a1aad17e2a","handleSpecialKeys","$bec5b73cd6722b6b$export$b215fe4466d8f847","DataSheetActionsRow","$bec5b73cd6722b6b$export$c2c7070a9fc246e1","DataSheetAction","$7e5384423bc0f425$export$135c527978291360","DataSheetProvider","$7e5384423bc0f425$export$de0bb697976d7dcb","singleFocusedCell","$7e5384423bc0f425$export$54fc6f5c8f914926","useStoreAPI","$7e5384423bc0f425$export$2105062e25df4afe","useSelector","$7e5384423bc0f425$export$88b0ba8661dc41b4","topLeftCell"],"version":3,"file":"index.js.map","sourceRoot":"../../../../"}
1
+ {"mappings":"A,M,2C,A,O,2C,A,O,2C,A,O,2C,C,S,E,C,C,C,E,O,O,I,C,G,O,C,S,C,E,Y,G,A,e,G,O,S,C,c,C,I,C,E,I,O,c,C,E,E,C,W,C,E,I,W,O,C,C,E,A,C,E,G,C,C,I,E,W,E,C,E,E,C,E,E,E,iB,A,O,I,A,C,E,S,C,E,G,K,E,O,C,C,E,C,O,C,G,K,E,C,I,E,C,C,E,A,Q,C,C,E,C,I,E,C,G,E,Q,C,C,E,O,C,C,E,C,E,E,I,C,E,O,C,E,E,O,E,E,O,A,C,I,E,A,M,uB,E,I,O,E,I,C,mB,C,C,E,Q,C,S,C,C,C,E,C,C,E,C,C,E,E,iB,C,G,E,Q,C,I,E,C,E,E,E,S,E,E,S,E,E,S,E,E,S,E,E,G,E,E,G,E,E,G,E,E,U,6C,gB,C,6C,S,C,4C,e,C,6C,Q,C,6C,kB,C,8D,I,C,6C,kB,C,6C,qB,C,6C,Y,C,6C,a,C,6C,c,C,6C,Y,C,4C,iB,C,6C,mB,C,4C,sB,C,6C,W,C,6C,S,C,6C,mB,C,6C,W,C,6C,gB,C,6C,iB,C,6C,mB,C,6C,e,C,6C,iB,C,6C,iB,C,6C,W,C,6C,W,C,6C,W","sources":["<anon>","packages/data-sheet/src/index.ts"],"sourcesContent":["import \"./data-sheet.820e5bc3.js\";\nimport \"./data-sheet.22cde343.js\";\nimport \"./data-sheet.86550c41.js\";\nimport \"./data-sheet.52753d1d.js\";\n\n\nfunction $parcel$exportWildcard(dest, source) {\n Object.keys(source).forEach(function(key) {\n if (key === 'default' || key === '__esModule' || Object.prototype.hasOwnProperty.call(dest, key)) {\n return;\n }\n\n Object.defineProperty(dest, key, {\n enumerable: true,\n get: function get() {\n return source[key];\n }\n });\n });\n\n return dest;\n}\n\n var $parcel$global = globalThis;\n \nvar $parcel$modules = {};\nvar $parcel$inits = {};\n\nvar parcelRequire = $parcel$global[\"parcelRequirea149\"];\n\nif (parcelRequire == null) {\n parcelRequire = function(id) {\n if (id in $parcel$modules) {\n return $parcel$modules[id].exports;\n }\n if (id in $parcel$inits) {\n var init = $parcel$inits[id];\n delete $parcel$inits[id];\n var module = {id: id, exports: {}};\n $parcel$modules[id] = module;\n init.call(module.exports, module, module.exports);\n return module.exports;\n }\n var err = new Error(\"Cannot find module '\" + id + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n };\n\n parcelRequire.register = function register(id, init) {\n $parcel$inits[id] = init;\n };\n\n $parcel$global[\"parcelRequirea149\"] = parcelRequire;\n}\n\nvar parcelRegister = parcelRequire.register;\nvar $c65828dbe869c24d$exports = {};\n\nvar $1ehpN = parcelRequire(\"1ehpN\");\n\nvar $gxLKL = parcelRequire(\"gxLKL\");\n\nvar $gZfn5 = parcelRequire(\"gZfn5\");\n\nvar $kib2Q = parcelRequire(\"kib2Q\");\n$parcel$exportWildcard($c65828dbe869c24d$exports, $1ehpN);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $gxLKL);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $gZfn5);\n$parcel$exportWildcard($c65828dbe869c24d$exports, $kib2Q);\n\n\nexport {$963b78d65282413b$export$b556effaa3ad7d4a as DataSheetDensity, $963b78d65282413b$export$dea56b0125f0282d as DataSheet, $963b78d65282413b$export$222fa1b971ddc36 as getRowsToDelete, $963b78d65282413b$export$41ad0bbfa4755cac as BaseCell, $963b78d65282413b$export$e7db3202e96fc463 as ScrollToRowControl, $963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea as Cell, $4d256d31a726a84a$export$34ce2a614f5dd320 as PostgRESTTableView, $4d256d31a726a84a$export$2022c252b5885348 as wrapWithErrorHandling, $4d256d31a726a84a$export$a346ab8a0cc01d91 as SearchAction, $4d256d31a726a84a$export$48a1a02e95eff0a2 as notifyOnError, $4d256d31a726a84a$export$85a23c82145eafdb as LongTextViewer, $4d256d31a726a84a$export$8d4d3113a9b124d2 as IntervalCell, $4d256d31a726a84a$export$2ad73a796d2d3eb as lithologyRenderer, $4d256d31a726a84a$export$5da000845ac52c4f as ExpandedLithologies, $07d30ec9100abcaa$export$4dffb9bb65ef8b2 as usePostgRESTLazyLoader, $36eead336b938625$export$2a7e60c8443c1751 as EditorPopup, $827916362b958415$export$24aecfe8a925020d as ColorCell, $827916362b958415$export$e5f546a5ba915f1c as colorSwatchRenderer, $827916362b958415$export$9feb1bc2e5f1ccb3 as ColorPicker, $1b3be825da79eb57$export$b8e68c321a6269f1 as EditableTextArea, $1b3be825da79eb57$export$52c8c5a1aad17e2a as handleSpecialKeys, $bec5b73cd6722b6b$export$b215fe4466d8f847 as DataSheetActionsRow, $bec5b73cd6722b6b$export$c2c7070a9fc246e1 as DataSheetAction, $7e5384423bc0f425$export$135c527978291360 as DataSheetProvider, $7e5384423bc0f425$export$de0bb697976d7dcb as singleFocusedCell, $7e5384423bc0f425$export$54fc6f5c8f914926 as useStoreAPI, $7e5384423bc0f425$export$2105062e25df4afe as useSelector, $7e5384423bc0f425$export$88b0ba8661dc41b4 as topLeftCell};\n//# sourceMappingURL=index.js.map\n","export * from \"./core\";\nexport * from \"./postgrest-table\";\nexport * from \"./components\";\nexport * from \"./provider\";\n"],"names":["$parcel$exportWildcard","dest","source","Object","keys","forEach","key","prototype","hasOwnProperty","call","defineProperty","enumerable","get","$parcel$global","globalThis","$parcel$modules","$parcel$inits","parcelRequire","id","exports","init","module","err","Error","code","register","$c65828dbe869c24d$exports","$1ehpN","$gxLKL","$gZfn5","$kib2Q","$963b78d65282413b$export$b556effaa3ad7d4a","DataSheetDensity","$963b78d65282413b$export$dea56b0125f0282d","DataSheet","$963b78d65282413b$export$222fa1b971ddc36","getRowsToDelete","$963b78d65282413b$export$41ad0bbfa4755cac","BaseCell","$963b78d65282413b$export$e7db3202e96fc463","ScrollToRowControl","$963b78d65282413b$import$5573889ca4ff9ca2$f6f0c3fe4ec306ea","Cell","$4d256d31a726a84a$export$34ce2a614f5dd320","PostgRESTTableView","$4d256d31a726a84a$export$2022c252b5885348","wrapWithErrorHandling","$4d256d31a726a84a$export$a346ab8a0cc01d91","SearchAction","$4d256d31a726a84a$export$48a1a02e95eff0a2","notifyOnError","$4d256d31a726a84a$export$85a23c82145eafdb","LongTextViewer","$4d256d31a726a84a$export$8d4d3113a9b124d2","IntervalCell","$4d256d31a726a84a$export$2ad73a796d2d3eb","lithologyRenderer","$4d256d31a726a84a$export$5da000845ac52c4f","ExpandedLithologies","$07d30ec9100abcaa$export$4dffb9bb65ef8b2","usePostgRESTLazyLoader","$36eead336b938625$export$2a7e60c8443c1751","EditorPopup","$827916362b958415$export$24aecfe8a925020d","ColorCell","$827916362b958415$export$e5f546a5ba915f1c","colorSwatchRenderer","$827916362b958415$export$9feb1bc2e5f1ccb3","ColorPicker","$1b3be825da79eb57$export$b8e68c321a6269f1","EditableTextArea","$1b3be825da79eb57$export$52c8c5a1aad17e2a","handleSpecialKeys","$bec5b73cd6722b6b$export$b215fe4466d8f847","DataSheetActionsRow","$bec5b73cd6722b6b$export$c2c7070a9fc246e1","DataSheetAction","$7e5384423bc0f425$export$135c527978291360","DataSheetProvider","$7e5384423bc0f425$export$de0bb697976d7dcb","singleFocusedCell","$7e5384423bc0f425$export$54fc6f5c8f914926","useStoreAPI","$7e5384423bc0f425$export$2105062e25df4afe","useSelector","$7e5384423bc0f425$export$88b0ba8661dc41b4","topLeftCell"],"version":3,"file":"index.js.map","sourceRoot":"../../../../"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/data-sheet",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "description": "Scalable data sheet with optional editing capabilities",
5
5
  "type": "module",
6
6
  "source": "src/index.ts",
@@ -30,10 +30,10 @@
30
30
  "dependencies": {
31
31
  "@blueprintjs/core": "^5.10.2",
32
32
  "@blueprintjs/table": "^5.1.4",
33
- "@macrostrat/color-utils": "^1.1.1",
34
- "@macrostrat/data-components": "^0.2.0",
33
+ "@macrostrat/color-utils": "^1.1.2",
34
+ "@macrostrat/data-components": "^0.2.2",
35
35
  "@macrostrat/hyper": "^3.0.6",
36
- "@macrostrat/ui-components": "^4.3.0",
36
+ "@macrostrat/ui-components": "^4.5.2",
37
37
  "@supabase/postgrest-js": "^1.17.7",
38
38
  "chroma-js": "^2.4.2",
39
39
  "classnames": "^2.3.1",
@@ -56,6 +56,6 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@types/underscore": "^1.13.0",
59
- "parcel": "^2.15.4"
59
+ "parcel": "^2.16.0"
60
60
  }
61
61
  }
@@ -10,8 +10,9 @@ interface GridElement extends ReactDataSheet.Cell<GridElement, number> {
10
10
  value: number | null;
11
11
  }
12
12
 
13
- interface SheetContainerProps<T = any>
14
- extends ReactDataSheet.DataSheetProps<T> {
13
+ interface SheetContainerProps<
14
+ T = any,
15
+ > extends ReactDataSheet.DataSheetProps<T> {
15
16
  height?: number;
16
17
  width?: number;
17
18
  children?: React.ReactNode;
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { useAsyncEffect } from "@macrostrat/ui-components";
4
4
  import { debounce } from "underscore";
5
- import { useCallback, useMemo, useReducer, useRef } from "react";
5
+ import { useCallback, useMemo, useReducer, useRef, useEffect } from "react";
6
6
  import update, { Spec } from "immutability-helper";
7
7
 
8
8
  interface ChunkIndex {
@@ -36,7 +36,8 @@ type LazyLoaderAction<T> =
36
36
  | { type: "loaded"; data: T[]; offset: number; totalSize: number }
37
37
  | { type: "error"; error: Error }
38
38
  | { type: "set-visible"; region: RowRegion }
39
- | { type: "update-data"; changes: Spec<T[]> };
39
+ | { type: "update-data"; changes: Spec<T[]> }
40
+ | { type: "reset" };
40
41
 
41
42
  function adjustArraySize<T>(arr: T[], newSize: number) {
42
43
  if (newSize == null || arr.length === newSize) {
@@ -84,6 +85,15 @@ function lazyLoadingReducer<T>(
84
85
  data,
85
86
  loading: false,
86
87
  };
88
+
89
+ case "reset":
90
+ return {
91
+ data: [],
92
+ loading: false,
93
+ error: null,
94
+ visibleRegion: { rowIndexStart: 0, rowIndexEnd: 0 },
95
+ initialized: false,
96
+ };
87
97
  case "error":
88
98
  return {
89
99
  ...state,
@@ -138,6 +148,7 @@ interface QueryConfig {
138
148
  offset?: number;
139
149
  order?: PostgrestOrder<any>;
140
150
  after?: any;
151
+ fullTextSearch?: string;
141
152
  filter?: (
142
153
  query: PostgrestFilterBuilder<any, any, any>,
143
154
  ) => PostgrestFilterBuilder<any, any, any>;
@@ -150,6 +161,8 @@ function buildQuery<T>(
150
161
  const { columns = "*", count } = config;
151
162
  const opts = { count };
152
163
 
164
+ console.log("config", config);
165
+
153
166
  let cols: string;
154
167
  if (Array.isArray(columns)) {
155
168
  cols = columns.join(", ");
@@ -162,6 +175,7 @@ function buildQuery<T>(
162
175
  if (config.filter) {
163
176
  query = config.filter(query);
164
177
  }
178
+ console.log("query", query.url.search);
165
179
 
166
180
  if (config.order != null) {
167
181
  const { key: orderKey, ...rest } = config.order;
@@ -4,13 +4,14 @@ import styles from "./main.module.sass";
4
4
  import { DataSheet, getRowsToDelete } from "../core"; //getRowsToDelete
5
5
  import { LithologyTag, Tag, TagSize } from "@macrostrat/data-components";
6
6
  import { PostgrestOrder, usePostgRESTLazyLoader } from "./data-loaders";
7
- import { Spinner } from "@blueprintjs/core";
7
+ import { Spinner, InputGroup } from "@blueprintjs/core";
8
8
 
9
9
  export * from "./data-loaders";
10
- import { useCallback } from "react";
10
+ import { useCallback, useState, useRef } from "react";
11
11
  import {
12
12
  ErrorBoundary,
13
13
  ToasterContext,
14
+ useAPIResult,
14
15
  useToaster,
15
16
  } from "@macrostrat/ui-components";
16
17
  import { Spec } from "immutability-helper";
@@ -31,8 +32,9 @@ export type GenericSchema = {
31
32
  Functions: Record<string, GenericFunction>;
32
33
  };
33
34
 
34
- interface PostgRESTTableViewProps<T extends object>
35
- extends DataSheetProviderProps<T> {
35
+ interface PostgRESTTableViewProps<
36
+ T extends object,
37
+ > extends DataSheetProviderProps<T> {
36
38
  endpoint: string;
37
39
  table: string;
38
40
  columnOptions?: any;
@@ -40,6 +42,8 @@ interface PostgRESTTableViewProps<T extends object>
40
42
  columns?: string;
41
43
  editable?: boolean;
42
44
  identityKey?: string;
45
+ enableFullTableSearch?: boolean;
46
+ dataSheetActions?: any;
43
47
  filter(
44
48
  query: PostgrestFilterBuilder<T, any, any>,
45
49
  ): PostgrestFilterBuilder<T, any, any>;
@@ -61,10 +65,32 @@ function _PostgRESTTableView<T>({
61
65
  order,
62
66
  columns,
63
67
  editable = false,
64
- filter,
68
+ filter = undefined,
69
+ enableFullTableSearch = false,
70
+ dataSheetActions,
65
71
  identityKey = "id",
66
72
  ...rest
67
73
  }: PostgRESTTableViewProps<T>) {
74
+ const [input, setInput] = useState("");
75
+
76
+ if (enableFullTableSearch) {
77
+ const columnList = columns ?? getColumnList(endpoint, table);
78
+
79
+ filter = (query) => {
80
+ const urlParams = new URLSearchParams(query.url.search);
81
+ urlParams.delete("or");
82
+ query.url.search = urlParams.toString() ? `?${urlParams.toString()}` : "";
83
+
84
+ if (input.length > 2 && enableFullTableSearch) {
85
+ const conditions = columnList?.map((col) => `${col}.ilike.*${input}*`);
86
+
87
+ return query.or(conditions.join(","));
88
+ }
89
+
90
+ return query;
91
+ };
92
+ }
93
+
68
94
  const { data, onScroll, dispatch, client } = usePostgRESTLazyLoader(
69
95
  endpoint,
70
96
  table,
@@ -99,6 +125,9 @@ function _PostgRESTTableView<T>({
99
125
  return h("div.data-sheet-outer", [
100
126
  h(DataSheet, {
101
127
  ...rest,
128
+ dataSheetActions: enableFullTableSearch
129
+ ? h(SearchAction, { input, setInput, dispatch })
130
+ : dataSheetActions,
102
131
  data,
103
132
  columnSpecOptions: columnOptions ?? {},
104
133
  editable,
@@ -231,3 +260,33 @@ export function ExpandedLithologies({ value, onChange }) {
231
260
  ]),
232
261
  ]);
233
262
  }
263
+
264
+ export function SearchAction({ input, setInput, dispatch }) {
265
+ return h(InputGroup, {
266
+ type: "search",
267
+ placeholder: "Search table...",
268
+ value: input,
269
+ onChange(event) {
270
+ const search = event.target.value;
271
+ if (search.length > 2 || (input.length === 3 && search.length < 3)) {
272
+ dispatch({ type: "reset" });
273
+ }
274
+ setInput(search.toLowerCase());
275
+ },
276
+ });
277
+ }
278
+
279
+ function getColumnList(endpoint: string, table: string) {
280
+ const url = `${endpoint}/${table}?select=*&limit=1`;
281
+ const res = useAPIResult(url);
282
+
283
+ if (!res || !Array.isArray(res) || res.length === 0) return [];
284
+
285
+ const sampleRow = res[0];
286
+
287
+ return Object.entries(sampleRow)
288
+ .filter(([_, value]) => {
289
+ return typeof value === "string";
290
+ })
291
+ .map(([key]) => key);
292
+ }
package/src/provider.ts CHANGED
@@ -7,9 +7,8 @@ import type {
7
7
  Region,
8
8
  Table2,
9
9
  } from "@blueprintjs/table";
10
- import { generateColumnSpec } from "./utils";
10
+ import { generateColumnSpec, range } from "./utils";
11
11
  import update, { Spec } from "immutability-helper";
12
- import { range } from "./utils";
13
12
  import React from "react";
14
13
 
15
14
  export interface ColumnSpec {
@@ -1 +0,0 @@
1
- {"mappings":";;;;;;AAAA,mDAAmD;;;;;AAwCnD,SAAS,sCAAmB,GAAQ,EAAE,OAAe;I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Q,QAAQ,OAAO;IACtC,GAAG;QACD;QACA,MAAM,aAAa,CAAC,aAAa;QACjC,MAAM,aAAa,CAAC,WAAW;KAChC;IAED,6CAA6C;IAC7C,MAAM,MAAM,CAAA,GAAA,aAAK,EAAE;IAEnB,MAAM,WAAW,CAAA,GAAA,kBAAU,EACzB,CAAA,GAAA,eAAO,EAAE,CAAC;QACR,IACE,aAAa,WAAW,IAAI,IAAI,OAAO,EAAE,eACzC,aAAa,aAAa,IAAI,IAAI,OAAO,EAAE,eAE3C;QAEF,QAAQ,GAAG,CAAC,yBAAyB;QACrC,SAAS;YACP,MAAM;YACN,QAAQ;QACV;QACA,IAAI,OAAO,GAAG;IAChB,GAAG,MACH;QAAC;KAAS;IAGZ,OAAO;cACL;iBACA;kBACA;kBACA;gBACA;IACF;AACF;AAEA,SAAS,4CACP,IAAkB,EAClB,aAAwB,EACxB,SAAiB;IAEjB,OAAO,+CAAyB,MAAM;AACxC;AAEA,SAAS,+CACP,IAAW,EACX,MAAiB;IAEjB,IAAK,IAAI,IAAI,OAAO,aAAa,EAAE,IAAI,OAAO,WAAW,EAAE,IAAK;QAC9D,IAAI,IAAI,CAAC,EAAE,IAAI,MACb,OAAO;IAEX;IACA,OAAO;AACT","sources":["packages/data-sheet/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, useMemo, useReducer, useRef } from \"react\";\nimport update, { Spec } from \"immutability-helper\";\n\ninterface ChunkIndex {\n startRow: number;\n endRow: number;\n lastValue: any;\n}\n\nimport {\n PostgrestClient,\n PostgrestQueryBuilder,\n PostgrestFilterBuilder,\n} from \"@supabase/postgrest-js\";\n\ninterface LazyLoaderState<T> {\n data: (T | null)[];\n loading: boolean;\n error: Error | null;\n visibleRegion: RowRegion;\n initialized: boolean;\n}\n\nexport interface PostgrestOrder<T> {\n key: string;\n ascending?: boolean;\n nullsFirst?: boolean;\n}\n\ntype LazyLoaderAction<T> =\n | { type: \"start-loading\" }\n | { type: \"loaded\"; data: T[]; offset: number; totalSize: number }\n | { type: \"error\"; error: Error }\n | { type: \"set-visible\"; region: RowRegion }\n | { type: \"update-data\"; changes: Spec<T[]> };\n\nfunction adjustArraySize<T>(arr: T[], newSize: number) {\n if (newSize == null || arr.length === newSize) {\n return arr;\n } else if (arr.length > newSize) {\n // Trim the array\n arr = arr.slice(0, newSize);\n }\n return [...arr, ...Array(newSize - arr.length).fill(null)];\n}\n\nfunction lazyLoadingReducer<T>(\n state: LazyLoaderState<T>,\n action: LazyLoaderAction<T>,\n): LazyLoaderState<T> {\n console.log(action);\n switch (action.type) {\n case \"start-loading\":\n return {\n ...state,\n loading: true,\n initialized: true,\n };\n case \"set-visible\":\n return {\n ...state,\n visibleRegion: action.region,\n };\n case \"update-data\":\n return {\n ...state,\n loading: false,\n data: update(state.data, action.changes),\n };\n case \"loaded\":\n let data = adjustArraySize(state.data, action.totalSize);\n data = [\n ...data.slice(0, action.offset),\n ...action.data,\n ...data.slice(action.offset + action.data.length),\n ];\n\n return {\n ...state,\n data,\n loading: false,\n };\n case \"error\":\n return {\n ...state,\n error: action.error,\n loading: false,\n };\n default:\n return state;\n }\n}\n\ninterface RowRegion {\n rowIndexStart: number;\n rowIndexEnd: number;\n}\n\nenum LoadDirection {\n \"up\",\n \"down\",\n}\n\nfunction overlapsNulls(data: any[], region: RowRegion) {\n for (let i = region.rowIndexStart; i < region.rowIndexEnd; i++) {\n if (data[i] == null) {\n return true;\n }\n }\n return false;\n}\n\nfunction distanceToNextNonEmptyRow(\n data: any[],\n start: number,\n direction: LoadDirection,\n limit: number,\n): number {\n let i = start;\n while (i < data.length && i > 0 && limit > 0) {\n if (data[i] != null) {\n return i;\n }\n i += direction === LoadDirection.down ? 1 : -1;\n limit -= 1;\n }\n return i;\n}\n\ninterface QueryConfig {\n columns?: string | string[];\n count?: \"exact\" | \"estimated\";\n limit?: number;\n offset?: number;\n order?: PostgrestOrder<any>;\n after?: any;\n filter?: (\n query: PostgrestFilterBuilder<any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any>;\n}\n\nfunction buildQuery<T>(\n client: PostgrestQueryBuilder<T, any>,\n config: QueryConfig,\n) {\n const { columns = \"*\", count } = 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 if (config.filter) {\n query = config.filter(query);\n }\n\n if (config.order != null) {\n const { key: orderKey, ...rest } = config.order;\n query = query.order(orderKey, rest);\n if (config.after != null) {\n const op = (rest.ascending ?? true) ? \"gt\" : \"lt\";\n query = query[op](orderKey, config.after);\n }\n }\n if (config.limit != null) {\n if (config.offset != null) {\n query = query.range(config.offset, config.offset + config.limit - 1);\n console.log(`Random seek from ${config.offset}, this will be slow`);\n } else {\n query = query.limit(config.limit);\n }\n }\n return query;\n}\n\nfunction _loadMoreData<T>(\n client: PostgrestQueryBuilder<T, any>,\n config: QueryConfig & { chunkSize: number },\n state: LazyLoaderState<T>,\n dispatch: any,\n) {\n const rowIndex = indexOfFirstNullInRegion(state.data, state.visibleRegion);\n if (state.loading || rowIndex == null) {\n if (state.initialized) {\n return;\n }\n }\n\n const { chunkSize = 100, ...rest } = config;\n\n const sortKey = config.order?.key ?? \"id\";\n\n let cfg: QueryConfig = {\n ...rest,\n limit: chunkSize,\n offset: null,\n };\n\n // Allows random seeking\n const isInitialQuery = !state.initialized;\n if (isInitialQuery) {\n cfg.count = \"exact\";\n }\n\n // This only works for forward queries\n if (!isInitialQuery) {\n cfg.after = state.data[rowIndex - 1]?.[sortKey];\n if (cfg.after == null) {\n cfg.offset = rowIndex;\n }\n }\n\n dispatch({ type: \"start-loading\" });\n\n const query = buildQuery(client, cfg);\n\n query.then((res) => {\n const { data, count } = res;\n dispatch({\n type: \"loaded\",\n data,\n offset: rowIndex,\n totalSize: count,\n });\n });\n}\n\n// Ensure only one data load is in progress at a time\nconst loadMoreData = debounce(_loadMoreData, 100);\n\ntype LazyLoaderOptions = Omit<QueryConfig, \"count\" | \"offset\" | \"limit\"> & {\n chunkSize?: number;\n sortKey?: string;\n filter?: (\n query: PostgrestFilterBuilder<any, any, any>,\n ) => PostgrestFilterBuilder<any, any, any>;\n};\n\nexport function usePostgRESTLazyLoader(\n endpoint: string,\n table: string,\n config: LazyLoaderOptions = {},\n) {\n const initialState: LazyLoaderState<any> = {\n data: [],\n loading: false,\n error: null,\n visibleRegion: { rowIndexStart: 0, rowIndexEnd: 0 },\n initialized: false,\n };\n\n const client = useMemo(() => {\n return new PostgrestClient(endpoint).from(table);\n }, [endpoint, table]);\n\n const [state, dispatch] = useReducer(lazyLoadingReducer, initialState);\n const { data, loading } = state;\n\n useAsyncEffect(async () => {\n loadMoreData(client, config, state, dispatch);\n }, [\n data,\n state.visibleRegion.rowIndexStart,\n state.visibleRegion.rowIndexEnd,\n ]);\n\n // Reference to hold onto the scroll position\n const ref = useRef(null);\n\n const onScroll = useCallback(\n debounce((visibleCells: RowRegion) => {\n if (\n visibleCells.rowIndexEnd == ref.current?.rowIndexEnd &&\n visibleCells.rowIndexStart == ref.current?.rowIndexStart\n ) {\n return;\n }\n console.log(\"Visible cells changed\", visibleCells);\n dispatch({\n type: \"set-visible\",\n region: visibleCells,\n });\n ref.current = visibleCells;\n }, 500),\n [dispatch],\n );\n\n return {\n data,\n loading,\n onScroll,\n dispatch,\n client,\n };\n}\n\nfunction getRowIndexToLoadFrom<T>(\n data: (T | null)[],\n visibleRegion: RowRegion,\n chunkSize: number,\n) {\n return indexOfFirstNullInRegion(data, visibleRegion);\n}\n\nfunction indexOfFirstNullInRegion(\n data: any[],\n region: RowRegion,\n): number | null {\n for (let i = region.rowIndexStart; i < region.rowIndexEnd; i++) {\n if (data[i] == null) {\n return i;\n }\n }\n return null;\n}\n"],"names":[],"version":3,"file":"data-sheet.4e347b27.js.map"}