-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
useLoader.ts
271 lines (240 loc) · 7.99 KB
/
useLoader.ts
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
import { asyncWritable, type AsyncWritable } from '../lib/asyncWritable'
import { useCache } from '../lib/cache'
type AsyncLoader = {
loadAsync: (url: string, onProgress?: (event: ProgressEvent) => void) => Promise<any>
}
type SyncLoader = {
load: (
url: string,
onLoad: (data: any) => void,
onProgress?: (event: ProgressEvent) => void,
onError?: (event: unknown) => void
) => unknown
}
export type Loader = AsyncLoader | SyncLoader
// Some loaders may not have any constructor arguments …
type LoaderProtoWithoutArgs = { new (): Loader }
// … but some other loaders do.
type LoaderProtoWithArgs = { new (...args: any[]): Loader }
export type UseLoaderLoadInput = string | string[] | Record<string, string>
type LoaderResultType<TLoader extends Loader> = TLoader extends AsyncLoader
? Awaited<ReturnType<TLoader['loadAsync']>>
: TLoader extends SyncLoader
? Parameters<TLoader['load']>[1] extends (data: infer Result) => void
? Result
: never
: never
export type UseLoaderLoadResult<
TLoader extends Loader,
Input extends UseLoaderLoadInput,
ResultType = LoaderResultType<TLoader>
> = Input extends string
? AsyncWritable<ResultType>
: Input extends string[]
? AsyncWritable<ResultType[]>
: AsyncWritable<Record<keyof Input, ResultType>>
type UseLoaderLoadTransform<TLoader extends Loader> = (result: LoaderResultType<TLoader>) => any
type UseLoaderLoadOptions<TLoader extends Loader> = {
onProgress?: (event: ProgressEvent) => void
transform?: UseLoaderLoadTransform<TLoader>
}
type ThrelteUseLoader<TLoader extends Loader> = {
loader: TLoader
load: <
Input extends UseLoaderLoadInput,
Options extends UseLoaderLoadOptions<TLoader> | undefined,
ResultType = Options extends UseLoaderLoadOptions<TLoader>
? Options['transform'] extends UseLoaderLoadTransform<TLoader>
? ReturnType<Options['transform']>
: LoaderResultType<TLoader>
: LoaderResultType<TLoader>
>(
input: Input,
options?: Options
) => UseLoaderLoadResult<TLoader, Input, ResultType>
clear: <Input extends string | string[] | Record<string, string>>(input: Input) => void
}
type UseLoaderOptionsWithoutArgs<Proto extends LoaderProtoWithoutArgs> = {
/**
* A loader can be extended to add custom
* functionality, e.g. add DRACO support.
*/
extend?: (loader: InstanceType<Proto>) => void
/**
* Arguments to pass to the loader.
*/
args?: ConstructorParameters<Proto>
}
type UseLoaderOptionsWithArgs<Proto extends LoaderProtoWithArgs> = {
/**
* A loader can be extended to add custom
* functionality, e.g. add DRACO support.
*/
extend?: (loader: InstanceType<Proto>) => void
/**
* Arguments to pass to the loader.
*/
args: ConstructorParameters<Proto>
}
export type UseLoaderOptions<Proto extends LoaderProtoWithoutArgs> =
ConstructorParameters<Proto> extends []
? UseLoaderOptionsWithoutArgs<Proto>
: undefined extends ConstructorParameters<Proto>[0]
? UseLoaderOptionsWithoutArgs<Proto>
: UseLoaderOptionsWithArgs<Proto>
export function useLoader<Proto extends LoaderProtoWithoutArgs>(
Proto: Proto,
options?: UseLoaderOptions<Proto>
): ThrelteUseLoader<InstanceType<Proto>>
export function useLoader<Proto extends LoaderProtoWithArgs>(
Proto: Proto,
options: UseLoaderOptions<Proto>
): ThrelteUseLoader<InstanceType<Proto>>
export function useLoader<Proto extends LoaderProtoWithoutArgs>(
Proto: Proto,
options?: UseLoaderOptions<Proto>
): ThrelteUseLoader<InstanceType<Proto>> {
const { remember, clear: clearCacheItem } = useCache()
let loader: InstanceType<Proto> | undefined
const initializeLoader = (): InstanceType<Proto> => {
// Type-wrestling galore
const lazyLoader = new Proto(...(((options as any)?.args as []) ?? [])) as InstanceType<Proto>
// extend the loader if necessary
options?.extend?.(lazyLoader)
return lazyLoader
}
const load: ThrelteUseLoader<InstanceType<Proto>>['load'] = (input, options) => {
// Allow Async and Sync loaders
const loadResource = async (url: string) => {
if (!loader) {
loader = initializeLoader()
}
if ('loadAsync' in loader) {
const result = await loader.loadAsync(url, options?.onProgress)
return options?.transform?.(result) ?? result
} else {
return new Promise((resolve, reject) => {
;(loader as SyncLoader).load(
url,
(data) => resolve(options?.transform?.(data) ?? data),
(event) => options?.onProgress?.(event),
reject
)
})
}
}
if (Array.isArray(input)) {
// map over the input array and return an array of promises
const promises = input.map((url) => {
return remember(() => loadResource(url), [Proto, url])
})
// return an AsyncWritable that resolves to the array of promises
const store = asyncWritable(Promise.all(promises))
return store as any // TODO: Dirty escape hatch
} else if (typeof input === 'string') {
const promise = remember(() => loadResource(input), [Proto, input])
// return an AsyncWritable that resolves to the promise
const store = asyncWritable(promise)
return store as any // TODO: Dirty escape hatch
} else {
// map over the input object and return an array of promises
const promises = Object.values(input).map((url) => {
return remember(() => loadResource(url), [Proto, url])
})
// return an AsyncWritable that resolves to the object of promises
const store = asyncWritable(
Promise.all(promises).then((results) => {
return Object.fromEntries(Object.entries(input).map(([key], i) => [key, results[i]]))
})
)
return store as any // TODO: Dirty escape hatch
}
}
const clear = (input: string | string[] | Record<string, string>) => {
if (Array.isArray(input)) {
input.forEach((url) => {
clearCacheItem([Proto, url])
})
} else if (typeof input === 'string') {
clearCacheItem([Proto, input])
} else {
Object.entries(input).forEach(([key, url]) => {
clearCacheItem([Proto, key, url])
})
}
}
return {
load,
clear,
loader
} as ThrelteUseLoader<InstanceType<Proto>>
}
// Type tests
// class WithConstructorParameters {
// constructor(hello: 'abc' | 'def') {
// console.log(hello)
// }
// loadAsync(url: string, onProgress?: (event: ProgressEvent) => void): Promise<any> {
// return new Promise((r) => r('hello'))
// }
// }
// class WithOptionalConstructorParameters {
// constructor(hello?: string) {
// console.log(hello)
// }
// loadAsync(url: string, onProgress?: (event: ProgressEvent) => void): Promise<any> {
// return new Promise((r) => r('hello'))
// }
// }
// class WithoutConstructorParameters {
// constructor() {
// console.log('without')
// }
// loadAsync(url: string, onProgress?: (event: ProgressEvent) => void): Promise<any> {
// return new Promise((r) => r('hello'))
// }
// }
// const shouldFail = () => {
// useLoader(WithConstructorParameters)
// useLoader(WithoutConstructorParameters, {
// args: ['hello']
// })
// }
// const shouldSucceed = () => {
// useLoader(WithConstructorParameters, {
// args: ['abc']
// })
// useLoader(WithConstructorParameters, {
// args: ['abc'],
// extend(loader) {
// // …
// }
// })
// useLoader(WithOptionalConstructorParameters)
// useLoader(WithOptionalConstructorParameters, {
// extend(loader) {
// // …
// }
// })
// useLoader(WithOptionalConstructorParameters, {
// args: [],
// extend(loader) {
// // …
// }
// })
// useLoader(WithOptionalConstructorParameters, {
// args: ['hello'],
// extend(loader) {
// // …
// }
// })
// useLoader(WithOptionalConstructorParameters, {
// args: ['hello']
// })
// useLoader(WithoutConstructorParameters)
// useLoader(WithoutConstructorParameters, {
// extend(loader) {
// // …
// }
// })
// }