@tanstack/table-core 9.0.0-beta.34 → 9.0.0-beta.36
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.
- package/dist/core/rows/coreRowsFeature.types.d.cts +2 -0
- package/dist/core/rows/coreRowsFeature.types.d.ts +2 -0
- package/dist/core/rows/coreRowsFeature.utils.cjs +11 -1
- package/dist/core/rows/coreRowsFeature.utils.cjs.map +1 -1
- package/dist/core/rows/coreRowsFeature.utils.js +11 -1
- package/dist/core/rows/coreRowsFeature.utils.js.map +1 -1
- package/dist/core/table/coreTablesFeature.types.d.cts +2 -2
- package/dist/core/table/coreTablesFeature.types.d.ts +2 -2
- package/dist/features/column-ordering/columnOrderingFeature.cjs +12 -11
- package/dist/features/column-ordering/columnOrderingFeature.cjs.map +1 -1
- package/dist/features/column-ordering/columnOrderingFeature.js +13 -12
- package/dist/features/column-ordering/columnOrderingFeature.js.map +1 -1
- package/dist/features/column-ordering/columnOrderingFeature.types.d.cts +26 -1
- package/dist/features/column-ordering/columnOrderingFeature.types.d.ts +26 -1
- package/dist/features/column-ordering/columnOrderingFeature.utils.cjs +26 -1
- package/dist/features/column-ordering/columnOrderingFeature.utils.cjs.map +1 -1
- package/dist/features/column-ordering/columnOrderingFeature.utils.d.cts +14 -2
- package/dist/features/column-ordering/columnOrderingFeature.utils.d.ts +14 -2
- package/dist/features/column-ordering/columnOrderingFeature.utils.js +27 -3
- package/dist/features/column-ordering/columnOrderingFeature.utils.js.map +1 -1
- package/dist/features/column-pinning/columnPinningFeature.utils.cjs +10 -6
- package/dist/features/column-pinning/columnPinningFeature.utils.cjs.map +1 -1
- package/dist/features/column-pinning/columnPinningFeature.utils.js +10 -6
- package/dist/features/column-pinning/columnPinningFeature.utils.js.map +1 -1
- package/dist/features/column-resizing/columnResizingFeature.utils.cjs +11 -2
- package/dist/features/column-resizing/columnResizingFeature.utils.cjs.map +1 -1
- package/dist/features/column-resizing/columnResizingFeature.utils.js +11 -2
- package/dist/features/column-resizing/columnResizingFeature.utils.js.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/static-functions.cjs +1 -0
- package/dist/static-functions.d.cts +2 -2
- package/dist/static-functions.d.ts +2 -2
- package/dist/static-functions.js +2 -2
- package/dist/types/RowModel.d.cts +2 -4
- package/dist/types/RowModel.d.ts +2 -4
- package/dist/utils.cjs +3 -2
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +2 -1
- package/dist/utils.d.ts +2 -1
- package/dist/utils.js +3 -2
- package/dist/utils.js.map +1 -1
- package/dist/worker/initTableWorker.cjs.map +1 -1
- package/dist/worker/initTableWorker.js.map +1 -1
- package/dist/worker/rebuildRowModel.cjs.map +1 -1
- package/dist/worker/rebuildRowModel.js.map +1 -1
- package/package.json +2 -1
- package/src/core/rows/coreRowsFeature.types.ts +5 -0
- package/src/core/rows/coreRowsFeature.utils.ts +13 -1
- package/src/core/table/coreTablesFeature.types.ts +2 -2
- package/src/features/column-ordering/columnOrderingFeature.ts +12 -8
- package/src/features/column-ordering/columnOrderingFeature.types.ts +26 -0
- package/src/features/column-ordering/columnOrderingFeature.utils.ts +56 -5
- package/src/features/column-pinning/columnPinningFeature.utils.ts +24 -10
- package/src/features/column-resizing/columnResizingFeature.utils.ts +22 -5
- package/src/types/RowModel.ts +6 -10
- package/src/utils.ts +3 -2
- package/src/worker/initTableWorker.ts +1 -1
- package/src/worker/rebuildRowModel.ts +8 -5
package/dist/utils.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { Table_Internal } from './types/Table'\nimport type { NoInfer, RowData, Updater } from './types/type-utils'\nimport type { TableFeatures } from './types/TableFeatures'\nimport type { TableState, TableState_All } from './types/TableState'\n\n/**\n * Applies a TanStack updater to a value.\n *\n * If the updater is a function it is called with the previous value; otherwise the updater value is returned directly.\n */\nexport function functionalUpdate<T>(updater: Updater<T>, input: T): T {\n return typeof updater === 'function'\n ? (updater as (i: T) => T)(input)\n : updater\n}\n\n/**\n * Clones table state values while preserving non-plain objects.\n *\n * Plain objects and arrays are copied recursively so state updates can avoid mutating existing references.\n */\nexport function cloneState<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map(cloneState) as T\n }\n\n if (value && typeof value === 'object') {\n const proto = Object.getPrototypeOf(value)\n\n if (proto !== Object.prototype && proto !== null) {\n return value\n }\n\n const copy: Record<string, unknown> = proto === null ? makeObjectMap() : {}\n const keys = Object.keys(value)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n Object.defineProperty(copy, key, {\n configurable: true,\n enumerable: true,\n value: cloneState((value as Record<string, unknown>)[key]),\n writable: true,\n })\n }\n\n return copy as T\n }\n\n return value\n}\n\n/**\n * Copies prototype-instance own properties without carrying over lazy memo\n * closures that were bound to the source instance.\n */\nexport function copyInstancePropertiesWithoutMemos<\n TTarget extends Record<string, any>,\n TSource extends Record<string, any>,\n>(target: TTarget, source: TSource): TTarget & TSource {\n const keys = Object.keys(source)\n const targetRecord = target as Record<string, any>\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n if (!key.startsWith('_memo_')) {\n targetRecord[key] = source[key]\n }\n }\n\n return target as TTarget & TSource\n}\n\n/**\n * Creates an object intended only for string-keyed dictionary lookups.\n *\n * The null prototype keeps user-controlled ids such as `__proto__` and\n * `hasOwnProperty` as plain data keys.\n */\nexport function makeObjectMap<TValue = unknown>(): Record<string, TValue> {\n return Object.create(null) as Record<string, TValue>\n}\n\n/**\n * Checks whether an object owns a key, including null-prototype dictionaries.\n */\nexport function hasOwn(obj: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key)\n}\n\n/**\n * Creates a table state updater for a single state slice.\n *\n * The updater writes through the table base atom for the slice and supports both value and functional updater forms.\n */\nexport function makeStateUpdater<\n TFeatures extends TableFeatures,\n K extends (string & {}) | keyof TableState_All | keyof TableState<TFeatures>,\n>(\n key: K,\n // Minimal structural shape so any table view (public `Table`,\n // `Table_Internal`, or a custom plugin table) can be passed without forcing\n // the compiler to relate the full table types.\n instance: {\n readonly options: { readonly atoms?: object | undefined }\n readonly baseAtoms: object\n },\n) {\n return (updater: Updater<TableState<any>[K & keyof TableState<any>]>) => {\n const externalAtom = (instance.options as any).atoms?.[key]\n const targetAtom = externalAtom ?? (instance.baseAtoms as any)[key]\n targetAtom.set((old: any) => functionalUpdate(updater, old))\n }\n}\n\ntype AnyFunction = (...args: any) => any\n\n/**\n * Returns whether a value is a function.\n */\nexport function isFunction<T extends AnyFunction>(d: any): d is T {\n return d instanceof Function\n}\n\n/**\n * Flattens a tree of nodes by recursively reading child nodes.\n *\n * The original nodes are preserved in depth-first order.\n */\nexport function flattenBy<TNode>(\n arr: Array<TNode>,\n getChildren: (item: TNode) => Array<TNode>,\n) {\n const flat: Array<TNode> = []\n\n const recurse = (subArr: Array<TNode>) => {\n subArr.forEach((item) => {\n flat.push(item)\n const children = getChildren(item)\n if (children.length) {\n recurse(children)\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\ninterface MemoOptions<TDeps extends ReadonlyArray<any>, TDepArgs, TResult> {\n fn: (...args: NoInfer<TDeps>) => TResult\n memoDeps?: (depArgs?: TDepArgs) => [...TDeps] | undefined\n onAfterCompare?: (depsChanged: boolean) => void\n onAfterUpdate?: (result: TResult) => void\n onBeforeCompare?: () => void\n onBeforeUpdate?: () => void\n}\n\n/**\n * Creates a dependency-tracked memoized function for table internals.\n *\n * The memo recomputes only when its dependency tuple changes and can emit debug timing information.\n */\nexport const memo = <TDeps extends ReadonlyArray<any>, TDepArgs, TResult>({\n fn,\n memoDeps,\n onAfterCompare,\n onAfterUpdate,\n onBeforeCompare,\n onBeforeUpdate,\n}: MemoOptions<TDeps, TDepArgs, TResult>): ((\n depArgs?: TDepArgs,\n) => TResult) => {\n let deps: Array<any> | undefined = []\n let result: TResult | undefined\n\n const memoizedFn = (depArgs?: TDepArgs): TResult => {\n onBeforeCompare?.()\n const newDeps = memoDeps?.(depArgs)\n let depsChanged = !newDeps || newDeps.length !== deps?.length\n if (!depsChanged && newDeps) {\n for (let i = 0; i < newDeps.length; i++) {\n if (newDeps[i] !== deps![i]) {\n depsChanged = true\n break\n }\n }\n }\n onAfterCompare?.(depsChanged)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n onBeforeUpdate?.()\n result = fn(...(newDeps ?? ([] as any)))\n onAfterUpdate?.(result)\n\n return result\n }\n\n return memoizedFn\n}\n\ninterface TableMemoOptions<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n> extends MemoOptions<TDeps, TDepArgs, TResult> {\n feature?: keyof TFeatures & string\n fnName: string\n objectId?: string\n onAfterUpdate?: () => void\n table: Table_Internal<TFeatures, any>\n}\n\nconst pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n}\n\n/**\n * Creates a table-aware memoized function.\n *\n * This wraps `memo` with table debug options and feature metadata so row models and derived APIs can share consistent diagnostics.\n */\nexport function tableMemo<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n>({\n feature,\n fnName,\n objectId,\n onAfterUpdate,\n table,\n ...memoOptions\n}: TableMemoOptions<TFeatures, TDeps, TDepArgs, TResult>) {\n let beforeCompareTime: number\n let afterCompareTime: number\n let startCalcTime: number\n let endCalcTime: number\n let runCount = 0\n let debug: boolean | undefined\n let debugCache: boolean | undefined\n\n if (process.env.NODE_ENV === 'development') {\n const { debugCache: _debugCache, debugAll } = table.options\n debugCache = _debugCache\n const { parentName } = getFunctionNameInfo(fnName, '.')\n\n const debugByParent =\n // @ts-expect-error\n table.options[\n `debug${(parentName != 'table' ? parentName + 's' : parentName).replace(\n parentName,\n parentName.charAt(0).toUpperCase() + parentName.slice(1),\n )}`\n ]\n const debugByFeature = feature\n ? // @ts-expect-error\n table.options[\n `debug${feature.charAt(0).toUpperCase() + feature.slice(1)}`\n ]\n : false\n\n debug = debugAll || debugByParent || debugByFeature\n }\n\n function logTime(time: number, depsChanged: boolean) {\n const runType =\n runCount === 0\n ? '(1st run)'\n : depsChanged\n ? '(rerun #' + runCount + ')'\n : '(cache)'\n runCount++\n\n console.groupCollapsed(\n `%c⏱ ${pad(`${time.toFixed(1)} ms`, 12)} %c${runType}%c ${fnName}%c ${objectId ? `(${fnName.split('.')[0]}Id: ${objectId})` : ''}`,\n `font-size: .6rem; font-weight: bold; ${\n depsChanged\n ? `color: hsl(\n ${Math.max(0, Math.min(120 - Math.log10(time) * 60, 120))}deg 100% 31%);`\n : ''\n } `,\n `color: ${runCount < 2 ? '#FF00FF' : '#FF1493'}`,\n 'color: #666',\n 'color: #87CEEB',\n )\n console.info({\n feature,\n state: table.store.state,\n deps: memoOptions.memoDeps?.toString(),\n })\n console.trace()\n console.groupEnd()\n }\n\n const onAfterUpdateHandler = () => {\n if (!onAfterUpdate) {\n return\n }\n\n const { schedule, untrack } = table._reactivity\n schedule(() => untrack(() => onAfterUpdate()))\n }\n\n const debugOptions =\n process.env.NODE_ENV === 'development'\n ? {\n onBeforeCompare: () => {\n if (debugCache) {\n beforeCompareTime = performance.now()\n }\n },\n onAfterCompare: (depsChanged: boolean) => {\n if (debugCache) {\n afterCompareTime = performance.now()\n const compareTime =\n Math.round((afterCompareTime - beforeCompareTime) * 100) / 100\n if (!depsChanged) {\n logTime(compareTime, depsChanged)\n }\n }\n },\n onBeforeUpdate: () => {\n if (debug) {\n startCalcTime = performance.now()\n }\n },\n onAfterUpdate: () => {\n if (debug) {\n endCalcTime = performance.now()\n const executionTime =\n Math.round((endCalcTime - startCalcTime) * 100) / 100\n logTime(executionTime, true)\n }\n onAfterUpdateHandler()\n },\n }\n : {\n onAfterUpdate: () => {\n onAfterUpdateHandler()\n },\n }\n\n return memo({\n ...memoOptions,\n ...debugOptions,\n })\n}\n\nexport interface API<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (...args: any) => any\n memoDeps?: (depArgs?: any) => [...any] | undefined\n}\n\nexport type APIObject<TDeps extends ReadonlyArray<any>, TDepArgs> = Record<\n string,\n API<TDeps, TDepArgs>\n>\n\n/**\n * Assumes that a function name is in the format of `parentName_fnKey` and returns the `fnKey` and `fnName` in the format of `parentName.fnKey`.\n */\nexport function getFunctionNameInfo(\n staticFnName: string,\n splitBy: '_' | '.' = '_',\n) {\n const [parentName, fnKey] = staticFnName.split(splitBy)\n const fnName = `${parentName}.${fnKey}`\n return { fnKey, fnName, parentName } as {\n fnKey: string\n fnName: string\n parentName: string\n }\n}\n\n/**\n * Assigns Table API methods directly to the table instance.\n * Unlike row/cell/column/header, the table is a singleton so methods are assigned directly.\n */\nexport function assignTableAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n table: Table_Internal<TFeatures, TData>,\n apis: APIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n ;(table as Record<string, any>)[fnKey] = memoDeps\n ? tableMemo({\n memoDeps,\n fn,\n fnName,\n table,\n feature,\n })\n : fn\n }\n}\n\nexport interface PrototypeAPI<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (self: any, ...args: any) => any\n memoDeps?: (self: any, depArgs?: any) => [...any] | undefined\n}\n\nexport type PrototypeAPIObject<\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n> = Record<string, PrototypeAPI<TDeps, TDepArgs>>\n\n/**\n * Assigns API methods to a prototype object for memory-efficient method sharing.\n * All instances created with this prototype will share the same method references.\n *\n * For memoized methods, the memo state is lazily created and stored on each instance.\n * This provides the best of both worlds: shared method code + per-instance caching.\n */\nexport function assignPrototypeAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n prototype: Record<string, any>,\n table: Table_Internal<TFeatures, TData>,\n apis: PrototypeAPIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n if (memoDeps) {\n // For memoized methods, create a function that lazily initializes\n // the memo on first access and stores it on the instance\n const memoKey = `_memo_${fnKey}`\n\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n // Lazily create memo on first access for this instance\n if (!this[memoKey]) {\n const self = this\n this[memoKey] = tableMemo({\n memoDeps: (depArgs) => memoDeps(self, depArgs),\n fn: (...deps) => fn(self, ...deps),\n fnName,\n objectId: self.id,\n table,\n feature,\n })\n }\n return this[memoKey](...args)\n }\n } else {\n // Non-memoized methods just call the static function with `this`\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n return fn(this, ...args)\n }\n }\n }\n}\n\n/**\n * Looks to run the memoized function with the builder pattern on the object if it exists, otherwise fallback to the static method passed in.\n */\nexport function callMemoOrStaticFn<\n TObject extends Record<string, any>,\n TArgs extends Array<any>,\n TReturn,\n>(\n obj: TObject,\n fnKey: string,\n staticFn: (obj: TObject, ...args: TArgs) => TReturn,\n ...args: TArgs\n): TReturn {\n return (\n (obj[fnKey] as Function | undefined)?.(...args) ?? staticFn(obj, ...args)\n )\n}\n"],"mappings":";;;;;;;AAUA,SAAgB,iBAAoB,SAAqB,OAAa;CACpE,OAAO,OAAO,YAAY,aACrB,QAAwB,KAAK,IAC9B;AACN;;;;;;AAOA,SAAgB,WAAc,OAAa;CACzC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,UAAU;CAG7B,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,QAAQ,OAAO,eAAe,KAAK;EAEzC,IAAI,UAAU,OAAO,aAAa,UAAU,MAC1C,OAAO;EAGT,MAAM,OAAgC,UAAU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,cACA,UAAqB,KACrB;CACA,MAAM,CAAC,YAAY,SAAS,aAAa,MAAM,OAAO;CAEtD,OAAO;EAAE;EAAO,WADE,WAAW,GAAG;EACR;CAAW;AAKrC;;;;;AAMA,SAAgB,gBAMd,SACA,OACA,MACM;CACN,KAAK,MAAM,CAAC,cAAc,EAAE,IAAI,eAAe,OAAO,QAAQ,IAAI,GAAG;EACnE,MAAM,EAAE,OAAO,WAAW,oBAAoB,YAAY;EAEzD,AAAC,MAA8B,SAAS,WACrC,UAAU;GACR;GACA;GACA;GACA;GACA;EACF,CAAC,IACD;CACN;AACF;;;;;;;;AAmBA,SAAgB,oBAMd,SACA,WACA,OACA,MACM;CACN,KAAK,MAAM,CAAC,cAAc,EAAE,IAAI,eAAe,OAAO,QAAQ,IAAI,GAAG;EACnE,MAAM,EAAE,OAAO,WAAW,oBAAoB,YAAY;EAE1D,IAAI,UAAU;GAGZ,MAAM,UAAU,SAAS;GAEzB,UAAU,SAAS,SAAqB,GAAG,MAAkB;IAE3D,IAAI,CAAC,KAAK,UAAU;KAClB,MAAM,OAAO;KACb,KAAK,WAAW,UAAU;MACxB,WAAW,YAAY,SAAS,MAAM,OAAO;MAC7C,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI;MACjC;MACA,UAAU,KAAK;MACf;MACA;KACF,CAAC;IACH;IACA,OAAO,KAAK,QAAQ,CAAC,GAAG,IAAI;GAC9B;EACF,OAEE,UAAU,SAAS,SAAqB,GAAG,MAAkB;GAC3D,OAAO,GAAG,MAAM,GAAG,IAAI;EACzB;CAEJ;AACF;;;;AAKA,SAAgB,mBAKd,KACA,OACA,UACA,GAAG,MACM;CACT,OACG,IAAI,MAAM,GAA4B,GAAG,IAAI,KAAK,SAAS,KAAK,GAAG,IAAI;AAE5E"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { Table_Internal } from './types/Table'\nimport type { NoInfer, RowData, Updater } from './types/type-utils'\nimport type { TableFeatures } from './types/TableFeatures'\nimport type { TableState, TableState_All } from './types/TableState'\n\n/**\n * Applies a TanStack updater to a value.\n *\n * If the updater is a function it is called with the previous value; otherwise the updater value is returned directly.\n */\nexport function functionalUpdate<T>(updater: Updater<T>, input: T): T {\n return typeof updater === 'function'\n ? (updater as (i: T) => T)(input)\n : updater\n}\n\n/**\n * Clones table state values while preserving non-plain objects.\n *\n * Plain objects and arrays are copied recursively so state updates can avoid mutating existing references.\n */\nexport function cloneState<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map(cloneState) as T\n }\n\n if (value && typeof value === 'object') {\n const proto = Object.getPrototypeOf(value)\n\n if (proto !== Object.prototype && proto !== null) {\n return value\n }\n\n const copy: Record<string, unknown> = proto === null ? makeObjectMap() : {}\n const keys = Object.keys(value)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n Object.defineProperty(copy, key, {\n configurable: true,\n enumerable: true,\n value: cloneState((value as Record<string, unknown>)[key]),\n writable: true,\n })\n }\n\n return copy as T\n }\n\n return value\n}\n\n/**\n * Copies prototype-instance own properties without carrying over lazy memo\n * closures or the per-row cell cache, both of which are bound to the source\n * instance (cached cells reference the source row).\n */\nexport function copyInstancePropertiesWithoutMemos<\n TTarget extends Record<string, any>,\n TSource extends Record<string, any>,\n>(target: TTarget, source: TSource): TTarget & TSource {\n const keys = Object.keys(source)\n const targetRecord = target as Record<string, any>\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n if (!key.startsWith('_memo_') && key !== '_cellsCache') {\n targetRecord[key] = source[key]\n }\n }\n\n return target as TTarget & TSource\n}\n\n/**\n * Creates an object intended only for string-keyed dictionary lookups.\n *\n * The null prototype keeps user-controlled ids such as `__proto__` and\n * `hasOwnProperty` as plain data keys.\n */\nexport function makeObjectMap<TValue = unknown>(): Record<string, TValue> {\n return Object.create(null) as Record<string, TValue>\n}\n\n/**\n * Checks whether an object owns a key, including null-prototype dictionaries.\n */\nexport function hasOwn(obj: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key)\n}\n\n/**\n * Creates a table state updater for a single state slice.\n *\n * The updater writes through the table base atom for the slice and supports both value and functional updater forms.\n */\nexport function makeStateUpdater<\n TFeatures extends TableFeatures,\n K extends (string & {}) | keyof TableState_All | keyof TableState<TFeatures>,\n>(\n key: K,\n // Minimal structural shape so any table view (public `Table`,\n // `Table_Internal`, or a custom plugin table) can be passed without forcing\n // the compiler to relate the full table types.\n instance: {\n readonly options: { readonly atoms?: object | undefined }\n readonly baseAtoms: object\n },\n) {\n return (updater: Updater<TableState<any>[K & keyof TableState<any>]>) => {\n const externalAtom = (instance.options as any).atoms?.[key]\n const targetAtom = externalAtom ?? (instance.baseAtoms as any)[key]\n targetAtom.set((old: any) => functionalUpdate(updater, old))\n }\n}\n\ntype AnyFunction = (...args: any) => any\n\n/**\n * Returns whether a value is a function.\n */\nexport function isFunction<T extends AnyFunction>(d: any): d is T {\n return d instanceof Function\n}\n\n/**\n * Flattens a tree of nodes by recursively reading child nodes.\n *\n * The original nodes are preserved in depth-first order.\n */\nexport function flattenBy<TNode>(\n arr: Array<TNode>,\n getChildren: (item: TNode) => Array<TNode>,\n) {\n const flat: Array<TNode> = []\n\n const recurse = (subArr: Array<TNode>) => {\n subArr.forEach((item) => {\n flat.push(item)\n const children = getChildren(item)\n if (children.length) {\n recurse(children)\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\ninterface MemoOptions<TDeps extends ReadonlyArray<any>, TDepArgs, TResult> {\n fn: (...args: NoInfer<TDeps>) => TResult\n memoDeps?: (depArgs?: TDepArgs) => [...TDeps] | undefined\n onAfterCompare?: (depsChanged: boolean) => void\n onAfterUpdate?: (result: TResult) => void\n onBeforeCompare?: () => void\n onBeforeUpdate?: () => void\n}\n\n/**\n * Creates a dependency-tracked memoized function for table internals.\n *\n * The memo recomputes only when its dependency tuple changes and can emit debug timing information.\n */\nexport const memo = <TDeps extends ReadonlyArray<any>, TDepArgs, TResult>({\n fn,\n memoDeps,\n onAfterCompare,\n onAfterUpdate,\n onBeforeCompare,\n onBeforeUpdate,\n}: MemoOptions<TDeps, TDepArgs, TResult>): ((\n depArgs?: TDepArgs,\n) => TResult) => {\n let deps: Array<any> | undefined = []\n let result: TResult | undefined\n\n const memoizedFn = (depArgs?: TDepArgs): TResult => {\n onBeforeCompare?.()\n const newDeps = memoDeps?.(depArgs)\n let depsChanged = !newDeps || newDeps.length !== deps?.length\n if (!depsChanged && newDeps) {\n for (let i = 0; i < newDeps.length; i++) {\n if (newDeps[i] !== deps![i]) {\n depsChanged = true\n break\n }\n }\n }\n onAfterCompare?.(depsChanged)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n onBeforeUpdate?.()\n result = fn(...(newDeps ?? ([] as any)))\n onAfterUpdate?.(result)\n\n return result\n }\n\n return memoizedFn\n}\n\ninterface TableMemoOptions<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n> extends MemoOptions<TDeps, TDepArgs, TResult> {\n feature?: keyof TFeatures & string\n fnName: string\n objectId?: string\n onAfterUpdate?: () => void\n table: Table_Internal<TFeatures, any>\n}\n\nconst pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n}\n\n/**\n * Creates a table-aware memoized function.\n *\n * This wraps `memo` with table debug options and feature metadata so row models and derived APIs can share consistent diagnostics.\n */\nexport function tableMemo<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n>({\n feature,\n fnName,\n objectId,\n onAfterUpdate,\n table,\n ...memoOptions\n}: TableMemoOptions<TFeatures, TDeps, TDepArgs, TResult>) {\n let beforeCompareTime: number\n let afterCompareTime: number\n let startCalcTime: number\n let endCalcTime: number\n let runCount = 0\n let debug: boolean | undefined\n let debugCache: boolean | undefined\n\n if (process.env.NODE_ENV === 'development') {\n const { debugCache: _debugCache, debugAll } = table.options\n debugCache = _debugCache\n const { parentName } = getFunctionNameInfo(fnName, '.')\n\n const debugByParent =\n // @ts-expect-error\n table.options[\n `debug${(parentName != 'table' ? parentName + 's' : parentName).replace(\n parentName,\n parentName.charAt(0).toUpperCase() + parentName.slice(1),\n )}`\n ]\n const debugByFeature = feature\n ? // @ts-expect-error\n table.options[\n `debug${feature.charAt(0).toUpperCase() + feature.slice(1)}`\n ]\n : false\n\n debug = debugAll || debugByParent || debugByFeature\n }\n\n function logTime(time: number, depsChanged: boolean) {\n const runType =\n runCount === 0\n ? '(1st run)'\n : depsChanged\n ? '(rerun #' + runCount + ')'\n : '(cache)'\n runCount++\n\n console.groupCollapsed(\n `%c⏱ ${pad(`${time.toFixed(1)} ms`, 12)} %c${runType}%c ${fnName}%c ${objectId ? `(${fnName.split('.')[0]}Id: ${objectId})` : ''}`,\n `font-size: .6rem; font-weight: bold; ${\n depsChanged\n ? `color: hsl(\n ${Math.max(0, Math.min(120 - Math.log10(time) * 60, 120))}deg 100% 31%);`\n : ''\n } `,\n `color: ${runCount < 2 ? '#FF00FF' : '#FF1493'}`,\n 'color: #666',\n 'color: #87CEEB',\n )\n console.info({\n feature,\n state: table.store.state,\n deps: memoOptions.memoDeps?.toString(),\n })\n console.trace()\n console.groupEnd()\n }\n\n const onAfterUpdateHandler = () => {\n if (!onAfterUpdate) {\n return\n }\n\n const { schedule, untrack } = table._reactivity\n schedule(() => untrack(() => onAfterUpdate()))\n }\n\n const debugOptions =\n process.env.NODE_ENV === 'development'\n ? {\n onBeforeCompare: () => {\n if (debugCache) {\n beforeCompareTime = performance.now()\n }\n },\n onAfterCompare: (depsChanged: boolean) => {\n if (debugCache) {\n afterCompareTime = performance.now()\n const compareTime =\n Math.round((afterCompareTime - beforeCompareTime) * 100) / 100\n if (!depsChanged) {\n logTime(compareTime, depsChanged)\n }\n }\n },\n onBeforeUpdate: () => {\n if (debug) {\n startCalcTime = performance.now()\n }\n },\n onAfterUpdate: () => {\n if (debug) {\n endCalcTime = performance.now()\n const executionTime =\n Math.round((endCalcTime - startCalcTime) * 100) / 100\n logTime(executionTime, true)\n }\n onAfterUpdateHandler()\n },\n }\n : {\n onAfterUpdate: () => {\n onAfterUpdateHandler()\n },\n }\n\n return memo({\n ...memoOptions,\n ...debugOptions,\n })\n}\n\nexport interface API<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (...args: any) => any\n memoDeps?: (depArgs?: any) => [...any] | undefined\n}\n\nexport type APIObject<TDeps extends ReadonlyArray<any>, TDepArgs> = Record<\n string,\n API<TDeps, TDepArgs>\n>\n\n/**\n * Assumes that a function name is in the format of `parentName_fnKey` and returns the `fnKey` and `fnName` in the format of `parentName.fnKey`.\n */\nexport function getFunctionNameInfo(\n staticFnName: string,\n splitBy: '_' | '.' = '_',\n) {\n const [parentName, fnKey] = staticFnName.split(splitBy)\n const fnName = `${parentName}.${fnKey}`\n return { fnKey, fnName, parentName } as {\n fnKey: string\n fnName: string\n parentName: string\n }\n}\n\n/**\n * Assigns Table API methods directly to the table instance.\n * Unlike row/cell/column/header, the table is a singleton so methods are assigned directly.\n */\nexport function assignTableAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n table: Table_Internal<TFeatures, TData>,\n apis: APIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n ;(table as Record<string, any>)[fnKey] = memoDeps\n ? tableMemo({\n memoDeps,\n fn,\n fnName,\n table,\n feature,\n })\n : fn\n }\n}\n\nexport interface PrototypeAPI<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (self: any, ...args: any) => any\n memoDeps?: (self: any, depArgs?: any) => [...any] | undefined\n}\n\nexport type PrototypeAPIObject<\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n> = Record<string, PrototypeAPI<TDeps, TDepArgs>>\n\n/**\n * Assigns API methods to a prototype object for memory-efficient method sharing.\n * All instances created with this prototype will share the same method references.\n *\n * For memoized methods, the memo state is lazily created and stored on each instance.\n * This provides the best of both worlds: shared method code + per-instance caching.\n */\nexport function assignPrototypeAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n prototype: Record<string, any>,\n table: Table_Internal<TFeatures, TData>,\n apis: PrototypeAPIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n if (memoDeps) {\n // For memoized methods, create a function that lazily initializes\n // the memo on first access and stores it on the instance\n const memoKey = `_memo_${fnKey}`\n\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n // Lazily create memo on first access for this instance\n if (!this[memoKey]) {\n const self = this\n this[memoKey] = tableMemo({\n memoDeps: (depArgs) => memoDeps(self, depArgs),\n fn: (...deps) => fn(self, ...deps),\n fnName,\n objectId: self.id,\n table,\n feature,\n })\n }\n return this[memoKey](...args)\n }\n } else {\n // Non-memoized methods just call the static function with `this`\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n return fn(this, ...args)\n }\n }\n }\n}\n\n/**\n * Looks to run the memoized function with the builder pattern on the object if it exists, otherwise fallback to the static method passed in.\n */\nexport function callMemoOrStaticFn<\n TObject extends Record<string, any>,\n TArgs extends Array<any>,\n TReturn,\n>(\n obj: TObject,\n fnKey: string,\n staticFn: (obj: TObject, ...args: TArgs) => TReturn,\n ...args: TArgs\n): TReturn {\n return (\n (obj[fnKey] as Function | undefined)?.(...args) ?? staticFn(obj, ...args)\n )\n}\n"],"mappings":";;;;;;;AAUA,SAAgB,iBAAoB,SAAqB,OAAa;CACpE,OAAO,OAAO,YAAY,aACrB,QAAwB,KAAK,IAC9B;AACN;;;;;;AAOA,SAAgB,WAAc,OAAa;CACzC,IAAI,MAAM,QAAQ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G,IAAI,MAAM,GAA4B,GAAG,IAAI,KAAK,SAAS,KAAK,GAAG,IAAI;AAE5E"}
|
package/dist/utils.d.cts
CHANGED
|
@@ -18,7 +18,8 @@ declare function functionalUpdate<T>(updater: Updater<T>, input: T): T;
|
|
|
18
18
|
declare function cloneState<T>(value: T): T;
|
|
19
19
|
/**
|
|
20
20
|
* Copies prototype-instance own properties without carrying over lazy memo
|
|
21
|
-
* closures
|
|
21
|
+
* closures or the per-row cell cache, both of which are bound to the source
|
|
22
|
+
* instance (cached cells reference the source row).
|
|
22
23
|
*/
|
|
23
24
|
declare function copyInstancePropertiesWithoutMemos<TTarget extends Record<string, any>, TSource extends Record<string, any>>(target: TTarget, source: TSource): TTarget & TSource;
|
|
24
25
|
/**
|
package/dist/utils.d.ts
CHANGED
|
@@ -18,7 +18,8 @@ declare function functionalUpdate<T>(updater: Updater<T>, input: T): T;
|
|
|
18
18
|
declare function cloneState<T>(value: T): T;
|
|
19
19
|
/**
|
|
20
20
|
* Copies prototype-instance own properties without carrying over lazy memo
|
|
21
|
-
* closures
|
|
21
|
+
* closures or the per-row cell cache, both of which are bound to the source
|
|
22
|
+
* instance (cached cells reference the source row).
|
|
22
23
|
*/
|
|
23
24
|
declare function copyInstancePropertiesWithoutMemos<TTarget extends Record<string, any>, TSource extends Record<string, any>>(target: TTarget, source: TSource): TTarget & TSource;
|
|
24
25
|
/**
|
package/dist/utils.js
CHANGED
|
@@ -34,14 +34,15 @@ function cloneState(value) {
|
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
36
|
* Copies prototype-instance own properties without carrying over lazy memo
|
|
37
|
-
* closures
|
|
37
|
+
* closures or the per-row cell cache, both of which are bound to the source
|
|
38
|
+
* instance (cached cells reference the source row).
|
|
38
39
|
*/
|
|
39
40
|
function copyInstancePropertiesWithoutMemos(target, source) {
|
|
40
41
|
const keys = Object.keys(source);
|
|
41
42
|
const targetRecord = target;
|
|
42
43
|
for (let i = 0; i < keys.length; i++) {
|
|
43
44
|
const key = keys[i];
|
|
44
|
-
if (!key.startsWith("_memo_")) targetRecord[key] = source[key];
|
|
45
|
+
if (!key.startsWith("_memo_") && key !== "_cellsCache") targetRecord[key] = source[key];
|
|
45
46
|
}
|
|
46
47
|
return target;
|
|
47
48
|
}
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { Table_Internal } from './types/Table'\nimport type { NoInfer, RowData, Updater } from './types/type-utils'\nimport type { TableFeatures } from './types/TableFeatures'\nimport type { TableState, TableState_All } from './types/TableState'\n\n/**\n * Applies a TanStack updater to a value.\n *\n * If the updater is a function it is called with the previous value; otherwise the updater value is returned directly.\n */\nexport function functionalUpdate<T>(updater: Updater<T>, input: T): T {\n return typeof updater === 'function'\n ? (updater as (i: T) => T)(input)\n : updater\n}\n\n/**\n * Clones table state values while preserving non-plain objects.\n *\n * Plain objects and arrays are copied recursively so state updates can avoid mutating existing references.\n */\nexport function cloneState<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map(cloneState) as T\n }\n\n if (value && typeof value === 'object') {\n const proto = Object.getPrototypeOf(value)\n\n if (proto !== Object.prototype && proto !== null) {\n return value\n }\n\n const copy: Record<string, unknown> = proto === null ? makeObjectMap() : {}\n const keys = Object.keys(value)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n Object.defineProperty(copy, key, {\n configurable: true,\n enumerable: true,\n value: cloneState((value as Record<string, unknown>)[key]),\n writable: true,\n })\n }\n\n return copy as T\n }\n\n return value\n}\n\n/**\n * Copies prototype-instance own properties without carrying over lazy memo\n * closures that were bound to the source instance.\n */\nexport function copyInstancePropertiesWithoutMemos<\n TTarget extends Record<string, any>,\n TSource extends Record<string, any>,\n>(target: TTarget, source: TSource): TTarget & TSource {\n const keys = Object.keys(source)\n const targetRecord = target as Record<string, any>\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n if (!key.startsWith('_memo_')) {\n targetRecord[key] = source[key]\n }\n }\n\n return target as TTarget & TSource\n}\n\n/**\n * Creates an object intended only for string-keyed dictionary lookups.\n *\n * The null prototype keeps user-controlled ids such as `__proto__` and\n * `hasOwnProperty` as plain data keys.\n */\nexport function makeObjectMap<TValue = unknown>(): Record<string, TValue> {\n return Object.create(null) as Record<string, TValue>\n}\n\n/**\n * Checks whether an object owns a key, including null-prototype dictionaries.\n */\nexport function hasOwn(obj: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key)\n}\n\n/**\n * Creates a table state updater for a single state slice.\n *\n * The updater writes through the table base atom for the slice and supports both value and functional updater forms.\n */\nexport function makeStateUpdater<\n TFeatures extends TableFeatures,\n K extends (string & {}) | keyof TableState_All | keyof TableState<TFeatures>,\n>(\n key: K,\n // Minimal structural shape so any table view (public `Table`,\n // `Table_Internal`, or a custom plugin table) can be passed without forcing\n // the compiler to relate the full table types.\n instance: {\n readonly options: { readonly atoms?: object | undefined }\n readonly baseAtoms: object\n },\n) {\n return (updater: Updater<TableState<any>[K & keyof TableState<any>]>) => {\n const externalAtom = (instance.options as any).atoms?.[key]\n const targetAtom = externalAtom ?? (instance.baseAtoms as any)[key]\n targetAtom.set((old: any) => functionalUpdate(updater, old))\n }\n}\n\ntype AnyFunction = (...args: any) => any\n\n/**\n * Returns whether a value is a function.\n */\nexport function isFunction<T extends AnyFunction>(d: any): d is T {\n return d instanceof Function\n}\n\n/**\n * Flattens a tree of nodes by recursively reading child nodes.\n *\n * The original nodes are preserved in depth-first order.\n */\nexport function flattenBy<TNode>(\n arr: Array<TNode>,\n getChildren: (item: TNode) => Array<TNode>,\n) {\n const flat: Array<TNode> = []\n\n const recurse = (subArr: Array<TNode>) => {\n subArr.forEach((item) => {\n flat.push(item)\n const children = getChildren(item)\n if (children.length) {\n recurse(children)\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\ninterface MemoOptions<TDeps extends ReadonlyArray<any>, TDepArgs, TResult> {\n fn: (...args: NoInfer<TDeps>) => TResult\n memoDeps?: (depArgs?: TDepArgs) => [...TDeps] | undefined\n onAfterCompare?: (depsChanged: boolean) => void\n onAfterUpdate?: (result: TResult) => void\n onBeforeCompare?: () => void\n onBeforeUpdate?: () => void\n}\n\n/**\n * Creates a dependency-tracked memoized function for table internals.\n *\n * The memo recomputes only when its dependency tuple changes and can emit debug timing information.\n */\nexport const memo = <TDeps extends ReadonlyArray<any>, TDepArgs, TResult>({\n fn,\n memoDeps,\n onAfterCompare,\n onAfterUpdate,\n onBeforeCompare,\n onBeforeUpdate,\n}: MemoOptions<TDeps, TDepArgs, TResult>): ((\n depArgs?: TDepArgs,\n) => TResult) => {\n let deps: Array<any> | undefined = []\n let result: TResult | undefined\n\n const memoizedFn = (depArgs?: TDepArgs): TResult => {\n onBeforeCompare?.()\n const newDeps = memoDeps?.(depArgs)\n let depsChanged = !newDeps || newDeps.length !== deps?.length\n if (!depsChanged && newDeps) {\n for (let i = 0; i < newDeps.length; i++) {\n if (newDeps[i] !== deps![i]) {\n depsChanged = true\n break\n }\n }\n }\n onAfterCompare?.(depsChanged)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n onBeforeUpdate?.()\n result = fn(...(newDeps ?? ([] as any)))\n onAfterUpdate?.(result)\n\n return result\n }\n\n return memoizedFn\n}\n\ninterface TableMemoOptions<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n> extends MemoOptions<TDeps, TDepArgs, TResult> {\n feature?: keyof TFeatures & string\n fnName: string\n objectId?: string\n onAfterUpdate?: () => void\n table: Table_Internal<TFeatures, any>\n}\n\nconst pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n}\n\n/**\n * Creates a table-aware memoized function.\n *\n * This wraps `memo` with table debug options and feature metadata so row models and derived APIs can share consistent diagnostics.\n */\nexport function tableMemo<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n>({\n feature,\n fnName,\n objectId,\n onAfterUpdate,\n table,\n ...memoOptions\n}: TableMemoOptions<TFeatures, TDeps, TDepArgs, TResult>) {\n let beforeCompareTime: number\n let afterCompareTime: number\n let startCalcTime: number\n let endCalcTime: number\n let runCount = 0\n let debug: boolean | undefined\n let debugCache: boolean | undefined\n\n if (process.env.NODE_ENV === 'development') {\n const { debugCache: _debugCache, debugAll } = table.options\n debugCache = _debugCache\n const { parentName } = getFunctionNameInfo(fnName, '.')\n\n const debugByParent =\n // @ts-expect-error\n table.options[\n `debug${(parentName != 'table' ? parentName + 's' : parentName).replace(\n parentName,\n parentName.charAt(0).toUpperCase() + parentName.slice(1),\n )}`\n ]\n const debugByFeature = feature\n ? // @ts-expect-error\n table.options[\n `debug${feature.charAt(0).toUpperCase() + feature.slice(1)}`\n ]\n : false\n\n debug = debugAll || debugByParent || debugByFeature\n }\n\n function logTime(time: number, depsChanged: boolean) {\n const runType =\n runCount === 0\n ? '(1st run)'\n : depsChanged\n ? '(rerun #' + runCount + ')'\n : '(cache)'\n runCount++\n\n console.groupCollapsed(\n `%c⏱ ${pad(`${time.toFixed(1)} ms`, 12)} %c${runType}%c ${fnName}%c ${objectId ? `(${fnName.split('.')[0]}Id: ${objectId})` : ''}`,\n `font-size: .6rem; font-weight: bold; ${\n depsChanged\n ? `color: hsl(\n ${Math.max(0, Math.min(120 - Math.log10(time) * 60, 120))}deg 100% 31%);`\n : ''\n } `,\n `color: ${runCount < 2 ? '#FF00FF' : '#FF1493'}`,\n 'color: #666',\n 'color: #87CEEB',\n )\n console.info({\n feature,\n state: table.store.state,\n deps: memoOptions.memoDeps?.toString(),\n })\n console.trace()\n console.groupEnd()\n }\n\n const onAfterUpdateHandler = () => {\n if (!onAfterUpdate) {\n return\n }\n\n const { schedule, untrack } = table._reactivity\n schedule(() => untrack(() => onAfterUpdate()))\n }\n\n const debugOptions =\n process.env.NODE_ENV === 'development'\n ? {\n onBeforeCompare: () => {\n if (debugCache) {\n beforeCompareTime = performance.now()\n }\n },\n onAfterCompare: (depsChanged: boolean) => {\n if (debugCache) {\n afterCompareTime = performance.now()\n const compareTime =\n Math.round((afterCompareTime - beforeCompareTime) * 100) / 100\n if (!depsChanged) {\n logTime(compareTime, depsChanged)\n }\n }\n },\n onBeforeUpdate: () => {\n if (debug) {\n startCalcTime = performance.now()\n }\n },\n onAfterUpdate: () => {\n if (debug) {\n endCalcTime = performance.now()\n const executionTime =\n Math.round((endCalcTime - startCalcTime) * 100) / 100\n logTime(executionTime, true)\n }\n onAfterUpdateHandler()\n },\n }\n : {\n onAfterUpdate: () => {\n onAfterUpdateHandler()\n },\n }\n\n return memo({\n ...memoOptions,\n ...debugOptions,\n })\n}\n\nexport interface API<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (...args: any) => any\n memoDeps?: (depArgs?: any) => [...any] | undefined\n}\n\nexport type APIObject<TDeps extends ReadonlyArray<any>, TDepArgs> = Record<\n string,\n API<TDeps, TDepArgs>\n>\n\n/**\n * Assumes that a function name is in the format of `parentName_fnKey` and returns the `fnKey` and `fnName` in the format of `parentName.fnKey`.\n */\nexport function getFunctionNameInfo(\n staticFnName: string,\n splitBy: '_' | '.' = '_',\n) {\n const [parentName, fnKey] = staticFnName.split(splitBy)\n const fnName = `${parentName}.${fnKey}`\n return { fnKey, fnName, parentName } as {\n fnKey: string\n fnName: string\n parentName: string\n }\n}\n\n/**\n * Assigns Table API methods directly to the table instance.\n * Unlike row/cell/column/header, the table is a singleton so methods are assigned directly.\n */\nexport function assignTableAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n table: Table_Internal<TFeatures, TData>,\n apis: APIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n ;(table as Record<string, any>)[fnKey] = memoDeps\n ? tableMemo({\n memoDeps,\n fn,\n fnName,\n table,\n feature,\n })\n : fn\n }\n}\n\nexport interface PrototypeAPI<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (self: any, ...args: any) => any\n memoDeps?: (self: any, depArgs?: any) => [...any] | undefined\n}\n\nexport type PrototypeAPIObject<\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n> = Record<string, PrototypeAPI<TDeps, TDepArgs>>\n\n/**\n * Assigns API methods to a prototype object for memory-efficient method sharing.\n * All instances created with this prototype will share the same method references.\n *\n * For memoized methods, the memo state is lazily created and stored on each instance.\n * This provides the best of both worlds: shared method code + per-instance caching.\n */\nexport function assignPrototypeAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n prototype: Record<string, any>,\n table: Table_Internal<TFeatures, TData>,\n apis: PrototypeAPIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n if (memoDeps) {\n // For memoized methods, create a function that lazily initializes\n // the memo on first access and stores it on the instance\n const memoKey = `_memo_${fnKey}`\n\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n // Lazily create memo on first access for this instance\n if (!this[memoKey]) {\n const self = this\n this[memoKey] = tableMemo({\n memoDeps: (depArgs) => memoDeps(self, depArgs),\n fn: (...deps) => fn(self, ...deps),\n fnName,\n objectId: self.id,\n table,\n feature,\n })\n }\n return this[memoKey](...args)\n }\n } else {\n // Non-memoized methods just call the static function with `this`\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n return fn(this, ...args)\n }\n }\n }\n}\n\n/**\n * Looks to run the memoized function with the builder pattern on the object if it exists, otherwise fallback to the static method passed in.\n */\nexport function callMemoOrStaticFn<\n TObject extends Record<string, any>,\n TArgs extends Array<any>,\n TReturn,\n>(\n obj: TObject,\n fnKey: string,\n staticFn: (obj: TObject, ...args: TArgs) => TReturn,\n ...args: TArgs\n): TReturn {\n return (\n (obj[fnKey] as Function | undefined)?.(...args) ?? staticFn(obj, ...args)\n )\n}\n"],"mappings":";;;;;;AAUA,SAAgB,iBAAoB,SAAqB,OAAa;CACpE,OAAO,OAAO,YAAY,aACrB,QAAwB,KAAK,IAC9B;AACN;;;;;;AAOA,SAAgB,WAAc,OAAa;CACzC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,UAAU;CAG7B,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,QAAQ,OAAO,eAAe,KAAK;EAEzC,IAAI,UAAU,OAAO,aAAa,UAAU,MAC1C,OAAO;EAGT,MAAM,OAAgC,UAAU,OAAO,cAAc,IAAI,CAAC;EAC1E,MAAM,OAAO,OAAO,KAAK,KAAK;EAE9B,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,MAAM,KAAK;GACjB,OAAO,eAAe,MAAM,KAAK;IAC/B,cAAc;IACd,YAAY;IACZ,OAAO,WAAY,MAAkC,IAAI;IACzD,UAAU;GACZ,CAAC;EACH;EAEA,OAAO;CACT;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,mCAGd,QAAiB,QAAoC;CACrD,MAAM,OAAO,OAAO,KAAK,MAAM;CAC/B,MAAM,eAAe;CAErB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,IAAI,WAAW,QAAQ,GAC1B,aAAa,OAAO,OAAO;CAE/B;CAEA,OAAO;AACT;;;;;;;AAQA,SAAgB,gBAA0D;CACxE,OAAO,OAAO,OAAO,IAAI;AAC3B;;;;AAKA,SAAgB,OAAO,KAAa,KAA2B;CAC7D,OAAO,OAAO,UAAU,eAAe,KAAK,KAAK,GAAG;AACtD;;;;;;AAOA,SAAgB,iBAId,KAIA,UAIA;CACA,Q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,GAAG,MAAM,GAAG,IAAI;MACjC;MACA,UAAU,KAAK;MACf;MACA;KACF,CAAC;IACH;IACA,OAAO,KAAK,QAAQ,CAAC,GAAG,IAAI;GAC9B;EACF,OAEE,UAAU,SAAS,SAAqB,GAAG,MAAkB;GAC3D,OAAO,GAAG,MAAM,GAAG,IAAI;EACzB;CAEJ;AACF;;;;AAKA,SAAgB,mBAKd,KACA,OACA,UACA,GAAG,MACM;CACT,OACG,IAAI,MAAM,GAA4B,GAAG,IAAI,KAAK,SAAS,KAAK,GAAG,IAAI;AAE5E"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { Table_Internal } from './types/Table'\nimport type { NoInfer, RowData, Updater } from './types/type-utils'\nimport type { TableFeatures } from './types/TableFeatures'\nimport type { TableState, TableState_All } from './types/TableState'\n\n/**\n * Applies a TanStack updater to a value.\n *\n * If the updater is a function it is called with the previous value; otherwise the updater value is returned directly.\n */\nexport function functionalUpdate<T>(updater: Updater<T>, input: T): T {\n return typeof updater === 'function'\n ? (updater as (i: T) => T)(input)\n : updater\n}\n\n/**\n * Clones table state values while preserving non-plain objects.\n *\n * Plain objects and arrays are copied recursively so state updates can avoid mutating existing references.\n */\nexport function cloneState<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map(cloneState) as T\n }\n\n if (value && typeof value === 'object') {\n const proto = Object.getPrototypeOf(value)\n\n if (proto !== Object.prototype && proto !== null) {\n return value\n }\n\n const copy: Record<string, unknown> = proto === null ? makeObjectMap() : {}\n const keys = Object.keys(value)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n Object.defineProperty(copy, key, {\n configurable: true,\n enumerable: true,\n value: cloneState((value as Record<string, unknown>)[key]),\n writable: true,\n })\n }\n\n return copy as T\n }\n\n return value\n}\n\n/**\n * Copies prototype-instance own properties without carrying over lazy memo\n * closures or the per-row cell cache, both of which are bound to the source\n * instance (cached cells reference the source row).\n */\nexport function copyInstancePropertiesWithoutMemos<\n TTarget extends Record<string, any>,\n TSource extends Record<string, any>,\n>(target: TTarget, source: TSource): TTarget & TSource {\n const keys = Object.keys(source)\n const targetRecord = target as Record<string, any>\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]!\n if (!key.startsWith('_memo_') && key !== '_cellsCache') {\n targetRecord[key] = source[key]\n }\n }\n\n return target as TTarget & TSource\n}\n\n/**\n * Creates an object intended only for string-keyed dictionary lookups.\n *\n * The null prototype keeps user-controlled ids such as `__proto__` and\n * `hasOwnProperty` as plain data keys.\n */\nexport function makeObjectMap<TValue = unknown>(): Record<string, TValue> {\n return Object.create(null) as Record<string, TValue>\n}\n\n/**\n * Checks whether an object owns a key, including null-prototype dictionaries.\n */\nexport function hasOwn(obj: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key)\n}\n\n/**\n * Creates a table state updater for a single state slice.\n *\n * The updater writes through the table base atom for the slice and supports both value and functional updater forms.\n */\nexport function makeStateUpdater<\n TFeatures extends TableFeatures,\n K extends (string & {}) | keyof TableState_All | keyof TableState<TFeatures>,\n>(\n key: K,\n // Minimal structural shape so any table view (public `Table`,\n // `Table_Internal`, or a custom plugin table) can be passed without forcing\n // the compiler to relate the full table types.\n instance: {\n readonly options: { readonly atoms?: object | undefined }\n readonly baseAtoms: object\n },\n) {\n return (updater: Updater<TableState<any>[K & keyof TableState<any>]>) => {\n const externalAtom = (instance.options as any).atoms?.[key]\n const targetAtom = externalAtom ?? (instance.baseAtoms as any)[key]\n targetAtom.set((old: any) => functionalUpdate(updater, old))\n }\n}\n\ntype AnyFunction = (...args: any) => any\n\n/**\n * Returns whether a value is a function.\n */\nexport function isFunction<T extends AnyFunction>(d: any): d is T {\n return d instanceof Function\n}\n\n/**\n * Flattens a tree of nodes by recursively reading child nodes.\n *\n * The original nodes are preserved in depth-first order.\n */\nexport function flattenBy<TNode>(\n arr: Array<TNode>,\n getChildren: (item: TNode) => Array<TNode>,\n) {\n const flat: Array<TNode> = []\n\n const recurse = (subArr: Array<TNode>) => {\n subArr.forEach((item) => {\n flat.push(item)\n const children = getChildren(item)\n if (children.length) {\n recurse(children)\n }\n })\n }\n\n recurse(arr)\n\n return flat\n}\n\ninterface MemoOptions<TDeps extends ReadonlyArray<any>, TDepArgs, TResult> {\n fn: (...args: NoInfer<TDeps>) => TResult\n memoDeps?: (depArgs?: TDepArgs) => [...TDeps] | undefined\n onAfterCompare?: (depsChanged: boolean) => void\n onAfterUpdate?: (result: TResult) => void\n onBeforeCompare?: () => void\n onBeforeUpdate?: () => void\n}\n\n/**\n * Creates a dependency-tracked memoized function for table internals.\n *\n * The memo recomputes only when its dependency tuple changes and can emit debug timing information.\n */\nexport const memo = <TDeps extends ReadonlyArray<any>, TDepArgs, TResult>({\n fn,\n memoDeps,\n onAfterCompare,\n onAfterUpdate,\n onBeforeCompare,\n onBeforeUpdate,\n}: MemoOptions<TDeps, TDepArgs, TResult>): ((\n depArgs?: TDepArgs,\n) => TResult) => {\n let deps: Array<any> | undefined = []\n let result: TResult | undefined\n\n const memoizedFn = (depArgs?: TDepArgs): TResult => {\n onBeforeCompare?.()\n const newDeps = memoDeps?.(depArgs)\n let depsChanged = !newDeps || newDeps.length !== deps?.length\n if (!depsChanged && newDeps) {\n for (let i = 0; i < newDeps.length; i++) {\n if (newDeps[i] !== deps![i]) {\n depsChanged = true\n break\n }\n }\n }\n onAfterCompare?.(depsChanged)\n\n if (!depsChanged) {\n return result!\n }\n\n deps = newDeps\n\n onBeforeUpdate?.()\n result = fn(...(newDeps ?? ([] as any)))\n onAfterUpdate?.(result)\n\n return result\n }\n\n return memoizedFn\n}\n\ninterface TableMemoOptions<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n> extends MemoOptions<TDeps, TDepArgs, TResult> {\n feature?: keyof TFeatures & string\n fnName: string\n objectId?: string\n onAfterUpdate?: () => void\n table: Table_Internal<TFeatures, any>\n}\n\nconst pad = (str: number | string, num: number) => {\n str = String(str)\n while (str.length < num) {\n str = ' ' + str\n }\n return str\n}\n\n/**\n * Creates a table-aware memoized function.\n *\n * This wraps `memo` with table debug options and feature metadata so row models and derived APIs can share consistent diagnostics.\n */\nexport function tableMemo<\n TFeatures extends TableFeatures,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n TResult,\n>({\n feature,\n fnName,\n objectId,\n onAfterUpdate,\n table,\n ...memoOptions\n}: TableMemoOptions<TFeatures, TDeps, TDepArgs, TResult>) {\n let beforeCompareTime: number\n let afterCompareTime: number\n let startCalcTime: number\n let endCalcTime: number\n let runCount = 0\n let debug: boolean | undefined\n let debugCache: boolean | undefined\n\n if (process.env.NODE_ENV === 'development') {\n const { debugCache: _debugCache, debugAll } = table.options\n debugCache = _debugCache\n const { parentName } = getFunctionNameInfo(fnName, '.')\n\n const debugByParent =\n // @ts-expect-error\n table.options[\n `debug${(parentName != 'table' ? parentName + 's' : parentName).replace(\n parentName,\n parentName.charAt(0).toUpperCase() + parentName.slice(1),\n )}`\n ]\n const debugByFeature = feature\n ? // @ts-expect-error\n table.options[\n `debug${feature.charAt(0).toUpperCase() + feature.slice(1)}`\n ]\n : false\n\n debug = debugAll || debugByParent || debugByFeature\n }\n\n function logTime(time: number, depsChanged: boolean) {\n const runType =\n runCount === 0\n ? '(1st run)'\n : depsChanged\n ? '(rerun #' + runCount + ')'\n : '(cache)'\n runCount++\n\n console.groupCollapsed(\n `%c⏱ ${pad(`${time.toFixed(1)} ms`, 12)} %c${runType}%c ${fnName}%c ${objectId ? `(${fnName.split('.')[0]}Id: ${objectId})` : ''}`,\n `font-size: .6rem; font-weight: bold; ${\n depsChanged\n ? `color: hsl(\n ${Math.max(0, Math.min(120 - Math.log10(time) * 60, 120))}deg 100% 31%);`\n : ''\n } `,\n `color: ${runCount < 2 ? '#FF00FF' : '#FF1493'}`,\n 'color: #666',\n 'color: #87CEEB',\n )\n console.info({\n feature,\n state: table.store.state,\n deps: memoOptions.memoDeps?.toString(),\n })\n console.trace()\n console.groupEnd()\n }\n\n const onAfterUpdateHandler = () => {\n if (!onAfterUpdate) {\n return\n }\n\n const { schedule, untrack } = table._reactivity\n schedule(() => untrack(() => onAfterUpdate()))\n }\n\n const debugOptions =\n process.env.NODE_ENV === 'development'\n ? {\n onBeforeCompare: () => {\n if (debugCache) {\n beforeCompareTime = performance.now()\n }\n },\n onAfterCompare: (depsChanged: boolean) => {\n if (debugCache) {\n afterCompareTime = performance.now()\n const compareTime =\n Math.round((afterCompareTime - beforeCompareTime) * 100) / 100\n if (!depsChanged) {\n logTime(compareTime, depsChanged)\n }\n }\n },\n onBeforeUpdate: () => {\n if (debug) {\n startCalcTime = performance.now()\n }\n },\n onAfterUpdate: () => {\n if (debug) {\n endCalcTime = performance.now()\n const executionTime =\n Math.round((endCalcTime - startCalcTime) * 100) / 100\n logTime(executionTime, true)\n }\n onAfterUpdateHandler()\n },\n }\n : {\n onAfterUpdate: () => {\n onAfterUpdateHandler()\n },\n }\n\n return memo({\n ...memoOptions,\n ...debugOptions,\n })\n}\n\nexport interface API<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (...args: any) => any\n memoDeps?: (depArgs?: any) => [...any] | undefined\n}\n\nexport type APIObject<TDeps extends ReadonlyArray<any>, TDepArgs> = Record<\n string,\n API<TDeps, TDepArgs>\n>\n\n/**\n * Assumes that a function name is in the format of `parentName_fnKey` and returns the `fnKey` and `fnName` in the format of `parentName.fnKey`.\n */\nexport function getFunctionNameInfo(\n staticFnName: string,\n splitBy: '_' | '.' = '_',\n) {\n const [parentName, fnKey] = staticFnName.split(splitBy)\n const fnName = `${parentName}.${fnKey}`\n return { fnKey, fnName, parentName } as {\n fnKey: string\n fnName: string\n parentName: string\n }\n}\n\n/**\n * Assigns Table API methods directly to the table instance.\n * Unlike row/cell/column/header, the table is a singleton so methods are assigned directly.\n */\nexport function assignTableAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n table: Table_Internal<TFeatures, TData>,\n apis: APIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n ;(table as Record<string, any>)[fnKey] = memoDeps\n ? tableMemo({\n memoDeps,\n fn,\n fnName,\n table,\n feature,\n })\n : fn\n }\n}\n\nexport interface PrototypeAPI<TDeps extends ReadonlyArray<any>, TDepArgs> {\n fn: (self: any, ...args: any) => any\n memoDeps?: (self: any, depArgs?: any) => [...any] | undefined\n}\n\nexport type PrototypeAPIObject<\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n> = Record<string, PrototypeAPI<TDeps, TDepArgs>>\n\n/**\n * Assigns API methods to a prototype object for memory-efficient method sharing.\n * All instances created with this prototype will share the same method references.\n *\n * For memoized methods, the memo state is lazily created and stored on each instance.\n * This provides the best of both worlds: shared method code + per-instance caching.\n */\nexport function assignPrototypeAPIs<\n TFeatures extends TableFeatures,\n TData extends RowData,\n TDeps extends ReadonlyArray<any>,\n TDepArgs,\n>(\n feature: keyof TFeatures & string,\n prototype: Record<string, any>,\n table: Table_Internal<TFeatures, TData>,\n apis: PrototypeAPIObject<TDeps, NoInfer<TDepArgs>>,\n): void {\n for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {\n const { fnKey, fnName } = getFunctionNameInfo(staticFnName)\n\n if (memoDeps) {\n // For memoized methods, create a function that lazily initializes\n // the memo on first access and stores it on the instance\n const memoKey = `_memo_${fnKey}`\n\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n // Lazily create memo on first access for this instance\n if (!this[memoKey]) {\n const self = this\n this[memoKey] = tableMemo({\n memoDeps: (depArgs) => memoDeps(self, depArgs),\n fn: (...deps) => fn(self, ...deps),\n fnName,\n objectId: self.id,\n table,\n feature,\n })\n }\n return this[memoKey](...args)\n }\n } else {\n // Non-memoized methods just call the static function with `this`\n prototype[fnKey] = function (this: any, ...args: Array<any>) {\n return fn(this, ...args)\n }\n }\n }\n}\n\n/**\n * Looks to run the memoized function with the builder pattern on the object if it exists, otherwise fallback to the static method passed in.\n */\nexport function callMemoOrStaticFn<\n TObject extends Record<string, any>,\n TArgs extends Array<any>,\n TReturn,\n>(\n obj: TObject,\n fnKey: string,\n staticFn: (obj: TObject, ...args: TArgs) => TReturn,\n ...args: TArgs\n): TReturn {\n return (\n (obj[fnKey] as Function | undefined)?.(...args) ?? staticFn(obj, ...args)\n )\n}\n"],"mappings":";;;;;;AAUA,SAAgB,iBAAoB,SAAqB,OAAa;CACpE,OAAO,OAAO,YAAY,aACrB,QAAwB,KAAK,IAC9B;AACN;;;;;;AAOA,SAAgB,WAAc,OAAa;CACzC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,UAAU;CAG7B,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,QAAQ,OAAO,eAAe,KAAK;EAEzC,IAAI,UAAU,OAAO,aAAa,UAAU,MAC1C,OAAO;EAGT,MAAM,OAAgC,UAAU,OAAO,cAAc,IAAI,CAAC;EAC1E,MAAM,OAAO,OAAO,KAAK,KAAK;EAE9B,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;GACpC,MAAM,MAAM,KAAK;GACjB,OAAO,eAAe,MAAM,KAAK;IAC/B,cAAc;IACd,YAAY;IACZ,OAAO,WAAY,MAAkC,IAAI;IACzD,UAAU;GACZ,CAAC;EACH;EAEA,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,SAAgB,mCAGd,QAAiB,QAAoC;CACrD,MAAM,OAAO,OAAO,KAAK,MAAM;CAC/B,MAAM,eAAe;CAErB,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,IAAI,WAAW,QAAQ,KAAK,QAAQ,eACvC,aAAa,OAAO,OAAO;CAE/B;CAEA,OAAO;AACT;;;;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GAGZ,MAAM,UAAU,SAAS;GAEzB,UAAU,SAAS,SAAqB,GAAG,MAAkB;IAE3D,IAAI,CAAC,KAAK,UAAU;KAClB,MAAM,OAAO;KACb,KAAK,WAAW,UAAU;MACxB,WAAW,YAAY,SAAS,MAAM,OAAO;MAC7C,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI;MACjC;MACA,UAAU,KAAK;MACf;MACA;KACF,CAAC;IACH;IACA,OAAO,KAAK,QAAQ,CAAC,GAAG,IAAI;GAC9B;EACF,OAEE,UAAU,SAAS,SAAqB,GAAG,MAAkB;GAC3D,OAAO,GAAG,MAAM,GAAG,IAAI;EACzB;CAEJ;AACF;;;;AAKA,SAAgB,mBAKd,KACA,OACA,UACA,GAAG,MACM;CACT,OACG,IAAI,MAAM,GAA4B,GAAG,IAAI,KAAK,SAAS,KAAK,GAAG,IAAI;AAE5E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initTableWorker.cjs","names":["makeObjectMap","constructTable","storeReactivityBindings","serializeRowModel"],"sources":["../../src/worker/initTableWorker.ts"],"sourcesContent":["import { constructTable } from '../core/table/constructTable'\nimport { storeReactivityBindings } from '../store-reactivity-bindings'\nimport { makeObjectMap } from '../utils'\nimport { serializeRowModel } from './serializeRowModel'\nimport type { RowData } from '../types/type-utils'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { TableOptions } from '../types/TableOptions'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRequest,\n TableWorkerResult,\n TableWorkerStage,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\nexport type TableWorkerConfig<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = Omit<TableOptions<TFeatures, TData>, 'data'>\n\nfunction capitalize(stage: string) {\n return stage.charAt(0).toUpperCase() + stage.slice(1)\n}\n\n/** Flatten column-group defs to leaf defs (mirrors core's id resolution). */\nfunction flattenColumnDefs(defs: Array<any>): Array<any> {\n return defs.flatMap((def) =>\n def.columns ? flattenColumnDefs(def.columns) : [def],\n )\n}\n\n/**\n * Runs a headless \"shadow table\" inside a dedicated Web Worker.\n *\n * Call this from a user-authored worker entry file, passing the same columns\n * and processing features used on the main thread. The shadow table runs the\n * real table-core row model pipeline (real fns, real Row objects) off the\n * main thread and posts back one payload per stage the main thread requested:\n * a transferable index permutation for flat results, a serialized row tree\n * (with eagerly computed aggregates) when grouping produces synthetic rows.\n *\n * Everything passed here must be thread-portable: `accessorKey` columns or\n * accessors defined in a shared module, and fns from registries or shared\n * modules (no closures over app state).\n *\n * @example\n * ```ts\n * // table.worker.ts\n * import { initTableWorker } from '@tanstack/table-core/experimental-worker-plugin'\n * import { columns, sharedFeatures } from './tableConfig'\n *\n * initTableWorker({ features: sharedFeatures, columns })\n * ```\n */\nexport function initTableWorker<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(config: TableWorkerConfig<TFeatures, TData>): void {\n let table: Table_Internal<TFeatures, TData> | undefined\n let dataVersion = 0\n let coreIndexById: Record<string, number> = makeObjectMap()\n let aggregateColumnIds: Array<string> = []\n // Last-sent model identity per stage: the memoized getters return stable\n // objects when their inputs did not change, so identity equality is exactly\n // \"this stage's result is unchanged\".\n let lastSentModels: { [K in TableWorkerStage]?: unknown } = {}\n\n self.onmessage = (event: MessageEvent<TableWorkerRequest<TData>>) => {\n const message = event.data\n\n if (message.type === 'data') {\n dataVersion = message.dataVersion\n lastSentModels = {}\n if (!table) {\n table = constructTable<TFeatures, TData>({\n ...(config as TableOptions<TFeatures, TData>),\n features: {\n coreReactivityFeature: storeReactivityBindings(),\n ...config.features,\n },\n data: message.data,\n })
|
|
1
|
+
{"version":3,"file":"initTableWorker.cjs","names":["makeObjectMap","constructTable","storeReactivityBindings","serializeRowModel"],"sources":["../../src/worker/initTableWorker.ts"],"sourcesContent":["import { constructTable } from '../core/table/constructTable'\nimport { storeReactivityBindings } from '../store-reactivity-bindings'\nimport { makeObjectMap } from '../utils'\nimport { serializeRowModel } from './serializeRowModel'\nimport type { RowData } from '../types/type-utils'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { TableOptions } from '../types/TableOptions'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRequest,\n TableWorkerResult,\n TableWorkerStage,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\nexport type TableWorkerConfig<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = Omit<TableOptions<TFeatures, TData>, 'data'>\n\nfunction capitalize(stage: string) {\n return stage.charAt(0).toUpperCase() + stage.slice(1)\n}\n\n/** Flatten column-group defs to leaf defs (mirrors core's id resolution). */\nfunction flattenColumnDefs(defs: Array<any>): Array<any> {\n return defs.flatMap((def) =>\n def.columns ? flattenColumnDefs(def.columns) : [def],\n )\n}\n\n/**\n * Runs a headless \"shadow table\" inside a dedicated Web Worker.\n *\n * Call this from a user-authored worker entry file, passing the same columns\n * and processing features used on the main thread. The shadow table runs the\n * real table-core row model pipeline (real fns, real Row objects) off the\n * main thread and posts back one payload per stage the main thread requested:\n * a transferable index permutation for flat results, a serialized row tree\n * (with eagerly computed aggregates) when grouping produces synthetic rows.\n *\n * Everything passed here must be thread-portable: `accessorKey` columns or\n * accessors defined in a shared module, and fns from registries or shared\n * modules (no closures over app state).\n *\n * @example\n * ```ts\n * // table.worker.ts\n * import { initTableWorker } from '@tanstack/table-core/experimental-worker-plugin'\n * import { columns, sharedFeatures } from './tableConfig'\n *\n * initTableWorker({ features: sharedFeatures, columns })\n * ```\n */\nexport function initTableWorker<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(config: TableWorkerConfig<TFeatures, TData>): void {\n let table: Table_Internal<TFeatures, TData> | undefined\n let dataVersion = 0\n let coreIndexById: Record<string, number> = makeObjectMap()\n let aggregateColumnIds: Array<string> = []\n // Last-sent model identity per stage: the memoized getters return stable\n // objects when their inputs did not change, so identity equality is exactly\n // \"this stage's result is unchanged\".\n let lastSentModels: { [K in TableWorkerStage]?: unknown } = {}\n\n self.onmessage = (event: MessageEvent<TableWorkerRequest<TData>>) => {\n const message = event.data\n\n if (message.type === 'data') {\n dataVersion = message.dataVersion\n lastSentModels = {}\n if (!table) {\n table = constructTable<TFeatures, TData>({\n ...(config as TableOptions<TFeatures, TData>),\n features: {\n coreReactivityFeature: storeReactivityBindings(),\n ...config.features,\n },\n data: message.data,\n })\n // Only columns with an explicit aggregation get eagerly aggregated\n // per group. Sync tables aggregate lazily (visible cells only), so\n // auto-aggregating every column would explode on high-cardinality\n // grouping for values nothing renders. Read the RAW column defs:\n // columnGroupingFeature injects default aggregatedCell/aggregationFn\n // into every resolved columnDef, so the resolved defs can't tell\n // explicit from default.\n aggregateColumnIds = flattenColumnDefs(config.columns as Array<any>)\n .filter(\n (def) => def.aggregationFn != null || def.aggregatedCell != null,\n )\n .map(\n (def) =>\n def.id ??\n (typeof def.accessorKey === 'string'\n ? def.accessorKey.replaceAll('.', '_')\n : undefined),\n )\n .filter((id): id is string => id != null)\n } else {\n table.setOptions((prev) => ({ ...prev, data: message.data }))\n }\n // Map row ids to data positions once per dataset; serialization uses it\n // to express every stage result in terms of core row positions.\n const coreFlatRows = table.getCoreRowModel().flatRows\n coreIndexById = makeObjectMap()\n for (let i = 0; i < coreFlatRows.length; i++) {\n coreIndexById[coreFlatRows[i]!.id] = i\n }\n return\n }\n\n if (!table) return\n\n const start = performance.now()\n\n // Apply the serializable state slices to the shadow table's base atoms.\n table._reactivity.batch(() => {\n for (const [key, value] of Object.entries(message.state)) {\n const baseAtom = (table!.baseAtoms as Record<string, any>)[key]\n if (baseAtom && value !== undefined) {\n baseAtom.set(value)\n }\n }\n })\n\n // Compute exactly the stages the main thread requested, skipping any this\n // shadow table has no row model factory for (the main thread warns).\n const stages: { [K in TableWorkerStage]?: TableWorkerStagePayload } = {}\n const transfer: Array<Transferable> = []\n\n for (const stage of message.stages) {\n if (!(config.features as Record<string, unknown>)[`${stage}RowModel`]) {\n continue\n }\n const model = (table as any)[`get${capitalize(stage)}RowModel`]()\n // Memoized getters return the same object when inputs are unchanged;\n // skip re-serializing (and the main thread skips rebuilding). Safe under\n // single-flight: results are never dropped within a dataVersion.\n if (lastSentModels[stage] === model) {\n stages[stage] = { kind: 'unchanged' }\n continue\n }\n lastSentModels[stage] = model\n stages[stage] = serializeRowModel(\n model,\n coreIndexById,\n aggregateColumnIds,\n transfer,\n )\n }\n\n const response: TableWorkerResult = {\n type: 'result',\n requestId: message.requestId,\n dataVersion,\n stages,\n computeMs: performance.now() - start,\n }\n postMessage(response, { transfer })\n }\n}\n"],"mappings":";;;;;;AAoBA,SAAS,WAAW,OAAe;CACjC,OAAO,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,MAAM,CAAC;AACtD;;AAGA,SAAS,kBAAkB,MAA8B;CACvD,OAAO,KAAK,SAAS,QACnB,IAAI,UAAU,kBAAkB,IAAI,OAAO,IAAI,CAAC,GAAG,CACrD;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBAGd,QAAmD;CACnD,IAAI;CACJ,IAAI,cAAc;CAClB,IAAI,gBAAwCA,4BAAc;CAC1D,IAAI,qBAAoC,CAAC;CAIzC,IAAI,iBAAwD,CAAC;CAE7D,KAAK,aAAa,UAAmD;EACnE,MAAM,UAAU,MAAM;EAEtB,IAAI,QAAQ,SAAS,QAAQ;GAC3B,cAAc,QAAQ;GACtB,iBAAiB,CAAC;GAClB,IAAI,CAAC,OAAO;IACV,QAAQC,sCAAiC;KACvC,GAAI;KACJ,UAAU;MACR,uBAAuBC,0DAAwB;MAC/C,GAAG,OAAO;KACZ;KACA,MAAM,QAAQ;IAChB,CAAC;IAQD,qBAAqB,kBAAkB,OAAO,OAAqB,CAAC,CACjE,QACE,QAAQ,IAAI,iBAAiB,QAAQ,IAAI,kBAAkB,IAC9D,CAAC,CACA,KACE,QACC,IAAI,OACH,OAAO,IAAI,gBAAgB,WACxB,IAAI,YAAY,WAAW,KAAK,GAAG,IACnC,OACR,CAAC,CACA,QAAQ,OAAqB,MAAM,IAAI;GAC5C,OACE,MAAM,YAAY,UAAU;IAAE,GAAG;IAAM,MAAM,QAAQ;GAAK,EAAE;GAI9D,MAAM,eAAe,MAAM,gBAAgB,CAAC,CAAC;GAC7C,gBAAgBF,4BAAc;GAC9B,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KACvC,cAAc,aAAa,EAAE,CAAE,MAAM;GAEvC;EACF;EAEA,IAAI,CAAC,OAAO;EAEZ,MAAM,QAAQ,YAAY,IAAI;EAG9B,MAAM,YAAY,YAAY;GAC5B,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,KAAK,GAAG;IACxD,MAAM,WAAY,MAAO,UAAkC;IAC3D,IAAI,YAAY,UAAU,QACxB,SAAS,IAAI,KAAK;GAEtB;EACF,CAAC;EAID,MAAM,SAAgE,CAAC;EACvE,MAAM,WAAgC,CAAC;EAEvC,KAAK,MAAM,SAAS,QAAQ,QAAQ;GAClC,IAAI,CAAE,OAAO,SAAqC,GAAG,MAAM,YACzD;GAEF,MAAM,QAAS,MAAc,MAAM,WAAW,KAAK,EAAE,UAAU,CAAC;GAIhE,IAAI,eAAe,WAAW,OAAO;IACnC,OAAO,SAAS,EAAE,MAAM,YAAY;IACpC;GACF;GACA,eAAe,SAAS;GACxB,OAAO,SAASG,4CACd,OACA,eACA,oBACA,QACF;EACF;EAEA,MAAM,WAA8B;GAClC,MAAM;GACN,WAAW,QAAQ;GACnB;GACA;GACA,WAAW,YAAY,IAAI,IAAI;EACjC;EACA,YAAY,UAAU,EAAE,SAAS,CAAC;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initTableWorker.js","names":[],"sources":["../../src/worker/initTableWorker.ts"],"sourcesContent":["import { constructTable } from '../core/table/constructTable'\nimport { storeReactivityBindings } from '../store-reactivity-bindings'\nimport { makeObjectMap } from '../utils'\nimport { serializeRowModel } from './serializeRowModel'\nimport type { RowData } from '../types/type-utils'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { TableOptions } from '../types/TableOptions'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRequest,\n TableWorkerResult,\n TableWorkerStage,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\nexport type TableWorkerConfig<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = Omit<TableOptions<TFeatures, TData>, 'data'>\n\nfunction capitalize(stage: string) {\n return stage.charAt(0).toUpperCase() + stage.slice(1)\n}\n\n/** Flatten column-group defs to leaf defs (mirrors core's id resolution). */\nfunction flattenColumnDefs(defs: Array<any>): Array<any> {\n return defs.flatMap((def) =>\n def.columns ? flattenColumnDefs(def.columns) : [def],\n )\n}\n\n/**\n * Runs a headless \"shadow table\" inside a dedicated Web Worker.\n *\n * Call this from a user-authored worker entry file, passing the same columns\n * and processing features used on the main thread. The shadow table runs the\n * real table-core row model pipeline (real fns, real Row objects) off the\n * main thread and posts back one payload per stage the main thread requested:\n * a transferable index permutation for flat results, a serialized row tree\n * (with eagerly computed aggregates) when grouping produces synthetic rows.\n *\n * Everything passed here must be thread-portable: `accessorKey` columns or\n * accessors defined in a shared module, and fns from registries or shared\n * modules (no closures over app state).\n *\n * @example\n * ```ts\n * // table.worker.ts\n * import { initTableWorker } from '@tanstack/table-core/experimental-worker-plugin'\n * import { columns, sharedFeatures } from './tableConfig'\n *\n * initTableWorker({ features: sharedFeatures, columns })\n * ```\n */\nexport function initTableWorker<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(config: TableWorkerConfig<TFeatures, TData>): void {\n let table: Table_Internal<TFeatures, TData> | undefined\n let dataVersion = 0\n let coreIndexById: Record<string, number> = makeObjectMap()\n let aggregateColumnIds: Array<string> = []\n // Last-sent model identity per stage: the memoized getters return stable\n // objects when their inputs did not change, so identity equality is exactly\n // \"this stage's result is unchanged\".\n let lastSentModels: { [K in TableWorkerStage]?: unknown } = {}\n\n self.onmessage = (event: MessageEvent<TableWorkerRequest<TData>>) => {\n const message = event.data\n\n if (message.type === 'data') {\n dataVersion = message.dataVersion\n lastSentModels = {}\n if (!table) {\n table = constructTable<TFeatures, TData>({\n ...(config as TableOptions<TFeatures, TData>),\n features: {\n coreReactivityFeature: storeReactivityBindings(),\n ...config.features,\n },\n data: message.data,\n })
|
|
1
|
+
{"version":3,"file":"initTableWorker.js","names":[],"sources":["../../src/worker/initTableWorker.ts"],"sourcesContent":["import { constructTable } from '../core/table/constructTable'\nimport { storeReactivityBindings } from '../store-reactivity-bindings'\nimport { makeObjectMap } from '../utils'\nimport { serializeRowModel } from './serializeRowModel'\nimport type { RowData } from '../types/type-utils'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { TableOptions } from '../types/TableOptions'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRequest,\n TableWorkerResult,\n TableWorkerStage,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\nexport type TableWorkerConfig<\n TFeatures extends TableFeatures,\n TData extends RowData,\n> = Omit<TableOptions<TFeatures, TData>, 'data'>\n\nfunction capitalize(stage: string) {\n return stage.charAt(0).toUpperCase() + stage.slice(1)\n}\n\n/** Flatten column-group defs to leaf defs (mirrors core's id resolution). */\nfunction flattenColumnDefs(defs: Array<any>): Array<any> {\n return defs.flatMap((def) =>\n def.columns ? flattenColumnDefs(def.columns) : [def],\n )\n}\n\n/**\n * Runs a headless \"shadow table\" inside a dedicated Web Worker.\n *\n * Call this from a user-authored worker entry file, passing the same columns\n * and processing features used on the main thread. The shadow table runs the\n * real table-core row model pipeline (real fns, real Row objects) off the\n * main thread and posts back one payload per stage the main thread requested:\n * a transferable index permutation for flat results, a serialized row tree\n * (with eagerly computed aggregates) when grouping produces synthetic rows.\n *\n * Everything passed here must be thread-portable: `accessorKey` columns or\n * accessors defined in a shared module, and fns from registries or shared\n * modules (no closures over app state).\n *\n * @example\n * ```ts\n * // table.worker.ts\n * import { initTableWorker } from '@tanstack/table-core/experimental-worker-plugin'\n * import { columns, sharedFeatures } from './tableConfig'\n *\n * initTableWorker({ features: sharedFeatures, columns })\n * ```\n */\nexport function initTableWorker<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(config: TableWorkerConfig<TFeatures, TData>): void {\n let table: Table_Internal<TFeatures, TData> | undefined\n let dataVersion = 0\n let coreIndexById: Record<string, number> = makeObjectMap()\n let aggregateColumnIds: Array<string> = []\n // Last-sent model identity per stage: the memoized getters return stable\n // objects when their inputs did not change, so identity equality is exactly\n // \"this stage's result is unchanged\".\n let lastSentModels: { [K in TableWorkerStage]?: unknown } = {}\n\n self.onmessage = (event: MessageEvent<TableWorkerRequest<TData>>) => {\n const message = event.data\n\n if (message.type === 'data') {\n dataVersion = message.dataVersion\n lastSentModels = {}\n if (!table) {\n table = constructTable<TFeatures, TData>({\n ...(config as TableOptions<TFeatures, TData>),\n features: {\n coreReactivityFeature: storeReactivityBindings(),\n ...config.features,\n },\n data: message.data,\n })\n // Only columns with an explicit aggregation get eagerly aggregated\n // per group. Sync tables aggregate lazily (visible cells only), so\n // auto-aggregating every column would explode on high-cardinality\n // grouping for values nothing renders. Read the RAW column defs:\n // columnGroupingFeature injects default aggregatedCell/aggregationFn\n // into every resolved columnDef, so the resolved defs can't tell\n // explicit from default.\n aggregateColumnIds = flattenColumnDefs(config.columns as Array<any>)\n .filter(\n (def) => def.aggregationFn != null || def.aggregatedCell != null,\n )\n .map(\n (def) =>\n def.id ??\n (typeof def.accessorKey === 'string'\n ? def.accessorKey.replaceAll('.', '_')\n : undefined),\n )\n .filter((id): id is string => id != null)\n } else {\n table.setOptions((prev) => ({ ...prev, data: message.data }))\n }\n // Map row ids to data positions once per dataset; serialization uses it\n // to express every stage result in terms of core row positions.\n const coreFlatRows = table.getCoreRowModel().flatRows\n coreIndexById = makeObjectMap()\n for (let i = 0; i < coreFlatRows.length; i++) {\n coreIndexById[coreFlatRows[i]!.id] = i\n }\n return\n }\n\n if (!table) return\n\n const start = performance.now()\n\n // Apply the serializable state slices to the shadow table's base atoms.\n table._reactivity.batch(() => {\n for (const [key, value] of Object.entries(message.state)) {\n const baseAtom = (table!.baseAtoms as Record<string, any>)[key]\n if (baseAtom && value !== undefined) {\n baseAtom.set(value)\n }\n }\n })\n\n // Compute exactly the stages the main thread requested, skipping any this\n // shadow table has no row model factory for (the main thread warns).\n const stages: { [K in TableWorkerStage]?: TableWorkerStagePayload } = {}\n const transfer: Array<Transferable> = []\n\n for (const stage of message.stages) {\n if (!(config.features as Record<string, unknown>)[`${stage}RowModel`]) {\n continue\n }\n const model = (table as any)[`get${capitalize(stage)}RowModel`]()\n // Memoized getters return the same object when inputs are unchanged;\n // skip re-serializing (and the main thread skips rebuilding). Safe under\n // single-flight: results are never dropped within a dataVersion.\n if (lastSentModels[stage] === model) {\n stages[stage] = { kind: 'unchanged' }\n continue\n }\n lastSentModels[stage] = model\n stages[stage] = serializeRowModel(\n model,\n coreIndexById,\n aggregateColumnIds,\n transfer,\n )\n }\n\n const response: TableWorkerResult = {\n type: 'result',\n requestId: message.requestId,\n dataVersion,\n stages,\n computeMs: performance.now() - start,\n }\n postMessage(response, { transfer })\n }\n}\n"],"mappings":";;;;;;AAoBA,SAAS,WAAW,OAAe;CACjC,OAAO,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,MAAM,MAAM,CAAC;AACtD;;AAGA,SAAS,kBAAkB,MAA8B;CACvD,OAAO,KAAK,SAAS,QACnB,IAAI,UAAU,kBAAkB,IAAI,OAAO,IAAI,CAAC,GAAG,CACrD;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBAGd,QAAmD;CACnD,IAAI;CACJ,IAAI,cAAc;CAClB,IAAI,gBAAwC,cAAc;CAC1D,IAAI,qBAAoC,CAAC;CAIzC,IAAI,iBAAwD,CAAC;CAE7D,KAAK,aAAa,UAAmD;EACnE,MAAM,UAAU,MAAM;EAEtB,IAAI,QAAQ,SAAS,QAAQ;GAC3B,cAAc,QAAQ;GACtB,iBAAiB,CAAC;GAClB,IAAI,CAAC,OAAO;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W,QAAQ;GACnB;GACA;GACA,WAAW,YAAY,IAAI,IAAI;EACjC;EACA,YAAY,UAAU,EAAE,SAAS,CAAC;CACpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rebuildRowModel.cjs","names":["constructRow","hasOwn"],"sources":["../../src/worker/rebuildRowModel.ts"],"sourcesContent":["import { constructRow } from '../core/rows/constructRow'\nimport { hasOwn } from '../utils'\nimport type { RowModel } from '../core/row-models/coreRowModelsFeature.types'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRowNode,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\n/** Payloads that carry data; `unchanged` never reaches the rebuilder. */\nexport type TableWorkerDataPayload = Exclude<\n TableWorkerStagePayload,\n { kind: 'unchanged' }\n>\n\
|
|
1
|
+
{"version":3,"file":"rebuildRowModel.cjs","names":["constructRow","hasOwn"],"sources":["../../src/worker/rebuildRowModel.ts"],"sourcesContent":["import { constructRow } from '../core/rows/constructRow'\nimport { hasOwn } from '../utils'\nimport type { RowModel } from '../core/row-models/coreRowModelsFeature.types'\nimport type { Table_Internal } from '../types/Table'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { RowData } from '../types/type-utils'\nimport type {\n TableWorkerRowNode,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\n/** Payloads that carry data; `unchanged` never reaches the rebuilder. */\nexport type TableWorkerDataPayload = Exclude<\n TableWorkerStagePayload,\n { kind: 'unchanged' }\n>\n\n// Main-thread side: payload + this table's core rows -> RowModel. Mirrors how\n// the sync row models treat rows: data rows are reused (with depth/parentId\n// rewritten, exactly like createGroupedRowModel does), synthetic group rows\n// are reconstructed via constructRow with their worker-computed aggregates\n// pre-seeded so no aggregation ever runs on the main thread.\n\nfunction collectLeafRows(subRows: Array<any>, out: Array<any>) {\n for (let i = 0; i < subRows.length; i++) {\n const row = subRows[i]\n if (row.groupingColumnId == null) {\n out.push(row)\n } else {\n collectLeafRows(row.subRows, out)\n }\n }\n}\n\nexport function rebuildRowModel<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n table: Table_Internal<TFeatures, TData>,\n payload: TableWorkerDataPayload,\n /**\n * Whether a flat payload should rewrite row depth/parentId. Mirrors core:\n * the grouped model's passthrough resets them, the filtered model never\n * touches them. Without this distinction a filtered rebuild could zero the\n * depths a grouped/sorted tree rebuild just assigned to shared row objects.\n */\n resetDepths: boolean,\n): RowModel<TFeatures, TData> {\n const core = table.getCoreRowModel()\n\n if (payload.kind === 'flat') {\n const { indices } = payload\n const rows = new Array(indices.length)\n for (let i = 0; i < indices.length; i++) {\n const row: any = core.flatRows[indices[i]!]!\n if (resetDepths) {\n row.depth = 0\n row.parentId = undefined\n }\n rows[i] = row\n }\n return { rows, flatRows: rows, rowsById: core.rowsById }\n }\n\n const flatRows: Array<any> = []\n // Data rows resolve through the prototype chain to the core map; only\n // synthetic group rows are added on top.\n const rowsById: Record<string, any> = Object.create(core.rowsById)\n\n const rebuildRows = (\n nodes: Array<TableWorkerRowNode>,\n depth: number,\n parentId: string | undefined,\n ): Array<any> => {\n const rows = new Array(nodes.length)\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]!\n if (typeof node === 'number') {\n const row: any = core.flatRows[node]!\n row.depth = depth\n row.parentId = parentId\n flatRows.push(row)\n rows[i] = row\n continue\n }\n\n const subRows = rebuildRows(node.children, depth + 1, node.id)\n const leafRows: Array<any> = []\n collectLeafRows(subRows, leafRows)\n\n const row: any = constructRow(\n table,\n node.id,\n leafRows[0]?.original,\n node.index,\n depth,\n undefined,\n parentId,\n )\n const aggregates = node.aggregates\n Object.assign(row, {\n groupingColumnId: node.groupingColumnId,\n groupingValue: node.groupingValue,\n subRows,\n leafRows,\n getValue: (columnId: string) =>\n hasOwn(aggregates, columnId) ? aggregates[columnId] : undefined,\n })\n\n flatRows.push(row)\n rowsById[node.id] = row\n rows[i] = row\n }\n return rows\n }\n\n const rows = rebuildRows(payload.children, 0, undefined)\n\n return {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,QACA,QACF;GACA,MAAM,aAAa,KAAK;GACxB,OAAO,OAAO,KAAK;IACjB,kBAAkB,KAAK;IACvB,eAAe,KAAK;IACpB;IACA;IACA,WAAW,aACTC,qBAAO,YAAY,QAAQ,IAAI,WAAW,YAAY;GAC1D,CAAC;GAED,SAAS,KAAK,GAAG;GACjB,SAAS,KAAK,MAAM;GACpB,KAAK,KAAK;EACZ;EACA,OAAO;CACT;CAIA,OAAO;EAAE,MAFI,YAAY,QAAQ,UAAU,GAAG,MAElC;EAAG;EAAU;CAAS;AACpC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rebuildRowModel.js","names":[],"sources":["../../src/worker/rebuildRowModel.ts"],"sourcesContent":["import { constructRow } from '../core/rows/constructRow'\nimport { hasOwn } from '../utils'\nimport type { RowModel } from '../core/row-models/coreRowModelsFeature.types'\nimport type { Table_Internal } from '../types/Table'\nimport type {\n TableWorkerRowNode,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\n/** Payloads that carry data; `unchanged` never reaches the rebuilder. */\nexport type TableWorkerDataPayload = Exclude<\n TableWorkerStagePayload,\n { kind: 'unchanged' }\n>\n\
|
|
1
|
+
{"version":3,"file":"rebuildRowModel.js","names":[],"sources":["../../src/worker/rebuildRowModel.ts"],"sourcesContent":["import { constructRow } from '../core/rows/constructRow'\nimport { hasOwn } from '../utils'\nimport type { RowModel } from '../core/row-models/coreRowModelsFeature.types'\nimport type { Table_Internal } from '../types/Table'\nimport type { TableFeatures } from '../types/TableFeatures'\nimport type { RowData } from '../types/type-utils'\nimport type {\n TableWorkerRowNode,\n TableWorkerStagePayload,\n} from './tableWorkerProtocol'\n\n/** Payloads that carry data; `unchanged` never reaches the rebuilder. */\nexport type TableWorkerDataPayload = Exclude<\n TableWorkerStagePayload,\n { kind: 'unchanged' }\n>\n\n// Main-thread side: payload + this table's core rows -> RowModel. Mirrors how\n// the sync row models treat rows: data rows are reused (with depth/parentId\n// rewritten, exactly like createGroupedRowModel does), synthetic group rows\n// are reconstructed via constructRow with their worker-computed aggregates\n// pre-seeded so no aggregation ever runs on the main thread.\n\nfunction collectLeafRows(subRows: Array<any>, out: Array<any>) {\n for (let i = 0; i < subRows.length; i++) {\n const row = subRows[i]\n if (row.groupingColumnId == null) {\n out.push(row)\n } else {\n collectLeafRows(row.subRows, out)\n }\n }\n}\n\nexport function rebuildRowModel<\n TFeatures extends TableFeatures,\n TData extends RowData,\n>(\n table: Table_Internal<TFeatures, TData>,\n payload: TableWorkerDataPayload,\n /**\n * Whether a flat payload should rewrite row depth/parentId. Mirrors core:\n * the grouped model's passthrough resets them, the filtered model never\n * touches them. Without this distinction a filtered rebuild could zero the\n * depths a grouped/sorted tree rebuild just assigned to shared row objects.\n */\n resetDepths: boolean,\n): RowModel<TFeatures, TData> {\n const core = table.getCoreRowModel()\n\n if (payload.kind === 'flat') {\n const { indices } = payload\n const rows = new Array(indices.length)\n for (let i = 0; i < indices.length; i++) {\n const row: any = core.flatRows[indices[i]!]!\n if (resetDepths) {\n row.depth = 0\n row.parentId = undefined\n }\n rows[i] = row\n }\n return { rows, flatRows: rows, rowsById: core.rowsById }\n }\n\n const flatRows: Array<any> = []\n // Data rows resolve through the prototype chain to the core map; only\n // synthetic group rows are added on top.\n const rowsById: Record<string, any> = Object.create(core.rowsById)\n\n const rebuildRows = (\n nodes: Array<TableWorkerRowNode>,\n depth: number,\n parentId: string | undefined,\n ): Array<any> => {\n const rows = new Array(nodes.length)\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]!\n if (typeof node === 'number') {\n const row: any = core.flatRows[node]!\n row.depth = depth\n row.parentId = parentId\n flatRows.push(row)\n rows[i] = row\n continue\n }\n\n const subRows = rebuildRows(node.children, depth + 1, node.id)\n const leafRows: Array<any> = []\n collectLeafRows(subRows, leafRows)\n\n const row: any = constructRow(\n table,\n node.id,\n leafRows[0]?.original,\n node.index,\n depth,\n undefined,\n parentId,\n )\n const aggregates = node.aggregates\n Object.assign(row, {\n groupingColumnId: node.groupingColumnId,\n groupingValue: node.groupingValue,\n subRows,\n leafRows,\n getValue: (columnId: string) =>\n hasOwn(aggregates, columnId) ? aggregates[columnId] : undefined,\n })\n\n flatRows.push(row)\n rowsById[node.id] = row\n rows[i] = row\n }\n return rows\n }\n\n const rows = rebuildRows(payload.children, 0, undefined)\n\n return { rows, flatRows, rowsById }\n}\n"],"mappings":";;;;AAuBA,SAAS,gBAAgB,SAAqB,KAAiB;CAC7D,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,MAAM,QAAQ;EACpB,IAAI,IAAI,oBAAoB,MAC1B,IAAI,KAAK,GAAG;OAEZ,gBAAgB,IAAI,SAAS,GAAG;CAEpC;AACF;AAEA,SAAgB,gBAId,OACA,SAOA,aAC4B;CAC5B,MAAM,OAAO,MAAM,gBAAgB;CAEnC,IAAI,QAAQ,SAAS,QAAQ;EAC3B,MAAM,EAAE,YAAY;EACpB,MAAM,OAAO,IAAI,MAAM,QAAQ,MAAM;EACrC,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;GACvC,MAAM,MAAW,KAAK,SAAS,QAAQ;GACvC,IAAI,aAAa;IACf,IAAI,QAAQ;IACZ,IAAI,WAAW;GACjB;GACA,KAAK,KAAK;EACZ;EACA,OAAO;GAAE;GAAM,UAAU;GAAM,UAAU,KAAK;EAAS;CACzD;CAEA,MAAM,WAAuB,CAAC;CAG9B,MAAM,WAAgC,OAAO,OAAO,KAAK,QAAQ;CAEjE,MAAM,eACJ,OACA,OACA,aACe;EACf,MAAM,OAAO,IAAI,MAAM,MAAM,MAAM;EACnC,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;GACrC,MAAM,OAAO,MAAM;GACnB,IAAI,OAAO,SAAS,UAAU;IAC5B,MAAM,MAAW,KAAK,SAAS;IAC/B,IAAI,QAAQ;IACZ,IAAI,WAAW;IACf,SAAS,KAAK,GAAG;IACjB,KAAK,KAAK;IACV;GACF;GAEA,MAAM,UAAU,YAAY,KAAK,UAAU,QAAQ,GAAG,KAAK,EAAE;GAC7D,MAAM,WAAuB,CAAC;GAC9B,gBAAgB,SAAS,QAAQ;GAEjC,MAAM,MAAW,aACf,OACA,KAAK,IACL,SAAS,EAAE,EAAE,UACb,KAAK,OACL,OACA,QACA,QACF;GACA,MAAM,aAAa,KAAK;GACxB,OAAO,OAAO,KAAK;IACjB,kBAAkB,KAAK;IACvB,eAAe,KAAK;IACpB;IACA;IACA,WAAW,aACT,OAAO,YAAY,QAAQ,IAAI,WAAW,YAAY;GAC1D,CAAC;GAED,SAAS,KAAK,GAAG;GACjB,SAAS,KAAK,MAAM;GACpB,KAAK,KAAK;EACZ;EACA,OAAO;CACT;CAIA,OAAO;EAAE,MAFI,YAAY,QAAQ,UAAU,GAAG,MAElC;EAAG;EAAU;CAAS;AACpC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/table-core",
|
|
3
|
-
"version": "9.0.0-beta.
|
|
3
|
+
"version": "9.0.0-beta.36",
|
|
4
4
|
"description": "Headless UI for building powerful tables & datagrids for TS/JS.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -73,6 +73,7 @@
|
|
|
73
73
|
"clean": "rimraf ./build && rimraf ./dist",
|
|
74
74
|
"lint:fix": "eslint ./src --fix",
|
|
75
75
|
"test:eslint": "eslint ./src",
|
|
76
|
+
"test:coverage": "vitest run --coverage",
|
|
76
77
|
"test:lib": "vitest",
|
|
77
78
|
"test:lib:dev": "pnpm test:lib --watch",
|
|
78
79
|
"test:types": "tsc && tsc -p tests/tsconfig.declaration-emit.json",
|
|
@@ -3,11 +3,16 @@ import type { RowData } from '../../types/type-utils'
|
|
|
3
3
|
import type { TableFeatures } from '../../types/TableFeatures'
|
|
4
4
|
import type { Row } from '../../types/Row'
|
|
5
5
|
import type { Cell } from '../../types/Cell'
|
|
6
|
+
import type { Column } from '../../types/Column'
|
|
6
7
|
|
|
7
8
|
export interface Row_CoreProperties<
|
|
8
9
|
in out TFeatures extends TableFeatures,
|
|
9
10
|
in out TData extends RowData,
|
|
10
11
|
> {
|
|
12
|
+
_cellsCache?: WeakMap<
|
|
13
|
+
Column<TFeatures, TData, unknown>,
|
|
14
|
+
Cell<TFeatures, TData, unknown>
|
|
15
|
+
>
|
|
11
16
|
_uniqueValuesCache: Record<string, unknown>
|
|
12
17
|
_valuesCache: Record<string, unknown>
|
|
13
18
|
/**
|
|
@@ -169,11 +169,23 @@ export function row_getAllCells<
|
|
|
169
169
|
TData extends RowData,
|
|
170
170
|
>(row: Row<TFeatures, TData>): Array<Cell<TFeatures, TData, unknown>> {
|
|
171
171
|
const columns = row.table.getAllLeafColumns()
|
|
172
|
+
// WeakMap so cells keyed by replaced column instances can be collected;
|
|
173
|
+
// rows are memoized on data only and outlive column generations
|
|
174
|
+
let cache = row._cellsCache
|
|
175
|
+
if (!cache) {
|
|
176
|
+
cache = row._cellsCache = new WeakMap()
|
|
177
|
+
}
|
|
172
178
|
const cells: Array<Cell<TFeatures, TData, unknown>> = new Array(
|
|
173
179
|
columns.length,
|
|
174
180
|
)
|
|
175
181
|
for (let i = 0; i < columns.length; i++) {
|
|
176
|
-
|
|
182
|
+
const column = columns[i]!
|
|
183
|
+
let cell = cache.get(column)
|
|
184
|
+
if (!cell) {
|
|
185
|
+
cell = constructCell(column, row, row.table)
|
|
186
|
+
cache.set(column, cell)
|
|
187
|
+
}
|
|
188
|
+
cells[i] = cell
|
|
177
189
|
}
|
|
178
190
|
return cells
|
|
179
191
|
}
|
|
@@ -74,13 +74,13 @@ export type ExternalAtoms<TFeatures extends TableFeatures> = Partial<{
|
|
|
74
74
|
* use optional chaining (`table.atoms.columnPinning?.get() ?? default`).
|
|
75
75
|
*/
|
|
76
76
|
export type BaseAtoms_All = {
|
|
77
|
-
[K in keyof TableState_All]?: Atom<TableState_All[K]
|
|
77
|
+
[K in keyof TableState_All]?: Atom<Exclude<TableState_All[K], undefined>>
|
|
78
78
|
}
|
|
79
79
|
export type Atoms_All = {
|
|
80
80
|
[K in keyof TableState_All]?: ReadonlyAtom<TableState_All[K]>
|
|
81
81
|
}
|
|
82
82
|
export type ExternalAtoms_All = Partial<{
|
|
83
|
-
[K in keyof TableState_All]: Atom<TableState_All[K]
|
|
83
|
+
[K in keyof TableState_All]: Atom<Exclude<TableState_All[K], undefined>>
|
|
84
84
|
}>
|
|
85
85
|
|
|
86
86
|
export interface TableOptions_Table<
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
column_getIsFirstColumn,
|
|
9
9
|
column_getIsLastColumn,
|
|
10
10
|
getDefaultColumnOrderState,
|
|
11
|
+
table_getColumnIndexes,
|
|
11
12
|
table_getOrderColumnsFn,
|
|
12
13
|
table_resetColumnOrder,
|
|
13
14
|
table_setColumnOrder,
|
|
@@ -35,14 +36,6 @@ export const columnOrderingFeature: TableFeature = {
|
|
|
35
36
|
assignPrototypeAPIs('columnOrderingFeature', prototype, table, {
|
|
36
37
|
column_getIndex: {
|
|
37
38
|
fn: (column, position) => column_getIndex(column, position),
|
|
38
|
-
memoDeps: (column, position) => [
|
|
39
|
-
position,
|
|
40
|
-
column.table.atoms.columnOrder?.get(),
|
|
41
|
-
column.table.atoms.columnPinning?.get(),
|
|
42
|
-
column.table.atoms.grouping?.get(),
|
|
43
|
-
column.table.atoms.columnVisibility?.get(),
|
|
44
|
-
column.table.options.groupedColumnMode,
|
|
45
|
-
],
|
|
46
39
|
},
|
|
47
40
|
column_getIsFirstColumn: {
|
|
48
41
|
fn: (column, position) => column_getIsFirstColumn(column, position),
|
|
@@ -55,6 +48,17 @@ export const columnOrderingFeature: TableFeature = {
|
|
|
55
48
|
|
|
56
49
|
constructTableAPIs: (table) => {
|
|
57
50
|
assignTableAPIs('columnOrderingFeature', table, {
|
|
51
|
+
table_getColumnIndexes: {
|
|
52
|
+
fn: () => table_getColumnIndexes(table),
|
|
53
|
+
memoDeps: () => [
|
|
54
|
+
table.options.columns,
|
|
55
|
+
table.atoms.columnOrder?.get(),
|
|
56
|
+
table.atoms.columnPinning?.get(),
|
|
57
|
+
table.atoms.columnVisibility?.get(),
|
|
58
|
+
table.atoms.grouping?.get(),
|
|
59
|
+
table.options.groupedColumnMode,
|
|
60
|
+
],
|
|
61
|
+
},
|
|
58
62
|
table_setColumnOrder: {
|
|
59
63
|
fn: (updater) => table_setColumnOrder(table, updater),
|
|
60
64
|
},
|
|
@@ -4,6 +4,25 @@ import type { ColumnPinningPosition } from '../column-pinning/columnPinningFeatu
|
|
|
4
4
|
|
|
5
5
|
export type ColumnOrderState = Array<string>
|
|
6
6
|
|
|
7
|
+
export interface ColumnIndexes {
|
|
8
|
+
/**
|
|
9
|
+
* Maps each visible leaf column id to its index in the full visible column list.
|
|
10
|
+
*/
|
|
11
|
+
all: Record<string, number>
|
|
12
|
+
/**
|
|
13
|
+
* Maps each unpinned visible leaf column id to its index within the center region.
|
|
14
|
+
*/
|
|
15
|
+
center: Record<string, number>
|
|
16
|
+
/**
|
|
17
|
+
* Maps each left-pinned visible leaf column id to its index within the left region.
|
|
18
|
+
*/
|
|
19
|
+
left: Record<string, number>
|
|
20
|
+
/**
|
|
21
|
+
* Maps each right-pinned visible leaf column id to its index within the right region.
|
|
22
|
+
*/
|
|
23
|
+
right: Record<string, number>
|
|
24
|
+
}
|
|
25
|
+
|
|
7
26
|
export interface TableState_ColumnOrdering {
|
|
8
27
|
columnOrder: ColumnOrderState
|
|
9
28
|
}
|
|
@@ -47,6 +66,13 @@ export interface Table_ColumnOrdering<
|
|
|
47
66
|
in out TFeatures extends TableFeatures,
|
|
48
67
|
in out TData extends RowData,
|
|
49
68
|
> {
|
|
69
|
+
/**
|
|
70
|
+
* Builds column-id to index records for each visible pinning region.
|
|
71
|
+
*
|
|
72
|
+
* This is the memoized source that `column.getIndex` reads from; most apps
|
|
73
|
+
* will not need to call it directly.
|
|
74
|
+
*/
|
|
75
|
+
getColumnIndexes: () => ColumnIndexes
|
|
50
76
|
/**
|
|
51
77
|
* Resets `columnOrder` to `initialState.columnOrder`.
|
|
52
78
|
*
|