forked from TanStack/table
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructTable.ts
More file actions
253 lines (228 loc) · 8.15 KB
/
Copy pathconstructTable.ts
File metadata and controls
253 lines (228 loc) · 8.15 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
import { coreFeatures } from '../coreFeatures'
import { cloneState } from '../../utils'
import { atomToStore } from '../reactivity/coreReactivityFeature.utils'
import { table_syncExternalStateToBaseAtoms } from './coreTablesFeature.utils'
import type { Atom } from '@tanstack/store'
import type { RowData } from '../../types/type-utils'
import type { TableFeature, TableFeatures } from '../../types/TableFeatures'
import type { Table, Table_Internal } from '../../types/Table'
import type { TableOptions } from '../../types/TableOptions'
import type { TableState, TableState_All } from '../../types/TableState'
/**
* Builds the initial table state from registered features and user initial state.
*
* Each feature contributes its default state before user-provided `initialState` values are merged in.
*/
export function getInitialTableState<TFeatures extends TableFeatures>(
features: TFeatures,
initialState: Partial<TableState<TFeatures>> | undefined = {},
): TableState<TFeatures> {
Object.values(features).forEach((feature) => {
initialState = feature.getInitialState?.(initialState) ?? initialState
})
return cloneState(initialState) as TableState<TFeatures>
}
/**
* Constructs a table instance from normalized table internals.
*
* This wires core properties, feature prototype APIs, and instance data used by table rendering and row-model operations.
*/
export function constructTable<
TFeatures extends TableFeatures,
TData extends RowData,
>(tableOptions: TableOptions<TFeatures, TData>): Table<TFeatures, TData> {
const _reactivity = tableOptions.features.coreReactivityFeature!
// Strip the non-feature slots: type-only meta slots, row model factories,
// and row model fn registries all live on the `features` option but are not
// table features themselves.
const {
aggregationFns,
columnMeta: _columnMeta,
coreRowModel,
expandedRowModel,
facetedMinMaxValues,
facetedRowModel,
facetedUniqueValues,
filterFns,
filterMeta: _filterMeta,
filteredRowModel,
groupedRowModel,
paginatedRowModel,
sortFns,
sortedRowModel,
tableMeta: _tableMeta,
...features
} = tableOptions.features
const table = {
_reactivity,
_features: { ...coreFeatures, ...features },
_rowModels: {},
_rowModelFns: { aggregationFns, filterFns, sortFns },
baseAtoms: {},
// Import diffs will make updating this hell -> any
_columnCache: new WeakMap<any, any>(),
atoms: {},
} as unknown as Table_Internal<TFeatures, TData>
const featuresList: Array<TableFeature> = Object.values(table._features)
const defaultOptions = featuresList.reduce((obj, feature) => {
return Object.assign(obj, feature.getDefaultTableOptions?.(table))
}, {}) as TableOptions<TFeatures, TData>
const mergedOptions = { ...defaultOptions, ...tableOptions }
if (_reactivity.wrapExternalAtoms && mergedOptions.atoms) {
for (const [atomKey, _atom] of Object.entries(mergedOptions.atoms)) {
const atom = _atom as Atom<any>
const wrappedAtom = _reactivity.createWritableAtom(atom.get(), {
debugName: `externalAtom/${atomKey}`,
})
;(mergedOptions.atoms as any)[atomKey] = wrappedAtom
// Two-way syncing between the original atom and the wrapped one.
let syncExternal = false
const syncAtomToWrappedSub = atom.subscribe((value) => {
if (syncExternal) return
wrappedAtom.set(value)
})
const syncWrappedToAtomSub = wrappedAtom.subscribe((value) => {
syncExternal = true
atom.set(value)
syncExternal = false
})
_reactivity.addSubscription(syncAtomToWrappedSub)
_reactivity.addSubscription(syncWrappedToAtomSub)
}
}
if (_reactivity.createOptionsStore) {
// @ts-ignore - direct set
table.optionsStore = _reactivity.createWritableAtom<
TableOptions<TFeatures, TData>
>(mergedOptions, { debugName: 'table/optionsStore' })
Object.defineProperty(table, 'options', {
configurable: true,
enumerable: true,
get() {
return table.optionsStore!.get()
},
set(value) {
table.optionsStore!.set(() => value) // or your real update shape
},
})
} else {
table.options = mergedOptions
}
table.initialState = getInitialTableState(
table._features,
table.options.initialState,
)
const stateKeys = Object.keys(table.initialState) as Array<
string & keyof TableState_All
>
for (let i = 0; i < stateKeys.length; i++) {
const key = stateKeys[i]!
table.baseAtoms[key] = _reactivity.createWritableAtom(
table.initialState[key],
{
debugName: `table/baseAtoms/${key}`,
},
) as any
// create readonly derived atom: on each get(), read either external atom or base atom
;(table.atoms as any)[key] = _reactivity.createReadonlyAtom(
() => {
const externalAtoms = table.options.atoms as
| Partial<Record<keyof TableState_All, Atom<unknown>>>
| undefined
const externalAtom = externalAtoms?.[key]
if (externalAtom) {
return externalAtom.get()
}
return table.baseAtoms[key]!.get()
},
{ debugName: `table/atoms/${key}` },
)
}
table_syncExternalStateToBaseAtoms(table)
table.store = atomToStore(
_reactivity.createReadonlyAtom(
() => {
const snapshot = {} as TableState<TFeatures> & TableState_All
for (let i = 0; i < stateKeys.length; i++) {
const key = stateKeys[i]!
;(snapshot as Record<string, unknown>)[key] = table.atoms[key]!.get()
}
return snapshot
},
{ debugName: 'table/store' },
),
)
// pre-compute the init functions to make the other constructors faster
const cellInstanceInitFns: Array<
NonNullable<TableFeature['initCellInstanceData']>
> = []
const columnInstanceInitFns: Array<
NonNullable<TableFeature['initColumnInstanceData']>
> = []
const headerGroupInstanceInitFns: Array<
NonNullable<TableFeature['initHeaderGroupInstanceData']>
> = []
const headerInstanceInitFns: Array<
NonNullable<TableFeature['initHeaderInstanceData']>
> = []
const rowInstanceInitFns: Array<
NonNullable<TableFeature['initRowInstanceData']>
> = []
for (let i = 0; i < featuresList.length; i++) {
const feature = featuresList[i]!
if (feature.initCellInstanceData) {
cellInstanceInitFns.push(feature.initCellInstanceData.bind(feature))
}
if (feature.initColumnInstanceData) {
columnInstanceInitFns.push(feature.initColumnInstanceData.bind(feature))
}
if (feature.initHeaderGroupInstanceData) {
headerGroupInstanceInitFns.push(
feature.initHeaderGroupInstanceData.bind(feature),
)
}
if (feature.initHeaderInstanceData) {
headerInstanceInitFns.push(feature.initHeaderInstanceData.bind(feature))
}
if (feature.initRowInstanceData) {
rowInstanceInitFns.push(feature.initRowInstanceData.bind(feature))
}
feature.initTableInstanceData?.(table)
}
table._cellInstanceInitFns = cellInstanceInitFns
table._columnInstanceInitFns = columnInstanceInitFns
table._headerGroupInstanceInitFns = headerGroupInstanceInitFns
table._headerInstanceInitFns = headerInstanceInitFns
table._rowInstanceInitFns = rowInstanceInitFns
if (
process.env.NODE_ENV === 'development' &&
(tableOptions.debugAll || tableOptions.debugTable)
) {
const features = Object.keys(table._features)
const rowModels = Object.entries({
coreRowModel,
filteredRowModel,
groupedRowModel,
sortedRowModel,
expandedRowModel,
paginatedRowModel,
facetedRowModel,
facetedMinMaxValues,
facetedUniqueValues,
})
.filter(([, factory]) => factory)
.map(([key]) => key)
const states = Object.keys(table.initialState)
console.log(
`Constructing Table Instance
Features: ${features.join('\n ')}
Row Models: ${rowModels.length ? rowModels.join('\n ') : '(none)'}
States: ${states.join('\n ')}\n`,
{ table },
)
}
for (let i = 0; i < featuresList.length; i++) {
featuresList[i]!.constructTableAPIs?.(table)
}
return table as unknown as Table<TFeatures, TData>
}