@shikiform/hooks 0.1.0 → 0.2.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/dist/index.d.ts CHANGED
@@ -1,46 +1,538 @@
1
- import { S as ShadowFormApi, U as UseShadowFormOptions } from './internal-DFNiCien.js';
2
- export { A as ArrayTableApi, a as ArrayTablePagination, b as ArrayTableRow, C as CascaderLabelsApi, c as CascaderLoader, d as CascaderOption, e as ColumnDragEvent, f as ColumnDragProps, g as ColumnSetting, h as ColumnSettingInput, i as ColumnSettingsApi, L as LazyCascaderApi, Q as QueryFilters, j as QueryHookArgs, k as QueryHookResult, l as QueryRequestArgs, m as QueryRequestResult, n as QuerySort, o as QueryTableApi, p as ShadowConfirmResult, q as ShadowInit, r as SuggestFetcher, s as SuggestionApi, T as TableDensity, t as TableSorterLike, u as UseArrayTableOptions, v as UseCascaderLabelsOptions, w as UseLazyCascaderOptions, x as UseQueryTableOptions, y as UseSuggestionOptions, z as useArrayTable, B as useBuiltinQuery, D as useCascaderLabels, E as useColumnSettings, F as useLazyCascader, G as useQueryTable, H as useShadowForm, I as useSuggestion } from './internal-DFNiCien.js';
3
- import { FormInstance } from '@shikiform/core/internal';
4
1
  export { ENUM_COLORS, EnumDisplayItem, EnumItemsOptions, enumItems } from '@shikiform/core';
5
- import '@shikiform/react/internal';
2
+ import { ArrayKey, useArrayAt } from '@shikiform/react/internal';
3
+ import { FormInstance, EffectDef, FormOptions, FieldPath, PathValue, FieldError, EnumOption } from '@shikiform/core/internal';
6
4
 
7
- /** What an array shadow was opened for. */
8
- type ArrayShadowContext = {
9
- mode: 'edit';
10
- index: number;
5
+ /**
6
+ * Arguments passed to {@link UseQueryTableOptions.request}.
7
+ * `params` is the submitted filter value. `page` / `pageSize` are the form fields.
8
+ * In client mode `page` is omitted from submit and a page change does not call `request` again.
9
+ */
10
+ interface QueryRequestArgs<TParams> {
11
+ params: TParams;
12
+ page: number;
13
+ pageSize: number;
14
+ /** Table sort, in priority order. Empty when the table is unsorted. */
15
+ sorter: QuerySort[];
16
+ /** Table column filters with at least one value, keyed by column key. */
17
+ filters: QueryFilters;
18
+ signal: AbortSignal;
19
+ }
20
+ /** One sorted column: the column key (antd `columnKey`, else `dataIndex`) and its direction. */
21
+ interface QuerySort {
22
+ field: string;
23
+ order: 'ascend' | 'descend';
24
+ }
25
+ /** Column filters keyed by column key. Only columns with a selected value appear. */
26
+ type QueryFilters = Record<string, Array<string | number | boolean>>;
27
+ /**
28
+ * The parts of an antd `Table` `onChange` sorter result the hook reads. Structural, so the hook does not import antd.
29
+ * `columnKey` wins over `field` (`dataIndex`); an array `field` is joined with `.`.
30
+ */
31
+ interface TableSorterLike {
32
+ columnKey?: unknown;
33
+ field?: unknown;
34
+ order?: 'ascend' | 'descend' | null;
35
+ }
36
+ /** `data` is the rows for this response. `total` is the unpaged count in server mode. */
37
+ interface QueryRequestResult<TRow> {
38
+ data: TRow[];
39
+ total: number;
40
+ }
41
+ /**
42
+ * What a TanStack Query `useQuery` (or a compatible hook) should accept.
43
+ * This package does not import `@tanstack/react-query`.
44
+ * Forward `placeholderData` to keep the previous rows visible while the next request is in flight.
45
+ *
46
+ * Pass the same hook on every render. Omit it to use the built-in request runner, which already keeps the previous result.
47
+ */
48
+ interface QueryHookArgs<TRow> {
49
+ queryKey: readonly unknown[];
50
+ queryFn: (ctx: {
51
+ signal: AbortSignal;
52
+ }) => Promise<QueryRequestResult<TRow>>;
53
+ placeholderData: <T>(previous: T | undefined) => T | undefined;
54
+ }
55
+ /** Result shape a compatible `useQuery` hook should return to {@link useQueryTable}. */
56
+ interface QueryHookResult<TRow> {
57
+ data: QueryRequestResult<TRow> | undefined;
58
+ isFetching: boolean;
59
+ isPlaceholderData?: boolean;
60
+ }
61
+ interface UseQueryTableOptions<TValues, TParams, TRow> {
62
+ /** Existing form. When omitted, one is created from `initialValues`. */
63
+ form?: FormInstance<TValues>;
64
+ initialValues?: TValues;
65
+ effects?: EffectDef<TValues>[];
66
+ fields?: FormOptions<TValues>['fields'];
67
+ /**
68
+ * Filter payload. A field path (`'params'`) or `(values) => filters`.
69
+ * Omit to use the whole form value. `TParams` is that payload; `TRow` is one element of `request`'s `data`.
70
+ */
71
+ params?: FieldPath<TValues> | ((values: TValues) => TParams);
72
+ /** Page field. Default `'page'`. Client mode omits it from submit; server mode leaves the caller's display alone. */
73
+ page?: FieldPath<TValues>;
74
+ /** Page size field. Default `'pageSize'`. */
75
+ pageSize?: FieldPath<TValues>;
76
+ /** Selection field, omitted from submit. Default `'selectedKeys'`. Survives page changes. Cleared by submit and reset. */
77
+ selectedKeys?: FieldPath<TValues>;
78
+ /**
79
+ * `server` (default) refetches on submit, reset, refresh, and page change.
80
+ * `client` refetches when filters are submitted and slices the cached rows. `page` is omitted from submit.
81
+ */
82
+ mode?: 'server' | 'client';
83
+ request: (args: QueryRequestArgs<TParams>) => Promise<QueryRequestResult<TRow>>;
84
+ /**
85
+ * Optional TanStack Query (or compatible) hook.
86
+ *
87
+ * ```tsx
88
+ * useQuery: (args) => {
89
+ * const query = useQuery({ queryKey: args.queryKey, queryFn: args.queryFn, placeholderData: args.placeholderData })
90
+ * return { data: query.data, isFetching: query.isFetching, isPlaceholderData: query.isPlaceholderData }
91
+ * }
92
+ * ```
93
+ */
94
+ useQuery?: (args: QueryHookArgs<TRow>) => QueryHookResult<TRow>;
95
+ defaultPageSize?: number;
96
+ /**
97
+ * Array field that receives each response's rows (`data`), so the page can be edited in place
98
+ * (`QueryList` in `@shikiform/antd`). Each response also becomes the initial value of that path,
99
+ * so the form is not `dirty` (or `edited`) until the user changes a row.
100
+ */
101
+ rows?: FieldPath<TValues>;
102
+ }
103
+ interface QueryTableApi<TValues, TParams, TRow> {
104
+ form: FormInstance<TValues>;
105
+ /** The `rows` option: the array field each page is written into (`undefined` without it). `QueryList` renders it. */
106
+ rows?: string;
107
+ /** Rows for the current page. The previous page stays up while the next request is in flight. */
108
+ data: TRow[];
109
+ total: number;
110
+ loading: boolean;
111
+ fetching: boolean;
112
+ isPlaceholderData: boolean;
113
+ page: number;
114
+ pageSize: number;
115
+ selectedKeys: string[];
116
+ /** Apply the current filters, go to page 1, clear the selection, reload. */
117
+ submit: () => void;
118
+ /** Restore initial values, clear the selection, reload. */
119
+ reset: () => void;
120
+ /** Reload the current page. Filters and selection stay. */
121
+ refresh: () => void;
122
+ /** Change page. Filters and the selection stay. A new search is what returns to page 1. */
123
+ onPageChange: (page: number, pageSize?: number) => void;
124
+ setSelectedKeys: (keys: string[]) => void;
125
+ /** Current table sort, sent to `request` as `sorter`. */
126
+ sorter: QuerySort[];
127
+ /** Current column filters, sent to `request` as `filters`. */
128
+ filters: QueryFilters;
129
+ /** Sort by these columns: back to page 1, reload. The selection stays (the result set is the same rows). */
130
+ setSorter: (sorter: QuerySort[]) => void;
131
+ /** Filter by these columns: back to page 1, clear the selection, reload. */
132
+ setFilters: (filters: QueryFilters | Record<string, unknown>) => void;
133
+ /**
134
+ * Pass to antd `Table` `onChange` (or call with the same arguments). Sort and filter changes go through
135
+ * {@link QueryTableApi.setSorter} / {@link QueryTableApi.setFilters}; a `paginate` action is ignored here, since the
136
+ * pager's own `onChange` calls {@link QueryTableApi.onPageChange}.
137
+ */
138
+ onTableChange: (pagination: unknown, filters?: Record<string, unknown>, sorter?: unknown, extra?: {
139
+ action?: string;
140
+ }) => void;
141
+ /** Controlled `sortOrder` for a column key (`null` when unsorted). */
142
+ sortOrderOf: (key: string) => 'ascend' | 'descend' | null;
143
+ /** Controlled `filteredValue` for a column key (`null` when unfiltered). */
144
+ filteredValueOf: (key: string) => Array<string | number | boolean> | null;
145
+ }
146
+ /**
147
+ * Headless query form + table, in the shape of ProTable / ahooks `useAntdTable`, built on ShikiForm.
148
+ * No UI dependency. `QueryList` in `@shikiform/antd` renders it (pass `rows`).
149
+ *
150
+ * `TValues` is inferred from `initialValues` or `form`. `TRow` is inferred from `request`'s `data`.
151
+ * `params: 'filters'` types the request payload as that field's value.
152
+ * `params: (values) => ...` types it as the function's return. Omit `params` to send the whole form value.
153
+ * `page` is omitted from submit in `client` mode and left alone in `server` mode (a caller's `hidden` / `none` stays).
154
+ * `selectedKeys` is always omitted from submit. Neither write touches the field's display.
155
+ */
156
+ /**
157
+ * `useQueryTable<Values>()({ initialValues, … })` fixes the form type (so `[]` / `{}` / union literals are checked
158
+ * against `Values`) and still infers the row and the `params` payload. `useQueryTable<Values>(options)` does not:
159
+ * one explicit type argument stops inference of the rest.
160
+ */
161
+ declare function useQueryTable<TValues>(): {
162
+ <TRow, const P extends FieldPath<TValues>>(options: UseQueryTableOptions<TValues, PathValue<TValues, P & string>, TRow> & {
163
+ params: P;
164
+ }): QueryTableApi<TValues, PathValue<TValues, P & string>, TRow>;
165
+ <TParams, TRow>(options: UseQueryTableOptions<TValues, TParams, TRow> & {
166
+ params: (values: TValues) => TParams;
167
+ }): QueryTableApi<TValues, TParams, TRow>;
168
+ <TRow = unknown>(options: Omit<UseQueryTableOptions<TValues, TValues, TRow>, 'params'> & {
169
+ params?: undefined;
170
+ }): QueryTableApi<TValues, TValues, TRow>;
171
+ };
172
+ declare function useQueryTable<TValues, TRow, const P extends FieldPath<TValues>>(options: UseQueryTableOptions<TValues, PathValue<TValues, P & string>, TRow> & {
173
+ params: P;
174
+ }): QueryTableApi<TValues, PathValue<TValues, P & string>, TRow>;
175
+ declare function useQueryTable<TValues, TParams, TRow>(options: UseQueryTableOptions<TValues, TParams, TRow> & {
176
+ params: (values: TValues) => TParams;
177
+ }): QueryTableApi<TValues, TParams, TRow>;
178
+ declare function useQueryTable<TValues, TRow = unknown>(options: Omit<UseQueryTableOptions<TValues, TValues, TRow>, 'params'> & {
179
+ params?: undefined;
180
+ }): QueryTableApi<TValues, TValues, TRow>;
181
+ /** Built-in runner. Keeps the previous `data` while `isFetching` is true. */
182
+ declare function useBuiltinQuery<TRow>(args: QueryHookArgs<TRow>): QueryHookResult<TRow>;
183
+
184
+ /** Client pagination (slice the array) or, when `total` is given, a controlled server page. */
185
+ interface ArrayTablePagination {
186
+ /** Rows per page. Default 10. */
187
+ pageSize?: number;
188
+ /** Controlled page (server mode). */
189
+ current?: number;
190
+ /** Server mode: the unpaged count. The array then holds exactly one page and is not sliced. */
191
+ total?: number;
192
+ /** Hide the pager when everything fits on one page. Default true. */
193
+ hideOnSinglePage?: boolean;
194
+ /** Called on every page / size change, in both modes. */
195
+ onChange?: (page: number, pageSize: number) => void;
196
+ }
197
+ interface UseArrayTableOptions<TRow = any> {
198
+ /** Row id property. Selection and expansion keys are this id (or a stable identity when rows have none). */
199
+ rowKey?: string;
200
+ /**
201
+ * New id for a row that needs one (requires `rowKey`): `copy` always calls it for the copied row, `add` calls it
202
+ * when the added row's `rowKey` is `undefined` / `null`. It receives the new row without its id.
203
+ * Without it, `copy` drops the id field (the copy is keyed by object identity until you give it one) and
204
+ * `add` inserts the row as given.
205
+ *
206
+ * ```ts
207
+ * let next = 1000
208
+ * useArrayTable<Row>('rows', { rowKey: 'id', createRowKey: () => ++next })
209
+ * ```
210
+ */
211
+ createRowKey?: (row: TRow) => unknown;
212
+ /** `false` shows every row. Default: client pages of 10. */
213
+ pagination?: false | ArrayTablePagination;
214
+ /** Keep selected keys across page changes. Default false (Pro.formily: a page change clears the selection). */
215
+ preserveSelection?: boolean;
216
+ /** Controlled selection (e.g. `useQueryTable().selectedKeys`). Pair with `onSelectionChange`. */
217
+ selectedKeys?: string[];
218
+ onSelectionChange?: (keys: string[]) => void;
219
+ /** Expand every expandable row of the current page, again after each page change. */
220
+ defaultExpandAll?: boolean;
221
+ /** Which rows can expand. Default: every row. */
222
+ rowExpandable?: (record: TRow, index: number) => boolean;
223
+ /** Runs before a row is removed. A rejected promise keeps the row. The row reports `removing` meanwhile. */
224
+ onRemove?: (index: number, record: TRow) => void | Promise<void>;
225
+ }
226
+ /** One rendered row of the current page. `index` is the index in the whole array. */
227
+ interface ArrayTableRow extends ArrayKey {
228
+ /** 1-based position across pages (what an index column shows). */
229
+ position: number;
230
+ }
231
+ /**
232
+ * Headless state for an array table (`ArrayTable`): page slice, row selection,
233
+ * expansion, and row actions over {@link useArrayField}. No UI. `ArrayTable` in `@shikiform/antd` renders it.
234
+ */
235
+ interface ArrayTableApi<TRow = any> {
236
+ path: string;
237
+ /** Every row (structure keys), in array order. */
238
+ rows: ArrayKey[];
239
+ /** Rows of the current page. In server mode, every row in the array. */
240
+ pageRows: ArrayTableRow[];
241
+ /** The array value (read on render; the hook itself subscribes to structure only). */
242
+ record: (index: number) => TRow;
243
+ /** 1-based position across pages of the row at array `index` (server paging adds the page offset). */
244
+ positionOf: (index: number) => number;
245
+ total: number;
246
+ page: number;
247
+ pageSize: number;
248
+ pageCount: number;
249
+ /** False when pagination is off, or `hideOnSinglePage` and one page is enough. */
250
+ showPager: boolean;
251
+ setPage: (page: number, pageSize?: number) => void;
252
+ selectedKeys: string[];
253
+ setSelectedKeys: (keys: string[]) => void;
254
+ toggleSelected: (key: string) => void;
255
+ /** Select every row on the current page. */
256
+ selectPage: () => void;
257
+ /** Invert the selection on the current page (Pro.formily 反选). */
258
+ invertPage: () => void;
259
+ clearSelection: () => void;
260
+ /** Records of the selected rows that are still in the array. */
261
+ selectedRecords: () => TRow[];
262
+ expandedKeys: string[];
263
+ setExpandedKeys: (keys: string[]) => void;
264
+ toggleExpanded: (key: string) => void;
265
+ isExpandable: (index: number) => boolean;
266
+ /** Keys whose `onRemove` is in flight. */
267
+ removing: string[];
268
+ /** Run `onRemove`, then remove the row. Resolves false when `onRemove` rejected. */
269
+ remove: (index: number) => Promise<boolean>;
270
+ /** Append a row. By default jumps to the page that shows it. */
271
+ add: (row: TRow, options?: {
272
+ jump?: boolean;
273
+ }) => void;
274
+ /**
275
+ * Insert a structured copy of the row right after it. With `rowKey`, the copy gets `createRowKey(copy)` as its id,
276
+ * or has the id field dropped when there is no `createRowKey`. `transform` runs last and returns the row to insert,
277
+ * e.g. `copy(i, (row) => ({ ...row, id: nextId(), name: row.name + ' (副本)' }))`.
278
+ */
279
+ copy: (index: number, transform?: (copy: TRow, source: TRow) => TRow) => void;
280
+ moveUp: (index: number) => void;
281
+ moveDown: (index: number) => void;
282
+ move: (from: number, to: number) => void;
283
+ }
284
+ /**
285
+ * Array table state: what `ArrayTable` (Pro.formily `ProArrayTable`) does, without the table.
286
+ *
287
+ * ```tsx
288
+ * const table = useArrayTable<Row>('list', { rowKey: 'id', pagination: { pageSize: 5 } })
289
+ * table.pageRows.map((row) => <RowScope key={row.key} path={`${table.path}.${row.index}`} index={row.index}>…</RowScope>)
290
+ * ```
291
+ */
292
+ declare function useArrayTable<TRow = any>(name: string, options?: UseArrayTableOptions<TRow>): ArrayTableApi<TRow>;
293
+ /** Internal: {@link useArrayTableAt} over an array subscription the caller already holds (`ArrayTable` also needs its `dragProps`). */
294
+ declare function useArrayTableOver<TRow = any>(path: string, array: Pick<ReturnType<typeof useArrayAt>, 'keys'>, options?: UseArrayTableOptions<TRow>): ArrayTableApi<TRow>;
295
+
296
+ /** What {@link useColumnSettings} needs to know about a column. */
297
+ interface ColumnSettingInput {
11
298
  key: string;
299
+ title?: unknown;
300
+ width?: number;
301
+ /** Start hidden. */
302
+ hidden?: boolean;
303
+ }
304
+ /** One column's user setting. */
305
+ interface ColumnSetting {
306
+ key: string;
307
+ title?: unknown;
308
+ show: boolean;
309
+ width?: number;
310
+ }
311
+ /** Table density, cycled by the settings toolbar. */
312
+ type TableDensity = 'large' | 'middle' | 'small';
313
+ interface ColumnSettingsApi {
314
+ /** Every column with its setting, in the user's order. */
315
+ items: ColumnSetting[];
316
+ /** Keys to render, in order. */
317
+ visibleKeys: string[];
318
+ toggle: (key: string) => void;
319
+ /** Move a column to its final index among all columns. */
320
+ move: (from: number, to: number) => void;
321
+ setWidth: (key: string, width: number) => void;
322
+ density: TableDensity;
323
+ setDensity: (density: TableDensity) => void;
324
+ /** Restore order, visibility, widths, and density. */
325
+ reset: () => void;
326
+ /** Move the column `from` to where the column `to` is (drag-and-drop by key). */
327
+ moveKey: (from: string, to: string) => void;
328
+ /**
329
+ * HTML5 drag-and-drop props for one settings row: spread them on the row element. Dropping a row on another moves
330
+ * it there. Keep `move` buttons beside them for keyboard users.
331
+ */
332
+ dragProps: (key: string) => ColumnDragProps;
333
+ /** Key being dragged and key under it, for styling. */
334
+ drag: {
335
+ from: string | null;
336
+ over: string | null;
337
+ };
338
+ }
339
+ /** Minimal drag event shape, so the hook does not depend on DOM or React event types. */
340
+ interface ColumnDragEvent {
341
+ preventDefault: () => void;
342
+ dataTransfer?: {
343
+ setData?: (format: string, data: string) => void;
344
+ effectAllowed?: string;
345
+ dropEffect?: string;
346
+ } | null;
347
+ }
348
+ /** What {@link ColumnSettingsApi.dragProps} returns. */
349
+ interface ColumnDragProps {
350
+ draggable: true;
351
+ 'data-dragging'?: 'true';
352
+ 'data-drag-over'?: 'true';
353
+ onDragStart: (event: ColumnDragEvent) => void;
354
+ onDragOver: (event: ColumnDragEvent) => void;
355
+ onDragLeave: () => void;
356
+ onDrop: (event: ColumnDragEvent) => void;
357
+ onDragEnd: () => void;
358
+ }
359
+ /**
360
+ * Headless column settings (Pro.formily `ProSettings`): show / hide, reorder (`move` by index, or drag-and-drop through
361
+ * `dragProps`), resize, density.
362
+ * Columns added later are appended; removed columns drop out.
363
+ */
364
+ declare function useColumnSettings(columns: readonly ColumnSettingInput[]): ColumnSettingsApi;
365
+
366
+ /** Where a shadow form's values come from when it opens: a value, or a (possibly async) loader. */
367
+ type ShadowInit<TValues> = TValues | Partial<TValues> | (() => TValues | Partial<TValues> | Promise<TValues | Partial<TValues>>);
368
+ /** Result of {@link ShadowFormApi.confirm}. `ok: false` keeps the shadow open with its errors. */
369
+ type ShadowConfirmResult<TValues> = {
370
+ ok: true;
371
+ values: TValues;
12
372
  } | {
13
- mode: 'add';
373
+ ok: false;
374
+ errors: FieldError[];
14
375
  };
15
- interface UseArrayShadowOptions<TRow> extends Omit<UseShadowFormOptions<TRow, ArrayShadowContext>, 'onOk'> {
376
+ interface UseShadowFormOptions<TValues, TContext = unknown> {
16
377
  /**
17
- * The host form, for a caller outside `<Form>` (e.g. next to a `QueryList`, which renders its own).
18
- * `name` is then an absolute path. Default: the surrounding form, `name` relative to the current scope.
378
+ * Bind to a path on the host form: relative to the current scope inside `<Form>`, or an absolute path when `form`
379
+ * is given. Omit inside a row / `<ObjectField>` scope to bind that scope's path automatically.
19
380
  */
381
+ name?: string;
382
+ /** Explicit host form when called outside `<Form>` (e.g. next to a `QueryList`). `name` is then absolute (`''` = root). */
20
383
  form?: FormInstance<any>;
21
- /** Row id property, as on the array. Used to find the edited row again if it moved while the draft was open. */
384
+ /**
385
+ * Append mode on a bound array path (`name: 'list'`): `true` opens `{}` and appends on confirm; an object opens
386
+ * a clone of that template and appends on confirm.
387
+ */
388
+ add?: boolean | Partial<TValues>;
389
+ /** Row id property when bound to an array element, used to locate the row if it moved before confirm. */
22
390
  rowKey?: string;
391
+ /** Custom merge when writing back an edited object or array row. Default shallow-merges plain objects so `virtual` keys survive. */
392
+ merge?: (current: TValues, values: TValues) => TValues;
393
+ /** Values the shadow opens with when `open()` gets none (overrides bound value when provided, or fallback in `add` mode). */
394
+ initialValues?: TValues;
395
+ /** Field declarations for the shadow form (merged over inherited `forkOptions` fields). */
396
+ fields?: FormOptions<TValues>['fields'];
397
+ /** Effects for the shadow form. They run again on every open (a fresh engine). */
398
+ effects?: FormOptions<TValues>['effects'];
399
+ /** Other engine options (validateTrigger, schema, pattern, messages…). Merged over inherited `forkOptions`. */
400
+ formOptions?: Omit<FormOptions<TValues>, 'initialValues' | 'fields' | 'effects'>;
23
401
  /**
24
- * Runs after validation, before the default write. Return `false` to skip the default write
25
- * (replace the edited row / append the added one) and handle the values yourself.
402
+ * Called with the submitted shadow values after validation passes, before any bound write-back.
403
+ * Return `false` to skip the automatic write-back; throw / reject to keep the shadow open.
26
404
  */
27
- onOk?: (values: TRow, context: ArrayShadowContext | undefined) => void | false | Promise<void | false>;
28
- /** How an edit lands on the row. Default: `{ ...row, ...values }`. */
29
- merge?: (row: TRow, values: TRow) => TRow;
30
- /** How an added row lands. Default: `pushArray`. `ArrayTable.ShadowAddition` passes the table's `add` so the pager follows. */
31
- append?: (row: TRow) => void;
405
+ onOk?: (values: TValues, context: TContext | undefined) => void | false | Promise<void | false>;
406
+ /** Called when the shadow closes without confirming. */
407
+ onCancel?: (context: TContext | undefined) => void;
408
+ }
409
+ /**
410
+ * A draft form, optionally bound to a host form path (object, array row, or array append).
411
+ * Every `open()` builds a fresh engine so `reset`, `dirty`, errors and effects start clean each time.
412
+ * Render its fields with `<Form form={shadow.form}>` or `ShadowModal` / `ShadowDrawer` / `ShadowPopconfirm` / `ShadowForm`.
413
+ */
414
+ interface ShadowFormApi<TValues, TContext = unknown> {
415
+ /** The current draft engine. Replaced on every `open()`. */
416
+ form: FormInstance<TValues>;
417
+ /** True between `open()` and `confirm()` success / `cancel()`. */
418
+ visible: boolean;
419
+ /** True while an async `open()` loader runs. */
420
+ loading: boolean;
421
+ /** True while `confirm()` validates and runs `onOk`. */
422
+ submitting: boolean;
423
+ /** Whatever `open()` was given as `context`. */
424
+ context: TContext | undefined;
425
+ /** Open with values (or a loader) and an optional context. A newer `open()` supersedes a pending loader. */
426
+ open: (init?: ShadowInit<TValues>, context?: TContext) => Promise<void>;
427
+ /** Validate the draft, call `onOk` (and the optional per-call handler), write back when bound unless `false` is returned, then close. */
428
+ confirm: (onOk?: (values: TValues, context: TContext | undefined) => void | false | Promise<void | false>) => Promise<ShadowConfirmResult<TValues>>;
429
+ /** Close without writing anything. */
430
+ cancel: () => void;
431
+ }
432
+ interface InternalShadowOptions<TValues, TContext = unknown> extends UseShadowFormOptions<TValues, TContext> {
433
+ /** Custom append used by `ArrayTable.ShadowAddition` so pagination follows the added row. */
434
+ append?: (row: TValues) => void;
435
+ }
436
+ /** @internal Shared implementation accepting `append` for `ArrayTable.ShadowAddition`. */
437
+ declare function useShadowFormOver<TValues = Record<string, any>, TContext = unknown>(options?: InternalShadowOptions<TValues, TContext>): ShadowFormApi<TValues, TContext>;
438
+ /**
439
+ * Headless ShadowForm (Pro.formily `ShadowForm` / `useShadowForm`): edit a draft copy of an object, array row,
440
+ * or standalone record in a separate form engine, writing back on `confirm()` when bound.
441
+ */
442
+ declare function useShadowForm<TValues = Record<string, any>, TContext = unknown>(options?: UseShadowFormOptions<TValues, TContext>): ShadowFormApi<TValues, TContext>;
443
+
444
+ /** Remote search for a suggestion box. `signal` aborts when a newer keyword supersedes this call. */
445
+ type SuggestFetcher = (keyword: string, ctx: {
446
+ signal: AbortSignal;
447
+ }) => Promise<readonly EnumOption[]> | readonly EnumOption[];
448
+ interface UseSuggestionOptions {
449
+ /** Load options for a keyword. */
450
+ fetch: SuggestFetcher;
451
+ /** Wait this long after the last keystroke. Default 300 ms. */
452
+ debounce?: number;
453
+ /** Keywords shorter than this clear the options without fetching. Default 1. */
454
+ minLength?: number;
455
+ }
456
+ interface SuggestionApi {
457
+ keyword: string;
458
+ /** Options for the latest finished keyword, plus remembered selections (so a picked value keeps its label). */
459
+ options: EnumOption[];
460
+ loading: boolean;
461
+ /** Last fetch error, cleared by the next search. */
462
+ error: unknown;
463
+ /** Set the keyword; fetches after `debounce`. Older requests are aborted and their results dropped. */
464
+ search: (keyword: string) => void;
465
+ /** Remember options the user picked so their labels survive the next search. */
466
+ remember: (options: readonly EnumOption[]) => void;
467
+ /** Label for a value from the current or remembered options. */
468
+ labelOf: (value: unknown) => string | undefined;
469
+ }
470
+ /**
471
+ * Headless remote suggestion (Pro.formily `Suggestion`): debounced, abortable, last-request-wins search.
472
+ * `Suggestion` in `@shikiform/antd` binds it to a field through a searchable Select.
473
+ */
474
+ declare function useSuggestion(options: UseSuggestionOptions): SuggestionApi;
475
+
476
+ /** A cascader node. `isLeaf: false` without `children` means "load on expand". */
477
+ interface CascaderOption {
478
+ label: string;
479
+ value: string | number;
480
+ isLeaf?: boolean;
481
+ disabled?: boolean;
482
+ children?: CascaderOption[];
483
+ /** Set while this node's children load. */
484
+ loading?: boolean;
485
+ }
486
+ /** Load the children of `path` (the selected values so far; `[]` is the root). */
487
+ type CascaderLoader = (path: Array<string | number>) => Promise<readonly CascaderOption[]> | readonly CascaderOption[];
488
+ interface UseLazyCascaderOptions {
489
+ load: CascaderLoader;
490
+ /** Value paths to show on open (反显). Each path's ancestors are loaded so the labels resolve. */
491
+ paths?: ReadonlyArray<ReadonlyArray<string | number>>;
492
+ /** Default true. `false` loads nothing (a read view whose value already carries its labels). */
493
+ enabled?: boolean;
494
+ }
495
+ interface LazyCascaderApi {
496
+ options: CascaderOption[];
497
+ /** True while the root or an echo path loads. */
498
+ loading: boolean;
499
+ /** Load the children of `path` unless they are loaded or the node is a leaf. */
500
+ loadChildren: (path: Array<string | number>) => Promise<void>;
501
+ /** Load what is missing for each path (反显). */
502
+ ensure: (paths: ReadonlyArray<ReadonlyArray<string | number>>) => Promise<void>;
503
+ /** Labels along a value path, as far as the tree is loaded. */
504
+ labelsOf: (path: ReadonlyArray<string | number>) => string[];
505
+ }
506
+ /**
507
+ * Headless lazy cascader (Pro.formily `CascaderPlus`): root on mount, children on demand, a loader shared by
508
+ * every level, and echo of an existing value by loading each ancestor level. A tree known up front is not this
509
+ * hook's job: give it to `<Field enum>` and use `Cascader`. `CascaderPlus` in
510
+ * `@shikiform/antd` renders it with Ant Design's Cascader and adds `multiple` / `labelInValue`.
511
+ */
512
+ declare function useLazyCascader(options: UseLazyCascaderOptions): LazyCascaderApi;
513
+ type Key = string | number;
514
+ /**
515
+ * The value paths a cascader field holds: one path, or (`multiple`) several. A `labelInValue` level
516
+ * (`{ label, value }`) contributes its `value`.
517
+ */
518
+ declare function cascaderPaths(value: unknown, multiple?: boolean): Key[][];
519
+ interface UseCascaderLabelsOptions {
520
+ value: unknown;
521
+ multiple?: boolean;
522
+ /** The same loader the editable cascader uses. Without it, levels without a label show their value. */
523
+ load?: CascaderLoader;
32
524
  }
33
- interface ArrayShadowApi<TRow> extends ShadowFormApi<TRow, ArrayShadowContext> {
34
- /** Open the draft on row `index`. `loader` maps (or fetches) the record first (Pro.formily `initLoader`). */
35
- edit: (index: number, loader?: (record: TRow) => TRow | Partial<TRow> | Promise<TRow | Partial<TRow>>) => Promise<void>;
36
- /** Open an empty (or `init`) draft whose confirm appends a row (Pro.formily `ProAddition`). */
37
- add: (init?: Partial<TRow>) => Promise<void>;
525
+ interface CascaderLabelsApi {
526
+ /** One label list per path. A level shows its `labelInValue` label, else the loaded label, else its value. */
527
+ labels: string[][];
528
+ /** True while the tree loads the ancestors needed to resolve a bare value. */
529
+ loading: boolean;
38
530
  }
39
531
  /**
40
- * Row editing through a shadow form (Pro.formily `DelegateAction` + `ShadowModal` + `ProAddition`):
41
- * one draft serves every row; confirm writes back to the row it was opened for, or appends.
42
- * Cancel leaves the array untouched.
532
+ * Labels for a cascader value, for a read view (`readPretty`). A `labelInValue` value already carries its labels and
533
+ * loads nothing. A bare value (`['zj', 'hz']`) is resolved by loading each ancestor level through `load`, the same way
534
+ * {@link useLazyCascader} echoes a value into the editor.
43
535
  */
44
- declare function useArrayShadow<TRow = Record<string, any>>(name: string, options?: UseArrayShadowOptions<TRow>): ArrayShadowApi<TRow>;
536
+ declare function useCascaderLabels(options: UseCascaderLabelsOptions): CascaderLabelsApi;
45
537
 
46
- export { type ArrayShadowApi, type ArrayShadowContext, ShadowFormApi, type UseArrayShadowOptions, UseShadowFormOptions, useArrayShadow };
538
+ export { type ArrayTableApi, type ArrayTablePagination, type ArrayTableRow, type CascaderLabelsApi, type CascaderLoader, type CascaderOption, type ColumnDragEvent, type ColumnDragProps, type ColumnSetting, type ColumnSettingInput, type ColumnSettingsApi, type LazyCascaderApi, type QueryFilters, type QueryHookArgs, type QueryHookResult, type QueryRequestArgs, type QueryRequestResult, type QuerySort, type QueryTableApi, type ShadowConfirmResult, type ShadowFormApi, type ShadowInit, type SuggestFetcher, type SuggestionApi, type TableDensity, type TableSorterLike, type UseArrayTableOptions, type UseCascaderLabelsOptions, type UseLazyCascaderOptions, type UseQueryTableOptions, type UseShadowFormOptions, type UseSuggestionOptions, useShadowFormOver as a, cascaderPaths as c, useArrayTableOver as u, useArrayTable, useBuiltinQuery, useCascaderLabels, useColumnSettings, useLazyCascader, useQueryTable, useShadowForm, useSuggestion };
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
1
- import { useShadowForm } from './chunk-XUI4UURI.js';
2
- export { useArrayTable, useCascaderLabels, useColumnSettings, useLazyCascader, useShadowForm, useSuggestion } from './chunk-XUI4UURI.js';
3
- import { useRef, useSyncExternalStore, useState, useCallback, useEffect, useContext } from 'react';
4
- import { engineOf, setAt, ShikiUsageError, joinPath } from '@shikiform/core/internal';
5
- import { useForm, FormContext, useScope } from '@shikiform/react/internal';
1
+ export { useArrayTable, useCascaderLabels, useColumnSettings, useLazyCascader, useShadowForm, useSuggestion } from './chunk-ODAZS5QS.js';
2
+ import { useRef, useSyncExternalStore, useState, useCallback, useEffect } from 'react';
3
+ import { engineOf, setAt } from '@shikiform/core/internal';
4
+ import { useForm } from '@shikiform/react/internal';
6
5
  export { ENUM_COLORS, enumItems } from '@shikiform/core';
7
6
 
8
7
  function useQueryTable(options) {
@@ -234,47 +233,7 @@ function stable(value) {
234
233
  return String(value);
235
234
  }
236
235
  }
237
- function useArrayShadow(name, options = {}) {
238
- const context = useContext(FormContext);
239
- const scope = useScope();
240
- const form = options.form ? engineOf(options.form) : context;
241
- if (!form) {
242
- if (process.env.NODE_ENV !== "production") {
243
- throw new ShikiUsageError("useArrayShadow needs a surrounding <Form> or a `form` option.");
244
- }
245
- throw new Error("useArrayShadow needs a surrounding <Form> or a `form` option");
246
- }
247
- const path = options.form ? name : joinPath(scope.path, name);
248
- const { onOk, merge, append, rowKey, form: _form, ...shadowOptions } = options;
249
- const shadow = useShadowForm({
250
- ...shadowOptions,
251
- onOk: async (values, context2) => {
252
- const handled = await onOk?.(values, context2);
253
- if (handled === false || !context2) return;
254
- if (context2.mode === "add") {
255
- if (append) append(values);
256
- else form.pushArray(path, values);
257
- return;
258
- }
259
- const row = form.structureKeys(path, rowKey).find((item) => item.key === context2.key);
260
- const index = row?.index ?? context2.index;
261
- const current = form.getValue(`${path}.${index}`);
262
- const next = merge ? merge(current, values) : { ...current, ...values };
263
- form.replaceArray(path, index, next);
264
- }
265
- });
266
- const edit = useCallback(
267
- (index, loader) => {
268
- const key = form.structureKeys(path, rowKey)[index]?.key ?? String(index);
269
- const record = form.getValue(`${path}.${index}`);
270
- return shadow.open(loader ? () => loader(record) : record, { mode: "edit", index, key });
271
- },
272
- [form, path, rowKey, shadow.open]
273
- );
274
- const add = useCallback((init) => shadow.open(init ?? {}, { mode: "add" }), [shadow.open]);
275
- return { ...shadow, edit, add };
276
- }
277
236
 
278
- export { useArrayShadow, useBuiltinQuery, useQueryTable };
237
+ export { useBuiltinQuery, useQueryTable };
279
238
  //# sourceMappingURL=index.js.map
280
239
  //# sourceMappingURL=index.js.map