@svadmin/core 0.69.2 → 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 +6 -2
- package/src/client-filter.ts +77 -0
- package/src/crud-operator-schema.ts +20 -0
- package/src/editable-table.svelte.ts +90 -0
- package/src/editable-table.ts +339 -0
- package/src/index.ts +15 -5
- package/src/inferencer-contract.ts +114 -0
- package/src/inferencer.ts +219 -42
- 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 +78 -37
- package/src/query-options.ts +79 -0
- package/src/query-snapshot.ts +3 -4
- package/src/resource-contract.ts +6 -3
- package/src/resource-schemas.ts +3 -6
- package/src/router-provider.ts +11 -0
- package/src/routing-hooks.svelte.ts +84 -3
- package/src/select-options.ts +49 -3
- package/src/select-query.svelte.ts +67 -16
- package/src/session-query.svelte.ts +6 -1
- package/src/strict-hooks.svelte.ts +53 -20
- package/src/table-hooks.svelte.ts +22 -60
- package/src/table-state.svelte.ts +4 -3
- package/src/types.ts +22 -7
- package/src/url-sync.ts +107 -30
- package/src/utility-hooks.svelte.ts +1 -19
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { isCrudFieldOperator, type CrudOperator, type Filter, CRUD_FIELD_OPERATORS } from './types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 各一手数据源实际执行的筛选协议。
|
|
5
|
+
* 未声明的运算符或逻辑组合必须失败关闭,不能改写成相等或丢掉条件组。
|
|
6
|
+
*/
|
|
7
|
+
export const FILTER_PROVIDER_IDS = [
|
|
8
|
+
'pocketbase',
|
|
9
|
+
'directus',
|
|
10
|
+
'sanity',
|
|
11
|
+
'elysia',
|
|
12
|
+
'supabase-table',
|
|
13
|
+
'scaffold-memory',
|
|
14
|
+
] as const;
|
|
15
|
+
|
|
16
|
+
export type FilterProviderId = (typeof FILTER_PROVIDER_IDS)[number];
|
|
17
|
+
|
|
18
|
+
export interface ProviderFilterCapability {
|
|
19
|
+
id: FilterProviderId;
|
|
20
|
+
/** 语义等价、会被真正下推的字段运算符。 */
|
|
21
|
+
operators: readonly CrudOperator[];
|
|
22
|
+
/** 是否执行嵌套 and/or。key 只是条件组身份,不是查询谓词。 */
|
|
23
|
+
logical: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function operators(values: readonly CrudOperator[]): readonly CrudOperator[] {
|
|
27
|
+
return values;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const PROVIDER_FILTER_CAPABILITIES: Record<FilterProviderId, ProviderFilterCapability> = {
|
|
31
|
+
pocketbase: {
|
|
32
|
+
id: 'pocketbase',
|
|
33
|
+
logical: true,
|
|
34
|
+
operators: operators([
|
|
35
|
+
'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
|
|
36
|
+
'contains', 'ncontains', 'startswith', 'nstartswith', 'endswith', 'nendswith',
|
|
37
|
+
'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
|
|
38
|
+
]),
|
|
39
|
+
},
|
|
40
|
+
directus: {
|
|
41
|
+
id: 'directus',
|
|
42
|
+
logical: true,
|
|
43
|
+
operators: operators([
|
|
44
|
+
'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
|
|
45
|
+
'contains', 'ncontains', 'containss', 'ncontainss',
|
|
46
|
+
'startswith', 'nstartswith', 'startswiths', 'nstartswiths',
|
|
47
|
+
'endswith', 'nendswith', 'endswiths', 'nendswiths',
|
|
48
|
+
'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
|
|
49
|
+
]),
|
|
50
|
+
},
|
|
51
|
+
sanity: {
|
|
52
|
+
id: 'sanity',
|
|
53
|
+
logical: true,
|
|
54
|
+
operators: operators([
|
|
55
|
+
'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
|
|
56
|
+
'contains', 'ncontains', 'startswith', 'endswith',
|
|
57
|
+
'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
|
|
58
|
+
]),
|
|
59
|
+
},
|
|
60
|
+
elysia: {
|
|
61
|
+
id: 'elysia',
|
|
62
|
+
logical: true,
|
|
63
|
+
operators: CRUD_FIELD_OPERATORS,
|
|
64
|
+
},
|
|
65
|
+
'supabase-table': {
|
|
66
|
+
id: 'supabase-table',
|
|
67
|
+
logical: false,
|
|
68
|
+
operators: operators(['eq']),
|
|
69
|
+
},
|
|
70
|
+
'scaffold-memory': {
|
|
71
|
+
id: 'scaffold-memory',
|
|
72
|
+
logical: true,
|
|
73
|
+
operators: operators(['eq', 'ne', 'contains', 'in', 'null', 'nnull']),
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const supportedOperators = new Map<FilterProviderId, ReadonlySet<string>>(
|
|
78
|
+
FILTER_PROVIDER_IDS.map((id) => [id, new Set(PROVIDER_FILTER_CAPABILITIES[id].operators)]),
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
export function providerSupportsOperator(provider: FilterProviderId, operator: CrudOperator): boolean {
|
|
82
|
+
return supportedOperators.get(provider)?.has(operator) ?? false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function visitFilter(provider: FilterProviderId, filter: Filter, depth: number, seen: Set<object>): void {
|
|
86
|
+
const capability = PROVIDER_FILTER_CAPABILITIES[provider];
|
|
87
|
+
const allowed = supportedOperators.get(provider);
|
|
88
|
+
if (!capability || !allowed) throw new Error(`Unknown filter provider: ${provider}`);
|
|
89
|
+
if (depth > 32) throw new Error(`Unsupported ${provider} filter: nesting is too deep`);
|
|
90
|
+
if (typeof filter !== 'object' || filter === null || seen.has(filter)) {
|
|
91
|
+
throw new Error(`Unsupported ${provider} filter: expected an object`);
|
|
92
|
+
}
|
|
93
|
+
seen.add(filter);
|
|
94
|
+
if ('field' in filter) {
|
|
95
|
+
if (!isCrudFieldOperator(filter.operator) || !allowed.has(filter.operator)) {
|
|
96
|
+
throw new Error(`Unsupported ${provider} filter operator: ${String(filter.operator)}`);
|
|
97
|
+
}
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (!capability.logical || (filter.operator !== 'and' && filter.operator !== 'or') || !Array.isArray(filter.value)) {
|
|
101
|
+
throw new Error(`Unsupported ${provider} logical operator: ${String(filter.operator)}`);
|
|
102
|
+
}
|
|
103
|
+
for (const child of filter.value) visitFilter(provider, child, depth + 1, seen);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 在翻译之前拒绝能力矩阵之外的运算符和逻辑组合。 */
|
|
107
|
+
export function assertFiltersExecutable(provider: FilterProviderId, filters: readonly Filter[] | undefined): void {
|
|
108
|
+
if (!FILTER_PROVIDER_IDS.includes(provider)) throw new Error(`Unknown filter provider: ${String(provider)}`);
|
|
109
|
+
const seen = new Set<object>();
|
|
110
|
+
for (const filter of filters ?? []) visitFilter(provider, filter, 0, seen);
|
|
111
|
+
}
|
|
@@ -19,19 +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 { listQuerySettings, type ResourceQueryOptions } from './query-options';
|
|
22
23
|
|
|
23
24
|
// ─── useList ───────────────────────────────────────────────────
|
|
24
25
|
|
|
25
26
|
export type MaybeGetter<T>=T|(() => T);
|
|
26
27
|
|
|
27
|
-
export interface UseListOptions<
|
|
28
|
+
export interface UseListOptions<
|
|
29
|
+
_TData extends BaseRecord=BaseRecord,
|
|
30
|
+
_TError=HttpError,
|
|
31
|
+
TSelected=GetListResult<_TData>,
|
|
32
|
+
> extends ContractOptions {
|
|
28
33
|
resource?: KnownResources;
|
|
29
34
|
pagination?: Pagination;
|
|
30
35
|
sorters?: Sort[];
|
|
31
36
|
filters?: Filter[];
|
|
32
37
|
meta?: Record<string,unknown>;
|
|
33
38
|
dataProviderName?: string;
|
|
34
|
-
queryOptions?:
|
|
39
|
+
queryOptions?: ResourceQueryOptions<GetListResult<_TData>, TSelected>;
|
|
35
40
|
successNotification?: NotificationConfig;
|
|
36
41
|
errorNotification?: NotificationConfig;
|
|
37
42
|
liveMode?: LiveMode;
|
|
@@ -44,8 +49,8 @@ export function useList(optionsOrGetter: MaybeGetter<UseListOptions>={}) {
|
|
|
44
49
|
return createListQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
45
50
|
}
|
|
46
51
|
|
|
47
|
-
export function createListQuery<TData extends BaseRecord
|
|
48
|
-
optionsOrGetter: MaybeGetter<UseListOptions
|
|
52
|
+
export function createListQuery<TData extends BaseRecord, TSelected = GetListResult<TData>>(
|
|
53
|
+
optionsOrGetter: MaybeGetter<UseListOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
49
54
|
) {
|
|
50
55
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
51
56
|
const parsed=useParsed();
|
|
@@ -54,7 +59,7 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
54
59
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
55
60
|
const getResource=() => getOptions().resource??parsed.resource??'';
|
|
56
61
|
|
|
57
|
-
const query=createSessionQuery<GetListResult<TData
|
|
62
|
+
const query=createSessionQuery<GetListResult<TData>, TSelected>(adminContext,() => {
|
|
58
63
|
const decode=getDecoder();
|
|
59
64
|
const opts=getOptions();
|
|
60
65
|
const checkId=opts.contract!==undefined;
|
|
@@ -63,6 +68,7 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
63
68
|
resource,...definedOptions({ dataProviderName: opts.dataProviderName,contract: opts.contract,meta: opts.meta }),
|
|
64
69
|
});
|
|
65
70
|
const queryOptions=opts.queryOptions;
|
|
71
|
+
const settings=listQuerySettings(queryOptions);
|
|
66
72
|
|
|
67
73
|
// Inject a parent filter for nested resources.
|
|
68
74
|
// Consume only parentParams parsed from the path, such as teamId in /teams/123/users,
|
|
@@ -94,7 +100,6 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
94
100
|
|
|
95
101
|
return {
|
|
96
102
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
97
|
-
decode: decodeResult,
|
|
98
103
|
queryKey: adminContext.queryKeys(resource,opts.dataProviderName).data.list(resource,{
|
|
99
104
|
...definedOptions({
|
|
100
105
|
pagination: params.pagination,sorters: params.sorters,filters: params.filters,meta: params.meta,
|
|
@@ -107,11 +112,21 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
107
112
|
});
|
|
108
113
|
return decodeResult(await current.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal }) })));
|
|
109
114
|
},
|
|
110
|
-
|
|
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
|
+
},
|
|
120
|
+
enabled: settings.enabled,
|
|
111
121
|
...definedOptions({
|
|
112
|
-
staleTime:
|
|
113
|
-
gcTime:
|
|
114
|
-
refetchOnWindowFocus:
|
|
122
|
+
staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
|
|
123
|
+
gcTime: settings.gcTime??adminOptions.reactQuery?.gcTime,
|
|
124
|
+
refetchOnWindowFocus: settings.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
125
|
+
retry: settings.retry,
|
|
126
|
+
retryDelay: settings.retryDelay,
|
|
127
|
+
refetchInterval: settings.refetchInterval,
|
|
128
|
+
refetchIntervalInBackground: settings.refetchIntervalInBackground,
|
|
129
|
+
placeholderData: settings.placeholderData as GetListResult<TData> | ((previousData: GetListResult<TData> | undefined) => GetListResult<TData> | undefined) | undefined,
|
|
115
130
|
}),
|
|
116
131
|
};
|
|
117
132
|
});
|
|
@@ -140,12 +155,16 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
140
155
|
|
|
141
156
|
// ─── useOne ────────────────────────────────────────────────────
|
|
142
157
|
|
|
143
|
-
export interface UseOneOptions<
|
|
158
|
+
export interface UseOneOptions<
|
|
159
|
+
_TData extends BaseRecord=BaseRecord,
|
|
160
|
+
_TError=HttpError,
|
|
161
|
+
TSelected=GetOneResult<_TData>,
|
|
162
|
+
> extends ContractOptions {
|
|
144
163
|
resource?: KnownResources;
|
|
145
164
|
id?: string|number;
|
|
146
165
|
meta?: Record<string,unknown>;
|
|
147
166
|
dataProviderName?: string;
|
|
148
|
-
queryOptions?:
|
|
167
|
+
queryOptions?: ResourceQueryOptions<GetOneResult<_TData>, TSelected>;
|
|
149
168
|
successNotification?: NotificationConfig;
|
|
150
169
|
errorNotification?: NotificationConfig;
|
|
151
170
|
liveMode?: LiveMode;
|
|
@@ -158,8 +177,8 @@ export function useOne(optionsOrGetter: MaybeGetter<UseOneOptions>={}) {
|
|
|
158
177
|
return createOneQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
159
178
|
}
|
|
160
179
|
|
|
161
|
-
export function createOneQuery<TData extends BaseRecord
|
|
162
|
-
optionsOrGetter: MaybeGetter<UseOneOptions
|
|
180
|
+
export function createOneQuery<TData extends BaseRecord, TSelected = GetOneResult<TData>>(
|
|
181
|
+
optionsOrGetter: MaybeGetter<UseOneOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
163
182
|
) {
|
|
164
183
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
165
184
|
const parsed=useParsed();
|
|
@@ -169,7 +188,7 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
169
188
|
const getResource=() => getOptions().resource??parsed.resource??'';
|
|
170
189
|
const getId=() => getOptions().id??parsed.id;
|
|
171
190
|
|
|
172
|
-
const query=createSessionQuery<GetOneResult<TData
|
|
191
|
+
const query=createSessionQuery<GetOneResult<TData>, TSelected>(adminContext,() => {
|
|
173
192
|
const decode=getDecoder();
|
|
174
193
|
const opts=getOptions();
|
|
175
194
|
const resource=opts.resource??parsed.resource??'';
|
|
@@ -182,14 +201,17 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
182
201
|
resource,id,...definedOptions({ meta: captured.meta }),
|
|
183
202
|
});
|
|
184
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
|
+
};
|
|
185
211
|
|
|
186
212
|
return {
|
|
187
213
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
188
|
-
decode:
|
|
189
|
-
const decoded=decodeOneResult(value,decode);
|
|
190
|
-
if(checkId && params && decoded.data['id']!==params.id) return rejectProviderResponse();
|
|
191
|
-
return decoded;
|
|
192
|
-
},
|
|
214
|
+
decode: project,
|
|
193
215
|
queryKey: adminContext.queryKeys(resource,opts.dataProviderName).data.one(resource,id??'',{
|
|
194
216
|
...definedOptions({ meta: captured.meta }),
|
|
195
217
|
source: captured.source,
|
|
@@ -201,11 +223,16 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
201
223
|
if(checkId && decoded.data['id']!==params.id) return rejectProviderResponse();
|
|
202
224
|
return decoded;
|
|
203
225
|
},
|
|
204
|
-
enabled:
|
|
226
|
+
enabled: settings.enabled&&id!=null,
|
|
205
227
|
...definedOptions({
|
|
206
|
-
staleTime:
|
|
207
|
-
gcTime:
|
|
208
|
-
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,
|
|
209
236
|
}),
|
|
210
237
|
};
|
|
211
238
|
});
|
|
@@ -234,8 +261,8 @@ export function createOneQuery<TData extends BaseRecord>(
|
|
|
234
261
|
}
|
|
235
262
|
|
|
236
263
|
// ─── useShow ──────────────────────────────────────────────────
|
|
237
|
-
export function createShowQuery<TData extends BaseRecord
|
|
238
|
-
optionsOrGetter: MaybeGetter<UseOneOptions
|
|
264
|
+
export function createShowQuery<TData extends BaseRecord, TSelected = GetOneResult<TData>>(
|
|
265
|
+
optionsOrGetter: MaybeGetter<UseOneOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
239
266
|
) {
|
|
240
267
|
const parsed=useParsed();
|
|
241
268
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
@@ -248,7 +275,7 @@ export function createShowQuery<TData extends BaseRecord>(
|
|
|
248
275
|
function setShowId(id: string|number) { _showId=id; }
|
|
249
276
|
|
|
250
277
|
// We wrap it in a getter so useOne evaluates it dynamically.
|
|
251
|
-
const result=createOneQuery(() => ({
|
|
278
|
+
const result=createOneQuery<TData, TSelected>(() => ({
|
|
252
279
|
...getOptions(),
|
|
253
280
|
...definedOptions({ id: showId }),
|
|
254
281
|
}), getDecoder);
|
|
@@ -258,12 +285,16 @@ export function createShowQuery<TData extends BaseRecord>(
|
|
|
258
285
|
|
|
259
286
|
// ─── useMany ───────────────────────────────────────────────────
|
|
260
287
|
|
|
261
|
-
export interface UseManyOptions<
|
|
288
|
+
export interface UseManyOptions<
|
|
289
|
+
_TData extends BaseRecord=BaseRecord,
|
|
290
|
+
_TError=HttpError,
|
|
291
|
+
TSelected=GetManyResult<_TData>,
|
|
292
|
+
> extends ContractOptions {
|
|
262
293
|
resource: KnownResources;
|
|
263
294
|
ids: (string|number)[];
|
|
264
295
|
meta?: Record<string,unknown>;
|
|
265
296
|
dataProviderName?: string;
|
|
266
|
-
queryOptions?:
|
|
297
|
+
queryOptions?: ResourceQueryOptions<GetManyResult<_TData>, TSelected>;
|
|
267
298
|
successNotification?: NotificationConfig;
|
|
268
299
|
errorNotification?: NotificationConfig;
|
|
269
300
|
liveMode?: LiveMode;
|
|
@@ -276,18 +307,19 @@ export function useMany(optionsOrGetter: MaybeGetter<UseManyOptions>) {
|
|
|
276
307
|
return createManyQuery(optionsOrGetter, () => decodeBaseRecord);
|
|
277
308
|
}
|
|
278
309
|
|
|
279
|
-
export function createManyQuery<TData extends BaseRecord
|
|
280
|
-
optionsOrGetter: MaybeGetter<UseManyOptions
|
|
310
|
+
export function createManyQuery<TData extends BaseRecord, TSelected = GetManyResult<TData>>(
|
|
311
|
+
optionsOrGetter: MaybeGetter<UseManyOptions<TData, HttpError, TSelected>>, getDecoder: () => RecordDecoder<TData>,
|
|
281
312
|
) {
|
|
282
313
|
const adminContext=captureContractContext(optionsOrGetter);
|
|
283
314
|
const adminOptions=getAdminOptions();
|
|
284
315
|
const getOptions=() => typeof optionsOrGetter==='function'? optionsOrGetter():optionsOrGetter;
|
|
285
316
|
|
|
286
|
-
const query=createSessionQuery<GetManyResult<TData
|
|
317
|
+
const query=createSessionQuery<GetManyResult<TData>, TSelected>(adminContext,() => {
|
|
287
318
|
const decode=getDecoder();
|
|
288
319
|
const opts=getOptions();
|
|
289
320
|
const checkId=opts.contract!==undefined;
|
|
290
321
|
const { resource,ids,meta,dataProviderName,queryOptions }=opts;
|
|
322
|
+
const settings=listQuerySettings(queryOptions);
|
|
291
323
|
const captured=captureQueryProvider(adminContext,{
|
|
292
324
|
resource,...definedOptions({ dataProviderName,contract: opts.contract,meta }),
|
|
293
325
|
});
|
|
@@ -305,7 +337,11 @@ export function createManyQuery<TData extends BaseRecord>(
|
|
|
305
337
|
|
|
306
338
|
return {
|
|
307
339
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
308
|
-
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
|
+
},
|
|
309
345
|
queryKey: adminContext.queryKeys(resource,dataProviderName).data.many(resource,{
|
|
310
346
|
ids: params.ids,
|
|
311
347
|
...definedOptions({ meta: params.meta }),
|
|
@@ -323,11 +359,16 @@ export function createManyQuery<TData extends BaseRecord>(
|
|
|
323
359
|
})),decode)));
|
|
324
360
|
return decodeResult({ data: results.map(r => r.data) });
|
|
325
361
|
},
|
|
326
|
-
enabled:
|
|
362
|
+
enabled: settings.enabled&¶ms.ids.length>0,
|
|
327
363
|
...definedOptions({
|
|
328
|
-
staleTime:
|
|
329
|
-
gcTime:
|
|
330
|
-
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,
|
|
331
372
|
}),
|
|
332
373
|
};
|
|
333
374
|
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { definedOptions } from './defined-options';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 查询钩子可以安全转发的 TanStack Query 选项。
|
|
5
|
+
* `select` 在解码之后执行,可以改变投影类型,且不会改写缓存里的原始响应。
|
|
6
|
+
*/
|
|
7
|
+
export interface ResourceQueryOptions<TQueryFnData = unknown, TData = TQueryFnData> {
|
|
8
|
+
staleTime?: number;
|
|
9
|
+
enabled?: boolean;
|
|
10
|
+
gcTime?: number;
|
|
11
|
+
refetchOnWindowFocus?: boolean | 'always';
|
|
12
|
+
retry?: boolean | number;
|
|
13
|
+
retryDelay?: number | ((failureCount: number, error: unknown) => number);
|
|
14
|
+
refetchInterval?: number | false;
|
|
15
|
+
refetchIntervalInBackground?: boolean;
|
|
16
|
+
placeholderData?: TQueryFnData | ((previousData: TQueryFnData | undefined) => TQueryFnData | undefined);
|
|
17
|
+
select?: (data: TQueryFnData) => TData;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ListQuerySettings<TData = unknown> {
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
staleTime?: number;
|
|
23
|
+
gcTime?: number;
|
|
24
|
+
refetchOnWindowFocus?: boolean | 'always';
|
|
25
|
+
retry?: boolean | number;
|
|
26
|
+
retryDelay?: ResourceQueryOptions<TData>['retryDelay'];
|
|
27
|
+
refetchInterval?: number | false;
|
|
28
|
+
refetchIntervalInBackground?: boolean;
|
|
29
|
+
placeholderData?: ResourceQueryOptions<TData>['placeholderData'];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function listQuerySettings<TQueryFnData>(
|
|
33
|
+
options: ResourceQueryOptions<TQueryFnData, unknown> | undefined,
|
|
34
|
+
): ListQuerySettings<TQueryFnData> {
|
|
35
|
+
return {
|
|
36
|
+
enabled: options?.enabled ?? true,
|
|
37
|
+
...definedOptions({
|
|
38
|
+
staleTime: options?.staleTime,
|
|
39
|
+
gcTime: options?.gcTime,
|
|
40
|
+
refetchOnWindowFocus: options?.refetchOnWindowFocus,
|
|
41
|
+
retry: options?.retry,
|
|
42
|
+
retryDelay: options?.retryDelay,
|
|
43
|
+
refetchInterval: options?.refetchInterval,
|
|
44
|
+
refetchIntervalInBackground: options?.refetchIntervalInBackground,
|
|
45
|
+
placeholderData: options?.placeholderData,
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function projectSelected<TQueryFnData, TData>(
|
|
51
|
+
data: TQueryFnData,
|
|
52
|
+
select?: (data: TQueryFnData) => TData,
|
|
53
|
+
): TQueryFnData | TData {
|
|
54
|
+
return select ? select(data) : data;
|
|
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/query-snapshot.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Type, type Static, type TSchema } from 'typebox';
|
|
2
2
|
import type { AdminContextAccessor } from './context.svelte';
|
|
3
3
|
import type { DataProvider, GetListParams, GetOneParams, GetManyParams } from './types';
|
|
4
|
+
import { crudFieldOperatorSchema } from './crud-operator-schema';
|
|
4
5
|
import { HttpError } from './types';
|
|
5
6
|
import { contractProvider, type ResourceContract } from './resource-contract';
|
|
6
7
|
import { definedOptions } from './defined-options';
|
|
@@ -12,13 +13,11 @@ const filters = Type.Cyclic({
|
|
|
12
13
|
Filters: Type.Union([
|
|
13
14
|
Type.Object({
|
|
14
15
|
field: Type.String(),
|
|
15
|
-
operator:
|
|
16
|
-
'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in', 'nin', 'contains', 'ncontains',
|
|
17
|
-
'startswith', 'endswith', 'null', 'nnull', 'between', 'nbetween',
|
|
18
|
-
] as const).map(value => Type.Literal(value))),
|
|
16
|
+
operator: crudFieldOperatorSchema,
|
|
19
17
|
value: Type.Unknown(),
|
|
20
18
|
}, { additionalProperties: false }),
|
|
21
19
|
Type.Object({
|
|
20
|
+
key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
22
21
|
operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
|
|
23
22
|
value: Type.Array(Type.Ref('Filters')),
|
|
24
23
|
}, { additionalProperties: false }),
|
package/src/resource-contract.ts
CHANGED
|
@@ -500,6 +500,7 @@ export function validateContractMutationParams(contract: ResourceContract | unde
|
|
|
500
500
|
}
|
|
501
501
|
|
|
502
502
|
const filterGroup = Type.Object({
|
|
503
|
+
key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
503
504
|
operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
|
|
504
505
|
value: Type.Array(Type.Unknown()),
|
|
505
506
|
}, { additionalProperties: false });
|
|
@@ -532,10 +533,12 @@ function checkFilters(filters: unknown, record: TObject, depth = 0): void {
|
|
|
532
533
|
}
|
|
533
534
|
const scalar = Type.Exclude(field, Type.Null());
|
|
534
535
|
switch (filter.operator) {
|
|
535
|
-
case 'eq': case 'ne': check(field, filter.value, filter.field); break;
|
|
536
|
-
case 'in': case 'nin': check(Type.Array(field), filter.value, filter.field); break;
|
|
536
|
+
case 'eq': case 'ne': case 'eqs': case 'nes': check(field, filter.value, filter.field); break;
|
|
537
|
+
case 'in': case 'nin': case 'ina': case 'nina': check(Type.Array(field), filter.value, filter.field); break;
|
|
537
538
|
case 'null': case 'nnull': check(Type.Null(), filter.value, filter.field); break;
|
|
538
|
-
case 'contains': case 'ncontains': case '
|
|
539
|
+
case 'contains': case 'ncontains': case 'containss': case 'ncontainss':
|
|
540
|
+
case 'startswith': case 'nstartswith': case 'startswiths': case 'nstartswiths':
|
|
541
|
+
case 'endswith': case 'nendswith': case 'endswiths': case 'nendswiths':
|
|
539
542
|
check(Type.Intersect([scalar, Type.String()]), filter.value, filter.field); break;
|
|
540
543
|
case 'lt': case 'lte': case 'gt': case 'gte':
|
|
541
544
|
check(Type.Intersect([scalar, Type.Union([Type.String(), Type.Number()])]), filter.value, filter.field); break;
|
package/src/resource-schemas.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
ResourceInputOperation,
|
|
12
12
|
GetOneResult, GetManyResult, GetListResult,
|
|
13
13
|
} from './types';
|
|
14
|
+
import { crudFieldOperatorSchema } from './crud-operator-schema';
|
|
14
15
|
|
|
15
16
|
export interface ResourceSchemas {
|
|
16
17
|
/** Schema for complete records returned by standard CRUD operations. */
|
|
@@ -46,17 +47,13 @@ const common = {
|
|
|
46
47
|
const filter = Type.Cyclic({
|
|
47
48
|
Filter: Type.Union([
|
|
48
49
|
Type.Object({
|
|
50
|
+
key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
49
51
|
operator: Type.Union([Type.Literal('or'), Type.Literal('and')]),
|
|
50
52
|
value: Type.Array(Type.Ref('Filter')),
|
|
51
53
|
}, { additionalProperties: false }),
|
|
52
54
|
Type.Object({
|
|
53
55
|
field: Type.String(),
|
|
54
|
-
operator:
|
|
55
|
-
Type.Literal('eq'), Type.Literal('ne'), Type.Literal('lt'), Type.Literal('gt'),
|
|
56
|
-
Type.Literal('lte'), Type.Literal('gte'), Type.Literal('contains'), Type.Literal('ncontains'),
|
|
57
|
-
Type.Literal('startswith'), Type.Literal('endswith'), Type.Literal('in'), Type.Literal('nin'),
|
|
58
|
-
Type.Literal('null'), Type.Literal('nnull'), Type.Literal('between'), Type.Literal('nbetween'),
|
|
59
|
-
]),
|
|
56
|
+
operator: crudFieldOperatorSchema,
|
|
60
57
|
value: Type.Unknown(),
|
|
61
58
|
}, { additionalProperties: false }),
|
|
62
59
|
]),
|
package/src/router-provider.ts
CHANGED
|
@@ -23,6 +23,17 @@ export interface RouterProvider {
|
|
|
23
23
|
};
|
|
24
24
|
/** Formats an internal path into an href string for <a> tags */
|
|
25
25
|
formatLink?: (path: string) => string;
|
|
26
|
+
/**
|
|
27
|
+
* Optional path builder. useGetToPath calls this when a router wants to
|
|
28
|
+
* map the default resource path onto its own routes.
|
|
29
|
+
*/
|
|
30
|
+
toPath?: (options: {
|
|
31
|
+
resource?: string;
|
|
32
|
+
action?: 'list' | 'create' | 'edit' | 'show' | 'clone';
|
|
33
|
+
id?: string | number;
|
|
34
|
+
meta?: Record<string, unknown>;
|
|
35
|
+
path: string;
|
|
36
|
+
}) => string;
|
|
26
37
|
}
|
|
27
38
|
|
|
28
39
|
// ─── Hash Router (default) ──────────────────────────────────
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { definedOptions } from './defined-options';
|
|
2
2
|
import { captureAdminContext } from './context.svelte';
|
|
3
|
+
import { getAdminOptions, setAdminOptions } from './options.svelte';
|
|
4
|
+
import type { MutationMode } from './types';
|
|
5
|
+
import { getUnsavedChanges, setUnsavedChanges } from './unsaved-changes.svelte';
|
|
3
6
|
import { useParsed } from './useParsed.svelte';
|
|
4
7
|
import { sanitizeListQueryParams } from './url-sync';
|
|
5
8
|
|
|
@@ -30,14 +33,92 @@ export function useGetToPath() {
|
|
|
30
33
|
else if(action==='show'&&id) path+=`/show/${id}`;
|
|
31
34
|
else if(action==='clone'&&id) path+=`/clone/${id}`;
|
|
32
35
|
|
|
33
|
-
|
|
34
|
-
if(
|
|
35
|
-
|
|
36
|
+
const provider = adminContext.routerProvider;
|
|
37
|
+
if (provider?.toPath) {
|
|
38
|
+
return provider.toPath({
|
|
39
|
+
path,
|
|
40
|
+
...definedOptions({ resource, action, id, meta }),
|
|
41
|
+
});
|
|
36
42
|
}
|
|
37
43
|
return path;
|
|
38
44
|
};
|
|
39
45
|
}
|
|
40
46
|
|
|
47
|
+
/** Refine migration hook: the configured mutation mode. */
|
|
48
|
+
export function useMutationMode(): MutationMode {
|
|
49
|
+
return getAdminOptions().mutationMode ?? 'pessimistic';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Refine migration hook for unsaved-change prompts.
|
|
54
|
+
* `setWarnWhen` marks the form dirty; `setWarnWhenUnsavedChanges` toggles the guard.
|
|
55
|
+
*/
|
|
56
|
+
export function useWarnAboutChange() {
|
|
57
|
+
return {
|
|
58
|
+
get warnWhenUnsavedChanges() {
|
|
59
|
+
return getAdminOptions().warnWhenUnsavedChanges ?? false;
|
|
60
|
+
},
|
|
61
|
+
setWarnWhen(value: boolean) {
|
|
62
|
+
setUnsavedChanges(value);
|
|
63
|
+
},
|
|
64
|
+
setWarnWhenUnsavedChanges(value: boolean) {
|
|
65
|
+
setAdminOptions({ warnWhenUnsavedChanges: value }, true);
|
|
66
|
+
},
|
|
67
|
+
get hasUnsavedChanges() {
|
|
68
|
+
return getUnsavedChanges();
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Refine migration hook: whether list state is synced to the URL, plus the current params. */
|
|
74
|
+
export function useSyncWithLocation() {
|
|
75
|
+
const parsed = useParsed();
|
|
76
|
+
return {
|
|
77
|
+
get syncWithLocation() {
|
|
78
|
+
return getAdminOptions().syncWithLocation ?? false;
|
|
79
|
+
},
|
|
80
|
+
get params() {
|
|
81
|
+
return parsed.params;
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Refine 迁移别名:当前资源的 query key 工厂。 */
|
|
87
|
+
export function useKeys(resourceName?: string, dataProviderName?: string) {
|
|
88
|
+
return captureAdminContext().queryKeys(resourceName, dataProviderName);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Refine 迁移别名:路由上的资源、动作和 id。 */
|
|
92
|
+
export function useResourceParams(resourceName?: string) {
|
|
93
|
+
const resourceState = useResource(resourceName);
|
|
94
|
+
const parsed = useParsed();
|
|
95
|
+
return {
|
|
96
|
+
get id() { return parsed.id; },
|
|
97
|
+
get action() { return parsed.action; },
|
|
98
|
+
get resource() { return resourceState.resource; },
|
|
99
|
+
get identifier() { return resourceState.identifier; },
|
|
100
|
+
get params() { return parsed.params; },
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Refine migration hook: resource meta merged with the current route. */
|
|
105
|
+
export function useMeta(resourceName?: string) {
|
|
106
|
+
const resourceState = useResource(resourceName);
|
|
107
|
+
const parsed = useParsed();
|
|
108
|
+
return {
|
|
109
|
+
get meta() {
|
|
110
|
+
const resource = resourceState.resource;
|
|
111
|
+
return {
|
|
112
|
+
...(resource?.meta ?? {}),
|
|
113
|
+
...(resourceState.parent ? { parent: resourceState.parent } : {}),
|
|
114
|
+
route: parsed.resource,
|
|
115
|
+
action: parsed.action,
|
|
116
|
+
id: parsed.id,
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
41
122
|
export function useGo() {
|
|
42
123
|
const adminContext=captureAdminContext();
|
|
43
124
|
const getToPath=useGetToPath();
|