@svadmin/core 0.69.2 → 0.69.3
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 +2 -2
- package/src/crud-operator-schema.ts +20 -0
- package/src/editable-table.svelte.ts +90 -0
- package/src/editable-table.ts +314 -0
- package/src/index.ts +8 -3
- package/src/inferencer-contract.ts +114 -0
- package/src/inferencer.ts +219 -42
- package/src/query-hooks.svelte.ts +16 -6
- package/src/query-options.ts +50 -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 +35 -1
- package/src/select-query.svelte.ts +20 -5
- package/src/session-query.svelte.ts +6 -1
- package/src/strict-hooks.svelte.ts +9 -5
- package/src/table-hooks.svelte.ts +12 -0
- package/src/types.ts +22 -7
- package/src/url-sync.ts +37 -17
|
@@ -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();
|
package/src/select-options.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BaseRecord } from './types';
|
|
1
|
+
import type { BaseRecord, Filter } from './types';
|
|
2
2
|
import { HttpError } from './types';
|
|
3
3
|
import type { RecordDecoder } from './record-decoder';
|
|
4
4
|
import { snapshotPlainData, type JsonValue } from './plain-data';
|
|
@@ -85,6 +85,40 @@ export function createSelectProjection<T extends BaseRecord, R extends { data: T
|
|
|
85
85
|
};
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
export type SelectedOptionsOrder = 'in-place' | 'selected-first';
|
|
89
|
+
|
|
90
|
+
export function normalizeSelectDefaultValue(
|
|
91
|
+
value: string | number | readonly (string | number)[] | null | undefined,
|
|
92
|
+
): (string | number)[] {
|
|
93
|
+
if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) return [value];
|
|
94
|
+
if (!Array.isArray(value)) return [];
|
|
95
|
+
const ids: (string | number)[] = [];
|
|
96
|
+
for (const item of value) {
|
|
97
|
+
if (typeof item === 'string' || (typeof item === 'number' && Number.isFinite(item))) ids.push(item);
|
|
98
|
+
}
|
|
99
|
+
return ids;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** onSearch 优先;否则按 searchField 生成 contains 过滤。 */
|
|
103
|
+
export function selectQueryFilters(input: {
|
|
104
|
+
text: string;
|
|
105
|
+
searchField?: string;
|
|
106
|
+
searched?: Filter[] | undefined;
|
|
107
|
+
}): Filter[] {
|
|
108
|
+
if (!input.text) return [];
|
|
109
|
+
if (input.searched) return input.searched;
|
|
110
|
+
if (input.searchField) return [{ field: input.searchField, operator: 'contains', value: input.text }];
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function orderSelectOptions(
|
|
115
|
+
list: SelectOption[],
|
|
116
|
+
selected: SelectOption[],
|
|
117
|
+
order: SelectedOptionsOrder = 'in-place',
|
|
118
|
+
): SelectOption[] {
|
|
119
|
+
return order === 'selected-first' ? mergeSelectOptions(selected, list) : mergeSelectOptions(list, selected);
|
|
120
|
+
}
|
|
121
|
+
|
|
88
122
|
export function mergeSelectOptions(...groups: SelectOption[][]): SelectOption[] {
|
|
89
123
|
const seen = new Set<string | number>();
|
|
90
124
|
return groups.flatMap(group => group.filter(option => {
|
|
@@ -9,7 +9,7 @@ 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 { createSelectProjection,
|
|
12
|
+
import { createSelectProjection, normalizeSelectDefaultValue, orderSelectOptions, selectQueryFilters, type SelectOption, type SelectedOptionsOrder } from './select-options';
|
|
13
13
|
import { HttpError, type BaseRecord, type KnownResources, type Pagination, type Sort, type Filter } from './types';
|
|
14
14
|
import type { QueryKey } from './query-keys';
|
|
15
15
|
|
|
@@ -26,7 +26,11 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
|
|
|
26
26
|
optionValue?: string | ((item: TData) => string | number);
|
|
27
27
|
sorters?: Sort[];
|
|
28
28
|
filters?: Filter[];
|
|
29
|
-
defaultValue?: (string | number)[];
|
|
29
|
+
defaultValue?: string | number | readonly (string | number)[];
|
|
30
|
+
/** 未提供 onSearch 时,用该字段生成 contains 过滤。 */
|
|
31
|
+
searchField?: string;
|
|
32
|
+
/** selected-first 把已选记录放在选项前面;默认保持列表原顺序。 */
|
|
33
|
+
selectedOptionsOrder?: SelectedOptionsOrder;
|
|
30
34
|
fetchSize?: number;
|
|
31
35
|
pagination?: Pagination;
|
|
32
36
|
debounce?: number;
|
|
@@ -160,6 +164,7 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
160
164
|
typeof options.optionValue === 'string' ? options.optionValue : 'callback',
|
|
161
165
|
].join(':'),
|
|
162
166
|
onSearch: options.onSearch,
|
|
167
|
+
searchField: options.searchField,
|
|
163
168
|
checkIds: contract !== undefined,
|
|
164
169
|
authProvider,
|
|
165
170
|
auth: captureAuthLiveScope(authProvider),
|
|
@@ -174,9 +179,13 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
174
179
|
const text = search?.scope === current && sessionCurrent(current) ? search.value : '';
|
|
175
180
|
try {
|
|
176
181
|
// Validate callback output before spreading it or giving it to the provider.
|
|
182
|
+
const searched = text && current.onSearch ? untrack(() => current.onSearch?.(text)) ?? [] : undefined;
|
|
177
183
|
const extra = snapshotListParams({
|
|
178
184
|
resource: current.params.resource,
|
|
179
|
-
filters:
|
|
185
|
+
filters: selectQueryFilters({
|
|
186
|
+
text,
|
|
187
|
+
...definedOptions({ searchField: current.searchField, searched }),
|
|
188
|
+
}),
|
|
180
189
|
});
|
|
181
190
|
return { params: snapshotListParams({
|
|
182
191
|
...current.params, filters: [...(current.params.filters ?? []), ...(extra.filters ?? [])],
|
|
@@ -227,7 +236,7 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
227
236
|
const origin = scope;
|
|
228
237
|
const { captured, decode, keys, params: base } = origin;
|
|
229
238
|
const params = snapshotManyParams({
|
|
230
|
-
resource: base.resource, ids: options.defaultValue
|
|
239
|
+
resource: base.resource, ids: normalizeSelectDefaultValue(options.defaultValue), ...definedOptions({ meta: base.meta }),
|
|
231
240
|
});
|
|
232
241
|
const label = origin.optionLabel ?? 'title';
|
|
233
242
|
const value = origin.optionValue ?? 'id';
|
|
@@ -291,7 +300,13 @@ export function createSelectQuery<TData extends BaseRecord>(
|
|
|
291
300
|
|
|
292
301
|
return {
|
|
293
302
|
query, defaultValueQuery, onSearchChange, cancel: cancelRequests,
|
|
294
|
-
get options() {
|
|
303
|
+
get options() {
|
|
304
|
+
return orderSelectOptions(
|
|
305
|
+
query.data?.options ?? [],
|
|
306
|
+
defaultValueQuery.data?.options ?? [],
|
|
307
|
+
options.selectedOptionsOrder ?? 'in-place',
|
|
308
|
+
);
|
|
309
|
+
},
|
|
295
310
|
get overtime() { return overtime; },
|
|
296
311
|
get isLoading() { return query.isLoading || defaultValueQuery.isLoading; },
|
|
297
312
|
get isFetching() { return query.isFetching || defaultValueQuery.isFetching; },
|
|
@@ -13,9 +13,12 @@ interface SessionQueryOptions<TQuery, T> extends QuerySessionOptions {
|
|
|
13
13
|
enabled: boolean;
|
|
14
14
|
staleTime?: number;
|
|
15
15
|
gcTime?: number;
|
|
16
|
-
refetchOnWindowFocus?: boolean;
|
|
16
|
+
refetchOnWindowFocus?: boolean | 'always';
|
|
17
|
+
retry?: boolean | number;
|
|
18
|
+
retryDelay?: number | ((failureCount: number, error: unknown) => number);
|
|
17
19
|
refetchInterval?: number | false;
|
|
18
20
|
refetchIntervalInBackground?: boolean;
|
|
21
|
+
placeholderData?: TQuery | ((previousData: TQuery | undefined) => TQuery | undefined);
|
|
19
22
|
}
|
|
20
23
|
|
|
21
24
|
// 只有显式提供错误归一化器的内部领域查询才承诺 Error;普通查询保留 unknown 契约。
|
|
@@ -56,7 +59,9 @@ export function createSessionQuery<TQuery, T = TQuery>(
|
|
|
56
59
|
enabled: origin.enabled && origin.auth.available,
|
|
57
60
|
...definedOptions({
|
|
58
61
|
staleTime: origin.staleTime, gcTime: origin.gcTime, refetchOnWindowFocus: origin.refetchOnWindowFocus,
|
|
62
|
+
retry: origin.retry, retryDelay: origin.retryDelay,
|
|
59
63
|
refetchInterval: origin.refetchInterval, refetchIntervalInBackground: origin.refetchIntervalInBackground,
|
|
64
|
+
placeholderData: origin.placeholderData,
|
|
60
65
|
}),
|
|
61
66
|
};
|
|
62
67
|
});
|
|
@@ -26,17 +26,17 @@ import { useContractCreate, type ContractCreateOptions } from './create-hooks.sv
|
|
|
26
26
|
type Field<T>=Extract<keyof T,string>;
|
|
27
27
|
type ValueField<T>={ [K in Field<T>]-?: T[K] extends string|number? K:never }[Field<T>];
|
|
28
28
|
type FieldPredicate<T>=
|
|
29
|
-
|{ operator: 'eq'|'ne'; value: Exclude<T,undefined> }
|
|
30
|
-
|{ operator: 'in'|'nin'; value: Exclude<T,undefined>[] }
|
|
29
|
+
|{ operator: 'eq'|'ne'|'eqs'|'nes'; value: Exclude<T,undefined> }
|
|
30
|
+
|{ operator: 'in'|'nin'|'ina'|'nina'; value: Exclude<T,undefined>[] }
|
|
31
31
|
|{ operator: 'null'|'nnull'; value: null }
|
|
32
|
-
|(NonNullable<T> extends string? { operator: 'contains'|'ncontains'|'startswith'|'endswith'; value: NonNullable<T> }:never)
|
|
32
|
+
|(NonNullable<T> extends string? { operator: 'contains'|'ncontains'|'containss'|'ncontainss'|'startswith'|'nstartswith'|'startswiths'|'nstartswiths'|'endswith'|'nendswith'|'endswiths'|'nendswiths'; value: NonNullable<T> }:never)
|
|
33
33
|
|(NonNullable<T> extends string|number? (
|
|
34
34
|
|{ operator: 'lt'|'lte'|'gt'|'gte'; value: NonNullable<T> }
|
|
35
35
|
|{ operator: 'between'|'nbetween'; value: [NonNullable<T>,NonNullable<T>] }
|
|
36
36
|
):never);
|
|
37
37
|
export type ContractFilter<T>=string extends keyof T ? Filter : Filter&(
|
|
38
38
|
|{ [K in Field<T>]: { field: K }&FieldPredicate<T[K]> }[Field<T>]
|
|
39
|
-
|{ operator: 'and'|'or'; value: ContractFilter<T>[] });
|
|
39
|
+
|{ key?: string; operator: 'and'|'or'; value: ContractFilter<T>[] });
|
|
40
40
|
export type ContractSort<T>={ field: Field<T>; order: 'asc'|'desc' };
|
|
41
41
|
type Bound<S extends ContractSchemas>={ resource: ResourceContract<S> };
|
|
42
42
|
type QueryOptions<O,S extends ContractSchemas>=
|
|
@@ -75,6 +75,10 @@ function recordDecoder<S extends ContractSchemas>(options: query.MaybeGetter<Bou
|
|
|
75
75
|
export function useList<S extends ContractSchemas>(options: query.MaybeGetter<ListOptions<query.UseListOptions,S>>) {
|
|
76
76
|
return query.createListQuery(getter(options),recordDecoder(options));
|
|
77
77
|
}
|
|
78
|
+
/** Refine 迁移别名,契约边界与 useList 相同。 */
|
|
79
|
+
export function useSimpleList<S extends ContractSchemas>(options: query.MaybeGetter<ListOptions<query.UseListOptions,S>>) {
|
|
80
|
+
return useList(options);
|
|
81
|
+
}
|
|
78
82
|
export function useOne<S extends ContractSchemas>(options: query.MaybeGetter<QueryOptions<query.UseOneOptions,S>&{ id: Id<S> }>) {
|
|
79
83
|
return query.createOneQuery(getter(options),recordDecoder(options));
|
|
80
84
|
}
|
|
@@ -100,7 +104,7 @@ export function useSelect<S extends ContractSchemas>(
|
|
|
100
104
|
options: ListOptions<Omit<bulk.UseSelectOptions<Row<S>>,'optionLabel'|'optionValue'|'defaultValue'|'onSearch'>,S>&{
|
|
101
105
|
optionLabel: Field<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string);
|
|
102
106
|
optionValue: ValueField<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string|number);
|
|
103
|
-
defaultValue?: Id<S>[];
|
|
107
|
+
defaultValue?: Id<S> | readonly Id<S>[];
|
|
104
108
|
onSearch?: (value: string) => ContractFilter<NoInfer<Row<S>>>[];
|
|
105
109
|
},
|
|
106
110
|
) {
|
|
@@ -245,16 +245,28 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
|
|
|
245
245
|
switch(f.operator) {
|
|
246
246
|
case 'eq': return val==fv;
|
|
247
247
|
case 'ne': return val!=fv;
|
|
248
|
+
case 'eqs': return Object.is(val, fv);
|
|
249
|
+
case 'nes': return !Object.is(val, fv);
|
|
248
250
|
case 'lt': return typeof val==='number'&&typeof fv==='number'&&val<fv;
|
|
249
251
|
case 'gt': return typeof val==='number'&&typeof fv==='number'&&val>fv;
|
|
250
252
|
case 'lte': return typeof val==='number'&&typeof fv==='number'&&val<=fv;
|
|
251
253
|
case 'gte': return typeof val==='number'&&typeof fv==='number'&&val>=fv;
|
|
252
254
|
case 'in': return !Array.isArray(fv)||fv.length===0||fv.includes(val);
|
|
253
255
|
case 'nin': return !Array.isArray(fv)||fv.length===0||!fv.includes(val);
|
|
256
|
+
case 'ina': return Array.isArray(val)&&Array.isArray(fv)&&fv.every(item => val.includes(item));
|
|
257
|
+
case 'nina': return Array.isArray(val)&&Array.isArray(fv)&&fv.some(item => !val.includes(item));
|
|
254
258
|
case 'contains': return typeof val==='string'&&typeof fv==='string'&&val.includes(fv);
|
|
255
259
|
case 'ncontains': return typeof val==='string'&&typeof fv==='string'&&!val.includes(fv);
|
|
260
|
+
case 'containss': return typeof val==='string'&&typeof fv==='string'&&val.includes(fv);
|
|
261
|
+
case 'ncontainss': return typeof val==='string'&&typeof fv==='string'&&!val.includes(fv);
|
|
256
262
|
case 'startswith': return typeof val==='string'&&typeof fv==='string'&&val.startsWith(fv);
|
|
263
|
+
case 'nstartswith': return typeof val==='string'&&typeof fv==='string'&&!val.startsWith(fv);
|
|
264
|
+
case 'startswiths': return typeof val==='string'&&typeof fv==='string'&&val.startsWith(fv);
|
|
265
|
+
case 'nstartswiths': return typeof val==='string'&&typeof fv==='string'&&!val.startsWith(fv);
|
|
257
266
|
case 'endswith': return typeof val==='string'&&typeof fv==='string'&&val.endsWith(fv);
|
|
267
|
+
case 'nendswith': return typeof val==='string'&&typeof fv==='string'&&!val.endsWith(fv);
|
|
268
|
+
case 'endswiths': return typeof val==='string'&&typeof fv==='string'&&val.endsWith(fv);
|
|
269
|
+
case 'nendswiths': return typeof val==='string'&&typeof fv==='string'&&!val.endsWith(fv);
|
|
258
270
|
case 'between': {
|
|
259
271
|
if(!Array.isArray(fv)||fv.length!==2) return true;
|
|
260
272
|
const [min,max]: unknown[]=fv;
|
package/src/types.ts
CHANGED
|
@@ -88,13 +88,26 @@ export interface Sort {
|
|
|
88
88
|
order: 'asc' | 'desc';
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
91
|
+
/**
|
|
92
|
+
* Refine v5 字段运算符。`and` / `or` 不在这里,它们属于可带 key 的条件过滤器。
|
|
93
|
+
* 带 s 的是大小写敏感变体;`ina` / `nina` 表示数组包含 / 不包含全部给定值。
|
|
94
|
+
*/
|
|
95
|
+
export const CRUD_FIELD_OPERATORS = [
|
|
96
|
+
'eq', 'ne', 'eqs', 'nes',
|
|
97
|
+
'lt', 'gt', 'lte', 'gte',
|
|
98
|
+
'in', 'nin', 'ina', 'nina',
|
|
99
|
+
'contains', 'ncontains', 'containss', 'ncontainss',
|
|
100
|
+
'startswith', 'nstartswith', 'startswiths', 'nstartswiths',
|
|
101
|
+
'endswith', 'nendswith', 'endswiths', 'nendswiths',
|
|
102
|
+
'null', 'nnull',
|
|
103
|
+
'between', 'nbetween',
|
|
104
|
+
] as const;
|
|
105
|
+
|
|
106
|
+
export type CrudOperator = (typeof CRUD_FIELD_OPERATORS)[number];
|
|
107
|
+
|
|
108
|
+
export function isCrudFieldOperator(value: unknown): value is CrudOperator {
|
|
109
|
+
return typeof value === 'string' && (CRUD_FIELD_OPERATORS as readonly string[]).includes(value);
|
|
110
|
+
}
|
|
98
111
|
|
|
99
112
|
export interface FieldFilter {
|
|
100
113
|
field: string;
|
|
@@ -105,6 +118,8 @@ export interface FieldFilter {
|
|
|
105
118
|
export type Filter = FieldFilter | LogicalFilter;
|
|
106
119
|
|
|
107
120
|
export interface LogicalFilter {
|
|
121
|
+
/** 顶层多个条件过滤器用 key 区分,避免被合并成同一组。 */
|
|
122
|
+
key?: string;
|
|
108
123
|
operator: 'or' | 'and';
|
|
109
124
|
value: Filter[];
|
|
110
125
|
}
|
package/src/url-sync.ts
CHANGED
|
@@ -1,31 +1,45 @@
|
|
|
1
|
-
import type { Filter } from './types';
|
|
1
|
+
import type { Filter, LogicalFilter } from './types';
|
|
2
|
+
import { isCrudFieldOperator } from './types';
|
|
2
3
|
import { captureAdminContext } from './context.svelte';
|
|
3
4
|
import type { AdminContextAccessor } from './context.svelte';
|
|
4
5
|
import { getAdminOptions } from './options.svelte';
|
|
5
6
|
|
|
6
|
-
const CRUD_OPERATORS = new Set([
|
|
7
|
-
'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
|
|
8
|
-
'contains', 'ncontains', 'startswith', 'endswith',
|
|
9
|
-
'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
|
|
10
|
-
]);
|
|
11
|
-
|
|
12
7
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
13
8
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
9
|
}
|
|
15
10
|
|
|
16
|
-
function
|
|
17
|
-
if (
|
|
11
|
+
function readFilterKey(value: Record<string, unknown>): string | undefined | null {
|
|
12
|
+
if (!('key' in value)) return undefined;
|
|
13
|
+
const key = value['key'];
|
|
14
|
+
if (typeof key !== 'string' || key.length < 1 || key.length > 128) return null;
|
|
15
|
+
return key;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 重新构造过滤器,只保留协议字段,避免把 URL 里的多余属性写回路由状态。 */
|
|
19
|
+
function readFilter(value: unknown, depth: number, budget: { remaining: number }): Filter | undefined {
|
|
20
|
+
if (depth > 20 || budget.remaining-- <= 0 || !isRecord(value)) return undefined;
|
|
18
21
|
|
|
19
22
|
if (typeof value['field'] === 'string') {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
if (value['field'].trim().length === 0 || !isCrudFieldOperator(value['operator']) || !('value' in value)) {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
return { field: value['field'], operator: value['operator'], value: value['value'] };
|
|
24
27
|
}
|
|
25
28
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
+
if ((value['operator'] !== 'and' && value['operator'] !== 'or') || !Array.isArray(value['value'])) {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
const key = readFilterKey(value);
|
|
33
|
+
if (key === null) return undefined;
|
|
34
|
+
const children: Filter[] = [];
|
|
35
|
+
for (const entry of value['value']) {
|
|
36
|
+
const child = readFilter(entry, depth + 1, budget);
|
|
37
|
+
if (!child) return undefined;
|
|
38
|
+
children.push(child);
|
|
39
|
+
}
|
|
40
|
+
const filter: LogicalFilter = { operator: value['operator'], value: children };
|
|
41
|
+
if (key !== undefined) filter.key = key;
|
|
42
|
+
return filter;
|
|
29
43
|
}
|
|
30
44
|
|
|
31
45
|
function parseFilters(value: string): Filter[] | undefined {
|
|
@@ -33,7 +47,13 @@ function parseFilters(value: string): Filter[] | undefined {
|
|
|
33
47
|
const parsed: unknown = JSON.parse(value);
|
|
34
48
|
if (!Array.isArray(parsed)) return undefined;
|
|
35
49
|
const budget = { remaining: 200 };
|
|
36
|
-
|
|
50
|
+
const filters: Filter[] = [];
|
|
51
|
+
for (const entry of parsed) {
|
|
52
|
+
const filter = readFilter(entry, 0, budget);
|
|
53
|
+
if (!filter) return undefined;
|
|
54
|
+
filters.push(filter);
|
|
55
|
+
}
|
|
56
|
+
return filters;
|
|
37
57
|
} catch {
|
|
38
58
|
return undefined;
|
|
39
59
|
}
|