@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.
@@ -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';
@@ -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[label];
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[value];
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
  });
@@ -85,6 +97,40 @@ export function createSelectProjection<T extends BaseRecord, R extends { data: T
85
97
  };
86
98
  }
87
99
 
100
+ export type SelectedOptionsOrder = 'in-place' | 'selected-first';
101
+
102
+ export function normalizeSelectDefaultValue(
103
+ value: string | number | readonly (string | number)[] | null | undefined,
104
+ ): (string | number)[] {
105
+ if (typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value))) return [value];
106
+ if (!Array.isArray(value)) return [];
107
+ const ids: (string | number)[] = [];
108
+ for (const item of value) {
109
+ if (typeof item === 'string' || (typeof item === 'number' && Number.isFinite(item))) ids.push(item);
110
+ }
111
+ return ids;
112
+ }
113
+
114
+ /** onSearch 优先;否则按 searchField 生成 contains 过滤。 */
115
+ export function selectQueryFilters(input: {
116
+ text: string;
117
+ searchField?: string;
118
+ searched?: Filter[] | undefined;
119
+ }): Filter[] {
120
+ if (!input.text) return [];
121
+ if (input.searched) return input.searched;
122
+ if (input.searchField) return [{ field: input.searchField, operator: 'contains', value: input.text }];
123
+ return [];
124
+ }
125
+
126
+ export function orderSelectOptions(
127
+ list: SelectOption[],
128
+ selected: SelectOption[],
129
+ order: SelectedOptionsOrder = 'in-place',
130
+ ): SelectOption[] {
131
+ return order === 'selected-first' ? mergeSelectOptions(selected, list) : mergeSelectOptions(list, selected);
132
+ }
133
+
88
134
  export function mergeSelectOptions(...groups: SelectOption[][]): SelectOption[] {
89
135
  const seen = new Set<string | number>();
90
136
  return groups.flatMap(group => group.filter(option => {
@@ -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 { createSelectProjection, mergeSelectOptions, type SelectOption } from './select-options';
12
+ import { listQuerySettings, type ResourceQueryOptions } from './query-options';
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
- export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends ContractOptions {
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;
@@ -26,14 +39,18 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
26
39
  optionValue?: string | ((item: TData) => string | number);
27
40
  sorters?: Sort[];
28
41
  filters?: Filter[];
29
- defaultValue?: (string | number)[];
42
+ defaultValue?: string | number | readonly (string | number)[];
43
+ /** 未提供 onSearch 时,用该字段生成 contains 过滤。 */
44
+ searchField?: string;
45
+ /** selected-first 把已选记录放在选项前面;默认保持列表原顺序。 */
46
+ selectedOptionsOrder?: SelectedOptionsOrder;
30
47
  fetchSize?: number;
31
48
  pagination?: Pagination;
32
49
  debounce?: number;
33
50
  /** Optional timeout in milliseconds for list and selected-record reads. */
34
51
  requestTimeout?: number;
35
- queryOptions?: { staleTime?: number; enabled?: boolean };
36
- defaultValueQueryOptions?: { staleTime?: number; enabled?: boolean };
52
+ queryOptions?: ResourceQueryOptions<SelectListResult<TData>, TSelected>;
53
+ defaultValueQueryOptions?: ResourceQueryOptions<SelectDefaultsResult<TData>>;
37
54
  meta?: Record<string, unknown>;
38
55
  dataProviderName?: string;
39
56
  onSearch?: (value: string) => Filter[];
@@ -42,8 +59,8 @@ export interface UseSelectOptions<TData extends BaseRecord = BaseRecord> extends
42
59
  overtimeOptions?: OvertimeOptions;
43
60
  }
44
61
 
45
- export function createSelectQuery<TData extends BaseRecord>(
46
- options: UseSelectOptions<TData>, getDecoder: () => RecordDecoder<TData>,
62
+ export function createSelectQuery<TData extends BaseRecord, TSelected = SelectListResult<TData>>(
63
+ options: UseSelectOptions<TData, TSelected>, getDecoder: () => RecordDecoder<TData>,
47
64
  ) {
48
65
  const context = captureContractContext(options);
49
66
  const adminOptions = getAdminOptions();
@@ -160,6 +177,7 @@ export function createSelectQuery<TData extends BaseRecord>(
160
177
  typeof options.optionValue === 'string' ? options.optionValue : 'callback',
161
178
  ].join(':'),
162
179
  onSearch: options.onSearch,
180
+ searchField: options.searchField,
163
181
  checkIds: contract !== undefined,
164
182
  authProvider,
165
183
  auth: captureAuthLiveScope(authProvider),
@@ -174,9 +192,13 @@ export function createSelectQuery<TData extends BaseRecord>(
174
192
  const text = search?.scope === current && sessionCurrent(current) ? search.value : '';
175
193
  try {
176
194
  // Validate callback output before spreading it or giving it to the provider.
195
+ const searched = text && current.onSearch ? untrack(() => current.onSearch?.(text)) ?? [] : undefined;
177
196
  const extra = snapshotListParams({
178
197
  resource: current.params.resource,
179
- filters: text && current.onSearch ? untrack(() => current.onSearch?.(text)) : [],
198
+ filters: selectQueryFilters({
199
+ text,
200
+ ...definedOptions({ searchField: current.searchField, searched }),
201
+ }),
180
202
  });
181
203
  return { params: snapshotListParams({
182
204
  ...current.params, filters: [...(current.params.filters ?? []), ...(extra.filters ?? [])],
@@ -188,7 +210,7 @@ export function createSelectQuery<TData extends BaseRecord>(
188
210
  });
189
211
  const query = createSessionQuery<
190
212
  { data: TData[]; total: number },
191
- { data: TData[]; total: number; options: SelectOption[] }
213
+ TSelected
192
214
  >(context, () => {
193
215
  const origin = scope;
194
216
  const { captured, decode, keys } = origin;
@@ -205,9 +227,15 @@ export function createSelectQuery<TData extends BaseRecord>(
205
227
  });
206
228
  const requestKey = withAuthSession(queryKey, origin.auth.cacheKey);
207
229
  currentListKey = requestKey;
230
+ const projection = createSelectProjection(decodeResult, label, value, decode, () => sessionCurrent(origin));
231
+ const settings = listQuerySettings(options.queryOptions);
208
232
  return {
209
233
  resource: params.resource, successNotification: options.successNotification, errorNotification: options.errorNotification,
210
- decode: createSelectProjection(decodeResult, label, value, decode, () => sessionCurrent(origin)),
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
+ },
211
239
  queryKey,
212
240
  // 同一 key 的请求可由其他 observer 共享,不能因本实例卸载或切换搜索而丢弃共享结果。
213
241
  allowRetiredQueryFn: true,
@@ -217,8 +245,17 @@ export function createSelectQuery<TData extends BaseRecord>(
217
245
  captured.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal: requestSignal }) })),
218
246
  ).then(decodeResult);
219
247
  },
220
- enabled: options.queryOptions?.enabled ?? true,
221
- ...definedOptions({ staleTime: options.queryOptions?.staleTime ?? adminOptions.reactQuery?.staleTime }),
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
+ }),
222
259
  };
223
260
  });
224
261
  const defaultValueQuery = createSessionQuery<
@@ -227,7 +264,7 @@ export function createSelectQuery<TData extends BaseRecord>(
227
264
  const origin = scope;
228
265
  const { captured, decode, keys, params: base } = origin;
229
266
  const params = snapshotManyParams({
230
- resource: base.resource, ids: options.defaultValue ?? [], ...definedOptions({ meta: base.meta }),
267
+ resource: base.resource, ids: normalizeSelectDefaultValue(options.defaultValue), ...definedOptions({ meta: base.meta }),
231
268
  });
232
269
  const label = origin.optionLabel ?? 'title';
233
270
  const value = origin.optionValue ?? 'id';
@@ -256,8 +293,16 @@ export function createSelectQuery<TData extends BaseRecord>(
256
293
  ).then(decodeResult);
257
294
  },
258
295
  enabled: (options.queryOptions?.enabled ?? true) &&
259
- (options.defaultValueQueryOptions?.enabled ?? true) && params.ids.length > 0,
260
- staleTime: options.defaultValueQueryOptions?.staleTime ?? Infinity,
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
+ }),
261
306
  };
262
307
  });
263
308
  const overtime = createOvertimeTracker(
@@ -291,7 +336,13 @@ export function createSelectQuery<TData extends BaseRecord>(
291
336
 
292
337
  return {
293
338
  query, defaultValueQuery, onSearchChange, cancel: cancelRequests,
294
- get options() { return mergeSelectOptions(query.data?.options ?? [], defaultValueQuery.data?.options ?? []); },
339
+ get options() {
340
+ return orderSelectOptions(
341
+ optionEntries(query.data),
342
+ defaultValueQuery.data?.options ?? [],
343
+ options.selectedOptionsOrder ?? 'in-place',
344
+ );
345
+ },
295
346
  get overtime() { return overtime; },
296
347
  get isLoading() { return query.isLoading || defaultValueQuery.isLoading; },
297
348
  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
  });
@@ -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,18 +27,33 @@ 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
- |{ operator: 'eq'|'ne'; value: Exclude<T,undefined> }
30
- |{ operator: 'in'|'nin'; value: Exclude<T,undefined>[] }
46
+ |{ operator: 'eq'|'ne'|'eqs'|'nes'; value: Exclude<T,undefined> }
47
+ |{ operator: 'in'|'nin'|'ina'|'nina'; value: Exclude<T,undefined>[] }
31
48
  |{ operator: 'null'|'nnull'; value: null }
32
- |(NonNullable<T> extends string? { operator: 'contains'|'ncontains'|'startswith'|'endswith'; value: NonNullable<T> }:never)
49
+ |(NonNullable<T> extends string? { operator: 'contains'|'ncontains'|'containss'|'ncontainss'|'startswith'|'nstartswith'|'startswiths'|'nstartswiths'|'endswith'|'nendswith'|'endswiths'|'nendswiths'; value: NonNullable<T> }:never)
33
50
  |(NonNullable<T> extends string|number? (
34
51
  |{ operator: 'lt'|'lte'|'gt'|'gte'; value: NonNullable<T> }
35
52
  |{ operator: 'between'|'nbetween'; value: [NonNullable<T>,NonNullable<T>] }
36
53
  ):never);
37
54
  export type ContractFilter<T>=string extends keyof T ? Filter : Filter&(
38
55
  |{ [K in Field<T>]: { field: K }&FieldPredicate<T[K]> }[Field<T>]
39
- |{ operator: 'and'|'or'; value: ContractFilter<T>[] });
56
+ |{ key?: string; operator: 'and'|'or'; value: ContractFilter<T>[] });
40
57
  export type ContractSort<T>={ field: Field<T>; order: 'asc'|'desc' };
41
58
  type Bound<S extends ContractSchemas>={ resource: ResourceContract<S> };
42
59
  type QueryOptions<O,S extends ContractSchemas>=
@@ -72,17 +89,31 @@ function recordDecoder<S extends ContractSchemas>(options: query.MaybeGetter<Bou
72
89
  };
73
90
  }
74
91
 
75
- export function useList<S extends ContractSchemas>(options: query.MaybeGetter<ListOptions<query.UseListOptions,S>>) {
76
- return query.createListQuery(getter(options),recordDecoder(options));
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
- export function useOne<S extends ContractSchemas>(options: query.MaybeGetter<QueryOptions<query.UseOneOptions,S>&{ id: Id<S> }>) {
79
- return query.createOneQuery(getter(options),recordDecoder(options));
97
+ /** Refine 迁移别名,契约边界与 useList 相同。 */
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);
80
102
  }
81
- export function useMany<S extends ContractSchemas>(options: query.MaybeGetter<QueryOptions<query.UseManyOptions,S>&{ ids: Id<S>[] }>) {
82
- return query.createManyQuery(getter(options),recordDecoder(options));
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));
83
107
  }
84
- export function useShow<S extends ContractSchemas>(options: query.MaybeGetter<QueryOptions<query.UseOneOptions,S>&{ id: Id<S> }>) {
85
- const result=query.createShowQuery(getter(options),recordDecoder(options));
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));
112
+ }
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));
86
117
  return replaceReactiveMembers(result,{
87
118
  get showId(): Id<S> {
88
119
  return parseContractId((typeof options==='function'? options():options).resource,result.showId);
@@ -93,18 +124,20 @@ export function useShow<S extends ContractSchemas>(options: query.MaybeGetter<Qu
93
124
  },
94
125
  });
95
126
  }
96
- export function useInfiniteList<S extends ContractSchemas>(options: ListOptions<bulk.UseInfiniteListOptions,S>) {
97
- return bulk.createInfiniteListQuery(bind(options),recordDecoder(options));
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));
98
131
  }
99
- export function useSelect<S extends ContractSchemas>(
100
- options: ListOptions<Omit<bulk.UseSelectOptions<Row<S>>,'optionLabel'|'optionValue'|'defaultValue'|'onSearch'>,S>&{
101
- optionLabel: Field<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string);
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);
102
135
  optionValue: ValueField<NoInfer<Row<S>>>|((row: NoInfer<Row<S>>) => string|number);
103
- defaultValue?: Id<S>[];
136
+ defaultValue?: Id<S> | readonly Id<S>[];
104
137
  onSearch?: (value: string) => ContractFilter<NoInfer<Row<S>>>[];
105
138
  },
106
139
  ) {
107
- return bulk.createSelectQuery(bind(options),recordDecoder(options));
140
+ return bulk.createSelectQuery<Row<S>, TSelected>(bind(options), recordDecoder(options));
108
141
  }
109
142
  export function useTable<S extends ContractSchemas>(
110
143
  options: query.MaybeGetter<QueryOptions<UseTableOptions,S>&{
@@ -1,6 +1,7 @@
1
1
  import { definedOptions } from './defined-options';
2
2
  import { createListQuery } from './query-hooks.svelte';
3
3
  import { decodeBaseRecord, type RecordDecoder } from './record-decoder';
4
+ import { matchClientFilter } from './client-filter';
4
5
  import { readURLState,writeURLState } from './url-sync';
5
6
  import { captureContractContext } from './contract-context.svelte';
6
7
  import { getAdminOptions } from './options.svelte';
@@ -61,7 +62,9 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
61
62
  pageSize: urlState.pageSize??initPagination.pageSize,
62
63
  });
63
64
  }
64
- if(urlState.sortField) {
65
+ if(urlState.sorters?.length) {
66
+ initSorters=urlState.sorters;
67
+ } else if(urlState.sortField) {
65
68
  initSorters=[{ field: urlState.sortField,order: urlState.sortOrder??'asc' }];
66
69
  }
67
70
  if(urlState.filters) {
@@ -82,7 +85,7 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
82
85
  ? pagination
83
86
  :{ current: 1,pageSize: 999999,mode: paginationMode });
84
87
 
85
- const tableQueryInfo=createListQuery(() => {
88
+ const tableQueryInfo=createListQuery<TQueryFnData>(() => {
86
89
  const currentOpts=getOptions();
87
90
  const { meta,syncWithLocation: _swl,dataProviderName,pagination: _p,sorters: _s,filters: _f,...restOptions }=currentOpts;
88
91
  return {
@@ -94,7 +97,7 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
94
97
  dataProviderName,
95
98
  }),
96
99
  ...restOptions
97
- };
100
+ } as UseListOptions<TQueryFnData>;
98
101
  }, getDecoder);
99
102
 
100
103
  const query=tableQueryInfo;
@@ -130,8 +133,7 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
130
133
  writeURLState({
131
134
  page: pagination.current,
132
135
  pageSize: pagination.pageSize,
133
- sortField: currentSorters[0]?.field,
134
- sortOrder: currentSorters[0]?.order,
136
+ sorters: currentSorters,
135
137
  ...definedOptions({
136
138
  filters: currentFilters
137
139
  })
@@ -149,13 +151,13 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
149
151
  if(newPageSize!==pagination.pageSize) {
150
152
  pagination={ ...pagination,pageSize: newPageSize };
151
153
  }
152
- if(urlState.sortField) {
153
- const newSorter: Sort={ field: urlState.sortField,order: urlState.sortOrder??'asc' };
154
- if(JSON.stringify([newSorter])!==JSON.stringify(currentSorters)) {
155
- currentSorters=[newSorter];
156
- }
157
- } else if(currentSorters.length>0) {
158
- currentSorters=[];
154
+ const nextSorters=urlState.sorters?.length
155
+ ? urlState.sorters
156
+ : urlState.sortField
157
+ ? [{ field: urlState.sortField,order: urlState.sortOrder??'asc' }]
158
+ : [];
159
+ if(JSON.stringify(nextSorters)!==JSON.stringify(currentSorters)) {
160
+ currentSorters=nextSorters;
159
161
  }
160
162
  if(urlState.filters&&JSON.stringify(urlState.filters)!==JSON.stringify(currentFilters)) {
161
163
  currentFilters=urlState.filters;
@@ -176,9 +178,13 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
176
178
  const params=new URLSearchParams();
177
179
  if(pagination.current) params.set('page',String(pagination.current));
178
180
  if(pagination.pageSize) params.set('pageSize',String(pagination.pageSize));
179
- if(currentSorters[0]) {
180
- params.set('sort',currentSorters[0].field);
181
- params.set('order',currentSorters[0].order);
181
+ if(currentSorters.length>0) {
182
+ const first=currentSorters[0];
183
+ if(first) {
184
+ params.set('sorters',JSON.stringify(currentSorters));
185
+ params.set('sort',first.field);
186
+ params.set('order',first.order);
187
+ }
182
188
  }
183
189
  if(currentFilters.length>0) {
184
190
  params.set('filters',JSON.stringify(currentFilters));
@@ -228,51 +234,7 @@ export function createTableQuery<TQueryFnData extends BaseRecord>(
228
234
  }
229
235
  const activeFilters=filtersMode==='off'? effectiveFilters:[];
230
236
  if(activeFilters.length>0) {
231
- function matchesFilter(item: Record<string,unknown>,f: Filter): boolean {
232
- if(!('field' in f)) {
233
- if(f.operator==='and') return f.value.every(sub => matchesFilter(item,sub));
234
- if(f.operator==='or') return f.value.length===0||f.value.some(sub => matchesFilter(item,sub));
235
- return true;
236
- }
237
- const val=item[f.field];
238
- const fv=f.value;
239
- switch(f.operator) {
240
- case 'null': return val==null;
241
- case 'nnull': return val!=null;
242
- default: break;
243
- }
244
- if(fv==null||fv==='') return true;
245
- switch(f.operator) {
246
- case 'eq': return val==fv;
247
- case 'ne': return val!=fv;
248
- case 'lt': return typeof val==='number'&&typeof fv==='number'&&val<fv;
249
- case 'gt': return typeof val==='number'&&typeof fv==='number'&&val>fv;
250
- case 'lte': return typeof val==='number'&&typeof fv==='number'&&val<=fv;
251
- case 'gte': return typeof val==='number'&&typeof fv==='number'&&val>=fv;
252
- case 'in': return !Array.isArray(fv)||fv.length===0||fv.includes(val);
253
- case 'nin': return !Array.isArray(fv)||fv.length===0||!fv.includes(val);
254
- case 'contains': return typeof val==='string'&&typeof fv==='string'&&val.includes(fv);
255
- case 'ncontains': return typeof val==='string'&&typeof fv==='string'&&!val.includes(fv);
256
- case 'startswith': return typeof val==='string'&&typeof fv==='string'&&val.startsWith(fv);
257
- case 'endswith': return typeof val==='string'&&typeof fv==='string'&&val.endsWith(fv);
258
- case 'between': {
259
- if(!Array.isArray(fv)||fv.length!==2) return true;
260
- const [min,max]: unknown[]=fv;
261
- return typeof val==='number'&&typeof min==='number'&&typeof max==='number'
262
- &&val>=min&&val<=max;
263
- }
264
- case 'nbetween': {
265
- if(!Array.isArray(fv)||fv.length!==2) return true;
266
- const [min,max]: unknown[]=fv;
267
- return typeof val==='number'&&typeof min==='number'&&typeof max==='number'
268
- &&(val<min||val>max);
269
- }
270
- default: return true;
271
- }
272
- }
273
- sorted=sorted.filter((item) => {
274
- return activeFilters.every(f => matchesFilter(item,f));
275
- });
237
+ sorted=sorted.filter((item) => activeFilters.every((filter) => matchClientFilter(item,filter)));
276
238
  }
277
239
  if(paginationMode==='off') return sorted;
278
240
  const start=((pagination.current??1)-1)*(pagination.pageSize??10);
@@ -83,7 +83,9 @@ export class TableState {
83
83
  pageSize: urlState.pageSize??initPagination.pageSize,
84
84
  });
85
85
  }
86
- if(urlState.sortField) {
86
+ if(urlState.sorters?.length) {
87
+ initSorters=urlState.sorters;
88
+ } else if(urlState.sortField) {
87
89
  initSorters=[{ field: urlState.sortField,order: urlState.sortOrder??'asc' }];
88
90
  }
89
91
  if(urlState.filters) {
@@ -114,8 +116,7 @@ export class TableState {
114
116
  writeURLState({
115
117
  page: this.pagination.current,
116
118
  pageSize: this.pagination.pageSize,
117
- sortField: this.currentSorters[0]?.field,
118
- sortOrder: this.currentSorters[0]?.order,
119
+ sorters: this.currentSorters,
119
120
  ...definedOptions({
120
121
  filters: this.currentFilters
121
122
  })
package/src/types.ts CHANGED
@@ -88,13 +88,26 @@ export interface Sort {
88
88
  order: 'asc' | 'desc';
89
89
  }
90
90
 
91
- export type CrudOperator =
92
- | 'eq' | 'ne' | 'lt' | 'gt' | 'lte' | 'gte'
93
- | 'contains' | 'ncontains'
94
- | 'startswith' | 'endswith'
95
- | 'in' | 'nin'
96
- | 'null' | 'nnull'
97
- | 'between' | 'nbetween';
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
  }