@shikiform/react 0.2.0 → 0.3.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,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentType, ReactNode, ComponentProps, FormHTMLAttributes, FunctionComponent, ComponentClass, ForwardRefExoticComponent, Ref, DragEvent } from 'react';
3
- import { Display, Pattern, EnumOption, UiName, FieldEnum, RulesInput, FieldPath, PathValue, ArrayPath, FieldError, FormInstance, Pos, Draft, FormOptions, DefaultSubmit, FieldsInput, ResolveSubmit, ArrayItemOf, FormEngine, UiDisplay, MoveResult, FormMessageKey, MessageArgs } from '@shikiform/core/internal';
3
+ import { EnumOption, UiName, FieldEnum, RulesInput, FieldPath, PathValue, ArrayPath, FieldError, FormInstance, Pos, Draft, FormOptions, DefaultSubmit, FieldsInput, ResolveSubmit, ArrayItemOf, FormEngine, MoveResult } from '@shikiform/core/internal';
4
4
 
5
5
  /**
6
6
  * Register the controls your app passes to `<Field component="Input">` (module augmentation):
@@ -71,11 +71,15 @@ interface FieldBinding<TValue> {
71
71
  onBlur(): void;
72
72
  errors: string[];
73
73
  warnings: string[];
74
- display: Display;
75
- pattern: Pattern;
76
- required: boolean;
74
+ /** Effective render flag (OR-inherited). `false` does not render; the value is still submitted unless `omit`. */
75
+ visible: boolean;
76
+ /** Effective disabled (OR-inherited). The preview wins when `readOnly` is also set. */
77
77
  disabled: boolean;
78
+ /** Effective read-only (OR-inherited). Renders the preview. Wins over `disabled`. */
78
79
  readOnly: boolean;
80
+ /** This field is left out of submit. Not inherited. */
81
+ omit: boolean;
82
+ required: boolean;
79
83
  /** True after blur. `reset` clears it. */
80
84
  touched: boolean;
81
85
  /** The value differs from its initial value (deep compare). Changing it back clears it. */
@@ -101,7 +105,7 @@ interface FieldBinding<TValue> {
101
105
  decoratorProps: Record<string, any>;
102
106
  /**
103
107
  * The UI instance name when this binding comes from `<Field name ui="echo">` / `useField(name, { ui })`: value,
104
- * errors and `onChange` are the field's; display, pattern, title, props and `id` (`<prefix>-<path>--<ui>`) are the instance's.
108
+ * errors and `onChange` are the field's; visible, disabled, readOnly, title, props and `id` (`<prefix>-<path>--<ui>`) are the instance's.
105
109
  */
106
110
  ui?: string;
107
111
  }
@@ -164,14 +168,14 @@ type RegisteredDecoratorSlot = RegisteredSlot<FieldDecorators>;
164
168
  /**
165
169
  * Field options a hook caller can pass. Same semantics as the `<Field>` props of the same name:
166
170
  * `rules` / `required` are a mount-scoped lease (applied while the calling component is mounted, released on unmount,
167
- * restoring a declaration, item template, or `$rules`). `display` and `pattern` are persistent flags.
171
+ * restoring a declaration, item template, or `$rules`). `visible` / `disabled` / `readOnly` / `omit` are the same lease.
168
172
  */
169
173
  interface UseFieldOptions<TValue = any> {
170
174
  /**
171
175
  * A second (third …) UI of the same field: `<Field name="amount" ui="slider" component={[Slider]} />`.
172
- * Shares the value, errors and rules; has its own display / pattern / title / props, addressed in effects as
173
- * `d.amount.$ui('slider')` (unset falls back to the field: pattern inherits). Own DOM id `<prefix>-<path>--<ui>`.
174
- * `rules` / `required` / `enum` belong on the field itself (the `<Field>` without `ui`). `display` is this instance's.
176
+ * Shares the value, errors and rules; has its own visible / disabled / readOnly / title / props, addressed in effects as
177
+ * `d.amount.$ui('slider')` (unset falls back to the field). Own DOM id `<prefix>-<path>--<ui>`.
178
+ * `rules` / `required` / `enum` / `omit` belong on the field itself (the `<Field>` without `ui`).
175
179
  */
176
180
  ui?: UiName;
177
181
  /**
@@ -182,9 +186,14 @@ interface UseFieldOptions<TValue = any> {
182
186
  enum?: FieldEnum<TValue>;
183
187
  rules?: RulesInput<TValue>;
184
188
  required?: boolean;
185
- /** `virtual` renders and validates but is not submitted. `hidden` / `none` do not render. */
186
- display?: Display;
187
- pattern?: Pattern;
189
+ /** `false` does not render. Inherited (OR); explicit `false` exits a shown parent. Still submitted unless `omit`. */
190
+ visible?: boolean;
191
+ /** Gray the control out. Inherited (OR); explicit `false` exits. Skips validation. */
192
+ disabled?: boolean;
193
+ /** Render the preview. Inherited (OR); explicit `false` exits. Wins over `disabled`. Skips validation. */
194
+ readOnly?: boolean;
195
+ /** Leave this field out of submit. Not inherited. */
196
+ omit?: boolean;
188
197
  /**
189
198
  * UI state, the render-time JSX layer: not stored on the model, so inline objects and handlers are free.
190
199
  * A reaction (`$title`, `$componentProps.x = …`) wins over it; it wins over `fields` declarations.
@@ -226,11 +235,13 @@ declare function useField<TScope, N extends FieldPath<TScope>>(name: N, options?
226
235
  interface FormSubmitHandlers<T> {
227
236
  /** Called with the submit values after validation passes. May be async; the submit waits for it. */
228
237
  onSubmit?: (values: T) => void | Promise<void>;
229
- /** Called with the errors when validation fails (`reason: 'invalid'`). Scroll to the first error, show a toast … */
238
+ /** Called with the errors when validation fails (`submit` / `validate` reject `FieldError[]`). */
230
239
  onInvalid?: (errors: FieldError[]) => void;
231
240
  /**
232
- * Called when `onSubmit` (or a form-level `validate`) throws or rejects (`reason: 'error'`).
241
+ * Called when `onSubmit` (or a form-level `validate`) throws or rejects.
233
242
  * Without it the error is reported with `console.error`; it never becomes an unhandled rejection.
243
+ * Includes `SubmitUnstableError` (values never settled). A `SubmitSupersededError` is swallowed:
244
+ * the newer submit owns that outcome.
234
245
  */
235
246
  onSubmitError?: (error: unknown) => void;
236
247
  }
@@ -255,8 +266,8 @@ type FormProps<T, TSubmit = T> = FormSubmitHandlers<TSubmit> & FormDomProps & {
255
266
  * Field DOM ids are prefixed with this form's `id`, or with React `useId()` when `id` is omitted, so two forms
256
267
  * do not share `id="email"`. The engine's `binding().id` stays the sanitized path (`user.name` → `user-name`);
257
268
  * the control's id is `<prefix>-user-name`.
258
- * `<Field>` returns null for display `hidden` and `none` after subscribing, so a mounted model stays registered.
259
- * `virtual` stays mounted: it renders and validates, and is omitted from submit.
269
+ * `<Field>` returns null when `visible` is false after subscribing, so a mounted model stays registered.
270
+ * `omit` still renders: the value is left out of submit only.
260
271
  * A field declared on the form, or given `$rules` / `registerField`, still validates when this component is not rendered.
261
272
  */
262
273
  declare function Form<T, TSubmit = T>({ form, children, onSubmit, onInvalid, onSubmitError, id, kit, ...rest }: FormProps<T, TSubmit>): react.JSX.Element;
@@ -265,9 +276,9 @@ interface FieldProps<TScope = any, N extends FieldPath<TScope> = FieldPath<TScop
265
276
  /** Name relative to the current `<ObjectField>` / `<ArrayField>` / `<TreeField>` scope. */
266
277
  name: N;
267
278
  /**
268
- * Another UI of the same field (`d.name.$ui('echo')` in effects): shared value / errors / rules, its own display,
269
- * pattern, title and props (unset falls back to the field's). Own DOM id `<prefix>-<path>--<ui>`. Leave rules / required /
270
- * enum to the `<Field>` without `ui`. `display` here is this instance's, not the field's.
279
+ * Another UI of the same field (`d.name.$ui('echo')` in effects): shared value / errors / rules, its own visible /
280
+ * disabled / readOnly, title and props (unset falls back to the field's). Own DOM id `<prefix>-<path>--<ui>`.
281
+ * Leave rules / required / enum / omit to the `<Field>` without `ui`.
271
282
  */
272
283
  ui?: UiName;
273
284
  /**
@@ -275,20 +286,21 @@ interface FieldProps<TScope = any, N extends FieldPath<TScope> = FieldPath<TScop
275
286
  * Option values are typed against the field value (its element type for an array field) when the name is typed
276
287
  * (`typed(form).Field`, `row.Field`). Wins over `fields.x.enum` while mounted; a reaction's `$enum` wins over it.
277
288
  * Changing the prop re-applies it; unmount restores the declared enum. Select / Radio / Checkbox.Group and their
278
- * readPretty views read it as `options`.
289
+ * read-only previews read it as `options`.
279
290
  */
280
291
  enum?: FieldEnum<PathValue<TScope, N & string>>;
281
292
  /** Mount-scoped rules. Cleared on unmount. Does not erase a declaration, a template, or `$rules`. `validator` receives this field's value. */
282
293
  rules?: RulesInput<PathValue<TScope, N & string>>;
283
294
  /** Mount-scoped required flag. Cleared on unmount. A declared or `$required` flag stays. */
284
295
  required?: boolean;
285
- /**
286
- * Initial display when no reaction has written `$display`. `virtual` renders and validates but is not submitted.
287
- * On `<Field ui>` this is the instance's display (`visible` | `hidden` | `none`); `virtual` belongs on the field.
288
- */
289
- display?: Display;
290
- /** Initial pattern when no reaction has written `$pattern`. `$pattern = undefined` inherits again. */
291
- pattern?: Pattern;
296
+ /** `false` does not render. Inherited (OR). Still submitted unless `omit`. On `<Field ui>` this is the instance's. */
297
+ visible?: boolean;
298
+ /** Gray the control out. Inherited (OR). Skips validation. Still submitted. */
299
+ disabled?: boolean;
300
+ /** Render the preview. Inherited (OR). Wins over `disabled`. Skips validation. Still submitted. */
301
+ readOnly?: boolean;
302
+ /** Leave this field out of submit. Not inherited. On `<Field ui>` this is ignored (it belongs to the field). */
303
+ omit?: boolean;
292
304
  /** Decorator label (`FormItem` shows it as `label`). A reaction's `$title` wins. */
293
305
  title?: ReactNode;
294
306
  /** Decorator help text (`FormItem` shows it as `extra`). A reaction's `$description` wins. */
@@ -325,23 +337,31 @@ type CheckedFieldProps<TScope = any, N extends FieldPath<TScope> = FieldPath<TSc
325
337
  *
326
338
  * `rules` may be a built-in rule, a Standard Schema, or a mix. JSX `rules` and `required` apply only while this
327
339
  * component is mounted; unmount restores rules from `useForm({ fields })`, `registerField`, an item template, or `$rules`.
328
- * `display="virtual"` renders and validates but omits the value from submit. `display="hidden"` still validates.
329
- * `display="none"` skips validation. `<Field<Row> name="price">` checks the name.
340
+ * `visible={false}` does not render and skips validation; the value is still submitted unless `omit`.
341
+ * `readOnly` renders the preview and skips validation. `omit` leaves the value out of submit.
342
+ * `<Field<Row> name="price">` checks the name.
330
343
  * `<Field<Row, 'price'> name="price">` types the value.
331
- * `<Field>` is a thin wrapper around {@link useField}: `useField(name, options)` + not rendered (`hidden` / `none`) → `null`
332
- * + the two slots. `virtual` still renders.
344
+ * `<Field>` is a thin wrapper around {@link useField}: `useField(name, options)` + `visible === false` → `null`
345
+ * + the two slots. `omit` still renders.
333
346
  */
334
347
  declare function Field<TScope = any, N extends FieldPath<TScope> = FieldPath<TScope>, C extends ComponentType<any> = ComponentType<any>, D extends ComponentType<any> = ComponentType<any>>({ name, children, ...options }: CheckedFieldProps<TScope, N, C, D>): react.JSX.Element | null;
335
348
  /**
336
349
  * Scope child names under an object path. Does not subscribe to child values.
337
- * `display="virtual"` omits this object (and its subtree) from submit (`getSubmitValues`).
338
- * Also list it in `useForm({ fields })` so the omission holds before this component mounts.
350
+ * `omit` leaves this object out of submit (`getSubmitValues`; nested keys go with it). `omit` does not inherit,
351
+ * so list the object in `useForm({ fields })` when the omission must hold before this component mounts.
352
+ * `visible` / `disabled` / `readOnly` are inherited by the fields inside (OR; a child `false` exits).
339
353
  * `<ObjectField<Values> name="address">` checks the name; `typed(form).ObjectField` also types the children.
340
354
  */
341
- declare function ObjectField<TScope = any>({ name, display, children, }: {
355
+ declare function ObjectField<TScope = any>({ name, visible, disabled, readOnly, omit, children, }: {
342
356
  name: FieldPath<TScope>;
343
- /** `virtual` omits this object from submit. `hidden` / `none` are inherited by the fields inside. */
344
- display?: Display;
357
+ /** `false` hides this object and, by inheritance, the fields inside. Explicit `false` on a child exits. */
358
+ visible?: boolean;
359
+ /** Disables this object and, by inheritance, the fields inside. */
360
+ disabled?: boolean;
361
+ /** Read-only preview for this object and, by inheritance, the fields inside. */
362
+ readOnly?: boolean;
363
+ /** Leave this object out of submit. Not inherited; nested keys disappear with the object. */
364
+ omit?: boolean;
345
365
  children?: ReactNode;
346
366
  }): react.JSX.Element;
347
367
  /**
@@ -351,7 +371,7 @@ declare function ObjectField<TScope = any>({ name, display, children, }: {
351
371
  * Names inside a row are relative to the row (`name="price"`, not `items.0.price`).
352
372
  * `component` is the container around the rows (Formily `ArrayItems` / `ArrayCards` / `ArrayTable` in
353
373
  * `@shikiform/antd`): `component={[ArrayItems, { addition: <ArrayItems.Addition /> }]}` renders
354
- * `<ArrayItems …>{rows}</ArrayItems>` inside the array's scope, so its buttons reach the array through {@link useArray}.
374
+ * `<ArrayItems …>{rows}</ArrayItems>` inside the array's scope, so its buttons reach the array through {@link useArrayField}.
355
375
  * A container that renders its own cells (`ArrayTable` with `columns`) needs no `children`.
356
376
  * `virtualScroll` windows the plain rows (TanStack Virtual); it does not combine with a container `component`.
357
377
  * `<ArrayField<Values> name="items">` checks the name; `typed(form).ArrayField` also types the row's fields.
@@ -379,17 +399,27 @@ declare function ArrayField<TScope = any, C extends ComponentType<any> = Compone
379
399
  }) => ReactNode;
380
400
  }): react.JSX.Element;
381
401
  /**
382
- * Mark the nearest array for {@link useArray} (`path` is absolute). `<ArrayField>` renders it; use it in a custom
383
- * array component built on `useArrayField`.
402
+ * Mark the nearest array for {@link useArrayField} (`path` is absolute). `<ArrayField>` renders it; use it in a custom
403
+ * array component built on `useArrayField(name)`.
384
404
  */
385
405
  declare function ArrayScope({ path, rowKey, children }: {
386
406
  path: string;
387
407
  rowKey?: string;
388
408
  children?: ReactNode;
389
409
  }): react.JSX.Element;
410
+ /**
411
+ * Mark the nearest tree for {@link useTreeField} (`path` is absolute). `<TreeField>` renders it.
412
+ * `childrenKey` / `rowKey` stay unset when the caller omitted them, so a prior `trees` registration is kept.
413
+ */
414
+ declare function TreeScope({ path, childrenKey, rowKey, children, }: {
415
+ path: string;
416
+ childrenKey?: string;
417
+ rowKey?: string;
418
+ children?: ReactNode;
419
+ }): react.JSX.Element;
390
420
  /**
391
421
  * Scope for one row (or tree node): relative names resolve under `path`, and {@link useIndex} / {@link useRecord}
392
- * (/ {@link useTreeNode} with `pos`) read it. Stable value, so a row that did not move does not wake its consumers.
422
+ * (/ {@link useTreeField} with `pos`) read it. Stable value, so a row that did not move does not wake its consumers.
393
423
  * For a tree node pass `pos` (and `index` = its last segment, or omit `index`).
394
424
  */
395
425
  declare function RowScope({ path, index, itemKey, pos, children, }: {
@@ -414,8 +444,11 @@ interface TreeNodeRender {
414
444
  * The owner of a tree path. Walks the tree recursively, wraps each node in a row scope keyed by the node id
415
445
  * (`rowKey`, else `id`, else a stable object identity), and hands `children` the pre-rendered subtree as `node.children`
416
446
  * (`null` on leaves) so the caller decides where to place it (`<li><NodeRow />{node.children && <ul>{node.children}</ul>}</li>`).
417
- * Inside a node, relative `<Field name="name">` / `useField('name')`, {@link useRecord} and {@link useTreeNode} read
418
- * that node, and field state / errors follow the node across moves.
447
+ * A move re-renders the moved node, nodes whose `pos` changed, and ancestors whose subtree changed.
448
+ * A sibling whose position and subtree did not change, and every other subtree, keep the previous element and do not re-render.
449
+ * The `children` render function is part of that identity: a new function (an inline callback while the parent re-renders) redraws every node.
450
+ * Inside a node, relative `<Field name="name">` / `useField('name')`, {@link useRecord}, and {@link useTreeField}
451
+ * (no name: this node, plus the tree's edits) read that node, and field state / errors follow the node across moves.
419
452
  * `<TreeField<Values> name="menu">` checks the name; `typed(form).TreeField` also types the node's fields.
420
453
  */
421
454
  declare function TreeField<TScope = any>({ name, childrenKey, rowKey, children, }: {
@@ -521,7 +554,7 @@ type FieldPropKey = 'value' | 'onChange' | 'onBlur' | 'disabled' | 'readOnly' |
521
554
  * Any other field state a `mapProps` object can hand to a prop (Formily: the key is a field path):
522
555
  * `{ title: 'placeholder' }`, `{ required: 'aria-required' }`, `{ 'componentProps.max': 'count' }`.
523
556
  */
524
- type FieldStateKey = 'title' | 'description' | 'required' | 'validating' | 'touched' | 'dirty' | 'edited' | 'pattern' | 'display' | 'path' | 'errors' | 'warnings' | `componentProps.${string}` | `decoratorProps.${string}`;
557
+ type FieldStateKey = 'title' | 'description' | 'required' | 'validating' | 'touched' | 'dirty' | 'edited' | 'visible' | 'disabled' | 'readOnly' | 'omit' | 'path' | 'errors' | 'warnings' | `componentProps.${string}` | `decoratorProps.${string}`;
525
558
  /**
526
559
  * Where blur validation goes when the control has no `onBlur` (a Lobe Select, a popover picker).
527
560
  * Without this, `validateTrigger: 'onBlur'` never runs because the `onBlur` prop is ignored.
@@ -539,7 +572,7 @@ type BlurOn = 'onChange' | 'onOpenChange' | {
539
572
  * more field state to a prop (`{ title: 'placeholder' }`; an explicit caller prop wins).
540
573
  * `format` / `parse` convert between the field value and the control value (a `'YYYY-MM-DD'` string in the field,
541
574
  * a `Date` / Dayjs in the control). `parse` replaces the default {@link valueFromEvent}. `format` runs after prop
542
- * transforms, so it sees the control's own props (`props.format`, …). `readPretty` is not converted: the view gets
575
+ * transforms, so it sees the control's own props (`props.format`, …). The `readOnly` preview is not converted: the view gets
543
576
  * the field value.
544
577
  * `blurOn` is the blur fallback for a control that does not call `onBlur` ({@link BlurOn}). It replaces the default
545
578
  * `onBlur` prop so the unused handler is not passed through.
@@ -554,7 +587,8 @@ type PropsMapping<P = any, F = any> = Partial<Record<FieldPropKey | FieldStateKe
554
587
  /** Control `onChange` arguments → the value stored on the field. Default: {@link valueFromEvent}. */
555
588
  parse?: ParseFn<P, F>;
556
589
  blurOn?: BlurOn;
557
- readPretty?: ComponentType<any> | readonly [ComponentType<any>, Record<string, unknown>?];
590
+ /** Component rendered when the field is `readOnly` (the preview). A tuple's props are its defaults. */
591
+ preview?: ComponentType<any> | readonly [ComponentType<any>, Record<string, unknown>?];
558
592
  };
559
593
  /** `true` when `P` is `any` (not a concrete props type). `unknown` is not `any`. */
560
594
  type IsAny<T> = 0 extends 1 & T ? true : false;
@@ -598,7 +632,7 @@ type PropsEnhancer = {
598
632
  transforms: PropsTransform[];
599
633
  /** Present when this mapping names a blur fallback, renames `onBlur`, or drops it on purpose. */
600
634
  blur?: BlurFlag;
601
- readPretty?: {
635
+ preview?: {
602
636
  component: ComponentType<any>;
603
637
  props?: Record<string, unknown>;
604
638
  };
@@ -744,7 +778,7 @@ interface UseFormOptions<T> extends FormOptions<T> {
744
778
  * The returned form is headless: nothing here imports a UI kit.
745
779
  *
746
780
  * `T` is inferred from `initialValues` / `values`. `getValue` / `setValue` / `batch` use that type.
747
- * Submit values: no type argument drops `fields` paths whose display is `virtual` / `none`.
781
+ * Submit values: no type argument drops `fields` paths with `omit: true`.
748
782
  * `useForm<V>(options)` keeps the submit type as `V`. To keep `V` and still infer `fields`, call
749
783
  * `typed<V>().useForm(options)`. An explicit second argument (`SubmitValues<V, …>`) is used as written.
750
784
  * `useForm()`, `useForm(undefined)` and `useForm({})` are the same call: each returns a form and runs the same hooks.
@@ -756,7 +790,7 @@ interface UseFormOptions<T> extends FormOptions<T> {
756
790
  * initialValues: { email: '', rows: [{ name: '' }] },
757
791
  * fields: { email: { required: true }, 'rows.*.name': { required: true } },
758
792
  * })
759
- * const edit = typed<Detail>().useForm({ values: record, fields: { token: { display: 'virtual' } } })
793
+ * const edit = typed<Detail>().useForm({ values: record, fields: { token: { omit: true } } })
760
794
  */
761
795
  type UseFormArg<T, F> = Omit<UseFormOptions<T>, 'fields'> & {
762
796
  fields?: F & FieldsInput<T>;
@@ -791,15 +825,34 @@ type ArrayHandle<TRow> = {
791
825
  * Dropping row A on row B moves A to B's index. Stable per path; dragging does not re-render.
792
826
  */
793
827
  dragProps: (index: number) => DragProps;
828
+ /** This array path's own messages. Descendant fields are not included. */
829
+ errors: readonly string[];
830
+ warnings: readonly string[];
794
831
  };
795
832
  /**
796
833
  * Array handle. Subscribes to row structure (length and ids), not to cell values.
797
834
  * `keys` use the row id when the row has one, otherwise a stable object identity.
798
835
  * `to` on `move` is the final index.
836
+ *
837
+ * `useArrayField()` is the nearest `<ArrayField>` (Formily `ArrayBase.useArray`): a row, or the container
838
+ * (`ArrayItems` / `ArrayCards` / `ArrayTable`, toolbar included). Nested arrays resolve to the inner one.
839
+ * Outside an array it throws.
840
+ *
841
+ * `useArrayField(name)` resolves `name` against the current scope (a repeated scope prefix throws in development),
842
+ * registers that path into the nearest `FieldGroup`, and returns the same handle.
799
843
  * `useArrayField<Values, 'rows'>('rows')` checks the name and types `push` / `replace` as one row.
800
844
  * `useArrayField<Values>('rows')` only checks the name. A bare `useArrayField('rows')` accepts any row.
801
- * Options are the second argument's object: `useArrayField('rows', { rowKey: 'id' })` (same shape as `useTreeField`).
845
+ * Options are the second argument's object: `useArrayField('rows', { rowKey: 'id' })`.
846
+ *
847
+ * ```tsx
848
+ * function RemoveButton() {
849
+ * const array = useArrayField()
850
+ * const index = useIndex()
851
+ * return <button onClick={() => array.remove(index)}>删除</button>
852
+ * }
853
+ * ```
802
854
  */
855
+ declare function useArrayField<TRow = unknown>(): ArrayHandle<TRow>;
803
856
  declare function useArrayField(name: string, opts?: {
804
857
  rowKey?: string;
805
858
  }): ArrayHandle<unknown>;
@@ -809,44 +862,13 @@ declare function useArrayField<TScope>(name: ArrayPath<TScope>, opts?: {
809
862
  declare function useArrayField<TScope, N extends ArrayPath<TScope>>(name: N, opts?: {
810
863
  rowKey?: string;
811
864
  }): ArrayHandle<ArrayItemOf<TScope, N & string>>;
812
- /**
813
- * The nearest enclosing array, no name needed (Formily `ArrayBase.useArray`): inside an `<ArrayField>` row or its container
814
- * (`ArrayItems` / `ArrayCards` / `ArrayTable`, toolbar included), the same handle {@link useArrayField} returns for that array.
815
- * Throws outside an array.
816
- *
817
- * ```tsx
818
- * function RemoveButton() {
819
- * const array = useArray()
820
- * const index = useIndex()
821
- * return <button onClick={() => array.remove(index)}>删除</button>
822
- * }
823
- * ```
824
- */
825
- declare function useArray<TRow = unknown>(): ArrayHandle<TRow>;
826
- /** {@link useArrayField} for an absolute path, without field-group registration (internal: containers, `useArrayTable`). */
827
- declare function useArrayAt(path: string, rowKey?: string): ArrayHandle<unknown>;
865
+ /** {@link useArrayField} for an absolute path, without field-group registration (internal: containers, `useArrayTable`). `null` subscribes to nothing. */
866
+ declare function useArrayAt(path: string | null, rowKey?: string): ArrayHandle<unknown>;
828
867
  /** This array path's own messages. Descendant fields are not included — those render on the row fields. */
829
868
  interface ArrayErrors {
830
869
  errors: readonly string[];
831
870
  warnings: readonly string[];
832
871
  }
833
- /**
834
- * The nearest array field's own validation messages (rules, schema, `form.setErrors` on that path).
835
- * A child field's "必填" is not in here: `d.items.$errors` aggregates descendants, this does not.
836
- * Subscribes to the array path only, so editing a cell does not re-render.
837
- * Throws outside an `<ArrayField>`, like {@link useArray}.
838
- *
839
- * `ArrayItems` / `ArrayCards` render this under the rows. A custom list does the same:
840
- *
841
- * ```tsx
842
- * function ListError() {
843
- * const { errors } = useArrayErrors()
844
- * if (!errors.length) return null
845
- * return <p role="alert">{errors.join('、')}</p>
846
- * }
847
- * ```
848
- */
849
- declare function useArrayErrors(): ArrayErrors;
850
872
 
851
873
  /** React scope for relative field names. `path` is the index path of the parent object or row. */
852
874
  interface ScopeValue {
@@ -863,9 +885,16 @@ interface ArrayScopeValue {
863
885
  path: string;
864
886
  rowKey?: string;
865
887
  }
888
+ /** The nearest enclosing tree (`<TreeField>`): its absolute path and the keys it was given (unset inherits). */
889
+ interface TreeScopeValue {
890
+ path: string;
891
+ childrenKey?: string;
892
+ rowKey?: string;
893
+ }
866
894
  declare const FormContext: react.Context<FormEngine<any, any> | null>;
867
895
  declare const ScopeContext: react.Context<ScopeValue>;
868
896
  declare const ArrayContext: react.Context<ArrayScopeValue | null>;
897
+ declare const TreeContext: react.Context<TreeScopeValue | null>;
869
898
  /**
870
899
  * Internal: a container's per-row wrapper (`ArrayCards` puts each row in a card). `<ArrayField>` rows are memoized,
871
900
  * so a container cannot rewrite them; it provides this and every row renders `wrap(rowContent)` inside its scope.
@@ -881,14 +910,15 @@ declare function useRequiredForm<T = any>(caller: string): FormEngine<T>;
881
910
  /** Parent path for `useField('price')` inside a row or object. */
882
911
  declare function useScope(): ScopeValue;
883
912
 
884
- /** What `<UI>` renders with: the node's effective state (reaction > JSX props > the scope's display / pattern). */
913
+ /** What `<UI>` renders with: the node's effective state (reaction > JSX props > the scope's flags). */
885
914
  interface UiBinding {
886
915
  /** The node name (`d.$ui(name)`). */
887
916
  ui: string;
888
917
  /** DOM id: `<prefix>-<scope>--<name>` (`<prefix>-ui--approvalTip` at the root). */
889
918
  id: string;
890
- display: UiDisplay;
891
- pattern: Pattern;
919
+ visible: boolean;
920
+ disabled: boolean;
921
+ readOnly: boolean;
892
922
  title: ReactNode;
893
923
  description: ReactNode;
894
924
  component: ComponentType<any> | undefined;
@@ -906,10 +936,12 @@ interface UIProps<C extends ComponentType<any> = ComponentType<any>, D extends C
906
936
  decorator?: FieldSlot<D> | RegisteredDecoratorSlot | false;
907
937
  title?: ReactNode;
908
938
  description?: ReactNode;
909
- /** Initial display when no reaction wrote `$visible` / `$display` (default: the scope's). */
910
- display?: UiDisplay;
911
- /** Initial pattern when no reaction wrote `$pattern` (default: inherited from the scope / form). */
912
- pattern?: Pattern;
939
+ /** `false` hides this UI (default: the scope's `visible`). An explicit `false` exits that fallback. */
940
+ visible?: boolean;
941
+ /** Gray this UI out (default: the scope's `disabled`). */
942
+ disabled?: boolean;
943
+ /** Render this UI's preview (default: the scope's `readOnly`). Wins over `disabled`. */
944
+ readOnly?: boolean;
913
945
  /** Rendered inside `component` (or alone), or a render prop `(ui) => …`. */
914
946
  children?: ReactNode | ((ui: UiBinding) => ReactNode);
915
947
  }
@@ -924,11 +956,11 @@ declare function useUiNodeOrNull(): UiBinding | null;
924
956
  * <UI name="approvalTip" component={[Alert, { type: 'warning', message: '金额 ≥ 5 万需要审批' }]} />
925
957
  * ```
926
958
  *
927
- * `$visible` / `$display` / `$pattern` / `$title` / `$description` / `$componentProps` / `$decoratorProps`, same
959
+ * `$visible` / `$disabled` / `$readOnly` / `$title` / `$description` / `$componentProps` / `$decoratorProps`, same
928
960
  * priority as a field's UI layer (reaction > these props). Hiding it unmounts its children but does **not** hide,
929
- * skip or drop the fields inside: a field's validation and submit depend only on its own `$visible` / display.
961
+ * skip or drop the fields inside: a field's validation and submit depend only on its own flags.
930
962
  */
931
- declare function UI<C extends ComponentType<any> = ComponentType<any>, D extends ComponentType<any> = ComponentType<any>>({ name, children, display, pattern, ...slots }: UIProps<C, D>): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | react.ReactPortal | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | react.JSX.Element | null | undefined;
963
+ declare function UI<C extends ComponentType<any> = ComponentType<any>, D extends ComponentType<any> = ComponentType<any>>({ name, children, visible, disabled, readOnly, ...slots }: UIProps<C, D>): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | react.ReactPortal | react.ReactElement<unknown, string | react.JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | react.JSX.Element | null | undefined;
932
964
 
933
965
  /**
934
966
  * Index of the row this component renders in (Formily `ArrayBase.useIndex`), from the surrounding `RowScope`
@@ -940,90 +972,76 @@ declare function useIndex(): number;
940
972
  * this row changes, and follows the row when it moves. Throws outside a row (or tree node).
941
973
  */
942
974
  declare function useRecord<TRow = any>(): TRow;
975
+
976
+ /** Options for a named {@link useTreeField}. Omitted keys keep a registration that is already there. */
977
+ interface TreeOptions {
978
+ childrenKey?: string;
979
+ rowKey?: string;
980
+ }
943
981
  /**
944
- * The tree node this component renders in: `path`, `pos`, `index` (last segment of `pos`), the reactive `record`,
945
- * plus `move(from, to)` and `dragProps(pos)` — the same node operations the tree handle gives, bound to the tree the
946
- * node belongs to (found by registering with the nearest tree, like `useArray()` does for arrays).
947
- * Render inside `<TreeField>` (which wraps each node in its row scope).
948
- * Throws outside a node.
982
+ * Edits on one tree. Field models follow the node id.
983
+ * `path` is always the thing this handle points at: the tree root for `useTreeField(name)`, the current node for `useTreeField()`.
984
+ * `treePath` is always the tree root (same as `path` on a root handle).
985
+ * `errors` / `warnings` are that path's own messages, not descendant fields.
986
+ * `value` is the current root array (`[]` when the stored value is not an array).
987
+ * `move(from, to)` uses final `pos` coordinates and refuses a move into a descendant (the result says why).
988
+ * `dragProps(pos)` is the HTML5 drag-and-drop props for the node at that coordinate; dropping A on B is `move(A, B)`.
949
989
  */
950
- declare function useTreeNode<TNode = any>(): {
990
+ interface TreeHandle<TNode = unknown> {
991
+ /** What this handle points at. Root handle: the tree root. Node handle: the current node. */
951
992
  path: string;
952
- pos: Pos;
953
- index: number;
954
- record: TNode;
993
+ /** The tree root. Equal to `path` on a root handle. */
994
+ treePath: string;
995
+ /** This path's own messages. Descendant fields are not included. */
996
+ errors: readonly string[];
997
+ warnings: readonly string[];
998
+ value: TNode[];
999
+ /** Append `node` at the root, or as the last child of `parentPos`. A missing children array is created. */
1000
+ push: (node: TNode, parentPos?: Pos) => void;
1001
+ /** Insert `node` so it sits at `pos`. Later siblings shift. */
1002
+ insert: (pos: Pos, node: TNode) => void;
1003
+ /** Remove the node at `pos`. Its field model is dropped. */
1004
+ remove: (pos: Pos) => void;
1005
+ /** Replace the node at `pos`. The previous node's field model is dropped. */
1006
+ replace: (pos: Pos, node: TNode) => void;
955
1007
  /** `to` is the final `pos`. Refuses a move into the node's own descendant. */
956
1008
  move: (from: Pos, to: Pos) => MoveResult;
957
- /** HTML5 drag-and-drop props for the node at `pos` (default: this node). */
958
- dragProps: (pos?: Pos) => DragProps;
959
- };
960
-
1009
+ /** HTML5 drag-and-drop props for the node at `pos`. Dropping A on B is `move(A, B)`. */
1010
+ dragProps: (pos: Pos) => DragProps;
1011
+ }
961
1012
  /**
962
- * A set of field paths collected from the JSX below a {@link FieldGroup}: every `<Field>` / `useField(name)` /
963
- * `<ArrayField>` mounted inside registers its absolute path while mounted (nested groups register into every
964
- * enclosing group). It owns no state of the form; it only answers "which fields are inside this region".
965
- *
966
- * Layout containers use it to badge a tab with the errors of its fields (`FormTab`, `FormCollapse`) and to validate
967
- * one step (`FormStep`: `form.validate(group.paths())`). A pure-layout `FormItem` could aggregate its children's
968
- * errors the same way.
1013
+ * `useTreeField()` inside a node: the current node plus the same tree edits.
1014
+ * `path` is this node's path (`items.0.children.1`). `treePath` is the tree root.
1015
+ * `errors` / `warnings` are this node's own messages. `value` is the enclosing tree.
1016
+ * `dragProps()` with no argument targets this node.
969
1017
  */
970
- interface FieldGroupHandle {
971
- /** Absolute paths mounted inside the group, in mount order. A path mounted twice is listed once. */
972
- paths(): string[];
973
- /** Called after a path is added or removed. */
974
- subscribe(listener: () => void): () => void;
975
- /** Bumped on every add / remove (a `useSyncExternalStore` snapshot). */
976
- version(): number;
977
- }
978
- /** Internal: the registry behind a {@link FieldGroupHandle}. */
979
- declare class FieldGroupStore implements FieldGroupHandle {
980
- private counts;
981
- private listeners;
982
- private ver;
983
- paths: () => string[];
984
- version: () => number;
985
- subscribe: (listener: () => void) => (() => void);
986
- /** Register `path` until the returned function runs. */
987
- add(path: string): () => void;
988
- private changed;
989
- }
990
- /** Internal: `add(path)` registers into the nearest group and every group around it. */
991
- interface GroupRegistrar {
992
- add(path: string): () => void;
1018
+ interface TreeNodeHandle<TNode = unknown> extends TreeHandle<TNode> {
1019
+ /** This node's path, not the tree root. */
1020
+ path: string;
1021
+ pos: Pos;
1022
+ index: number;
1023
+ record: TNode;
1024
+ treePath: string;
1025
+ dragProps: (pos?: Pos) => DragProps;
993
1026
  }
994
- declare const FieldGroupContext: react.Context<GroupRegistrar | null>;
995
- /** Create a group handle that lives as long as the component (pass it to {@link FieldGroup}). */
996
- declare function useFieldGroup(): FieldGroupHandle;
997
1027
  /**
998
- * Collect the fields rendered inside `children` into `value` (from {@link useFieldGroup}). Renders no DOM.
1028
+ * One tree hook.
999
1029
  *
1000
- * ```tsx
1001
- * const group = useFieldGroup()
1002
- * const errors = useFieldGroupErrors(group) // FieldError[] of the fields inside
1003
- * <FieldGroup value={group}><Field name="a" … /><Field name="b" … /></FieldGroup>
1004
- * await form.validate(group.paths()) // validate only those fields
1005
- * ```
1006
- */
1007
- declare function FieldGroup({ value, children }: {
1008
- value: FieldGroupHandle;
1009
- children?: ReactNode;
1010
- }): react.JSX.Element;
1011
- /** Internal: register `path` with the enclosing groups while mounted (`useField(name)`, `useArrayField`). */
1012
- declare function useFieldGroupRegistration(path: string): void;
1013
- /** Internal: the shown errors of each group (one entry per field with messages), re-rendering when they change. */
1014
- declare function useGroupsErrors(form: FormEngine<any, any>, groups: readonly FieldGroupHandle[]): FieldError[][];
1015
- /**
1016
- * The errors of the fields inside a {@link FieldGroup}: one `{ path, messages }` per field with shown errors
1017
- * (display `none` excluded), re-rendering only when that list changes. `errors.length` is a tab's badge count.
1030
+ * `useTreeField(name)` resolves `name` against the current scope and returns the tree.
1031
+ * `path` and `treePath` are both the root. It registers that path into the nearest `FieldGroup`.
1032
+ *
1033
+ * `useTreeField()` takes the nearest `<TreeField>` node: `path` is the node, `treePath` is the root,
1034
+ * plus `pos`, `index`, `record`, and the tree's `push` / `insert` / `remove` / `replace` / `move` / `dragProps`.
1035
+ * Outside a node it throws.
1018
1036
  */
1019
- declare function useFieldGroupErrors(group: FieldGroupHandle): FieldError[];
1020
-
1037
+ declare function useTreeField<TNode = unknown>(): TreeNodeHandle<TNode>;
1038
+ declare function useTreeField(name: string, opts?: TreeOptions): TreeHandle<unknown>;
1021
1039
  /**
1022
- * Resolve built-in texts for the nearest form: its `messages` → `setDefaultMessages` → `zhCN`.
1023
- * Outside a form only the app defaults apply. Component labels in `@shikiform/antd` read through this,
1024
- * so a custom component can follow the same locale: `const t = useFormMessage(); t('submit')`.
1040
+ * {@link useTreeField} for an absolute path, without field-group registration. `null` subscribes to nothing.
1041
+ * `subscribe` is false for the current node: structure paints from the named tree hook, and this call
1042
+ * only reads the value at render time.
1025
1043
  */
1026
- declare function useFormMessage(): <K extends FormMessageKey>(key: K, ...params: MessageArgs<K>) => string;
1044
+ declare function useTreeAt(path: string | null, opts?: TreeOptions, subscribe?: boolean): TreeHandle<unknown>;
1027
1045
 
1028
1046
  /**
1029
1047
  * Subscribe to the `$` reads inside `select`.
@@ -1044,4 +1062,4 @@ declare function useFormMessage(): <K extends FormMessageKey>(key: K, ...params:
1044
1062
  declare function useWatch<T>(): <S>(select: (d: Draft<T>) => S) => S;
1045
1063
  declare function useWatch<T = any, S = unknown>(select: (d: Draft<T>) => S): S;
1046
1064
 
1047
- export { useArray as $, type ArrayContainerSlot as A, type BlurFlag as B, type CheckedFieldProps as C, type DragProps as D, type FormDomProps as E, type FormSubmitHandlers as F, type FormProps as G, type PropsTransform as H, type RegisteredComponentSlot as I, type RegisteredDecoratorSlot as J, type RegisteredSlot as K, type ScopeValue as L, TreeField as M, UI as N, ObjectField as O, type PropsMapping as P, type UIProps as Q, type ResetState as R, type SubmitState as S, type TreeNodeRender as T, type UseFieldOptions as U, type UiBinding as V, type UseResetOptions as W, type UseSubmitOptions as X, Watch as Y, connect as Z, mapProps as _, type FieldProps as a, useArrayErrors as a0, useArrayField as a1, useField as a2, useFieldGroup as a3, useFieldGroupErrors as a4, useForm as a5, useFormContext as a6, useFormMessage as a7, useIndex as a8, useRecord as a9, useReset as aa, useSubmit as ab, useTreeNode as ac, useWatch as ad, ArrayContext as ae, ArrayScope as af, FieldContext as ag, FieldGroupContext as ah, FieldGroupStore as ai, FormContext as aj, type PropsEnhancer as ak, RowScope as al, RowWrapContext as am, ScopeContext as an, UiNodeContext as ao, useArrayAt as ap, useFieldGroupRegistration as aq, useGroupsErrors as ar, useRequiredForm as as, useScope as at, useUiNodeOrNull as au, valueFromEvent as av, type ArrayKey as b, type FieldBinding as c, type ArrayHandle as d, type UseFormOptions as e, type ArrayErrors as f, ArrayField as g, type ArrayScopeValue as h, type BlurOn as i, type ClickEvent as j, type ComponentStatics as k, type ConnectEnhancer as l, type ConnectFieldProps as m, type ConnectedComponent as n, Field as o, type FieldComponents as p, type FieldDecorators as q, FieldGroup as r, type FieldGroupHandle as s, FieldKit as t, type FieldKitDecorator as u, type FieldKitSpec as v, type FieldPropKey as w, type FieldSlot as x, type FieldStateKey as y, Form as z };
1065
+ export { useForm as $, type ArrayContainerSlot as A, type BlurFlag as B, type CheckedFieldProps as C, type RegisteredComponentSlot as D, type RegisteredDecoratorSlot as E, type FormSubmitHandlers as F, type RegisteredSlot as G, type ScopeValue as H, TreeField as I, type TreeHandle as J, type TreeNodeHandle as K, type TreeOptions as L, type TreeScopeValue as M, UI as N, ObjectField as O, type PropsMapping as P, type UIProps as Q, type ResetState as R, type SubmitState as S, type TreeNodeRender as T, type UseFieldOptions as U, type UiBinding as V, Watch as W, connect as X, mapProps as Y, useArrayField as Z, useField as _, type FieldProps as a, useFormContext as a0, useIndex as a1, useRecord as a2, useTreeField as a3, useWatch as a4, ArrayContext as a5, ArrayScope as a6, type DragProps as a7, FieldContext as a8, FormContext as a9, type PropsEnhancer as aa, RowScope as ab, RowWrapContext as ac, ScopeContext as ad, TreeContext as ae, TreeScope as af, UiNodeContext as ag, useArrayAt as ah, useRequiredForm as ai, useReset as aj, useScope as ak, useSubmit as al, useTreeAt as am, useUiNodeOrNull as an, valueFromEvent as ao, type ArrayKey as b, type FieldBinding as c, type ArrayHandle as d, type UseFormOptions as e, type ArrayErrors as f, ArrayField as g, type ArrayScopeValue as h, type BlurOn as i, type ComponentStatics as j, type ConnectEnhancer as k, type ConnectFieldProps as l, type ConnectedComponent as m, Field as n, type FieldComponents as o, type FieldDecorators as p, FieldKit as q, type FieldKitDecorator as r, type FieldKitSpec as s, type FieldPropKey as t, type FieldSlot as u, type FieldStateKey as v, Form as w, type FormDomProps as x, type FormProps as y, type PropsTransform as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shikiform/react",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Headless React bindings for ShikiForm. Re-exports @shikiform/core.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -25,7 +25,7 @@
25
25
  "access": "public"
26
26
  },
27
27
  "dependencies": {
28
- "@shikiform/core": "0.2.0",
28
+ "@shikiform/core": "0.3.0",
29
29
  "@tanstack/react-virtual": "^3.13.12"
30
30
  },
31
31
  "peerDependencies": {