@woodger/antd 0.1.1 → 0.1.2

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.
Files changed (266) hide show
  1. package/dist/affix/Affix.svelte +5 -2
  2. package/dist/alert/Alert.svelte +5 -2
  3. package/dist/anchor/Anchor.svelte +5 -2
  4. package/dist/auto-complete/AutoComplete.svelte +3 -2
  5. package/dist/avatar/Avatar.svelte +3 -2
  6. package/dist/avatar/AvatarGroup.svelte +3 -1
  7. package/dist/avatar/avatar.component.d.ts +7 -0
  8. package/dist/avatar/avatar.component.js +4 -0
  9. package/dist/badge/Badge.svelte +3 -2
  10. package/dist/badge/BadgeRibbon.svelte +3 -2
  11. package/dist/badge/badge.component.d.ts +7 -0
  12. package/dist/badge/badge.component.js +4 -0
  13. package/dist/border-beam/BorderBeam.svelte +5 -3
  14. package/dist/breadcrumb/Breadcrumb.svelte +5 -2
  15. package/dist/button/Button.svelte +7 -4
  16. package/dist/calendar/CalendarCore.svelte +3 -1
  17. package/dist/calendar/calendar.component.d.ts +7 -0
  18. package/dist/calendar/calendar.component.js +4 -0
  19. package/dist/card/Card.svelte +6 -3
  20. package/dist/card/card.component.d.ts +9 -0
  21. package/dist/card/card.component.js +5 -0
  22. package/dist/carousel/Carousel.svelte +6 -3
  23. package/dist/cascader/CascaderCore.svelte +8 -2
  24. package/dist/cascader/cascader.component.d.ts +11 -0
  25. package/dist/cascader/cascader.component.js +9 -0
  26. package/dist/cascader/cascader.types.d.ts +8 -0
  27. package/dist/checkbox/Checkbox.svelte +9 -4
  28. package/dist/checkbox/CheckboxGroup.svelte +6 -3
  29. package/dist/checkbox/checkbox-group.types.d.ts +2 -0
  30. package/dist/checkbox/checkbox.component.d.ts +7 -0
  31. package/dist/checkbox/checkbox.component.js +4 -0
  32. package/dist/collapse/Collapse.svelte +5 -2
  33. package/dist/collapse/collapse.engine.d.ts +1 -1
  34. package/dist/color-picker/ColorPicker.svelte +6 -3
  35. package/dist/color-picker/ColorPickerPresets.svelte +5 -3
  36. package/dist/component-refs.types.d.ts +45 -0
  37. package/dist/component-refs.types.js +1 -0
  38. package/dist/component.types.d.ts +13 -0
  39. package/dist/component.types.js +1 -0
  40. package/dist/config-provider/ConfigProvider.svelte +18 -6
  41. package/dist/config-provider/ConfigProvider.svelte.d.ts +2 -0
  42. package/dist/config-provider/config-context.d.ts +7 -0
  43. package/dist/config-provider/config-context.js +1 -0
  44. package/dist/config-provider/config-provider.component.d.ts +6 -0
  45. package/dist/config-provider/config-provider.component.js +10 -1
  46. package/dist/descriptions/Descriptions.svelte +6 -4
  47. package/dist/dialog/dialog-container.model.svelte.d.ts +1 -1
  48. package/dist/dialog/dialog-container.model.svelte.js +14 -2
  49. package/dist/dialog/dialog-focus.dom.d.ts +3 -1
  50. package/dist/dialog/dialog-focus.dom.js +8 -7
  51. package/dist/divider/Divider.svelte +5 -2
  52. package/dist/drawer/Drawer.svelte +3 -2
  53. package/dist/dropdown/Dropdown.svelte +9 -5
  54. package/dist/empty/Empty.svelte +5 -2
  55. package/dist/flex/Flex.svelte +5 -2
  56. package/dist/float-button/FloatButton.svelte +6 -3
  57. package/dist/float-button/FloatButtonGroup.svelte +6 -3
  58. package/dist/float-button/float-button.component.d.ts +9 -0
  59. package/dist/float-button/float-button.component.js +5 -0
  60. package/dist/form/Form.svelte +237 -42
  61. package/dist/form/Form.svelte.d.ts +4 -4
  62. package/dist/form/FormErrorList.svelte +19 -69
  63. package/dist/form/FormItem.svelte +271 -62
  64. package/dist/form/FormItem.svelte.d.ts +31 -5
  65. package/dist/form/FormItemControlBinding.svelte +68 -0
  66. package/dist/form/FormItemControlBinding.svelte.d.ts +10 -0
  67. package/dist/form/FormItemMessages.svelte +142 -0
  68. package/dist/form/FormItemMessages.svelte.d.ts +23 -0
  69. package/dist/form/FormList.svelte +49 -4
  70. package/dist/form/FormMessageMotion.svelte +133 -0
  71. package/dist/form/FormMessageMotion.svelte.d.ts +18 -0
  72. package/dist/form/FormProvider.svelte +9 -0
  73. package/dist/form/FormProvider.svelte.d.ts +4 -0
  74. package/dist/form/form-context.d.ts +24 -6
  75. package/dist/form/form-context.js +18 -0
  76. package/dist/form/form-control.engine.d.ts +2 -0
  77. package/dist/form/form-control.engine.js +13 -0
  78. package/dist/form/form-error-list-state.svelte.d.ts +21 -0
  79. package/dist/form/form-error-list-state.svelte.js +77 -0
  80. package/dist/form/form-error-list.engine.js +3 -1
  81. package/dist/form/form-error-list.types.d.ts +3 -2
  82. package/dist/form/form-field.dom.js +27 -4
  83. package/dist/form/form-internal.d.ts +32 -8
  84. package/dist/form/form-internal.js +2 -0
  85. package/dist/form/form-item-status.d.ts +2 -1
  86. package/dist/form/form-item-status.js +3 -1
  87. package/dist/form/form-list-context.d.ts +4 -0
  88. package/dist/form/form-list-context.js +3 -0
  89. package/dist/form/form-list.types.d.ts +5 -2
  90. package/dist/form/form-no-style.engine.d.ts +6 -5
  91. package/dist/form/form-provider-context.d.ts +13 -0
  92. package/dist/form/form-provider-context.js +74 -0
  93. package/dist/form/form-ref.engine.d.ts +5 -0
  94. package/dist/form/form-ref.engine.js +43 -0
  95. package/dist/form/form-store.engine.d.ts +3 -1
  96. package/dist/form/form-store.engine.js +25 -3
  97. package/dist/form/form-update.engine.d.ts +29 -0
  98. package/dist/form/form-update.engine.js +40 -0
  99. package/dist/form/form-watch.svelte.d.ts +25 -0
  100. package/dist/form/form-watch.svelte.js +56 -0
  101. package/dist/form/form.component.d.ts +28 -0
  102. package/dist/form/form.component.js +25 -0
  103. package/dist/form/form.model.svelte.d.ts +25 -3
  104. package/dist/form/form.model.svelte.js +728 -179
  105. package/dist/form/form.types.d.ts +117 -11
  106. package/dist/form/validation-message.engine.d.ts +17 -3
  107. package/dist/form/validation-message.engine.js +39 -2
  108. package/dist/form/validation-messages.types.d.ts +11 -0
  109. package/dist/form/validation-nested.engine.d.ts +5 -4
  110. package/dist/form/validation.engine.d.ts +8 -6
  111. package/dist/form/validation.engine.js +2 -2
  112. package/dist/grid/Col.svelte +4 -6
  113. package/dist/grid/Row.svelte +7 -4
  114. package/dist/grid/grid.svelte.d.ts +7 -0
  115. package/dist/grid/grid.svelte.js +30 -0
  116. package/dist/image/Image.svelte +147 -58
  117. package/dist/image/ImagePreview.svelte +280 -137
  118. package/dist/image/ImagePreview.svelte.d.ts +10 -2
  119. package/dist/image/ImagePreviewGroup.svelte +40 -7
  120. package/dist/image/ImagePreviewIcons.svelte +18 -0
  121. package/dist/image/ImagePreviewIcons.svelte.d.ts +29 -0
  122. package/dist/image/ImageProgress.svelte +84 -0
  123. package/dist/image/ImageProgress.svelte.d.ts +13 -0
  124. package/dist/image/image-group-context.d.ts +2 -1
  125. package/dist/image/image-prefix.engine.js +4 -0
  126. package/dist/image/image-preview-group.types.d.ts +8 -8
  127. package/dist/image/image-preview-motion.dom.d.ts +16 -0
  128. package/dist/image/image-preview-motion.dom.js +72 -0
  129. package/dist/image/image-semantic.engine.d.ts +39 -0
  130. package/dist/image/image-semantic.engine.js +61 -0
  131. package/dist/image/image.component.d.ts +7 -0
  132. package/dist/image/image.component.js +4 -0
  133. package/dist/image/image.types.d.ts +84 -11
  134. package/dist/index.d.ts +51 -41
  135. package/dist/index.js +24 -19
  136. package/dist/input/Input.svelte +6 -3
  137. package/dist/input/InputOTP.svelte +5 -2
  138. package/dist/input/InputPassword.svelte +5 -1
  139. package/dist/input/InputSearch.svelte +6 -3
  140. package/dist/input/TextArea.svelte +6 -3
  141. package/dist/input/input.component.d.ts +13 -0
  142. package/dist/input/input.component.js +12 -0
  143. package/dist/input-number/InputNumberControl.svelte +5 -2
  144. package/dist/layout/Layout.svelte +5 -2
  145. package/dist/layout/LayoutPart.svelte +7 -2
  146. package/dist/layout/LayoutSider.svelte +5 -2
  147. package/dist/layout/layout.component.d.ts +13 -0
  148. package/dist/layout/layout.component.js +7 -0
  149. package/dist/listy/Listy.svelte +3 -2
  150. package/dist/masonry/Masonry.svelte +5 -3
  151. package/dist/mentions/Mentions.svelte +3 -2
  152. package/dist/mentions/mentions.component.d.ts +7 -0
  153. package/dist/mentions/mentions.component.js +4 -0
  154. package/dist/menu/Menu.svelte +7 -2
  155. package/dist/message/MessageHolder.svelte +3 -1
  156. package/dist/modal/Modal.svelte +112 -14
  157. package/dist/modal/ModalFooterScope.svelte +15 -0
  158. package/dist/modal/ModalFooterScope.svelte.d.ts +7 -0
  159. package/dist/modal/modal-layout.engine.d.ts +1 -1
  160. package/dist/modal/modal-layout.engine.js +20 -3
  161. package/dist/modal/modal-motion.dom.d.ts +1 -0
  162. package/dist/modal/modal-motion.dom.js +21 -5
  163. package/dist/modal/modal-named-motion.dom.d.ts +1 -1
  164. package/dist/modal/modal-named-motion.dom.js +1 -2
  165. package/dist/modal/modal-semantic.engine.d.ts +1 -1
  166. package/dist/modal/modal.types.d.ts +3 -1
  167. package/dist/notification/NotificationHolder.svelte +3 -1
  168. package/dist/pagination/Pagination.svelte +3 -2
  169. package/dist/picker/DatePicker.svelte.d.ts +1 -1
  170. package/dist/picker/RangePickerCore.svelte +3 -1
  171. package/dist/picker/SinglePicker.svelte +3 -1
  172. package/dist/picker/picker-popup.model.svelte.d.ts +3 -1
  173. package/dist/picker/time-picker.component.d.ts +4 -1
  174. package/dist/picker/time-picker.component.js +3 -1
  175. package/dist/popconfirm/Popconfirm.svelte +6 -1
  176. package/dist/popconfirm/popconfirm.types.d.ts +2 -0
  177. package/dist/popover/Popover.svelte +31 -13
  178. package/dist/popover/popover.types.d.ts +2 -0
  179. package/dist/popup/popup-container.model.svelte.d.ts +4 -1
  180. package/dist/popup/popup-container.model.svelte.js +7 -2
  181. package/dist/popup/popup-geometry.dom.d.ts +8 -0
  182. package/dist/popup/popup-geometry.dom.js +29 -0
  183. package/dist/popup/popup.dom.d.ts +3 -0
  184. package/dist/popup/popup.dom.js +3 -1
  185. package/dist/progress/Progress.svelte +5 -2
  186. package/dist/progress/progress-circle.engine.d.ts +1 -1
  187. package/dist/qr-code/QRCode.svelte +5 -3
  188. package/dist/radio/Radio.svelte +9 -4
  189. package/dist/radio/RadioGroup.svelte +6 -3
  190. package/dist/radio/radio.component.d.ts +9 -0
  191. package/dist/radio/radio.component.js +5 -0
  192. package/dist/rate/Rate.svelte +3 -2
  193. package/dist/result/Result.svelte +5 -2
  194. package/dist/segmented/Segmented.svelte +5 -2
  195. package/dist/select/Select.svelte +3 -2
  196. package/dist/select/select-style.engine.d.ts +1 -1
  197. package/dist/skeleton/Skeleton.svelte +5 -2
  198. package/dist/skeleton/SkeletonElement.svelte +5 -2
  199. package/dist/slider/SliderRange.svelte +9 -41
  200. package/dist/slider/SliderSingle.svelte +35 -30
  201. package/dist/slider/SliderTooltip.svelte +224 -0
  202. package/dist/slider/SliderTooltip.svelte.d.ts +17 -0
  203. package/dist/space/Space.svelte +6 -3
  204. package/dist/space/SpaceAddon.svelte +6 -3
  205. package/dist/space/SpaceCompact.svelte +5 -2
  206. package/dist/space/space.component.d.ts +9 -0
  207. package/dist/space/space.component.js +5 -0
  208. package/dist/spin/Spin.svelte +5 -2
  209. package/dist/splitter/Splitter.svelte +6 -3
  210. package/dist/splitter/SplitterArrow.svelte.d.ts +1 -1
  211. package/dist/statistic/Statistic.svelte +5 -3
  212. package/dist/statistic/statistic.component.d.ts +7 -0
  213. package/dist/statistic/statistic.component.js +4 -0
  214. package/dist/steps/Steps.svelte +5 -2
  215. package/dist/styles.css +1 -0
  216. package/dist/styles.css.d.ts +1 -0
  217. package/dist/switch/Switch.svelte +5 -2
  218. package/dist/table/Table.svelte +3 -2
  219. package/dist/table/table-cell.engine.d.ts +6 -6
  220. package/dist/table/table.types.d.ts +2 -0
  221. package/dist/tabs/Tabs.svelte +6 -4
  222. package/dist/tag/CheckableTag.svelte +3 -1
  223. package/dist/tag/CheckableTagGroup.svelte +3 -1
  224. package/dist/tag/Tag.svelte +3 -1
  225. package/dist/tag/tag.component.d.ts +10 -0
  226. package/dist/tag/tag.component.js +5 -0
  227. package/dist/theme/theme-context.svelte.d.ts +2 -0
  228. package/dist/theme/theme-context.svelte.js +6 -1
  229. package/dist/timeline/Timeline.svelte +5 -2
  230. package/dist/tooltip/Tooltip.svelte +16 -7
  231. package/dist/tooltip/TooltipPopup.svelte +22 -6
  232. package/dist/tooltip/tooltip-popup.types.d.ts +6 -0
  233. package/dist/tooltip/tooltip.types.d.ts +16 -0
  234. package/dist/tour/Tour.svelte +3 -1
  235. package/dist/transfer/Transfer.svelte +3 -1
  236. package/dist/transfer/TransferCheckbox.svelte +3 -1
  237. package/dist/transfer/TransferPagination.svelte +3 -1
  238. package/dist/tree/Tree.svelte +3 -2
  239. package/dist/tree/tree.component.d.ts +10 -0
  240. package/dist/tree/tree.component.js +5 -0
  241. package/dist/tree-select/TreeSelectControl.svelte +5 -4
  242. package/dist/types.d.ts +2 -2
  243. package/dist/typography/TypographyEditable.svelte +5 -2
  244. package/dist/typography/TypographyElement.svelte +6 -3
  245. package/dist/typography/TypographyTooltip.svelte +19 -8
  246. package/dist/typography/typography.component.d.ts +13 -0
  247. package/dist/typography/typography.component.js +7 -0
  248. package/dist/upload/Upload.svelte +44 -4
  249. package/dist/upload/Upload.svelte.d.ts +1 -1
  250. package/dist/upload/UploadDragger.svelte +3 -2
  251. package/dist/upload/UploadDragger.svelte.d.ts +4 -4
  252. package/dist/upload/UploadList.svelte.d.ts +1 -1
  253. package/dist/upload/UploadListItem.svelte +52 -11
  254. package/dist/upload/upload.component.d.ts +9 -0
  255. package/dist/upload/upload.component.js +5 -0
  256. package/dist/upload/upload.engine.d.ts +8 -2
  257. package/dist/upload/upload.engine.js +80 -4
  258. package/dist/upload/upload.types.d.ts +2 -1
  259. package/dist/vendor/compute-scroll-into-view.d.ts +3 -1
  260. package/dist/vendor/compute-scroll-into-view.js +3 -2
  261. package/dist/vendor/dropdown-motion.css +105 -0
  262. package/dist/vendor/image-prefix.css.js +3 -3
  263. package/dist/vendor/image.css +16 -2
  264. package/dist/version.d.ts +2 -0
  265. package/dist/version.js +3 -0
  266. package/package.json +15 -4
@@ -4,9 +4,18 @@ import { tick, untrack } from 'svelte';
4
4
  import { FormValidationError } from './FormValidationError';
5
5
  import { setFormHooks } from './form-internal';
6
6
  import { focusFormField, getFormFieldElement, scrollFormField } from './form-field.dom';
7
- import { mergeValidationMessages } from './validation-message.engine';
8
- import { containsFormPath, copyFormValue, formNamePath, getFormValue, mergeFormValues, sameFormPath, sameFormValue, setFormValue } from './form-store.engine';
7
+ import { readFormControlValue } from './form-control.engine';
8
+ import { copyValidationMessages, mergeValidationMessages, snapshotValidationMessages, validationMessageTexts } from './validation-message.engine';
9
+ import { containsFormPath, copyFormValue, formNamePath, getFormValue, hasFormValue, mergeFormValues, sameFormPath, sameFormValue, setFormValue } from './form-store.engine';
9
10
  import { validateFieldValue, resolveValidationRules } from './validation.engine';
11
+ // A snapshot fed back through Form.fields does not replace the running validator.
12
+ const fieldSnapshotOrigin = Symbol('ant-design-form-field-snapshot');
13
+ /** Matches configured event names without treating false as a trigger. */
14
+ function allowsValidationTrigger(triggers, event) {
15
+ return typeof triggers === 'string'
16
+ ? triggers !== '' && triggers === event
17
+ : triggers !== false && triggers.includes(event);
18
+ }
10
19
  /** Preserves numeric path segments, including infinities and the strict equality rule for NaN. */
11
20
  function fieldSelectionKey(path) {
12
21
  if (path.some(part => typeof part === 'number' && Number.isNaN(part))) {
@@ -46,18 +55,28 @@ function selectNamedFields(names, bindings) {
46
55
  * validation cannot replace errors for newer values.
47
56
  */
48
57
  export function createForm({ initialValues, rules = {} }) {
49
- const defaults = copyFormValue(initialValues);
58
+ const modelDefaults = copyFormValue(initialValues);
59
+ let defaults = modelDefaults;
50
60
  let valuesRevision = $state(0);
51
61
  let validationSequence = 0;
52
62
  let latestValidationRun = 0;
63
+ let submissionRevision = 0;
64
+ let mountedForms = 0;
65
+ let storeLifetime = 0;
66
+ let restoreDefaultsOnMount = false;
53
67
  let registrationOrder = 0;
54
68
  let initialValueOrder = 0;
55
69
  let values = $state(copyFormValue(defaults));
56
70
  let resetKey = $state.raw({});
57
71
  // At teardown Svelte reads the previous $state; the registry stores up-to-date registrations.
58
72
  const fieldRegistry = new Set();
73
+ const pendingRemovals = [];
59
74
  const validationDelays = new Map();
60
75
  const messageProviders = new Set();
76
+ const callbackProviders = new Set();
77
+ const storeListeners = new Set();
78
+ let storeSnapshot;
79
+ const controlDrivenFields = new WeakSet();
61
80
  let fields = $state.raw([]);
62
81
  let isSubmitting = $state(false);
63
82
  let submissionError = $state.raw();
@@ -65,16 +84,30 @@ export function createForm({ initialValues, rules = {} }) {
65
84
  function fieldPath(field) {
66
85
  return formNamePath(field.registration?.name ?? field.path);
67
86
  }
68
- // Compares the full path, keeping the difference of the string key and the index.
87
+ // A new editor can register before its predecessor releases a persistent field record.
69
88
  function findField(name) {
70
- return fields.find((field) => sameFormPath(fieldPath(field), name));
89
+ let unmounted;
90
+ for (const field of fields) {
91
+ if (!sameFormPath(fieldPath(field), name)) {
92
+ continue;
93
+ }
94
+ if (field.registration) {
95
+ return field;
96
+ }
97
+ unmounted ??= field;
98
+ }
99
+ return unmounted;
100
+ }
101
+ // A name can refer to multiple editors. The mount key identifies the emitting registration.
102
+ function findFieldByMountKey(mountKey) {
103
+ return fields.find((field) => field.registration?.mountKey === mountKey);
71
104
  }
72
105
  // Copies the arrays so that the listener does not change the metadata in the repository.
73
- function fieldMeta(field) {
106
+ function fieldMeta(field, path = fieldPath(field)) {
107
+ const messages = snapshotValidationMessages(field.errors, field.warnings);
74
108
  return {
75
- name: [...fieldPath(field)], touched: field.touched, validating: field.validating,
76
- validated: field.validated, errors: [...(field.errors ?? [])],
77
- warnings: [...(field.warnings ?? [])]
109
+ name: [...path], touched: field.touched, validating: field.validating,
110
+ validated: field.validated, ...messages
78
111
  };
79
112
  }
80
113
  // Publishes only a new state or signal to remove registration.
@@ -136,22 +169,73 @@ export function createForm({ initialValues, rules = {} }) {
136
169
  ? rules[path[0]] : undefined)
137
170
  ?? [];
138
171
  }
172
+ // Falsy defined initial values count, even when the field has never been touched.
173
+ function isValidationDirty(field, path = fieldPath(field)) {
174
+ return field.dirty || field.touched || field.registration?.initialValue !== undefined
175
+ || getFormValue(defaults, path) !== undefined;
176
+ }
177
+ // Follow the live paths and stop at pristine fields. Visit each registration once even in cycles.
178
+ function dependentFields(names) {
179
+ const byDependency = new Map();
180
+ for (const field of fields) {
181
+ for (const path of field.registration?.dependencies ?? []) {
182
+ const key = fieldSelectionKey(formNamePath(path));
183
+ const group = byDependency.get(key);
184
+ if (group) {
185
+ group.push(field);
186
+ }
187
+ else {
188
+ byDependency.set(key, [field]);
189
+ }
190
+ }
191
+ }
192
+ const visited = new Set();
193
+ const result = [];
194
+ for (const name of names) {
195
+ visit(formNamePath(name));
196
+ }
197
+ return result;
198
+ // Preserve the registration and path at the time an edit traverses the graph.
199
+ function visit(namePath) {
200
+ const list = byDependency.get(fieldSelectionKey(namePath));
201
+ if (!list) {
202
+ return;
203
+ }
204
+ for (const field of list) {
205
+ if (visited.has(field)) {
206
+ continue;
207
+ }
208
+ visited.add(field);
209
+ const path = fieldPath(field);
210
+ if (path.length && isValidationDirty(field, path)) {
211
+ result.push({ path, field });
212
+ visit(path);
213
+ }
214
+ }
215
+ }
216
+ }
139
217
  function rootErrors(entries) {
140
218
  return Object.fromEntries(entries.filter((field) => field.name.length === 1)
141
219
  .map((field) => [field.name[0], [...field.errors]]));
142
220
  }
143
221
  function getFieldsError(names) {
144
- return names
145
- ? names.map((name) => ({
146
- name: formNamePath(name),
147
- errors: [...(findField(name)?.errors ?? [])],
148
- warnings: [...(findField(name)?.warnings ?? [])]
149
- }))
150
- : fields.map((field) => ({
151
- name: fieldPath(field),
152
- errors: [...(field.errors ?? [])],
153
- warnings: [...(field.warnings ?? [])]
154
- }));
222
+ if (names) {
223
+ return names.map(name => {
224
+ const path = formNamePath(name);
225
+ const field = findField(path);
226
+ const messages = snapshotValidationMessages(field?.errors, field?.warnings);
227
+ return { name: path, ...messages };
228
+ });
229
+ }
230
+ return fields.map(field => ({
231
+ name: fieldPath(field),
232
+ ...snapshotValidationMessages(field.errors, field.warnings)
233
+ }));
234
+ }
235
+ // Reads one message list so error and warning accessors keep separate reactive dependencies.
236
+ function getFieldMessages(name, kind) {
237
+ const field = findField(name);
238
+ return field?.[kind] ?? [];
155
239
  }
156
240
  function isFieldTouched(name) {
157
241
  return fields.some((field) => containsFormPath(name, fieldPath(field)) && field.touched);
@@ -192,18 +276,14 @@ export function createForm({ initialValues, rules = {} }) {
192
276
  lists.push(path);
193
277
  continue;
194
278
  }
195
- const meta = field ? {
196
- touched: field.touched,
197
- validating: field.validating,
198
- errors: [...(field.errors ?? [])],
199
- warnings: [...(field.warnings ?? [])],
200
- name: [...path],
201
- validated: field.validated
202
- } : null;
203
- if (!filter || filter(meta)) {
204
- const currentValue = getFormValue(values, path);
205
- result = setFormValue(result, path, currentValue);
279
+ if (filter) {
280
+ const meta = field ? fieldMeta(field, path) : null;
281
+ if (!filter(meta)) {
282
+ continue;
283
+ }
206
284
  }
285
+ const currentValue = getFormValue(values, path);
286
+ result = setFormValue(result, path, currentValue);
207
287
  }
208
288
  for (const path of lists) {
209
289
  if (!getFormValue(result, path)) {
@@ -228,7 +308,77 @@ export function createForm({ initialValues, rules = {} }) {
228
308
  const selected = names ? selectNamedFields(names, bindings) : bindings;
229
309
  return projectFieldValues(selected, select);
230
310
  }
231
- // Confirms that for the field there was and the expectation of debounce was canceled.
311
+ // All mounted observers can read the same projection without subscribing to validation metadata.
312
+ const watchValues = $derived(getFieldsValue());
313
+ // Share one immutable root per write without copying the store when there are no observers.
314
+ function readStoreSnapshot() {
315
+ if (storeListeners.size) {
316
+ storeSnapshot ??= untrack(() => ({ ...values }));
317
+ return storeSnapshot;
318
+ }
319
+ }
320
+ // Predicates run in store order. Reads in a predicate cannot subscribe the writer's effect.
321
+ function notifyStoreUpdate(previous, update) {
322
+ if (!previous) {
323
+ return;
324
+ }
325
+ const current = readStoreSnapshot();
326
+ if (current) {
327
+ const listeners = [...storeListeners];
328
+ untrack(() => {
329
+ for (const listener of listeners) {
330
+ listener(previous, current, update);
331
+ }
332
+ });
333
+ }
334
+ }
335
+ // The last attached Form owns callbacks for this model until its registration is released.
336
+ function currentCallbackProvider() {
337
+ return [...callbackProviders].at(-1);
338
+ }
339
+ // Build both arguments from one field snapshot, including current indexed paths in lists.
340
+ function publishFieldsChange(names, owner = currentCallbackProvider()) {
341
+ if (!names.length || !owner) {
342
+ return;
343
+ }
344
+ untrack(() => {
345
+ if (owner !== currentCallbackProvider()) {
346
+ return;
347
+ }
348
+ const onFieldsChange = owner()?.onFieldsChange;
349
+ if (!onFieldsChange) {
350
+ return;
351
+ }
352
+ const allFields = [];
353
+ const changedFields = [];
354
+ for (const { path, field } of fieldBindings()) {
355
+ const value = getFormValue(values, path);
356
+ const snapshot = { ...fieldMeta(field, path), value: copyFormValue(value) };
357
+ Object.defineProperty(snapshot, fieldSnapshotOrigin, { value: true });
358
+ allFields.push(snapshot);
359
+ if (names.some((name) => sameFormPath(name, path))) {
360
+ changedFields.push(snapshot);
361
+ }
362
+ }
363
+ if (changedFields.length) {
364
+ onFieldsChange(changedFields, allFields);
365
+ }
366
+ });
367
+ }
368
+ // The edited path can include data outside the projection of mounted fields, such as a list row.
369
+ function publishValueChange(name, dependencies) {
370
+ untrack(() => {
371
+ const onValuesChange = currentCallbackProvider()?.()?.onValuesChange;
372
+ if (onValuesChange) {
373
+ const value = getFormValue(values, name);
374
+ const changed = setFormValue({}, name, value);
375
+ const all = setFormValue(getFieldsValue(), name, value);
376
+ onValuesChange(changed, all);
377
+ }
378
+ publishFieldsChange([name, ...dependencies]);
379
+ });
380
+ }
381
+ // Releases a waiting debounce timer or dependency frame when its field is superseded.
232
382
  function cancelValidationDelay(field) {
233
383
  const cancel = validationDelays.get(field);
234
384
  if (!cancel) {
@@ -237,22 +387,36 @@ export function createForm({ initialValues, rules = {} }) {
237
387
  cancel();
238
388
  return true;
239
389
  }
240
- // Finishes waiting both after the timer and after an obvious cancellation.
390
+ // Resolves true when the scheduled wait elapses, or false when the owner cancels it.
241
391
  function delayValidation(field, delay) {
242
392
  return new Promise((resolve) => {
243
- const timer = setTimeout(() => {
244
- validationDelays.delete(field);
245
- resolve(true);
246
- }, delay);
247
- validationDelays.set(field, () => {
393
+ let cancel;
394
+ function finish(elapsed) {
395
+ if (validationDelays.get(field) === cancel) {
396
+ validationDelays.delete(field);
397
+ }
398
+ resolve(elapsed);
399
+ }
400
+ if (delay === 'frame' && typeof requestAnimationFrame === 'function'
401
+ && typeof cancelAnimationFrame === 'function') {
402
+ const frame = requestAnimationFrame(() => finish(true));
403
+ cancel = () => {
404
+ cancelAnimationFrame(frame);
405
+ finish(false);
406
+ };
407
+ validationDelays.set(field, cancel);
408
+ return;
409
+ }
410
+ const timer = setTimeout(() => finish(true), delay === 'frame' ? 0 : delay);
411
+ cancel = () => {
248
412
  clearTimeout(timer);
249
- validationDelays.delete(field);
250
- resolve(false);
251
- });
413
+ finish(false);
414
+ };
415
+ validationDelays.set(field, cancel);
252
416
  });
253
417
  }
254
418
  // Runs selected checks at the same time and rejects an outdated shot.
255
- async function validate(selected, validateOnly = false, triggered = false) {
419
+ async function validate(selected, { source, validateOnly = false, trigger, changedList }) {
256
420
  if (!validateOnly) {
257
421
  for (const field of selected) {
258
422
  if (cancelValidationDelay(field)) {
@@ -266,13 +430,18 @@ export function createForm({ initialValues, rules = {} }) {
266
430
  const validationRun = ++validationSequence;
267
431
  // Promises share freshness tracking. validateOnly leaves the visible validation's field.run unchanged.
268
432
  latestValidationRun = validationRun;
269
- const entries = selected.map((field) => ({
270
- field,
271
- path: fieldPath(field),
272
- run: field.run,
273
- hasRules: fieldRules(field).length > 0,
274
- delay: triggered ? field.registration?.validateDebounce : undefined
275
- }));
433
+ const publishesChanges = source !== 'refresh' || changedList !== undefined;
434
+ const callbacks = publishesChanges ? currentCallbackProvider() : undefined;
435
+ const entries = selected.map((field) => {
436
+ const hasRules = fieldRules(field).length > 0;
437
+ const publishes = Boolean(callbacks && hasRules && (!changedList || changedList === field));
438
+ const event = source === 'control' ? trigger : field === changedList ? 'onChange' : undefined;
439
+ const debounced = source === 'refresh' || (source === 'control' && !!event);
440
+ return {
441
+ field, path: fieldPath(field), run: field.run, hasRules, publishes, event,
442
+ delay: debounced ? field.registration?.validateDebounce : undefined
443
+ };
444
+ });
276
445
  if (!validateOnly) {
277
446
  for (const { field, hasRules } of entries) {
278
447
  if (!hasRules) {
@@ -283,13 +452,45 @@ export function createForm({ initialValues, rules = {} }) {
283
452
  }
284
453
  field.run = validationRun;
285
454
  field.validating = true;
455
+ if (source === 'control' || source === 'dependency' || field === changedList) {
456
+ field.errors = [];
457
+ }
286
458
  field.warnings = [];
287
459
  field.dirty = true;
288
460
  field.validated = false;
289
461
  notifyFieldMeta(field);
290
462
  }
291
463
  }
292
- const results = await Promise.all(entries.map(validateEntry));
464
+ let results;
465
+ try {
466
+ if (callbacks) {
467
+ const started = entries.filter((entry) => entry.publishes).map(({ path }) => path);
468
+ publishFieldsChange(started, callbacks);
469
+ }
470
+ }
471
+ finally {
472
+ // A throwing listener must not leave validation pending forever.
473
+ results = await Promise.all(entries.map(validateEntry));
474
+ }
475
+ if ((callbacks || storeListeners.size) && valuesRevision === snapshotRevision) {
476
+ const validatedPaths = [];
477
+ const completed = [];
478
+ for (const [index, entry] of entries.entries()) {
479
+ const { field, path, run, hasRules, publishes } = entry;
480
+ if (hasRules && !results[index].cancelled && field.run === (validateOnly ? run : validationRun)
481
+ && fields.includes(field) && sameFormPath(path, fieldPath(field))) {
482
+ validatedPaths.push(path);
483
+ if (publishes)
484
+ completed.push(path);
485
+ }
486
+ }
487
+ if (storeListeners.size && (validatedPaths.length || entries.every(entry => !entry.hasRules))) {
488
+ notifyStoreUpdate(readStoreSnapshot(), { type: 'validateFinish', names: validatedPaths });
489
+ }
490
+ if (callbacks && valuesRevision === snapshotRevision) {
491
+ publishFieldsChange(completed, callbacks);
492
+ }
493
+ }
293
494
  const nextErrors = results.filter((field) => field.errors.length);
294
495
  const outOfDate = latestValidationRun !== validationRun || valuesRevision !== snapshotRevision
295
496
  || results.some((result) => result.cancelled)
@@ -299,12 +500,27 @@ export function createForm({ initialValues, rules = {} }) {
299
500
  throw new FormValidationError(snapshot, rootErrors(nextErrors), outOfDate, nextErrors);
300
501
  }
301
502
  return snapshot;
302
- // Rules and messages are read when you start a specific field. After await, only the owner of
303
- // the current inspection can publish its result.
304
- async function validateEntry({ field, path, hasRules, delay }) {
503
+ // A control event publishes pending metadata before the control finishes its own handler.
504
+ // Dependent rule factories run after the UI has had a frame to apply changes from the edit.
505
+ async function validateEntry({ field, path, hasRules, delay, event }) {
305
506
  if (!hasRules) {
306
507
  return { name: path, errors: [], warnings: [] };
307
508
  }
509
+ if (source === 'dependency') {
510
+ if (!isCurrent(field, path)) {
511
+ return cancelledEntry(field, path);
512
+ }
513
+ const elapsed = await delayValidation(field, 'frame');
514
+ if (!elapsed || !isCurrent(field, path)) {
515
+ return cancelledEntry(field, path);
516
+ }
517
+ }
518
+ else if (source === 'control') {
519
+ await tick();
520
+ if (!isCurrent(field, path)) {
521
+ return cancelledEntry(field, path);
522
+ }
523
+ }
308
524
  let rules;
309
525
  try {
310
526
  rules = resolveValidationRules(fieldRules(field), form);
@@ -316,6 +532,9 @@ export function createForm({ initialValues, rules = {} }) {
316
532
  }
317
533
  throw error;
318
534
  }
535
+ if (event) {
536
+ rules = rules.filter(({ validateTrigger }) => !validateTrigger || allowsValidationTrigger(validateTrigger, event));
537
+ }
319
538
  const messageContext = {
320
539
  name: path.map(String).join('.'),
321
540
  variables: { label: path.map(String).join('.'), ...field.registration?.messageVariables },
@@ -323,14 +542,12 @@ export function createForm({ initialValues, rules = {} }) {
323
542
  };
324
543
  const validateFirst = field.registration?.validateFirst;
325
544
  if (delay) {
545
+ if (!isCurrent(field, path)) {
546
+ return cancelledEntry(field, path);
547
+ }
326
548
  const elapsed = await delayValidation(field, delay);
327
- if (!elapsed || field.run !== validationRun || valuesRevision !== snapshotRevision
328
- || !fields.includes(field) || !sameFormPath(path, fieldPath(field))) {
329
- if (field.run === validationRun) {
330
- field.validating = false;
331
- notifyFieldMeta(field);
332
- }
333
- return { name: path, errors: [], warnings: [], cancelled: true };
549
+ if (!elapsed || !isCurrent(field, path)) {
550
+ return cancelledEntry(field, path);
334
551
  }
335
552
  }
336
553
  const value = getFormValue(snapshot, path);
@@ -338,13 +555,26 @@ export function createForm({ initialValues, rules = {} }) {
338
555
  if (!validateOnly && field.run === validationRun) {
339
556
  field.validating = false;
340
557
  if (valuesRevision === snapshotRevision && sameFormPath(path, fieldPath(field))) {
341
- field.errors = messages.errors;
342
- field.warnings = messages.warnings;
558
+ field.errors = copyValidationMessages(messages.errors);
559
+ field.warnings = copyValidationMessages(messages.warnings);
343
560
  field.validated = true;
344
561
  }
345
562
  notifyFieldMeta(field);
346
563
  }
347
- return { name: path, ...messages };
564
+ return { name: path, ...snapshotValidationMessages(messages.errors, messages.warnings) };
565
+ }
566
+ // A pending timer or frame cannot continue with another value or a reassigned list row.
567
+ function isCurrent(field, path) {
568
+ return field.run === validationRun && valuesRevision === snapshotRevision
569
+ && fieldRegistry.has(field) && sameFormPath(path, fieldPath(field));
570
+ }
571
+ // Only clear the pending flag if a newer check has not claimed this field.
572
+ function cancelledEntry(field, path) {
573
+ if (field.run === validationRun) {
574
+ field.validating = false;
575
+ notifyFieldMeta(field);
576
+ }
577
+ return { name: path, errors: [], warnings: [], cancelled: true };
348
578
  }
349
579
  }
350
580
  // Selects registered fields, descendants of the prefix or obvious paths.
@@ -364,28 +594,111 @@ export function createForm({ initialValues, rules = {} }) {
364
594
  }
365
595
  }
366
596
  if (settings?.dirty) {
367
- selected = selected.filter((field) => field.dirty || field.touched
368
- || field.registration?.initialValue !== undefined
369
- || getFormValue(defaults, fieldPath(field)) !== undefined);
597
+ selected = selected.filter((field) => isValidationDirty(field));
370
598
  }
371
- return validate(selected, settings?.validateOnly);
599
+ return validate(selected, { source: 'explicit', validateOnly: settings?.validateOnly });
372
600
  }
373
- // After changing the list, you check the touched fields if you do not submit.
374
- function revalidateTouched() {
375
- if (isSubmitting) {
601
+ // Automatic checks keep validation errors in the model; programming errors still surface.
602
+ function validateAutomatically(selected, request) {
603
+ void validate(selected, request).catch((error) => {
604
+ if (!(error instanceof FormValidationError)) {
605
+ throw error;
606
+ }
607
+ });
608
+ }
609
+ // A declared event or dependency opts a binding into the control validation path.
610
+ function usesControlValidation(field) {
611
+ const registration = field.registration;
612
+ return controlDrivenFields.has(field) || registration?.validateTrigger !== undefined
613
+ || registration?.dependencies !== undefined;
614
+ }
615
+ // Checks the field's event configuration before individual rules are filtered.
616
+ function validateControlEvent(field, trigger, sharedPath) {
617
+ const triggers = field.registration?.validateTrigger ?? 'onChange';
618
+ if (!allowsValidationTrigger(triggers, trigger) || !fieldRules(field).length) {
376
619
  return;
377
620
  }
378
- const selected = fields.filter((field) => field.touched);
379
- if (selected.length) {
380
- void validate(selected, false, true).catch((error) => {
381
- if (!(error instanceof FormValidationError)) {
382
- throw error;
621
+ const selected = sharedPath === undefined ? [field] : fields.filter((candidate) => sameFormPath(sharedPath, fieldPath(candidate)));
622
+ validateAutomatically(selected, { source: 'control', trigger });
623
+ }
624
+ // Dispatches through the originating editor and reports when it must receive the committed value.
625
+ function handleFieldEvent(mountKey, event, args) {
626
+ const field = findFieldByMountKey(mountKey);
627
+ const registration = field?.registration;
628
+ if (!field || !registration) {
629
+ return false;
630
+ }
631
+ const name = fieldPath(field);
632
+ const writesValue = event === (registration.trigger ?? 'onChange');
633
+ controlDrivenFields.add(field);
634
+ if (writesValue) {
635
+ applyControlValue(field, name, () => {
636
+ const extract = registration.getValueFromEvent;
637
+ if (extract) {
638
+ return extract(...args);
383
639
  }
640
+ return readFormControlValue(registration.valuePropName ?? 'value', args);
384
641
  });
385
642
  }
643
+ validateControlEvent(field, event, name);
644
+ return writesValue;
645
+ }
646
+ // Returns the affected paths so a control edit can include them in its field-change callback.
647
+ function startDependentValidation(names) {
648
+ const dependents = untrack(() => dependentFields(names));
649
+ if (dependents.length) {
650
+ validateAutomatically(dependents.map(({ field }) => field), { source: 'dependency' });
651
+ }
652
+ return dependents.map(({ path }) => path);
653
+ }
654
+ // Dependent fields enter validation before either value-change callback sees the new store.
655
+ function publishControlEdit(name, previous) {
656
+ notifyStoreUpdate(previous, { type: 'valueUpdate', source: 'internal', names: [name] });
657
+ const dependents = startDependentValidation([name]);
658
+ notifyStoreUpdate(previous, { type: 'dependenciesUpdate', names: [name, ...dependents] });
659
+ publishValueChange(name, dependents);
660
+ }
661
+ // Compatibility for manually wired fields, including list paths that change after a flush.
662
+ function revalidateTouched({ explicitTouch = false, changedList } = {}) {
663
+ if (isSubmitting) {
664
+ return;
665
+ }
666
+ const selected = fields.filter((field) => {
667
+ if (field === changedList) {
668
+ return allowsValidationTrigger(field.registration?.validateTrigger ?? 'onChange', 'onChange');
669
+ }
670
+ return field.touched && (explicitTouch || !usesControlValidation(field));
671
+ });
672
+ if (selected.length) {
673
+ validateAutomatically(selected, { source: 'refresh', changedList });
674
+ }
675
+ }
676
+ function markTouched(field) {
677
+ field.touched = true;
678
+ field.dirty = true;
679
+ notifyFieldMeta(field);
680
+ }
681
+ // Touch precedes extraction and normalization. Validation uses the value committed by this edit.
682
+ function applyControlValue(field, name, readValue) {
683
+ markTouched(field);
684
+ const previous = getFormValue(values, name);
685
+ const value = readValue();
686
+ const normalize = field.registration?.normalize;
687
+ // Keep the old root while preserving field identities for the synchronous normalizer.
688
+ const nextValue = normalize ? normalize(value, previous, { ...values }) : value;
689
+ if (previous === nextValue) {
690
+ return;
691
+ }
692
+ const previousStore = readStoreSnapshot();
693
+ const next = setFormValue(values, name, nextValue);
694
+ updateValues(next);
695
+ valuesRevision++;
696
+ submissionError = undefined;
697
+ publishControlEdit(name, previousStore);
386
698
  }
387
699
  // Updates the current proxy keys by saving the model’s reader links.
388
700
  function updateValues(next) {
701
+ storeSnapshot = undefined;
389
702
  // Svelte lists inherited names only in the presence of own property in the original target.
390
703
  if (Object.keys(next).some((name) => !Object.hasOwn(values, name)
391
704
  && Object.hasOwn(Object.prototype, name))) {
@@ -400,6 +713,69 @@ export function createForm({ initialValues, rules = {} }) {
400
713
  values[name] = next[name];
401
714
  }
402
715
  }
716
+ // A field batch applies values and metadata in the caller's order without validating.
717
+ function applyFieldUpdates(updates, controlled) {
718
+ const previousStore = readStoreSnapshot();
719
+ for (const update of updates) {
720
+ const { name, ...data } = update;
721
+ const hasValue = 'value' in data;
722
+ if (hasValue) {
723
+ const next = setFormValue(values, name, data.value);
724
+ const changed = !sameFormValue(values, next);
725
+ // Equal controlled echoes can read their data from the store itself.
726
+ if (!controlled || changed) {
727
+ updateValues(next);
728
+ }
729
+ else {
730
+ storeSnapshot = undefined;
731
+ }
732
+ if (changed) {
733
+ valuesRevision++;
734
+ submissionError = undefined;
735
+ for (const field of fields) {
736
+ if (containsFormPath(name, fieldPath(field))) {
737
+ cancelValidationDelay(field);
738
+ field.run = ++validationSequence;
739
+ const wasValidating = field.validating;
740
+ field.validating = false;
741
+ if (wasValidating)
742
+ notifyFieldMeta(field);
743
+ }
744
+ }
745
+ }
746
+ }
747
+ const keepValidator = controlled && Object.hasOwn(update, fieldSnapshotOrigin);
748
+ for (const field of fields) {
749
+ if (!sameFormPath(name, fieldPath(field))
750
+ || (!field.registration && !fieldRules(field).length)) {
751
+ continue;
752
+ }
753
+ if ('touched' in update)
754
+ field.touched = !!update.touched;
755
+ if ('validating' in update && !keepValidator) {
756
+ cancelValidationDelay(field);
757
+ field.run = ++validationSequence;
758
+ field.validating = !!update.validating;
759
+ field.validated = !field.validating;
760
+ }
761
+ if ('errorMessages' in update) {
762
+ field.errors = copyValidationMessages(update.errorMessages ?? []);
763
+ }
764
+ else if ('errors' in update) {
765
+ field.errors = [...(update.errors ?? [])];
766
+ }
767
+ if ('warningMessages' in update) {
768
+ field.warnings = copyValidationMessages(update.warningMessages ?? []);
769
+ }
770
+ else if ('warnings' in update) {
771
+ field.warnings = [...(update.warnings ?? [])];
772
+ }
773
+ field.dirty = true;
774
+ notifyFieldMeta(field);
775
+ }
776
+ notifyStoreUpdate(previousStore, { type: 'setField', name, hasValue });
777
+ }
778
+ }
403
779
  // Purifies the result of the field and deprives the previous verification of the right to publish.
404
780
  function clearField(field) {
405
781
  cancelValidationDelay(field);
@@ -409,6 +785,173 @@ export function createForm({ initialValues, rules = {} }) {
409
785
  field.run = ++validationSequence;
410
786
  notifyFieldMeta(field);
411
787
  }
788
+ // Resets flags and messages and releases work owned by the previous field lifetime.
789
+ function resetFieldMetadata(field) {
790
+ cancelValidationDelay(field);
791
+ field.errors = undefined;
792
+ field.warnings = undefined;
793
+ field.touched = false;
794
+ field.dirty = false;
795
+ field.validating = false;
796
+ field.validated = false;
797
+ field.run = ++validationSequence;
798
+ }
799
+ // Discard after the Svelte flush so sibling registrations and keyed list moves are visible.
800
+ function scheduleFieldRemoval(registration) {
801
+ if (registration.preserve !== false) {
802
+ return;
803
+ }
804
+ const path = formNamePath(registration.name);
805
+ const resolvePath = registration.isListField ? registration.getRemovalPath : () => path;
806
+ if (!resolvePath) {
807
+ return;
808
+ }
809
+ if (!pendingRemovals.length) {
810
+ queueMicrotask(discardUnmountedValues);
811
+ }
812
+ pendingRemovals.push({ resolvePath, isListField: registration.isListField });
813
+ }
814
+ // A restored parent represents its whole initial value, including nested list entries.
815
+ function discardUnmountedValues() {
816
+ const removals = pendingRemovals.splice(0);
817
+ if (!removals.length) {
818
+ return;
819
+ }
820
+ const mountedPaths = new Set();
821
+ for (const field of fieldRegistry) {
822
+ if (field.registration) {
823
+ mountedPaths.add(fieldSelectionKey(fieldPath(field)));
824
+ }
825
+ }
826
+ const updates = new Map();
827
+ for (const { resolvePath, isListField } of removals) {
828
+ const path = resolvePath((name) => getFormValue(values, name));
829
+ if (!path?.length) {
830
+ continue;
831
+ }
832
+ const key = fieldSelectionKey(path);
833
+ if (mountedPaths.has(key)) {
834
+ continue;
835
+ }
836
+ const value = isListField ? undefined : getFormValue(defaults, path);
837
+ if (!Object.is(getFormValue(values, path), value)) {
838
+ updates.set(key, { path, value });
839
+ }
840
+ }
841
+ let next = values;
842
+ const restored = [];
843
+ const ordered = [...updates.values()].sort((first, second) => first.path.length - second.path.length);
844
+ for (const { path, value } of ordered) {
845
+ if (!restored.some((parent) => containsFormPath(parent, path))) {
846
+ next = setFormValue(next, path, value, true);
847
+ restored.push(path);
848
+ }
849
+ }
850
+ if (next === values) {
851
+ return;
852
+ }
853
+ const previous = readStoreSnapshot();
854
+ updateValues(next);
855
+ valuesRevision++;
856
+ submissionError = undefined;
857
+ notifyStoreUpdate(previous, { type: 'remove', names: restored });
858
+ if (mountedForms) {
859
+ const names = ordered.map(({ path }) => path);
860
+ const dependents = startDependentValidation(names);
861
+ notifyStoreUpdate(previous, { type: 'dependenciesUpdate', names: [...names, ...dependents] });
862
+ }
863
+ }
864
+ // Clearing the last owner invalidates work from that attachment and defers defaults until remount.
865
+ function clearDetachedForm() {
866
+ storeLifetime++;
867
+ pendingRemovals.length = 0;
868
+ latestValidationRun = ++validationSequence;
869
+ for (const field of fieldRegistry) {
870
+ resetFieldMetadata(field);
871
+ }
872
+ storeSnapshot = undefined;
873
+ values = {};
874
+ valuesRevision++;
875
+ submissionRevision++;
876
+ isSubmitting = false;
877
+ submissionError = undefined;
878
+ restoreDefaultsOnMount = true;
879
+ }
880
+ // Form defaults take priority on reset. Connecting a model fills gaps beneath its current store.
881
+ function setInitialValues(initial, seed) {
882
+ defaults = initial === undefined ? modelDefaults : mergeFormValues(modelDefaults, initial);
883
+ if (!seed) {
884
+ return;
885
+ }
886
+ untrack(() => {
887
+ if (initial === undefined && !restoreDefaultsOnMount) {
888
+ return;
889
+ }
890
+ restoreDefaultsOnMount = false;
891
+ const next = mergeFormValues(defaults, values);
892
+ if (!sameFormValue(values, next)) {
893
+ updateValues(next);
894
+ valuesRevision++;
895
+ }
896
+ });
897
+ }
898
+ let submit = wrapSubmission(submitWithFinish);
899
+ /** Each read keeps its delegate when a caller wraps the callback-based submission method. */
900
+ function wrapSubmission(run) {
901
+ function submit(onFinish) {
902
+ if (typeof onFinish === 'function') {
903
+ return run.call(form, onFinish);
904
+ }
905
+ const provider = currentCallbackProvider();
906
+ const attachedSubmit = provider?.()?.submit;
907
+ if (attachedSubmit) {
908
+ attachedSubmit();
909
+ }
910
+ else {
911
+ void run.call(form, () => { });
912
+ }
913
+ }
914
+ return submit;
915
+ }
916
+ async function submitWithFinish(onFinish) {
917
+ if (isSubmitting) {
918
+ return { status: 'busy' };
919
+ }
920
+ const callbacks = currentCallbackProvider();
921
+ const revision = ++submissionRevision;
922
+ isSubmitting = true;
923
+ submissionError = undefined;
924
+ for (const field of fields) {
925
+ field.touched = true;
926
+ notifyFieldMeta(field);
927
+ }
928
+ try {
929
+ const result = await validateFields();
930
+ if (revision !== submissionRevision) {
931
+ const error = new FormValidationError(result, {}, true);
932
+ return { status: 'invalid', error };
933
+ }
934
+ if (callbacks && callbacks === currentCallbackProvider()) {
935
+ callbacks()?.onProviderFinish?.(result);
936
+ }
937
+ await onFinish(result);
938
+ return { status: 'success' };
939
+ }
940
+ catch (error) {
941
+ if (error instanceof FormValidationError) {
942
+ return { status: 'invalid', error };
943
+ }
944
+ if (revision === submissionRevision) {
945
+ submissionError = error;
946
+ }
947
+ return { status: 'failed', error };
948
+ }
949
+ finally {
950
+ if (revision === submissionRevision) {
951
+ isSubmitting = false;
952
+ }
953
+ }
954
+ }
412
955
  const form = {
413
956
  get values() {
414
957
  void valuesRevision;
@@ -416,7 +959,10 @@ export function createForm({ initialValues, rules = {} }) {
416
959
  },
417
960
  get errors() {
418
961
  return rootErrors(fields.filter((field) => field.errors !== undefined)
419
- .map((field) => ({ name: fieldPath(field), errors: field.errors ?? [], warnings: [] })));
962
+ .map(field => ({
963
+ name: fieldPath(field),
964
+ errors: validationMessageTexts(field.errors ?? [])
965
+ })));
420
966
  },
421
967
  get isSubmitting() {
422
968
  return isSubmitting;
@@ -432,13 +978,11 @@ export function createForm({ initialValues, rules = {} }) {
432
978
  getFieldsError,
433
979
  // An unknown path returns an empty list, like a field without errors.
434
980
  getFieldError(name) {
435
- const field = findField(name);
436
- return field?.errors ?? [];
981
+ return validationMessageTexts(getFieldMessages(name, 'errors'));
437
982
  },
438
983
  // Warnings are read separately from the errors that block submitted.
439
984
  getFieldWarning(name) {
440
- const field = findField(name);
441
- return field?.warnings ?? [];
985
+ return validationMessageTexts(getFieldMessages(name, 'warnings'));
442
986
  },
443
987
  getFieldInstance(name) {
444
988
  const registration = controlRegistration(name);
@@ -468,11 +1012,34 @@ export function createForm({ initialValues, rules = {} }) {
468
1012
  return field ? resolveValidationRules(fieldRules(field), form)
469
1013
  .some((rule) => rule.required && !rule.warningOnly) : false;
470
1014
  },
1015
+ changeFieldValue(name, value, trigger = 'onChange') {
1016
+ const field = ensureField(name);
1017
+ controlDrivenFields.add(field);
1018
+ applyControlValue(field, name, () => value);
1019
+ validateControlEvent(field, trigger);
1020
+ },
1021
+ validateFieldOn(name, trigger) {
1022
+ const field = findField(name);
1023
+ if (field) {
1024
+ controlDrivenFields.add(field);
1025
+ validateControlEvent(field, trigger);
1026
+ }
1027
+ },
471
1028
  setFieldValue(name, value) {
1029
+ const previous = readStoreSnapshot();
472
1030
  if (Object.is(getFormValue(values, name), value)) {
473
1031
  const field = findField(name);
474
1032
  if (field)
475
1033
  field.dirty = true;
1034
+ // An explicit undefined entry can suppress a default when a Form attaches later.
1035
+ if (value === undefined && !hasFormValue(values, formNamePath(name))) {
1036
+ const next = setFormValue(values, name, value);
1037
+ updateValues(next);
1038
+ valuesRevision++;
1039
+ }
1040
+ // Even equal writes publish a fresh store root to predicates.
1041
+ storeSnapshot = undefined;
1042
+ notifyStoreUpdate(previous, { type: 'setField', name, hasValue: true });
476
1043
  return;
477
1044
  }
478
1045
  updateValues(setFormValue(values, name, value));
@@ -485,9 +1052,11 @@ export function createForm({ initialValues, rules = {} }) {
485
1052
  }
486
1053
  valuesRevision++;
487
1054
  submissionError = undefined;
1055
+ notifyStoreUpdate(previous, { type: 'setField', name, hasValue: true });
488
1056
  revalidateTouched();
489
1057
  },
490
1058
  setFieldsValue(next) {
1059
+ const previous = readStoreSnapshot();
491
1060
  const merged = mergeFormValues(values, next);
492
1061
  for (const field of fields) {
493
1062
  const path = fieldPath(field);
@@ -495,9 +1064,7 @@ export function createForm({ initialValues, rules = {} }) {
495
1064
  field.dirty = true;
496
1065
  field.validated = true;
497
1066
  }
498
- const parent = getFormValue(next, path.slice(0, -1));
499
- const provided = parent !== null && typeof parent === 'object'
500
- && path.length > 0 && Object.hasOwn(parent, path[path.length - 1]);
1067
+ const provided = hasFormValue(next, path);
501
1068
  if (!Object.is(getFormValue(values, path), getFormValue(merged, path))
502
1069
  || provided) {
503
1070
  clearField(field);
@@ -506,61 +1073,21 @@ export function createForm({ initialValues, rules = {} }) {
506
1073
  updateValues(merged);
507
1074
  valuesRevision++;
508
1075
  submissionError = undefined;
1076
+ notifyStoreUpdate(previous, { type: 'valueUpdate', source: 'external' });
509
1077
  revalidateTouched();
510
1078
  },
511
1079
  setFields(updates) {
512
- for (const update of updates) {
513
- const { name, ...data } = update;
514
- if ('value' in data) {
515
- const next = setFormValue(values, name, data.value);
516
- const changed = !sameFormValue(values, next);
517
- updateValues(next);
518
- if (changed) {
519
- valuesRevision++;
520
- submissionError = undefined;
521
- for (const field of fields) {
522
- if (containsFormPath(name, fieldPath(field))) {
523
- cancelValidationDelay(field);
524
- field.run = ++validationSequence;
525
- const wasValidating = field.validating;
526
- field.validating = false;
527
- if (wasValidating)
528
- notifyFieldMeta(field);
529
- }
530
- }
531
- }
532
- }
533
- for (const field of fields) {
534
- if (!sameFormPath(name, fieldPath(field))
535
- || (!field.registration && !fieldRules(field).length)) {
536
- continue;
537
- }
538
- if ('touched' in update)
539
- field.touched = !!update.touched;
540
- if ('validating' in update) {
541
- cancelValidationDelay(field);
542
- field.run = ++validationSequence;
543
- field.validating = !!update.validating;
544
- field.validated = !field.validating;
545
- }
546
- if ('errors' in update)
547
- field.errors = [...(update.errors ?? [])];
548
- if ('warnings' in update)
549
- field.warnings = [...(update.warnings ?? [])];
550
- field.dirty = true;
551
- notifyFieldMeta(field);
552
- }
553
- }
1080
+ applyFieldUpdates(updates, false);
554
1081
  },
555
1082
  touchField(name) {
556
1083
  const field = ensureField(name);
557
- field.touched = true;
558
- field.dirty = true;
559
- notifyFieldMeta(field);
560
- revalidateTouched();
1084
+ markTouched(field);
1085
+ revalidateTouched({ explicitTouch: true });
561
1086
  },
562
1087
  resetFields(names) {
1088
+ const previous = readStoreSnapshot();
563
1089
  if (names?.length === 0) {
1090
+ notifyStoreUpdate(previous, { type: 'reset', names });
564
1091
  return;
565
1092
  }
566
1093
  const selected = names ? fields.filter((field) => names.some((name) => sameFormPath(name, fieldPath(field)))) : [...fields];
@@ -593,51 +1120,26 @@ export function createForm({ initialValues, rules = {} }) {
593
1120
  }
594
1121
  else {
595
1122
  valuesRevision++;
1123
+ storeSnapshot = undefined;
596
1124
  values = next;
597
1125
  resetKey = {};
598
1126
  }
599
1127
  for (const field of selected) {
600
- cancelValidationDelay(field);
601
- field.errors = undefined;
602
- field.warnings = undefined;
603
- field.touched = false;
604
- field.dirty = false;
605
- field.validating = false;
606
- field.validated = false;
607
- field.run = ++validationSequence;
1128
+ resetFieldMetadata(field);
608
1129
  notifyFieldMeta(field);
609
1130
  }
610
1131
  submissionError = undefined;
611
1132
  selected.sort((first, second) => (first.registrationOrder ?? 0) - (second.registrationOrder ?? 0));
612
1133
  for (const field of selected)
613
1134
  field.registration?.onReset?.();
1135
+ notifyStoreUpdate(previous, { type: 'reset', names });
614
1136
  },
615
1137
  validateFields,
616
- async submit(onFinish) {
617
- if (isSubmitting) {
618
- return { status: 'busy' };
619
- }
620
- isSubmitting = true;
621
- submissionError = undefined;
622
- for (const field of fields) {
623
- field.touched = true;
624
- notifyFieldMeta(field);
625
- }
626
- try {
627
- const result = await validateFields();
628
- await onFinish(result);
629
- return { status: 'success' };
630
- }
631
- catch (error) {
632
- if (error instanceof FormValidationError) {
633
- return { status: 'invalid', error };
634
- }
635
- submissionError = error;
636
- return { status: 'failed', error };
637
- }
638
- finally {
639
- isSubmitting = false;
640
- }
1138
+ get submit() {
1139
+ return submit;
1140
+ },
1141
+ set submit(run) {
1142
+ submit = wrapSubmission(run);
641
1143
  }
642
1144
  };
643
1145
  // Applies initialValue only to the missing value, without subscribing to the store.
@@ -653,29 +1155,73 @@ export function createForm({ initialValues, rules = {} }) {
653
1155
  get resetKey() {
654
1156
  return resetKey;
655
1157
  },
1158
+ setInitialValues,
1159
+ attachForm(getClearOnDestroy) {
1160
+ mountedForms++;
1161
+ return () => {
1162
+ mountedForms--;
1163
+ if (!mountedForms && getClearOnDestroy()) {
1164
+ clearDetachedForm();
1165
+ }
1166
+ };
1167
+ },
656
1168
  registerValidateMessages(getMessages) {
657
1169
  messageProviders.add(getMessages);
658
1170
  return () => { messageProviders.delete(getMessages); };
659
1171
  },
1172
+ registerCallbacks(getCallbacks) {
1173
+ callbackProviders.add(getCallbacks);
1174
+ return () => { callbackProviders.delete(getCallbacks); };
1175
+ },
1176
+ subscribeStoreUpdates(listener) {
1177
+ storeListeners.add(listener);
1178
+ return () => {
1179
+ storeListeners.delete(listener);
1180
+ if (!storeListeners.size)
1181
+ storeSnapshot = undefined;
1182
+ };
1183
+ },
1184
+ setControlledFields: (updates) => applyFieldUpdates(updates, true),
1185
+ getWatchValues: () => watchValues,
1186
+ getFieldMessages,
660
1187
  getFieldMeta(name) {
661
1188
  const field = findField(name);
662
1189
  return field ? fieldMeta(field) : undefined;
663
1190
  },
1191
+ handleFieldBlur(name) {
1192
+ const field = ensureField(name);
1193
+ if (usesControlValidation(field)) {
1194
+ validateControlEvent(field, 'onBlur');
1195
+ }
1196
+ else {
1197
+ markTouched(field);
1198
+ revalidateTouched();
1199
+ }
1200
+ },
1201
+ handleFieldEvent,
664
1202
  initializeField: initializeFieldValue,
665
1203
  initializeList: initializeFieldValue,
666
1204
  markFieldMounted(mountKey) {
667
- const field = fields.find((field) => field.registration?.mountKey === mountKey);
1205
+ const field = findFieldByMountKey(mountKey);
668
1206
  if (field)
669
1207
  field.initialValueOrder = ++initialValueOrder;
670
1208
  },
671
1209
  changeList(name, next) {
1210
+ const previous = readStoreSnapshot();
672
1211
  updateValues(setFormValue(values, name, next));
673
1212
  valuesRevision++;
674
1213
  submissionError = undefined;
675
1214
  const list = ensureField(name);
676
- clearField(list);
677
- list.touched = true;
678
- list.dirty = true;
1215
+ if (list.registration?.validateTrigger === undefined) {
1216
+ clearField(list);
1217
+ }
1218
+ else {
1219
+ // With explicit triggers, an edit retains the manual result until validation runs again.
1220
+ cancelValidationDelay(list);
1221
+ list.run = ++validationSequence;
1222
+ list.validating = false;
1223
+ }
1224
+ markTouched(list);
679
1225
  for (const field of fields) {
680
1226
  if (field !== list && containsFormPath(name, fieldPath(field))) {
681
1227
  cancelValidationDelay(field);
@@ -684,16 +1230,16 @@ export function createForm({ initialValues, rules = {} }) {
684
1230
  notifyFieldMeta(field);
685
1231
  }
686
1232
  }
1233
+ publishControlEdit(name, previous);
687
1234
  // The names of keyed rows will be updated with flush; the metadata remains with the previous line instance.
688
- void tick().then(revalidateTouched);
1235
+ void tick().then(() => revalidateTouched({ changedList: list }));
689
1236
  },
690
1237
  registerField(registration) {
691
1238
  return untrack(() => {
692
1239
  initializeFieldValue(registration.name, registration.initialValue);
693
- let field = findField(registration.name);
694
- if (!field || field.registration)
695
- field = addField(registration.name);
696
- const registered = field;
1240
+ const registeredLifetime = storeLifetime;
1241
+ const available = fields.find(field => !field.registration && sameFormPath(fieldPath(field), registration.name));
1242
+ const registered = available ?? addField(registration.name);
697
1243
  registered.registration = registration;
698
1244
  registered.registrationOrder = ++registrationOrder;
699
1245
  registered.initialValueOrder = ++initialValueOrder;
@@ -702,21 +1248,21 @@ export function createForm({ initialValues, rules = {} }) {
702
1248
  || registered.errors?.length || registered.warnings?.length) {
703
1249
  notifyFieldMeta(registered);
704
1250
  }
1251
+ if (registration.initialValue !== undefined) {
1252
+ notifyStoreUpdate(readStoreSnapshot(), {
1253
+ type: 'valueUpdate', source: 'internal', names: [registration.name]
1254
+ });
1255
+ }
705
1256
  return () => {
1257
+ controlDrivenFields.delete(registered);
706
1258
  notifyFieldMeta(registered, true);
707
1259
  if (cancelValidationDelay(registered)) {
708
1260
  registered.run = ++validationSequence;
709
1261
  registered.validating = false;
710
1262
  }
711
1263
  if (registered.persistent) {
712
- if (registration.rules !== undefined) {
713
- registered.run = ++validationSequence;
714
- registered.errors = undefined;
715
- registered.warnings = undefined;
716
- registered.touched = false;
717
- registered.dirty = false;
718
- registered.validating = false;
719
- registered.validated = false;
1264
+ if (registration.rules !== undefined || registration.preserve === false) {
1265
+ resetFieldMetadata(registered);
720
1266
  }
721
1267
  registered.registration = undefined;
722
1268
  }
@@ -725,6 +1271,9 @@ export function createForm({ initialValues, rules = {} }) {
725
1271
  fieldRegistry.delete(registered);
726
1272
  fields = [...fieldRegistry];
727
1273
  }
1274
+ if (registeredLifetime === storeLifetime) {
1275
+ scheduleFieldRemoval(registration);
1276
+ }
728
1277
  };
729
1278
  });
730
1279
  }