@svadmin/core 0.69.3 → 0.70.0
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/package.json +5 -1
- package/src/client-filter.ts +77 -0
- package/src/editable-table.ts +28 -3
- package/src/index.ts +7 -2
- package/src/infinite-query.svelte.ts +45 -17
- package/src/provider-bundle.ts +0 -25
- package/src/provider-filter-capabilities.ts +111 -0
- package/src/query-hooks.svelte.ts +68 -37
- package/src/query-options.ts +36 -7
- package/src/select-options.ts +14 -2
- package/src/select-query.svelte.ts +48 -12
- package/src/strict-hooks.svelte.ts +46 -17
- package/src/table-hooks.svelte.ts +22 -72
- package/src/table-state.svelte.ts +4 -3
- package/src/url-sync.ts +71 -14
- package/src/utility-hooks.svelte.ts +1 -19
|
@@ -19,20 +19,24 @@ import { decodeBaseRecord, decodeListResult, decodeOneResult, decodeManyResult,
|
|
|
19
19
|
import { HttpError } from './types';
|
|
20
20
|
import { extendReactiveMembers } from './reactive-projection';
|
|
21
21
|
import { captureQueryProvider, snapshotListParams, snapshotOneParams, snapshotManyParams } from './query-snapshot';
|
|
22
|
-
import {
|
|
22
|
+
import { listQuerySettings, type ResourceQueryOptions } from './query-options';
|
|
23
23
|
|
|
24
24
|
// ─── useList ───────────────────────────────────────────────────
|
|
25
25
|
|
|
26
26
|
export type MaybeGetter<T>=T|(() => T);
|
|
27
27
|
|
|
28
|
-
export interface UseListOptions<
|
|
28
|
+
export interface UseListOptions<
|
|
29
|
+
_TData extends BaseRecord=BaseRecord,
|
|
30
|
+
_TError=HttpError,
|
|
31
|
+
TSelected=GetListResult<_TData>,
|
|
32
|
+
> extends ContractOptions {
|
|
29
33
|
resource?: KnownResources;
|
|
30
34
|
pagination?: Pagination;
|
|
31
35
|
sorters?: Sort[];
|
|
32
36
|
filters?: Filter[];
|
|
33
37
|
meta?: Record<string,unknown>;
|
|
34
38
|
dataProviderName?: string;
|
|
35
|
-
queryOptions?: ResourceQueryOptions<GetListResult<_TData
|
|
39
|
+
queryOptions?: ResourceQueryOptions<GetListResult<_TData>, TSelected>;
|
|
36
40
|
successNotification?: NotificationConfig;
|
|
37
41
|
errorNotification?: NotificationConfig;
|
|
38
42
|
liveMode?: LiveMode;
|
|
@@ -45,8 +49,8 @@ export function useList(optionsOrGetter: MaybeGetter<UseListOptions>={}) {
|
|
|
45
49
|
return createListQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
46
50
|
}
|
|
47
51
|
|
|
48
|
-
export function createListQuery<TData extends BaseRecord
|
|
49
|
-
optionsOrGetter: MaybeGetter<UseListOptions
|
|
52
|
+
export function createListQuery<TData extends BaseRecord, TSelected = GetListResult<TData>>(
|
|
53
|
+
optionsOrGetter: MaybeGetter<UseListOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
50
54
|
) {
|
|
51
55
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
52
56
|
const parsed=useParsed();
|
|
@@ -55,7 +59,7 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
55
59
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
56
60
|
const getResource=() => getOptions().resource??parsed.resource??'';
|
|
57
61
|
|
|
58
|
-
const query=createSessionQuery<GetListResult<TData
|
|
62
|
+
const query=createSessionQuery<GetListResult<TData>, TSelected>(adminContext,() => {
|
|
59
63
|
const decode=getDecoder();
|
|
60
64
|
const opts=getOptions();
|
|
61
65
|
const checkId=opts.contract!==undefined;
|
|
@@ -108,10 +112,11 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
108
112
|
});
|
|
109
113
|
return decodeResult(await current.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal }) })));
|
|
110
114
|
},
|
|
111
|
-
decode: (value):
|
|
112
|
-
decodeResult(value)
|
|
113
|
-
queryOptions?.select as ((data: GetListResult<TData>) =>
|
|
114
|
-
|
|
115
|
+
decode: (value): TSelected => {
|
|
116
|
+
const decoded=decodeResult(value);
|
|
117
|
+
const select=queryOptions?.select as ((data: GetListResult<TData>) => TSelected) | undefined;
|
|
118
|
+
return select ? select(decoded) : decoded as TSelected;
|
|
119
|
+
},
|
|
115
120
|
enabled: settings.enabled,
|
|
116
121
|
...definedOptions({
|
|
117
122
|
staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
|
|
@@ -150,12 +155,16 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
150
155
|
|
|
151
156
|
// ─── useOne ────────────────────────────────────────────────────
|
|
152
157
|
|
|
153
|
-
export interface UseOneOptions<
|
|
158
|
+
export interface UseOneOptions<
|
|
159
|
+
_TData extends BaseRecord=BaseRecord,
|
|
160
|
+
_TError=HttpError,
|
|
161
|
+
TSelected=GetOneResult<_TData>,
|
|
162
|
+
> extends ContractOptions {
|
|
154
163
|
resource?: KnownResources;
|
|
155
164
|
id?: string|number;
|
|
156
165
|
meta?: Record<string,unknown>;
|
|
157
166
|
dataProviderName?: string;
|
|
158
|
-
queryOptions?:
|
|
167
|
+
queryOptions?: ResourceQueryOptions<GetOneResult<_TData>, TSelected>;
|
|
159
168
|
successNotification?: NotificationConfig;
|
|
160
169
|
errorNotification?: NotificationConfig;
|
|
161
170
|
liveMode?: LiveMode;
|
|
@@ -168,8 +177,8 @@ export function useOne(optionsOrGetter: MaybeGetter<UseOneOptions>={}) {
|
|
|
168
177
|
return createOneQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
169
178
|
}
|
|
170
179
|
|
|
171
|
-
export function createOneQuery<TData extends BaseRecord
|
|
172
|
-
optionsOrGetter: MaybeGetter<UseOneOptions
|
|
180
|
+
export function createOneQuery<TData extends BaseRecord, TSelected = GetOneResult<TData>>(
|
|
181
|
+
optionsOrGetter: MaybeGetter<UseOneOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
173
182
|
) {
|
|
174
183
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
175
184
|
const parsed=useParsed();
|
|
@@ -179,7 +188,7 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
179
188
|
const getResource=() => getOptions().resource??parsed.resource??'';
|
|
180
189
|
const getId=() => getOptions().id??parsed.id;
|
|
181
190
|
|
|
182
|
-
const query=createSessionQuery<GetOneResult<TData
|
|
191
|
+
const query=createSessionQuery<GetOneResult<TData>, TSelected>(adminContext,() => {
|
|
183
192
|
const decode=getDecoder();
|
|
184
193
|
const opts=getOptions();
|
|
185
194
|
const resource=opts.resource??parsed.resource??'';
|
|
@@ -192,14 +201,17 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
192
201
|
resource,id,...definedOptions({ meta: captured.meta }),
|
|
193
202
|
});
|
|
194
203
|
const queryOptions=opts.queryOptions;
|
|
204
|
+
const settings=listQuerySettings(queryOptions);
|
|
205
|
+
const project=(value: unknown): TSelected => {
|
|
206
|
+
const decoded=decodeOneResult(value,decode);
|
|
207
|
+
if(checkId && params && decoded.data['id']!==params.id) return rejectProviderResponse();
|
|
208
|
+
const select=queryOptions?.select as ((data: GetOneResult<TData>) => TSelected) | undefined;
|
|
209
|
+
return select ? select(decoded) : decoded as TSelected;
|
|
210
|
+
};
|
|
195
211
|
|
|
196
212
|
return {
|
|
197
213
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
198
|
-
decode:
|
|
199
|
-
const decoded=decodeOneResult(value,decode);
|
|
200
|
-
if(checkId && params && decoded.data['id']!==params.id) return rejectProviderResponse();
|
|
201
|
-
return decoded;
|
|
202
|
-
},
|
|
214
|
+
decode: project,
|
|
203
215
|
queryKey: adminContext.queryKeys(resource,opts.dataProviderName).data.one(resource,id??'',{
|
|
204
216
|
...definedOptions({ meta: captured.meta }),
|
|
205
217
|
source: captured.source,
|
|
@@ -211,11 +223,16 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
211
223
|
if(checkId && decoded.data['id']!==params.id) return rejectProviderResponse();
|
|
212
224
|
return decoded;
|
|
213
225
|
},
|
|
214
|
-
enabled:
|
|
226
|
+
enabled: settings.enabled&&id!=null,
|
|
215
227
|
...definedOptions({
|
|
216
|
-
staleTime:
|
|
217
|
-
gcTime:
|
|
218
|
-
refetchOnWindowFocus:
|
|
228
|
+
staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
|
|
229
|
+
gcTime: settings.gcTime??adminOptions.reactQuery?.gcTime,
|
|
230
|
+
refetchOnWindowFocus: settings.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
231
|
+
retry: settings.retry,
|
|
232
|
+
retryDelay: settings.retryDelay,
|
|
233
|
+
refetchInterval: settings.refetchInterval,
|
|
234
|
+
refetchIntervalInBackground: settings.refetchIntervalInBackground,
|
|
235
|
+
placeholderData: settings.placeholderData as GetOneResult<TData> | ((previousData: GetOneResult<TData> | undefined) => GetOneResult<TData> | undefined) | undefined,
|
|
219
236
|
}),
|
|
220
237
|
};
|
|
221
238
|
});
|
|
@@ -244,8 +261,8 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
244
261
|
}
|
|
245
262
|
|
|
246
263
|
// ─── useShow ──────────────────────────────────────────────────
|
|
247
|
-
export function createShowQuery<TData extends BaseRecord
|
|
248
|
-
optionsOrGetter: MaybeGetter<UseOneOptions
|
|
264
|
+
export function createShowQuery<TData extends BaseRecord, TSelected = GetOneResult<TData>>(
|
|
265
|
+
optionsOrGetter: MaybeGetter<UseOneOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
249
266
|
) {
|
|
250
267
|
const parsed=useParsed();
|
|
251
268
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
@@ -258,7 +275,7 @@ export function createShowQuery<TData extends BaseRecord>(
|
|
|
258
275
|
function setShowId(id: string|number) { _showId=id; }
|
|
259
276
|
|
|
260
277
|
// We wrap it in a getter so useOne evaluates it dynamically.
|
|
261
|
-
const result=createOneQuery(() => ({
|
|
278
|
+
const result=createOneQuery<TData, TSelected>(() => ({
|
|
262
279
|
...getOptions(),
|
|
263
280
|
...definedOptions({ id: showId }),
|
|
264
281
|
}), getDecoder);
|
|
@@ -268,12 +285,16 @@ export function createShowQuery<TData extends BaseRecord>(
|
|
|
268
285
|
|
|
269
286
|
// ─── useMany ───────────────────────────────────────────────────
|
|
270
287
|
|
|
271
|
-
export interface UseManyOptions<
|
|
288
|
+
export interface UseManyOptions<
|
|
289
|
+
_TData extends BaseRecord=BaseRecord,
|
|
290
|
+
_TError=HttpError,
|
|
291
|
+
TSelected=GetManyResult<_TData>,
|
|
292
|
+
> extends ContractOptions {
|
|
272
293
|
resource: KnownResources;
|
|
273
294
|
ids: (string|number)[];
|
|
274
295
|
meta?: Record<string,unknown>;
|
|
275
296
|
dataProviderName?: string;
|
|
276
|
-
queryOptions?:
|
|
297
|
+
queryOptions?: ResourceQueryOptions<GetManyResult<_TData>, TSelected>;
|
|
277
298
|
successNotification?: NotificationConfig;
|
|
278
299
|
errorNotification?: NotificationConfig;
|
|
279
300
|
liveMode?: LiveMode;
|
|
@@ -286,18 +307,19 @@ export function useMany(optionsOrGetter: MaybeGetter<UseManyOptions>) {
|
|
|
286
307
|
return createManyQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
287
308
|
}
|
|
288
309
|
|
|
289
|
-
export function createManyQuery<TData extends BaseRecord
|
|
290
|
-
optionsOrGetter: MaybeGetter<UseManyOptions
|
|
310
|
+
export function createManyQuery<TData extends BaseRecord, TSelected = GetManyResult<TData>>(
|
|
311
|
+
optionsOrGetter: MaybeGetter<UseManyOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
291
312
|
) {
|
|
292
313
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
293
314
|
const adminOptions=getAdminOptions();
|
|
294
315
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
295
316
|
|
|
296
|
-
const query=createSessionQuery<GetManyResult<TData
|
|
317
|
+
const query=createSessionQuery<GetManyResult<TData>, TSelected>(adminContext,() => {
|
|
297
318
|
const decode=getDecoder();
|
|
298
319
|
const opts=getOptions();
|
|
299
320
|
const checkId=opts.contract!==undefined;
|
|
300
321
|
const { resource,ids,meta,dataProviderName,queryOptions }=opts;
|
|
322
|
+
const settings=listQuerySettings(queryOptions);
|
|
301
323
|
const captured=captureQueryProvider(adminContext,{
|
|
302
324
|
resource,...definedOptions({ dataProviderName,contract: opts.contract,meta }),
|
|
303
325
|
});
|
|
@@ -315,7 +337,11 @@ export function createManyQuery<TData extends BaseRecord>(
|
|
|
315
337
|
|
|
316
338
|
return {
|
|
317
339
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
318
|
-
decode:
|
|
340
|
+
decode: (value): TSelected => {
|
|
341
|
+
const decoded=decodeResult(value);
|
|
342
|
+
const select=queryOptions?.select as ((data: GetManyResult<TData>) => TSelected) | undefined;
|
|
343
|
+
return select ? select(decoded) : decoded as TSelected;
|
|
344
|
+
},
|
|
319
345
|
queryKey: adminContext.queryKeys(resource,dataProviderName).data.many(resource,{
|
|
320
346
|
ids: params.ids,
|
|
321
347
|
...definedOptions({ meta: params.meta }),
|
|
@@ -333,11 +359,16 @@ export function createManyQuery<TData extends BaseRecord>(
|
|
|
333
359
|
})),decode)));
|
|
334
360
|
return decodeResult({ data: results.map(r => r.data) });
|
|
335
361
|
},
|
|
336
|
-
enabled:
|
|
362
|
+
enabled: settings.enabled&¶ms.ids.length>0,
|
|
337
363
|
...definedOptions({
|
|
338
|
-
staleTime:
|
|
339
|
-
gcTime:
|
|
340
|
-
refetchOnWindowFocus:
|
|
364
|
+
staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
|
|
365
|
+
gcTime: settings.gcTime??adminOptions.reactQuery?.gcTime,
|
|
366
|
+
refetchOnWindowFocus: settings.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
367
|
+
retry: settings.retry,
|
|
368
|
+
retryDelay: settings.retryDelay,
|
|
369
|
+
refetchInterval: settings.refetchInterval,
|
|
370
|
+
refetchIntervalInBackground: settings.refetchIntervalInBackground,
|
|
371
|
+
placeholderData: settings.placeholderData as GetManyResult<TData> | ((previousData: GetManyResult<TData> | undefined) => GetManyResult<TData> | undefined) | undefined,
|
|
341
372
|
}),
|
|
342
373
|
};
|
|
343
374
|
});
|
package/src/query-options.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { definedOptions } from './defined-options';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
* `select`
|
|
4
|
+
* 查询钩子可以安全转发的 TanStack Query 选项。
|
|
5
|
+
* `select` 在解码之后执行,可以改变投影类型,且不会改写缓存里的原始响应。
|
|
6
6
|
*/
|
|
7
|
-
export interface ResourceQueryOptions<TData =
|
|
7
|
+
export interface ResourceQueryOptions<TQueryFnData = unknown, TData = TQueryFnData> {
|
|
8
8
|
staleTime?: number;
|
|
9
9
|
enabled?: boolean;
|
|
10
10
|
gcTime?: number;
|
|
@@ -13,8 +13,8 @@ export interface ResourceQueryOptions<TData = unknown> {
|
|
|
13
13
|
retryDelay?: number | ((failureCount: number, error: unknown) => number);
|
|
14
14
|
refetchInterval?: number | false;
|
|
15
15
|
refetchIntervalInBackground?: boolean;
|
|
16
|
-
placeholderData?:
|
|
17
|
-
select?: (data:
|
|
16
|
+
placeholderData?: TQueryFnData | ((previousData: TQueryFnData | undefined) => TQueryFnData | undefined);
|
|
17
|
+
select?: (data: TQueryFnData) => TData;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
export interface ListQuerySettings<TData = unknown> {
|
|
@@ -29,7 +29,9 @@ export interface ListQuerySettings<TData = unknown> {
|
|
|
29
29
|
placeholderData?: ResourceQueryOptions<TData>['placeholderData'];
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
export function listQuerySettings<
|
|
32
|
+
export function listQuerySettings<TQueryFnData>(
|
|
33
|
+
options: ResourceQueryOptions<TQueryFnData, unknown> | undefined,
|
|
34
|
+
): ListQuerySettings<TQueryFnData> {
|
|
33
35
|
return {
|
|
34
36
|
enabled: options?.enabled ?? true,
|
|
35
37
|
...definedOptions({
|
|
@@ -45,6 +47,33 @@ export function listQuerySettings<TData>(options: ResourceQueryOptions<TData> |
|
|
|
45
47
|
};
|
|
46
48
|
}
|
|
47
49
|
|
|
48
|
-
|
|
50
|
+
function projectSelected<TQueryFnData, TData>(
|
|
51
|
+
data: TQueryFnData,
|
|
52
|
+
select?: (data: TQueryFnData) => TData,
|
|
53
|
+
): TQueryFnData | TData {
|
|
49
54
|
return select ? select(data) : data;
|
|
50
55
|
}
|
|
56
|
+
|
|
57
|
+
export function applyQuerySelect<TQueryFnData>(data: TQueryFnData, select?: undefined): TQueryFnData;
|
|
58
|
+
export function applyQuerySelect<TQueryFnData, TData>(
|
|
59
|
+
data: TQueryFnData,
|
|
60
|
+
select: (data: TQueryFnData) => TData,
|
|
61
|
+
): TData;
|
|
62
|
+
export function applyQuerySelect<TQueryFnData, TData>(
|
|
63
|
+
data: TQueryFnData,
|
|
64
|
+
select?: (data: TQueryFnData) => TData,
|
|
65
|
+
): TQueryFnData | TData {
|
|
66
|
+
return projectSelected(data, select);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function applyListSelect<TQueryFnData>(data: TQueryFnData, select?: undefined): TQueryFnData;
|
|
70
|
+
export function applyListSelect<TQueryFnData, TData>(
|
|
71
|
+
data: TQueryFnData,
|
|
72
|
+
select: (data: TQueryFnData) => TData,
|
|
73
|
+
): TData;
|
|
74
|
+
export function applyListSelect<TQueryFnData, TData>(
|
|
75
|
+
data: TQueryFnData,
|
|
76
|
+
select?: (data: TQueryFnData) => TData,
|
|
77
|
+
): TQueryFnData | TData {
|
|
78
|
+
return projectSelected(data, select);
|
|
79
|
+
}
|
package/src/select-options.ts
CHANGED
|
@@ -8,6 +8,18 @@ export interface SelectOption {
|
|
|
8
8
|
value: string | number;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
+
/** 点分路径读取记录字段,例如 `nested.title`。不走原型链。 */
|
|
12
|
+
export function readRecordPath(record: BaseRecord, path: string): unknown {
|
|
13
|
+
if (!path.includes('.')) return record[path];
|
|
14
|
+
let current: unknown = record;
|
|
15
|
+
for (const segment of path.split('.')) {
|
|
16
|
+
if (!segment || current === null || typeof current !== 'object' || Array.isArray(current)) return undefined;
|
|
17
|
+
if (!Object.hasOwn(current, segment)) return undefined;
|
|
18
|
+
current = (current as Record<string, unknown>)[segment];
|
|
19
|
+
}
|
|
20
|
+
return current;
|
|
21
|
+
}
|
|
22
|
+
|
|
11
23
|
export function selectOptionValue(value: unknown): string | number {
|
|
12
24
|
if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) return value;
|
|
13
25
|
throw new HttpError('Invalid select option', 422, undefined, { code: 'INVALID_SELECT_OPTION' });
|
|
@@ -25,13 +37,13 @@ export function mapSelectOptions<T extends BaseRecord>(
|
|
|
25
37
|
return records.map(record => {
|
|
26
38
|
if (!isCurrent()) throw new Error('Obsolete select mapping');
|
|
27
39
|
const labelRecord = decode(snapshotPlainData(record));
|
|
28
|
-
const mappedLabel = typeof label === 'function' ? label(labelRecord) : labelRecord
|
|
40
|
+
const mappedLabel = typeof label === 'function' ? label(labelRecord) : readRecordPath(labelRecord, label);
|
|
29
41
|
if (!isCurrent()) throw new Error('Obsolete select mapping');
|
|
30
42
|
if (typeof label === 'function' && typeof mappedLabel !== 'string') {
|
|
31
43
|
throw new TypeError('Select label callbacks must return strings');
|
|
32
44
|
}
|
|
33
45
|
const valueRecord = decode(snapshotPlainData(record));
|
|
34
|
-
const mappedValue = typeof value === 'function' ? value(valueRecord) : valueRecord
|
|
46
|
+
const mappedValue = typeof value === 'function' ? value(valueRecord) : readRecordPath(valueRecord, value);
|
|
35
47
|
if (!isCurrent()) throw new Error('Obsolete select mapping');
|
|
36
48
|
return { label: String(selectOptionValue(mappedLabel)), value: selectOptionValue(mappedValue) };
|
|
37
49
|
});
|
|
@@ -9,16 +9,29 @@ import { captureQueryProvider, snapshotListParams, snapshotManyParams } from './
|
|
|
9
9
|
import { decodeListResult, decodeManyResult, decodeBaseRecord, rejectProviderResponse, type RecordDecoder } from './record-decoder';
|
|
10
10
|
import { createOvertimeTracker } from './hook-utils.svelte';
|
|
11
11
|
import type { NotificationConfig, OvertimeOptions } from './hook-utils.svelte';
|
|
12
|
+
import { listQuerySettings, type ResourceQueryOptions } from './query-options';
|
|
12
13
|
import { createSelectProjection, normalizeSelectDefaultValue, orderSelectOptions, selectQueryFilters, type SelectOption, type SelectedOptionsOrder } from './select-options';
|
|
13
14
|
import { HttpError, type BaseRecord, type KnownResources, type Pagination, type Sort, type Filter } from './types';
|
|
14
15
|
import type { QueryKey } from './query-keys';
|
|
15
16
|
|
|
17
|
+
function optionEntries(value: unknown): SelectOption[] {
|
|
18
|
+
if (!value || typeof value !== 'object' || !('options' in value)) return [];
|
|
19
|
+
const options = value.options;
|
|
20
|
+
return Array.isArray(options) ? options as SelectOption[] : [];
|
|
21
|
+
}
|
|
22
|
+
|
|
16
23
|
function withAuthSession(key: QueryKey, authSession: string): QueryKey {
|
|
17
24
|
const descriptor = key[0];
|
|
18
25
|
return [{ ...descriptor, params: { ...decodeBaseRecord(descriptor.params), authSession } }];
|
|
19
26
|
}
|
|
20
27
|
|
|
21
|
-
|
|
28
|
+
type SelectListResult<TData extends BaseRecord> = { data: TData[]; total: number; options: SelectOption[] };
|
|
29
|
+
type SelectDefaultsResult<TData extends BaseRecord> = { data: TData[]; options: SelectOption[] };
|
|
30
|
+
|
|
31
|
+
export interface UseSelectOptions<
|
|
32
|
+
TData extends BaseRecord = BaseRecord,
|
|
33
|
+
TSelected = SelectListResult<TData>,
|
|
34
|
+
> extends ContractOptions {
|
|
22
35
|
resource: KnownResources;
|
|
23
36
|
/** @internal Distinguishes consumers that use different projection semantics. */
|
|
24
37
|
projectionKey?: string;
|
|
@@ -36,8 +49,8 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
|
|
|
36
49
|
debounce?: number;
|
|
37
50
|
/** Optional timeout in milliseconds for list and selected-record reads. */
|
|
38
51
|
requestTimeout?: number;
|
|
39
|
-
queryOptions?:
|
|
40
|
-
defaultValueQueryOptions?:
|
|
52
|
+
queryOptions?: ResourceQueryOptions<SelectListResult<TData>, TSelected>;
|
|
53
|
+
defaultValueQueryOptions?: ResourceQueryOptions<SelectDefaultsResult<TData>>;
|
|
41
54
|
meta?: Record<string, unknown>;
|
|
42
55
|
dataProviderName?: string;
|
|
43
56
|
onSearch?: (value: string) => Filter[];
|
|
@@ -46,8 +59,8 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
|
|
|
46
59
|
overtimeOptions?: OvertimeOptions;
|
|
47
60
|
}
|
|
48
61
|
|
|
49
|
-
export function createSelectQuery<TData extends BaseRecord
|
|
50
|
-
options: UseSelectOptions<TData>, getDecoder: () => RecordDecoder<TData>,
|
|
62
|
+
export function createSelectQuery<TData extends BaseRecord, TSelected = SelectListResult<TData>>(
|
|
63
|
+
options: UseSelectOptions<TData, TSelected>, getDecoder: () => RecordDecoder<TData>,
|
|
51
64
|
) {
|
|
52
65
|
const context = captureContractContext(options);
|
|
53
66
|
const adminOptions = getAdminOptions();
|
|
@@ -197,7 +210,7 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
197
210
|
});
|
|
198
211
|
const query = createSessionQuery<
|
|
199
212
|
{ data: TData[]; total: number },
|
|
200
|
-
|
|
213
|
+
TSelected
|
|
201
214
|
>(context, () => {
|
|
202
215
|
const origin = scope;
|
|
203
216
|
const { captured, decode, keys } = origin;
|
|
@@ -214,9 +227,15 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
214
227
|
});
|
|
215
228
|
const requestKey = withAuthSession(queryKey, origin.auth.cacheKey);
|
|
216
229
|
currentListKey = requestKey;
|
|
230
|
+
const projection = createSelectProjection(decodeResult, label, value, decode, () => sessionCurrent(origin));
|
|
231
|
+
const settings = listQuerySettings(options.queryOptions);
|
|
217
232
|
return {
|
|
218
233
|
resource: params.resource, successNotification: options.successNotification, errorNotification: options.errorNotification,
|
|
219
|
-
decode:
|
|
234
|
+
decode: (value: unknown, version: number): TSelected => {
|
|
235
|
+
const projected = projection(value, version);
|
|
236
|
+
const select = options.queryOptions?.select;
|
|
237
|
+
return select ? select(projected) : projected as TSelected;
|
|
238
|
+
},
|
|
220
239
|
queryKey,
|
|
221
240
|
// 同一 key 的请求可由其他 observer 共享,不能因本实例卸载或切换搜索而丢弃共享结果。
|
|
222
241
|
allowRetiredQueryFn: true,
|
|
@@ -226,8 +245,17 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
226
245
|
captured.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal: requestSignal }) })),
|
|
227
246
|
).then(decodeResult);
|
|
228
247
|
},
|
|
229
|
-
enabled:
|
|
230
|
-
...definedOptions({
|
|
248
|
+
enabled: settings.enabled,
|
|
249
|
+
...definedOptions({
|
|
250
|
+
staleTime: settings.staleTime ?? adminOptions.reactQuery?.staleTime,
|
|
251
|
+
gcTime: settings.gcTime ?? adminOptions.reactQuery?.gcTime,
|
|
252
|
+
refetchOnWindowFocus: settings.refetchOnWindowFocus ?? adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
253
|
+
retry: settings.retry,
|
|
254
|
+
retryDelay: settings.retryDelay,
|
|
255
|
+
refetchInterval: settings.refetchInterval,
|
|
256
|
+
refetchIntervalInBackground: settings.refetchIntervalInBackground,
|
|
257
|
+
placeholderData: settings.placeholderData as { data: TData[]; total: number } | ((previousData: { data: TData[]; total: number } | undefined) => { data: TData[]; total: number } | undefined) | undefined,
|
|
258
|
+
}),
|
|
231
259
|
};
|
|
232
260
|
});
|
|
233
261
|
const defaultValueQuery = createSessionQuery<
|
|
@@ -265,8 +293,16 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
265
293
|
).then(decodeResult);
|
|
266
294
|
},
|
|
267
295
|
enabled: (options.queryOptions?.enabled ?? true) &&
|
|
268
|
-
(options.defaultValueQueryOptions
|
|
269
|
-
|
|
296
|
+
(listQuerySettings(options.defaultValueQueryOptions).enabled) && params.ids.length > 0,
|
|
297
|
+
...definedOptions({
|
|
298
|
+
staleTime: options.defaultValueQueryOptions?.staleTime ?? Infinity,
|
|
299
|
+
gcTime: options.defaultValueQueryOptions?.gcTime,
|
|
300
|
+
refetchOnWindowFocus: options.defaultValueQueryOptions?.refetchOnWindowFocus,
|
|
301
|
+
retry: options.defaultValueQueryOptions?.retry,
|
|
302
|
+
retryDelay: options.defaultValueQueryOptions?.retryDelay,
|
|
303
|
+
refetchInterval: options.defaultValueQueryOptions?.refetchInterval,
|
|
304
|
+
refetchIntervalInBackground: options.defaultValueQueryOptions?.refetchIntervalInBackground,
|
|
305
|
+
}),
|
|
270
306
|
};
|
|
271
307
|
});
|
|
272
308
|
const overtime = createOvertimeTracker(
|
|
@@ -302,7 +338,7 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
302
338
|
query, defaultValueQuery, onSearchChange, cancel: cancelRequests,
|
|
303
339
|
get options() {
|
|
304
340
|
return orderSelectOptions(
|
|
305
|
-
query.data
|
|
341
|
+
optionEntries(query.data),
|
|
306
342
|
defaultValueQuery.data?.options ?? [],
|
|
307
343
|
options.selectedOptionsOrder ?? 'in-place',
|
|
308
344
|
);
|
|
@@ -6,7 +6,9 @@ import type { ContractOptions } from './contract-context.svelte';
|
|
|
6
6
|
import { captureAdminContext } from './context.svelte';
|
|
7
7
|
import { contractKey,validateContractId,parseContractId,parseContractRecord,type ResourceContract,type ContractSchemas,type ContractRecord,type ContractId,type ContractFormAction } from './resource-contract';
|
|
8
8
|
import type { RecordDecoder } from './record-decoder';
|
|
9
|
-
import type { KnownResources,Filter } from './types';
|
|
9
|
+
import type { GetListResult, GetManyResult, GetOneResult, HttpError, KnownResources, Filter } from './types';
|
|
10
|
+
import type { InfinitePages } from './infinite-query.svelte';
|
|
11
|
+
import type { SelectOption } from './select-options';
|
|
10
12
|
import { useQueryClient } from '@tanstack/svelte-query';
|
|
11
13
|
import { replaceReactiveMembers } from './reactive-projection';
|
|
12
14
|
import { snapshotInvalidationParams } from './invalidation-contract';
|
|
@@ -25,6 +27,21 @@ import { useContractCreate, type ContractCreateOptions } from './create-hooks.sv
|
|
|
25
27
|
|
|
26
28
|
type Field<T>=Extract<keyof T,string>;
|
|
27
29
|
type ValueField<T>={ [K in Field<T>]-?: T[K] extends string|number? K:never }[Field<T>];
|
|
30
|
+
type CallableMember<T>=true extends { [K in keyof T]: T[K] extends (...args: never)=>unknown? true:never }[keyof T]? true:false;
|
|
31
|
+
/** 与 readRecordPath 一致:点分路径只进入普通对象,不进入数组、字典或方法。 */
|
|
32
|
+
type JsonObject<T>=T extends object
|
|
33
|
+
? T extends readonly unknown[]? false
|
|
34
|
+
: CallableMember<T>extends true? false
|
|
35
|
+
: string extends keyof T? false
|
|
36
|
+
: true
|
|
37
|
+
: false;
|
|
38
|
+
type LabelPaths<T,Depth extends readonly unknown[]= []>=Depth['length']extends 4? Extract<keyof T,string>
|
|
39
|
+
: T extends unknown? JsonObject<T>extends true? {
|
|
40
|
+
[K in Extract<keyof T,string>]: JsonObject<NonNullable<T[K]>>extends true
|
|
41
|
+
? K|`${K}.${LabelPaths<NonNullable<T[K]>,[...Depth,unknown]> & string}`
|
|
42
|
+
: K
|
|
43
|
+
}[Extract<keyof T,string>]: never: never;
|
|
44
|
+
type OptionLabel<T>=string extends Field<T>? string: Field<T>|(LabelPaths<T>extends string? LabelPaths<T>: never);
|
|
28
45
|
type FieldPredicate<T>=
|
|
29
46
|
|{ operator: 'eq'|'ne'|'eqs'|'nes'; value: Exclude<T,undefined> }
|
|
30
47
|
|{ operator: 'in'|'nin'|'ina'|'nina'; value: Exclude<T,undefined>[] }
|
|
@@ -72,21 +89,31 @@ function recordDecoder<S extends ContractSchemas>(options: query.MaybeGetter<Bou
|
|
|
72
89
|
};
|
|
73
90
|
}
|
|
74
91
|
|
|
75
|
-
export function useList<S extends ContractSchemas
|
|
76
|
-
|
|
92
|
+
export function useList<S extends ContractSchemas, TSelected = GetListResult<Row<S>>>(
|
|
93
|
+
options: query.MaybeGetter<ListOptions<query.UseListOptions<Row<S>, HttpError, TSelected>, S>>,
|
|
94
|
+
) {
|
|
95
|
+
return query.createListQuery<Row<S>, TSelected>(getter(options), recordDecoder(options));
|
|
77
96
|
}
|
|
78
97
|
/** Refine 迁移别名,契约边界与 useList 相同。 */
|
|
79
|
-
export function useSimpleList<S extends ContractSchemas
|
|
80
|
-
|
|
98
|
+
export function useSimpleList<S extends ContractSchemas, TSelected = GetListResult<Row<S>>>(
|
|
99
|
+
options: query.MaybeGetter<ListOptions<query.UseListOptions<Row<S>, HttpError, TSelected>, S>>,
|
|
100
|
+
) {
|
|
101
|
+
return useList<S, TSelected>(options);
|
|
81
102
|
}
|
|
82
|
-
export function useOne<S extends ContractSchemas
|
|
83
|
-
|
|
103
|
+
export function useOne<S extends ContractSchemas, TSelected = GetOneResult<Row<S>>>(
|
|
104
|
+
options: query.MaybeGetter<QueryOptions<query.UseOneOptions<Row<S>, HttpError, TSelected>, S> & { id: Id<S> }>,
|
|
105
|
+
) {
|
|
106
|
+
return query.createOneQuery<Row<S>, TSelected>(getter(options), recordDecoder(options));
|
|
84
107
|
}
|
|
85
|
-
export function useMany<S extends ContractSchemas
|
|
86
|
-
|
|
108
|
+
export function useMany<S extends ContractSchemas, TSelected = GetManyResult<Row<S>>>(
|
|
109
|
+
options: query.MaybeGetter<QueryOptions<query.UseManyOptions<Row<S>, HttpError, TSelected>, S> & { ids: Id<S>[] }>,
|
|
110
|
+
) {
|
|
111
|
+
return query.createManyQuery<Row<S>, TSelected>(getter(options), recordDecoder(options));
|
|
87
112
|
}
|
|
88
|
-
export function useShow<S extends ContractSchemas
|
|
89
|
-
|
|
113
|
+
export function useShow<S extends ContractSchemas, TSelected = GetOneResult<Row<S>>>(
|
|
114
|
+
options: query.MaybeGetter<QueryOptions<query.UseOneOptions<Row<S>, HttpError, TSelected>, S> & { id: Id<S> }>,
|
|
115
|
+
) {
|
|
116
|
+
const result=query.createShowQuery<Row<S>, TSelected>(getter(options), recordDecoder(options));
|
|
90
117
|
return replaceReactiveMembers(result,{
|
|
91
118
|
get showId(): Id<S> {
|
|
92
119
|
return parseContractId((typeof options==='function'? options():options).resource,result.showId);
|
|
@@ -97,18 +124,20 @@ export function useShow<S extends ContractSchemas>(options: query.MaybeGetter<Qu
|
|
|
97
124
|
},
|
|
98
125
|
});
|
|
99
126
|
}
|
|
100
|
-
export function useInfiniteList<S extends ContractSchemas
|
|
101
|
-
|
|
127
|
+
export function useInfiniteList<S extends ContractSchemas, TSelected = InfinitePages<Row<S>>>(
|
|
128
|
+
options: ListOptions<bulk.UseInfiniteListOptions<Row<S>, TSelected>, S>,
|
|
129
|
+
) {
|
|
130
|
+
return bulk.createInfiniteListQuery<Row<S>, TSelected>(bind(options), recordDecoder(options));
|
|
102
131
|
}
|
|
103
|
-
export function useSelect<S extends ContractSchemas>(
|
|
104
|
-
options: ListOptions<Omit<bulk.UseSelectOptions<Row<S
|
|
105
|
-
optionLabel:
|
|
132
|
+
export function useSelect<S extends ContractSchemas, TSelected = { data: Row<S>[]; total: number; options: SelectOption[] }>(
|
|
133
|
+
options: ListOptions<Omit<bulk.UseSelectOptions<Row<S>, TSelected>,'optionLabel'|'optionValue'|'defaultValue'|'onSearch'>,S>&{
|
|
134
|
+
optionLabel: OptionLabel<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string);
|
|
106
135
|
optionValue: ValueField<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string|number);
|
|
107
136
|
defaultValue?: Id<S> | readonly Id<S>[];
|
|
108
137
|
onSearch?: (value: string) => ContractFilter<NoInfer<Row<S>>>[];
|
|
109
138
|
},
|
|
110
139
|
) {
|
|
111
|
-
return bulk.createSelectQuery(bind(options),recordDecoder(options));
|
|
140
|
+
return bulk.createSelectQuery<Row<S>, TSelected>(bind(options), recordDecoder(options));
|
|
112
141
|
}
|
|
113
142
|
export function useTable<S extends ContractSchemas>(
|
|
114
143
|
options: query.MaybeGetter<QueryOptions<UseTableOptions,S>&{
|