-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathutils.ts
More file actions
executable file
·418 lines (373 loc) · 11.3 KB
/
utils.ts
File metadata and controls
executable file
·418 lines (373 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import type { Table, Table_Internal } from './types/Table'
import type { NoInfer, RowData, Updater } from './types/type-utils'
import type { TableFeatures } from './types/TableFeatures'
import type { TableState, TableState_All } from './types/TableState'
export function functionalUpdate<T>(updater: Updater<T>, input: T): T {
return typeof updater === 'function'
? (updater as (i: T) => T)(input)
: updater
}
export function shallowEqual<T>(a: T, b: T): boolean {
if (Object.is(a, b)) return true
if (
typeof a !== 'object' ||
typeof b !== 'object' ||
a === null ||
b === null
) {
return false
}
const keysA = Object.keys(a)
const keysB = Object.keys(b)
if (keysA.length !== keysB.length) return false
for (const key of keysA) {
if (!Object.is((a as any)[key], (b as any)[key])) return false
}
return true
}
export function noop() {}
export function makeStateUpdater<
TFeatures extends TableFeatures,
K extends (string & {}) | keyof TableState_All | keyof TableState<TFeatures>,
>(key: K, instance: Table<TFeatures, any>) {
return (updater: Updater<TableState<any>[K & keyof TableState<any>]>) => {
instance.baseStore.setState(
<TTableState extends TableState_All>(old: TTableState) => {
return {
...old,
[key]: functionalUpdate(updater, (old as any)[key]),
}
},
)
}
}
type AnyFunction = (...args: any) => any
export function isFunction<T extends AnyFunction>(d: any): d is T {
return d instanceof Function
}
export function isNumberArray(d: any): d is Array<number> {
return Array.isArray(d) && d.every((val) => typeof val === 'number')
}
export function flattenBy<TNode>(
arr: Array<TNode>,
getChildren: (item: TNode) => Array<TNode>,
) {
const flat: Array<TNode> = []
const recurse = (subArr: Array<TNode>) => {
subArr.forEach((item) => {
flat.push(item)
const children = getChildren(item)
if (children.length) {
recurse(children)
}
})
}
recurse(arr)
return flat
}
export const $internalMemoFnMeta = Symbol('memoFnMeta')
export type MemoFnMeta = { originalArgsLength?: number }
/**
* @internal
*/
function setMemoFnMeta(fn: Function, meta: MemoFnMeta) {
Object.defineProperty(fn, $internalMemoFnMeta, { value: meta })
}
/**
* @internal
*/
export function getMemoFnMeta(fn: any): MemoFnMeta | null {
return (typeof fn === 'function' && fn[$internalMemoFnMeta]) ?? null
}
interface MemoOptions<TDeps extends ReadonlyArray<any>, TDepArgs, TResult> {
fn: (...args: NoInfer<TDeps>) => TResult
memoDeps?: (depArgs?: TDepArgs) => [...TDeps] | undefined
onAfterCompare?: (depsChanged: boolean) => void
onAfterUpdate?: (result: TResult) => void
onBeforeCompare?: () => void
onBeforeUpdate?: () => void
}
export const memo = <TDeps extends ReadonlyArray<any>, TDepArgs, TResult>({
fn,
memoDeps,
onAfterCompare,
onAfterUpdate,
onBeforeCompare,
onBeforeUpdate,
}: MemoOptions<TDeps, TDepArgs, TResult>): ((
depArgs?: TDepArgs,
) => TResult) => {
let deps: Array<any> | undefined = []
let result: TResult | undefined
const memoizedFn = (depArgs?: TDepArgs): TResult => {
onBeforeCompare?.()
const newDeps = memoDeps?.(depArgs)
const depsChanged =
!newDeps ||
newDeps.length !== deps?.length ||
newDeps.some((dep: any, index: number) => deps?.[index] !== dep)
onAfterCompare?.(depsChanged)
if (!depsChanged) {
return result!
}
deps = newDeps
onBeforeUpdate?.()
result = fn(...(newDeps ?? ([] as any)))
onAfterUpdate?.(result)
return result
}
setMemoFnMeta(memoizedFn, { originalArgsLength: fn.length })
return memoizedFn
}
interface TableMemoOptions<
TFeatures extends TableFeatures,
TDeps extends ReadonlyArray<any>,
TDepArgs,
TResult,
> extends MemoOptions<TDeps, TDepArgs, TResult> {
feature?: keyof TFeatures & string
fnName: string
objectId?: string
onAfterUpdate?: () => void
table: Table_Internal<TFeatures, any>
}
const pad = (str: number | string, num: number) => {
str = String(str)
while (str.length < num) {
str = ' ' + str
}
return str
}
export function tableMemo<
TFeatures extends TableFeatures,
TDeps extends ReadonlyArray<any>,
TDepArgs,
TResult,
>({
feature,
fnName,
objectId,
onAfterUpdate,
table,
...memoOptions
}: TableMemoOptions<TFeatures, TDeps, TDepArgs, TResult>) {
let beforeCompareTime: number
let afterCompareTime: number
let startCalcTime: number
let endCalcTime: number
let runCount = 0
let debug: boolean | undefined
let debugCache: boolean | undefined
if (process.env.NODE_ENV === 'development') {
const { debugCache: _debugCache, debugAll } = table.options
debugCache = _debugCache
const { parentName } = getFunctionNameInfo(fnName, '.')
const debugByParent =
// @ts-expect-error
table.options[
`debug${(parentName != 'table' ? parentName + 's' : parentName).replace(
parentName,
parentName.charAt(0).toUpperCase() + parentName.slice(1),
)}`
]
const debugByFeature = feature
? // @ts-expect-error
table.options[
`debug${feature.charAt(0).toUpperCase() + feature.slice(1)}`
]
: false
debug = debugAll || debugByParent || debugByFeature
}
function logTime(time: number, depsChanged: boolean) {
const runType =
runCount === 0
? '(1st run)'
: depsChanged
? '(rerun #' + runCount + ')'
: '(cache)'
runCount++
console.groupCollapsed(
`%c⏱ ${pad(`${time.toFixed(1)} ms`, 12)} %c${runType}%c ${fnName}%c ${objectId ? `(${fnName.split('.')[0]}Id: ${objectId})` : ''}`,
`font-size: .6rem; font-weight: bold; ${
depsChanged
? `color: hsl(
${Math.max(0, Math.min(120 - Math.log10(time) * 60, 120))}deg 100% 31%);`
: ''
} `,
`color: ${runCount < 2 ? '#FF00FF' : '#FF1493'}`,
'color: #666',
'color: #87CEEB',
)
console.info({
feature,
state: table.store.state,
deps: memoOptions.memoDeps?.toString(),
})
console.trace()
console.groupEnd()
}
const debugOptions =
process.env.NODE_ENV === 'development'
? {
onBeforeCompare: () => {
if (debugCache) {
beforeCompareTime = performance.now()
}
},
onAfterCompare: (depsChanged: boolean) => {
if (debugCache) {
afterCompareTime = performance.now()
const compareTime =
Math.round((afterCompareTime - beforeCompareTime) * 100) / 100
if (!depsChanged) {
logTime(compareTime, depsChanged)
}
}
},
onBeforeUpdate: () => {
if (debug) {
startCalcTime = performance.now()
}
},
onAfterUpdate: () => {
if (debug) {
endCalcTime = performance.now()
const executionTime =
Math.round((endCalcTime - startCalcTime) * 100) / 100
logTime(executionTime, true)
}
queueMicrotask(() => onAfterUpdate?.())
},
}
: {
onAfterUpdate: () => {
queueMicrotask(() => onAfterUpdate?.())
},
}
return memo({
...memoOptions,
...debugOptions,
})
}
export interface API<TDeps extends ReadonlyArray<any>, TDepArgs> {
fn: (...args: any) => any
memoDeps?: (depArgs?: any) => [...any] | undefined
}
export type APIObject<TDeps extends ReadonlyArray<any>, TDepArgs> = Record<
string,
API<TDeps, TDepArgs>
>
/**
* Assumes that a function name is in the format of `parentName_fnKey` and returns the `fnKey` and `fnName` in the format of `parentName.fnKey`.
*/
export function getFunctionNameInfo(
staticFnName: string,
splitBy: '_' | '.' = '_',
) {
const [parentName, fnKey] = staticFnName.split(splitBy)
const fnName = `${parentName}.${fnKey}`
return { fnKey, fnName, parentName } as {
fnKey: string
fnName: string
parentName: string
}
}
/**
* Assigns Table API methods directly to the table instance.
* Unlike row/cell/column/header, the table is a singleton so methods are assigned directly.
*/
export function assignTableAPIs<
TFeatures extends TableFeatures,
TData extends RowData,
TDeps extends ReadonlyArray<any>,
TDepArgs,
>(
feature: keyof TFeatures & string,
table: Table_Internal<TFeatures, TData>,
apis: APIObject<TDeps, NoInfer<TDepArgs>>,
): void {
for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {
const { fnKey, fnName } = getFunctionNameInfo(staticFnName)
;(table as Record<string, any>)[fnKey] = memoDeps
? tableMemo({
memoDeps,
fn,
fnName,
table,
feature,
})
: fn
}
}
export interface PrototypeAPI<TDeps extends ReadonlyArray<any>, TDepArgs> {
fn: (self: any, ...args: any) => any
memoDeps?: (self: any, depArgs?: any) => [...any] | undefined
}
export type PrototypeAPIObject<
TDeps extends ReadonlyArray<any>,
TDepArgs,
> = Record<string, PrototypeAPI<TDeps, TDepArgs>>
/**
* Assigns API methods to a prototype object for memory-efficient method sharing.
* All instances created with this prototype will share the same method references.
*
* For memoized methods, the memo state is lazily created and stored on each instance.
* This provides the best of both worlds: shared method code + per-instance caching.
*/
export function assignPrototypeAPIs<
TFeatures extends TableFeatures,
TData extends RowData,
TDeps extends ReadonlyArray<any>,
TDepArgs,
>(
feature: keyof TFeatures & string,
prototype: Record<string, any>,
table: Table_Internal<TFeatures, TData>,
apis: PrototypeAPIObject<TDeps, NoInfer<TDepArgs>>,
): void {
for (const [staticFnName, { fn, memoDeps }] of Object.entries(apis)) {
const { fnKey, fnName } = getFunctionNameInfo(staticFnName)
if (memoDeps) {
// For memoized methods, create a function that lazily initializes
// the memo on first access and stores it on the instance
const memoKey = `_memo_${fnKey}`
prototype[fnKey] = function (this: any, ...args: Array<any>) {
// Lazily create memo on first access for this instance
if (!this[memoKey]) {
const self = this
this[memoKey] = tableMemo({
memoDeps: () => memoDeps(self),
fn: (...deps) => fn(self, ...deps),
fnName,
objectId: self.id,
table,
feature,
})
}
return this[memoKey](...args)
}
} else {
// Non-memoized methods just call the static function with `this`
prototype[fnKey] = function (this: any, ...args: Array<any>) {
return fn(this, ...args)
}
}
setMemoFnMeta(prototype[fnKey], { originalArgsLength: fn.length })
}
}
/**
* Looks to run the memoized function with the builder pattern on the object if it exists, otherwise fallback to the static method passed in.
*/
export function callMemoOrStaticFn<
TObject extends Record<string, any>,
TStaticFn extends AnyFunction,
>(
obj: TObject,
fnKey: string,
staticFn: TStaticFn,
...args: Parameters<TStaticFn> extends [any, ...infer Rest] ? Rest : never
): ReturnType<TStaticFn> {
return (
(obj[fnKey] as Function | undefined)?.(...args) ?? staticFn(obj, ...args)
)
}