@teamnovu/kit-vue-forms 0.2.16 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.2.18] - 2025-03-03
9
+
10
+ ### Fixed
11
+
12
+ - Correctly pass `validationState` to subForm creation instead of `formOptions`
13
+ - Fix build error through type on `FormFieldWrapper`
14
+
15
+ ## [0.2.17] - 2025-01-22
16
+
17
+ ### Fixed
18
+
19
+ - `keepValuesOnUnmount` was `false` instead of `true` by default
20
+
21
+ ## [0.1.27] - 2025-01-22
22
+
23
+ ### Fixed
24
+
25
+ - `keepValuesOnUnmount` was `false` instead of `true` by default
@@ -12,9 +12,7 @@ declare const _default: <TData extends FormDataDefault, TPath extends Paths<TDat
12
12
  props: __VLS_PrettifyLocal<Pick<Partial<{}> & Omit<{} & VNodeProps & AllowedComponentProps & ComponentCustomProps, never>, never> & FormFieldWrapperProps<TData, TPath, TComponent, TDataOut> & Partial<{}>> & PublicProps;
13
13
  expose(exposed: ShallowUnwrapRef<{}>): void;
14
14
  attrs: any;
15
- slots: Partial<Record<number, (_: any) => any>> & {
16
- default?(_: {}): any;
17
- };
15
+ slots: Readonly<Record<string, (props: any) => any>> & Record<string, (props: any) => any>;
18
16
  emit: {};
19
17
  }>) => VNode & {
20
18
  __ctx?: Awaited<typeof __VLS_setup>;
@@ -1,6 +1,6 @@
1
1
  import { Form, FormDataDefault } from '../types/form';
2
2
  import { EntityPaths, PickEntity } from '../types/util';
3
- import { UseFormOptions } from './useForm';
3
+ import { ValidationState } from './useValidation';
4
4
  export interface SubformOptions<_T extends FormDataDefault> {
5
5
  }
6
- export declare function createSubformInterface<T extends FormDataDefault, K extends EntityPaths<T>, TOut = T>(mainForm: Form<T, TOut>, path: K, formOptions?: UseFormOptions<T, TOut>, _options?: SubformOptions<PickEntity<T, K>>): Form<PickEntity<T, K>, PickEntity<TOut, K>>;
6
+ export declare function createSubformInterface<T extends FormDataDefault, K extends EntityPaths<T>, TOut = T>(mainForm: Form<T, TOut>, path: K, validationState: ValidationState<T, TOut>, _options?: SubformOptions<PickEntity<T, K>>): Form<PickEntity<T, K>, PickEntity<TOut, K>>;
package/dist/index.js CHANGED
@@ -3,7 +3,6 @@ var re = (r, t, e) => t in r ? te(r, t, { enumerable: !0, configurable: !0, writ
3
3
  var P = (r, t, e) => re(r, typeof t != "symbol" ? t + "" : t, e);
4
4
  import { toValue as J, toRaw as ae, shallowRef as O, watch as b, computed as m, unref as h, isRef as x, reactive as A, toRefs as G, shallowReactive as se, toRef as U, onScopeDispose as ne, triggerRef as ie, ref as Z, getCurrentScope as oe, onBeforeUnmount as le, defineComponent as N, renderSlot as C, normalizeProps as T, guardReactiveProps as W, createBlock as K, openBlock as L, withCtx as M, resolveDynamicComponent as ue, mergeProps as ce, createSlots as de, renderList as fe } from "vue";
5
5
  import { cloneDeep as he, merge as ve, omit as me } from "lodash-es";
6
- import "zod";
7
6
  function D(r) {
8
7
  const t = J(r), e = ae(t);
9
8
  return he(e);
@@ -290,7 +289,7 @@ function Pe(r, t, e) {
290
289
  s.set(o, i);
291
290
  }, v = (i) => {
292
291
  var o;
293
- n != null && n.keepValuesOnUnmount || (o = s.get(i)) == null || o.reset(), s.delete(i);
292
+ h((n == null ? void 0 : n.keepValuesOnUnmount) ?? !0) || (o = s.get(i)) == null || o.reset(), s.delete(i);
294
293
  }, y = (i) => {
295
294
  var o;
296
295
  a.has(i) ? (o = a.get(i)) == null || o.inc() : a.set(i, new Re(() => v(i)));
@@ -359,13 +358,16 @@ function $e(r) {
359
358
  };
360
359
  }
361
360
  function Ie(r) {
362
- const t = r.issues.filter((a) => a.path.length === 0).map((a) => a.message), e = r.issues.filter((a) => a.path.length > 0).reduce((a, s) => {
363
- const n = s.path.join(".");
364
- return {
365
- ...a,
366
- [n]: [...a[n] ?? [], s.message]
367
- };
368
- }, {});
361
+ const t = r.issues.filter((a) => a.path.length === 0).map((a) => a.message), e = r.issues.filter((a) => a.path.length > 0).reduce(
362
+ (a, s) => {
363
+ const n = s.path.join(".");
364
+ return {
365
+ ...a,
366
+ [n]: [...a[n] ?? [], s.message]
367
+ };
368
+ },
369
+ {}
370
+ );
369
371
  return {
370
372
  general: t,
371
373
  propertyErrors: e
@@ -450,10 +452,12 @@ class Be {
450
452
  }
451
453
  }
452
454
  function _(r) {
453
- return m(() => new Be(
454
- h(r.schema),
455
- h(r.validateFn)
456
- ));
455
+ return m(
456
+ () => new Be(
457
+ h(r.schema),
458
+ h(r.validateFn)
459
+ )
460
+ );
457
461
  }
458
462
  function ke(r, t) {
459
463
  const e = A({
@@ -461,15 +465,22 @@ function ke(r, t) {
461
465
  isValidated: !1,
462
466
  errors: h(t.errors) ?? w.errors
463
467
  }), a = (i = w.errors) => {
464
- e.errors = j(h(t.errors) ?? w.errors, i);
468
+ e.errors = j(
469
+ h(t.errors) ?? w.errors,
470
+ i
471
+ );
465
472
  };
466
- b(() => h(t.errors), async () => {
467
- if (e.isValidated) {
468
- const i = await n();
469
- a(i.errors);
470
- } else
471
- a();
472
- }, { immediate: !0 }), b(
473
+ b(
474
+ () => h(t.errors),
475
+ async () => {
476
+ if (e.isValidated) {
477
+ const i = await n();
478
+ a(i.errors);
479
+ } else
480
+ a();
481
+ },
482
+ { immediate: !0 }
483
+ ), b(
473
484
  [() => e.validators],
474
485
  async (i) => {
475
486
  if (e.isValidated)
@@ -485,7 +496,9 @@ function ke(r, t) {
485
496
  });
486
497
  const s = (i) => {
487
498
  const o = x(i) ? i : _(i);
488
- return e.validators.push(o), oe() && le(() => {
499
+ return e.validators.push(
500
+ o
501
+ ), oe() && le(() => {
489
502
  e.validators = e.validators.filter(
490
503
  (f) => f !== o
491
504
  );
@@ -613,7 +626,7 @@ function Ue(r, t, e, a) {
613
626
  p
614
627
  );
615
628
  },
616
- submitHandler: (u) => X(k, e ?? {})(u),
629
+ submitHandler: (u) => X(k, e)(u),
617
630
  getFieldArray: (u, p) => Y(k, u, p)
618
631
  };
619
632
  return k;
@@ -622,7 +635,7 @@ const je = {
622
635
  keepValuesOnUnmount: !0,
623
636
  ...Oe
624
637
  };
625
- function ze(r) {
638
+ function We(r) {
626
639
  r = ve({}, je, r);
627
640
  const t = m(() => D(r.initialData)), e = Z(D(t)), a = A({
628
641
  initialData: t,
@@ -661,7 +674,7 @@ function ze(r) {
661
674
  data: U(a, "data"),
662
675
  validateForm: s.validateForm,
663
676
  submitHandler: (l) => X(y, s)(l),
664
- getSubForm: (l, d) => Ue(y, l, r),
677
+ getSubForm: (l, d) => Ue(y, l, s),
665
678
  getFieldArray: (l, d) => Y(y, l, d)
666
679
  };
667
680
  return y;
@@ -685,7 +698,7 @@ const _e = /* @__PURE__ */ N({
685
698
  }), a = A(e);
686
699
  return (s, n) => C(s.$slots, "default", T(W(a)));
687
700
  }
688
- }), He = /* @__PURE__ */ N({
701
+ }), ze = /* @__PURE__ */ N({
689
702
  inheritAttrs: !1,
690
703
  __name: "FormFieldWrapper",
691
704
  props: {
@@ -724,7 +737,7 @@ const _e = /* @__PURE__ */ N({
724
737
  _: 3
725
738
  }, 8, ["form", "path"]));
726
739
  }
727
- }), Ke = /* @__PURE__ */ N({
740
+ }), He = /* @__PURE__ */ N({
728
741
  __name: "FormPart",
729
742
  props: {
730
743
  form: {},
@@ -737,7 +750,7 @@ const _e = /* @__PURE__ */ N({
737
750
  });
738
751
  export {
739
752
  _e as Field,
740
- He as FormFieldWrapper,
741
- Ke as FormPart,
742
- ze as useForm
753
+ ze as FormFieldWrapper,
754
+ He as FormPart,
755
+ We as useForm
743
756
  };
@@ -1,4 +1,4 @@
1
1
  import { Awaitable } from '@vueuse/core';
2
2
  import { ValidationState } from '../composables/useValidation';
3
3
  import { Form, FormDataDefault } from '../types/form';
4
- export declare function makeSubmitHandler<T extends FormDataDefault, TOut = T>(form: Form<T, TOut>, validationState: ValidationState<T, TOut>): (onSubmit: (data: TOut) => Awaitable<void>) => (event?: SubmitEvent) => Promise<void>;
4
+ export declare function makeSubmitHandler<T extends FormDataDefault, TOut = T>(form: Form<T, TOut>, validationState: Pick<ValidationState<T, TOut>, 'canValidate'>): (onSubmit: (data: TOut) => Awaitable<void>) => (event?: SubmitEvent) => Promise<void>;
@@ -16,43 +16,54 @@ In the example below we use a text field `TextField.vue`.
16
16
 
17
17
  Example:
18
18
  ```vue
19
- <!-- FormTextInput.vue -->
19
+ <!-- FormTextField.vue -->
20
20
  <template>
21
21
  <FormFieldWrapper
22
22
  :component="TextField"
23
- :component-props="$props"
24
- :path="path"
23
+ :component-props="omit($props, 'form', 'path')"
25
24
  :form="form"
26
- />
25
+ :path="path"
26
+ >
27
+ <slot />
28
+ <!-- https://vue-land.github.io/faq/forwarding-slots#passing-all-slots -->
29
+ <template
30
+ v-for="(_, slotName) in $slots"
31
+ #[slotName]="slotProps"
32
+ >
33
+ <slot :name="slotName" v-bind="slotProps ?? {}" />
34
+ </template>
35
+ </FormFieldWrapper>
27
36
  </template>
28
37
 
29
- <script setup lang="ts" generic="TData extends object, TPath extends Paths<TData>">
30
- import type { TextFieldProps } from '#components/utils/form/plainInput/TextField.vue';
31
- import TextField from '#components/utils/form/plainInput/TextField.vue';
32
- import { type Paths, FormFieldWrapper } from '@teamnovu/kit-vue-forms';
33
- import type {
34
- ExcludedFieldProps,
35
- FormComponentProps,
36
- } from '#types/form/FormComponentProps';
38
+ <script setup lang="ts" generic="TData extends object, TPath extends Paths<TData>, TDataOut = TData">
39
+ import TextField, { type TextFieldProps } from '#components/utils/form/plainInput/TextField.vue'
40
+ import { FormFieldWrapper, type ExcludedFieldProps, type FormComponentProps, type Paths } from '@teamnovu/kit-vue-forms'
41
+ import { omit } from 'lodash-es'
37
42
 
38
- export type Props<TData extends object, TPath extends Paths<TData>> =
39
- FormComponentProps<TData, TPath, TextFieldProps['modelValue']> & Omit<TextFieldProps, ExcludedFieldProps>;
43
+ export type Props<
44
+ TData extends object,
45
+ TPath extends Paths<TData>,
46
+ TDataOut = TData,
47
+ > = FormComponentProps<TData, TPath, TextFieldProps['modelValue'], TDataOut> & Omit<TextFieldProps, ExcludedFieldProps>
40
48
 
41
- defineProps<Props<TData, TPath>>();
49
+ defineProps<Props<TData, TPath, TDataOut>>()
42
50
  </script>
43
51
  ```
44
- Note the usage of the generic types `TData` and `TPath` to make the component fully type-safe. With this, the `path` prop
52
+ Note the usage of the generic types `TData`, `TPath`, and `TDataOut` to make the component fully type-safe. With this, the `path` prop
45
53
  will only allow valid paths of the form data. Moreover, it will throw a type error if the property at `path` of the `form`
46
54
  has the wrong type. This is ensured by using the `FormComponentProps` type above.
47
55
 
56
+ The `omit($props, 'form', 'path')` ensures that only the underlying component's props are passed through.
57
+ The slot forwarding pattern allows slots defined on the form input to be passed to the underlying plain input component.
58
+
48
59
  The usage of such a form input component is as follows (assuming the input should handle the "firstName" property of the form data):
49
60
  ```vue
50
- <FormTextInput
61
+ <FormTextField
51
62
  :form="form"
52
63
  path="firstName"
53
64
  />
54
65
  ```
55
- Here, `form` is the Form component that was created with [`useForm`](index.md#useform). All additional props are passed
66
+ Here, `form` is the form object that was created with [`useForm`](./reference.md#composable-useform). All additional props are passed
56
67
  to the underlying plain input component, e.g. `label`, `placeholder`, etc.
57
68
 
58
69
  It is recommended to use this pattern of a styled "plain input" that works with v-model and a "form input" to work with form
package/docs/example.md CHANGED
@@ -20,7 +20,7 @@ We can create a form like this:
20
20
 
21
21
  ```vue
22
22
  <template>
23
- <form @submit.prevent="submit">
23
+ <form @submit="form.submitHandler(sendToBackend)">
24
24
  <!-- Simple form inputs -->
25
25
  <!-- the "label" prop is passed through the FormTextField to the underlying TextField -->
26
26
  <FormTextField
@@ -56,13 +56,15 @@ We can create a form like this:
56
56
  <FormAddressField :form="subform" />
57
57
  </FormPart>
58
58
 
59
- <div v-for="(_, index) in unref(form.data).person.hobbies" :key="index" class="ml-4">
60
- <!-- Note the path format of an array item. You just use the index number in the dot-path -->
59
+ <!-- Using getFieldArray for dynamic lists with add/remove functionality -->
60
+ <div v-for="field in hobbies.items.value" :key="field.id" class="ml-4">
61
61
  <FormTextField
62
62
  :form="form"
63
- :path="`person.hobbies.${index}`"
63
+ :path="field.path"
64
64
  />
65
+ <button type="button" @click="hobbies.remove(field.id)">Remove</button>
65
66
  </div>
67
+ <button type="button" @click="hobbies.push('')">Add Hobby</button>
66
68
 
67
69
  <button type="button" @click="toggleComment">
68
70
  Toggle Comment
@@ -151,20 +153,12 @@ const form = useForm<{ // this type might be inferred automatically from the ini
151
153
  }),
152
154
  });
153
155
 
154
- const sendToBackend = async (data) => {
155
- // send data object to backend
156
- };
157
-
158
- const submit = async () => {
159
- // validate the form
160
- // if the zod schema is not satisfied, isValid will be false and the errors will be set on the corresponding fields
161
- // if your TextInput component handles errors correctly, it should be directly visible
162
- const { isValid } = await form.validateForm();
156
+ // getFieldArray for managing the hobbies list
157
+ const hobbies = form.getFieldArray('person.hobbies');
163
158
 
164
- // only submit if the form is valid
165
- if (isValid) {
166
- await sendToBackend(unref(form.data));
167
- }
159
+ const sendToBackend = async (data) => {
160
+ // send validated data object to backend
161
+ // note: data is the validated/transformed output type (TOut)
168
162
  };
169
163
 
170
164
  // To programmatically change form values, use form.getField to get a ref and a setter function
package/docs/index.md CHANGED
@@ -16,9 +16,10 @@ but pass it down as a prop to guarantee type safety.
16
16
  ## Usage
17
17
 
18
18
  1. Wrap your plain input components into `FormFieldWrapper`, see [FormInput Example](./FormInput-example.md).
19
- 2. Inside your parent component where you want to use a form, use the composable `useForm` to create a form object.
20
- This object contains the form data, errors, and methods to define
21
- fields, validate the form, reset it, and create subforms for nested objects or arrays, see [here](./reference#composable-useform).
19
+ 2. Inside your parent component where you want to use a form, use the composable `useForm` to create a form object.
20
+ This object contains the form data, errors, and methods to define fields, validate the form, reset it,
21
+ create subforms for nested objects, and manage dynamic lists with `getFieldArray`.
22
+ Use `submitHandler` for form submission with automatic validation, see [here](./reference#composable-useform).
22
23
  3. Pass this form object to any form input component together with a path to the property of the form data that this input
23
24
  should manage. You can also make subforms, pass the form down to child components, etc. See the examples for inspiration.
24
25
  4. See Reference documentation for all types and methods: [here](./reference.md).
package/docs/reference.md CHANGED
@@ -2,35 +2,53 @@
2
2
  ## Composable `useForm`
3
3
  This is the main composable which creates the form. It has the following signature:
4
4
  ```typescript
5
- function useForm<T extends object>(options: {
5
+ function useForm<T extends object, TOut = T>(options: {
6
6
  // the initial data of the form
7
7
  // reactive changes to this object will propagate to the form data
8
8
  initialData: MaybeRefOrGetter<T>
9
9
  // an ErrorBag object or ref of an ErrorBag object with external errors
10
10
  // this is used e.g. for server side validation errors
11
- // these errors will be merged with the internal errors of the form based on validationFn below and/or the zod schema
11
+ // these errors will be merged with the internal errors of the form based on validateFn below and/or the zod schema
12
12
  errors?: MaybeRef<ErrorBag | undefined>
13
13
  // a zod schema of the form data
14
- // this is validated based on the validationStrategy or by manually triggering validateForm on the form object
15
- schema?: MaybeRef<z.ZodType>
14
+ // this is validated based on the validation flags or by manually triggering validateForm on the form object
15
+ // TOut is inferred from the schema's output type if provided
16
+ schema?: MaybeRef<z.ZodType<TOut>>
16
17
  // a custom validation function which is called with the current form data
17
18
  // this is additional to the schema for custom validations
18
- validateFn?: MaybeRef<ValidationFunction<T>>
19
+ validateFn?: MaybeRef<ValidationFunction<T, TOut>>
19
20
  // if the form data of a property should be reset or kept if all fields corresponding to this property are unmounted
21
+ // defaults to true
20
22
  keepValuesOnUnmount?: MaybeRef<boolean>
21
- // when validation should be done (on touch, pre submit, etc.)
22
- validationStrategy?: MaybeRef<ValidationStrategy>
23
- }): Form<T>
23
+ // validation flags before first submit (defaults: validateOnSubmit: true, all others: false)
24
+ validationBeforeSubmit?: ValidationFlags
25
+ // validation flags after first submit (defaults: validateOnSubmit: true, validateOnDataChange: true, validateOnFieldRegister: true)
26
+ validationAfterSubmit?: ValidationFlags
27
+ }): Form<T, TOut>
24
28
  ```
25
- This composable returns a `Form<T>` object.
29
+ This composable returns a `Form<T, TOut>` object.
26
30
 
27
- ## Type `Form<T>`
31
+ ## Type `ValidationFlags`
32
+ Controls when validation is triggered:
33
+ ```typescript
34
+ interface ValidationFlags {
35
+ validateOnBlur?: MaybeRefOrGetter<boolean>
36
+ validateOnFormOpen?: MaybeRefOrGetter<boolean>
37
+ validateOnSubmit?: MaybeRefOrGetter<boolean>
38
+ validateOnDataChange?: MaybeRefOrGetter<boolean>
39
+ validateOnFieldRegister?: MaybeRefOrGetter<boolean>
40
+ }
41
+ ```
42
+
43
+ ## Type `Form<T, TOut>`
28
44
  Here, `T` is the type of the form data, which is inferred from the `initialData` property of the options object passed to `useForm`.
45
+ `TOut` is the output type after validation/transformation. When a zod schema is provided, `TOut` is a merge of `T` with the schema's output type,
46
+ where the schema type takes precedence for properties it defines, and `T` provides types for properties unknown to the schema.
29
47
  You can also explicitly provide a type argument to `useForm<T>` if needed (useful if the initial data is an empty object `{}`).
30
48
 
31
49
  This object has the following properties and methods:
32
50
  ```typescript
33
- interface Form<T extends object> {
51
+ interface Form<T extends object, TOut = T> {
34
52
  // the current working data of the form
35
53
  // this might differ from initialData if the user has changed some values
36
54
  data: Ref<T>
@@ -66,24 +84,85 @@ interface Form<T extends object> {
66
84
  // defines a custom validator for the form
67
85
  // with this, a subcomponent might add a validator function and/or schema to the form
68
86
  // without needing access to the initial useForm call
69
- defineValidator: <TData extends T>(options: ValidatorOptions<TData> | Ref<Validator<TData>>) => Ref<Validator<TData> | undefined>
87
+ defineValidator: <TData extends T, TDataOut extends TOut>(
88
+ options: ValidatorOptions<TData, TDataOut> | Ref<Validator<TData, TDataOut>>
89
+ ) => Ref<Validator<TData, TDataOut> | undefined>
70
90
 
71
91
  // resets the form data and errors, as well as the dirty, touched etc. state of all fields
72
92
  reset: () => void
73
93
  // manually triggers validation of the form data based on schema and/or validateFn
74
- validateForm: () => Promise<ValidationResult>
94
+ // returns the validation result with errors and parsed data (if valid)
95
+ validateForm: () => Promise<ValidationResult<TOut>>
96
+
97
+ // creates a submit handler that validates the form before calling onSubmit
98
+ // onSubmit receives the validated/transformed data (TOut)
99
+ submitHandler: (onSubmit: (data: TOut) => Awaitable<void>) => (event: SubmitEvent) => Promise<void>
75
100
 
76
101
  // creates a subform for a nested object or array property of the form data
77
- // the subform is again a Form<T> object, where T is the type of the nested property
102
+ // the subform is again a Form object, where T is the type of the nested property
78
103
  // it will contain all errors that have paths starting with the path of the subform
79
104
  // changes to the subform data will propagate to the main form data and vice versa
80
105
  getSubForm: <P extends EntityPaths<T>>(
81
106
  path: P,
82
107
  options?: SubformOptions<PickEntity<T, P>>,
83
108
  ) => Form<PickEntity<T, P>>
109
+
110
+ // creates a field array for managing dynamic lists
111
+ // see the Field Arrays section below for details
112
+ getFieldArray: <K extends Paths<T>>(
113
+ path: PickProps<T, K> extends unknown[] ? K : never,
114
+ options?: FieldArrayOptions<PickProps<T, K> extends (infer U)[] ? U : never>,
115
+ ) => FieldArray<PickProps<T, K> extends (infer U)[] ? U : never, K>
84
116
  }
85
117
  ```
86
118
 
119
+ ## Method `setInitialData`
120
+ The `setInitialData` method is available on `FormField` objects (returned by `getField` or `defineField`). It updates what is considered the "initial" value of a field. If the field is not dirty, it also updates the current data.
121
+
122
+ This is useful when loading data asynchronously after the form is initialized:
123
+
124
+ ```typescript
125
+ const { setInitialData } = form.getField('person.firstName')
126
+
127
+ // After fetching data from an API
128
+ const fetchedData = await fetchUserData()
129
+ setInitialData(fetchedData.firstName)
130
+ // If the field wasn't dirty, the current data is also updated
131
+ ```
132
+
133
+ ## Method `defineValidator`
134
+ The `defineValidator` method allows subcomponents to add validation rules to a form without needing access to the initial `useForm` call. The validator is automatically removed when the component unmounts.
135
+
136
+ This is particularly useful on subforms, where a reusable component can define its own validation:
137
+
138
+ ```vue
139
+ <!-- AddressFields.vue - a reusable address component -->
140
+ <script setup lang="ts">
141
+ import type { Form } from '@teamnovu/kit-vue-forms'
142
+ import { z } from 'zod'
143
+
144
+ const props = defineProps<{
145
+ form: Form<{ street: string; city: string; zip: string }>
146
+ }>()
147
+
148
+ // This validation only applies while AddressFields is mounted
149
+ props.form.defineValidator({
150
+ schema: z.object({
151
+ street: z.string().min(1, 'Street is required'),
152
+ city: z.string().min(1, 'City is required'),
153
+ zip: z.string().regex(/^\d{4}$/, 'Invalid zip code'),
154
+ }),
155
+ })
156
+ </script>
157
+ ```
158
+
159
+ ```vue
160
+ <!-- Parent component using FormPart -->
161
+ <FormPart :form="form" path="person.address" #="{ subform }">
162
+ <AddressFields :form="subform" />
163
+ </FormPart>
164
+ ```
165
+
87
166
  ## Type `ErrorBag`
88
167
  The errors in the form are structured in an `ErrorBag` object. Most errors are tied to properties in the form. However,
89
168
  there might be cases where there are errors, that cannot be tied to one property. To account for that the `ErrorBag` satisfies the following interface:
@@ -98,6 +177,33 @@ interface ErrorBag {
98
177
  }
99
178
  ```
100
179
 
180
+ ## Field Arrays
181
+ For managing dynamic lists (add, remove, reorder items), use `getFieldArray`. It provides stable IDs for each item,
182
+ which is important for efficient Vue rendering with `v-for`.
183
+
184
+ ```typescript
185
+ const hobbies = form.getFieldArray('person.hobbies')
186
+
187
+ // add item
188
+ hobbies.push('new hobby')
189
+
190
+ // remove by id
191
+ hobbies.remove(hobbies.items.value[0].id)
192
+ ```
193
+ ```vue
194
+ <div v-for="field in hobbies.items.value" :key="field.id">
195
+ <FormTextField :form="form" :path="field.path" />
196
+ <button @click="hobbies.remove(field.id)">Remove</button>
197
+ </div>
198
+ ```
199
+
200
+ For objects where identity should be based on a property (e.g. `id`) rather than reference equality, provide a `hashFn`:
201
+ ```typescript
202
+ const products = form.getFieldArray('products', {
203
+ hashFn: (item) => item.id
204
+ })
205
+ ```
206
+
101
207
  ## Component `FormPart`
102
208
  A component to define a subform part for a nested object or array property of the form data. This corresponds to the
103
209
  `getSubForm` method of the `Form<T>` object, but in component form to be easily used in the template. An example usage is as follows:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnovu/kit-vue-forms",
3
- "version": "0.2.16",
3
+ "version": "0.2.18",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -60,4 +60,6 @@ defineOptions({
60
60
  })
61
61
 
62
62
  defineProps<FormFieldWrapperProps<TData, TPath, TComponent, TDataOut>>()
63
+
64
+ defineSlots<Record<string, (props: any) => any>>()
63
65
  </script>
@@ -82,7 +82,7 @@ export function useFieldRegistry<T extends FormDataDefault, TOut = T>(
82
82
  ) {
83
83
  const fieldReferenceCounter = new Map<Paths<T>, Rc>()
84
84
  const fields = shallowReactive(new Map()) as FieldRegistryCache<T>
85
- const registryOptions = {
85
+ const registryOptions: FieldRegistryOptions = {
86
86
  ...optionDefaults,
87
87
  ...fieldRegistryOptions,
88
88
  }
@@ -95,7 +95,7 @@ export function useFieldRegistry<T extends FormDataDefault, TOut = T>(
95
95
  }
96
96
 
97
97
  const deregisterField = (path: Paths<T>) => {
98
- if (!registryOptions?.keepValuesOnUnmount) {
98
+ if (!unref(registryOptions?.keepValuesOnUnmount ?? true)) {
99
99
  fields.get(path)?.reset()
100
100
  }
101
101
  fields.delete(path)
@@ -113,7 +113,7 @@ export function useForm<T extends FormDataDefault, TOut = T>(
113
113
  validateForm: validationState.validateForm as Form<T, TOut>['validateForm'],
114
114
  submitHandler: onSubmit => makeSubmitHandler(form, validationState)(onSubmit),
115
115
  getSubForm: (path, subformOptions) => {
116
- return createSubformInterface(form, path, options, subformOptions)
116
+ return createSubformInterface(form, path, validationState, subformOptions)
117
117
  },
118
118
  getFieldArray: (path, fieldArrayOptions) => {
119
119
  return useFieldArray(form, path, fieldArrayOptions)
@@ -16,10 +16,10 @@ import {
16
16
  import { makeSubmitHandler } from '../utils/submitHandler'
17
17
  import { useFieldArray } from './useFieldArray'
18
18
  import type { DefineFieldOptions } from './useFieldRegistry'
19
- import type { UseFormOptions } from './useForm'
20
19
  import {
21
20
  createValidator,
22
21
  SuccessValidationResult,
22
+ type ValidationState,
23
23
  type ValidatorOptions,
24
24
  } from './useValidation'
25
25
 
@@ -65,7 +65,7 @@ export function createSubformInterface<
65
65
  >(
66
66
  mainForm: Form<T, TOut>,
67
67
  path: K,
68
- formOptions?: UseFormOptions<T, TOut>,
68
+ validationState: ValidationState<T, TOut>,
69
69
  _options?: SubformOptions<PickEntity<T, K>>,
70
70
  ): Form<PickEntity<T, K>, PickEntity<TOut, K>> {
71
71
  type ST = PickEntity<T, K>
@@ -158,7 +158,10 @@ export function createSubformInterface<
158
158
  const errors = computed(() =>
159
159
  filterErrorsForPath(unref(mainForm.errors), path))
160
160
 
161
- const validateForm = (() => mainForm.validateForm()) as Form<ST, STOut>['validateForm']
161
+ const validateForm = (() => mainForm.validateForm()) as Form<
162
+ ST,
163
+ STOut
164
+ >['validateForm']
162
165
 
163
166
  // Nested subforms
164
167
  const getSubForm = <P extends EntityPaths<ST>>(
@@ -203,7 +206,8 @@ export function createSubformInterface<
203
206
  reset,
204
207
  validateForm,
205
208
  getSubForm,
206
- submitHandler: onSubmit => makeSubmitHandler(subForm, formOptions ?? {})(onSubmit),
209
+ submitHandler: onSubmit =>
210
+ makeSubmitHandler(subForm, validationState)(onSubmit),
207
211
  getFieldArray: (fieldArrayPath, fieldArrayOptions) => {
208
212
  return useFieldArray(subForm, fieldArrayPath, fieldArrayOptions)
209
213
  },
@@ -1,7 +1,26 @@
1
- import { computed, getCurrentScope, isRef, onBeforeUnmount, reactive, ref, toRefs, toValue, unref, watch, type MaybeRef, type MaybeRefOrGetter, type Ref } from 'vue'
2
- import z from 'zod'
1
+ import {
2
+ computed,
3
+ getCurrentScope,
4
+ isRef,
5
+ onBeforeUnmount,
6
+ reactive,
7
+ ref,
8
+ toRefs,
9
+ toValue,
10
+ unref,
11
+ watch,
12
+ type MaybeRef,
13
+ type MaybeRefOrGetter,
14
+ type Ref,
15
+ } from 'vue'
16
+ import type z from 'zod'
3
17
  import type { FormDataDefault } from '../types/form'
4
- import type { ErrorBag, ValidationFunction, ValidationResult, Validator } from '../types/validation'
18
+ import type {
19
+ ErrorBag,
20
+ ValidationFunction,
21
+ ValidationResult,
22
+ Validator,
23
+ } from '../types/validation'
5
24
  import { hasErrors, isValidResult, mergeErrors } from '../utils/validation'
6
25
  import { flattenError } from '../utils/zod'
7
26
 
@@ -35,7 +54,8 @@ export interface ValidatorOptions<T, TOut = T> {
35
54
  validateFn?: MaybeRef<ValidationFunction<T, TOut> | undefined>
36
55
  }
37
56
 
38
- export interface ValidationOptions<T, TOut = T> extends ValidatorOptions<T, TOut> {
57
+ export interface ValidationOptions<T, TOut = T>
58
+ extends ValidatorOptions<T, TOut> {
39
59
  errors?: MaybeRef<ErrorBag | undefined>
40
60
  validationBeforeSubmit?: ValidationFlags
41
61
  validationAfterSubmit?: ValidationFlags
@@ -48,7 +68,8 @@ export const SuccessValidationResult: ValidationResult<never> = {
48
68
  },
49
69
  }
50
70
 
51
- class ZodSchemaValidator<T extends FormDataDefault, TOut = T> implements Validator<T, TOut> {
71
+ class ZodSchemaValidator<T extends FormDataDefault, TOut = T>
72
+ implements Validator<T, TOut> {
52
73
  constructor(private schema?: z.ZodType<TOut, T>) {}
53
74
 
54
75
  async validate(data: T): Promise<ValidationResult<TOut>> {
@@ -74,7 +95,8 @@ class ZodSchemaValidator<T extends FormDataDefault, TOut = T> implements Validat
74
95
  }
75
96
  }
76
97
 
77
- class FunctionValidator<T extends FormDataDefault, TOut = T> implements Validator<T, TOut> {
98
+ class FunctionValidator<T extends FormDataDefault, TOut = T>
99
+ implements Validator<T, TOut> {
78
100
  constructor(private validateFn?: ValidationFunction<T, TOut>) {}
79
101
 
80
102
  async validate(data: T): Promise<ValidationResult<TOut>> {
@@ -101,7 +123,8 @@ class FunctionValidator<T extends FormDataDefault, TOut = T> implements Validato
101
123
  }
102
124
  }
103
125
 
104
- class CombinedValidator<T extends FormDataDefault, TOut = T> implements Validator<T, TOut> {
126
+ class CombinedValidator<T extends FormDataDefault, TOut = T>
127
+ implements Validator<T, TOut> {
105
128
  private schemaValidator: ZodSchemaValidator<T, TOut>
106
129
  private functionValidator: FunctionValidator<T, TOut>
107
130
 
@@ -129,10 +152,13 @@ class CombinedValidator<T extends FormDataDefault, TOut = T> implements Validato
129
152
  export function createValidator<T extends FormDataDefault, TOut = T>(
130
153
  options: ValidatorOptions<T, TOut>,
131
154
  ): Ref<Validator<T, TOut> | undefined> {
132
- return computed(() => new CombinedValidator(
133
- unref(options.schema) as z.ZodType<TOut, T>,
134
- unref(options.validateFn) as ValidationFunction<T, TOut>,
135
- ))
155
+ return computed(
156
+ () =>
157
+ new CombinedValidator(
158
+ unref(options.schema) as z.ZodType<TOut, T>,
159
+ unref(options.validateFn) as ValidationFunction<T, TOut>,
160
+ ),
161
+ )
136
162
  }
137
163
 
138
164
  export function useValidation<T extends FormDataDefault, TOut = T>(
@@ -145,20 +171,29 @@ export function useValidation<T extends FormDataDefault, TOut = T>(
145
171
  errors: unref(options.errors) ?? SuccessValidationResult.errors,
146
172
  })
147
173
 
148
- const updateErrors = (newErrors: ErrorBag = SuccessValidationResult.errors) => {
149
- validationState.errors = mergeErrors(unref(options.errors) ?? SuccessValidationResult.errors, newErrors)
174
+ const updateErrors = (
175
+ newErrors: ErrorBag = SuccessValidationResult.errors,
176
+ ) => {
177
+ validationState.errors = mergeErrors(
178
+ unref(options.errors) ?? SuccessValidationResult.errors,
179
+ newErrors,
180
+ )
150
181
  }
151
182
 
152
183
  // Watch for changes in the error bag and update validation state
153
- watch(() => unref(options.errors), async () => {
154
- if (validationState.isValidated) {
155
- const validationResults = await getValidationResults()
184
+ watch(
185
+ () => unref(options.errors),
186
+ async () => {
187
+ if (validationState.isValidated) {
188
+ const validationResults = await getValidationResults()
156
189
 
157
- updateErrors(validationResults.errors)
158
- } else {
159
- updateErrors()
160
- }
161
- }, { immediate: true })
190
+ updateErrors(validationResults.errors)
191
+ } else {
192
+ updateErrors()
193
+ }
194
+ },
195
+ { immediate: true },
196
+ )
162
197
 
163
198
  // Watch for changes in validation function or schema
164
199
  // to trigger validation. Only run if validation is already validated.
@@ -187,11 +222,15 @@ export function useValidation<T extends FormDataDefault, TOut = T>(
187
222
  })
188
223
 
189
224
  const defineValidator = <TData extends T, TDataOut extends TOut>(
190
- options: ValidatorOptions<TData, TDataOut> | Ref<Validator<TData, TDataOut>>,
225
+ options:
226
+ | ValidatorOptions<TData, TDataOut>
227
+ | Ref<Validator<TData, TDataOut>>,
191
228
  ) => {
192
229
  const validator = isRef(options) ? options : createValidator(options)
193
230
 
194
- validationState.validators.push(validator as Ref<Validator<T, TOut> | undefined>)
231
+ validationState.validators.push(
232
+ validator as Ref<Validator<T, TOut> | undefined>,
233
+ )
195
234
 
196
235
  if (getCurrentScope()) {
197
236
  onBeforeUnmount(() => {
@@ -240,7 +279,9 @@ export function useValidation<T extends FormDataDefault, TOut = T>(
240
279
  }
241
280
  }
242
281
 
243
- const validateField = async (path: string): Promise<ValidationResult<TOut>> => {
282
+ const validateField = async (
283
+ path: string,
284
+ ): Promise<ValidationResult<TOut>> => {
244
285
  const validationResults = await getValidationResults()
245
286
 
246
287
  updateErrors({
@@ -272,7 +313,10 @@ export function useValidation<T extends FormDataDefault, TOut = T>(
272
313
  return toValue(flags?.[flag] ?? false)
273
314
  }
274
315
 
275
- const validateStrategy = <K extends keyof ValidationFlags>(flag: K, path: string) => {
316
+ const validateStrategy = <K extends keyof ValidationFlags>(
317
+ flag: K,
318
+ path: string,
319
+ ) => {
276
320
  if (!canValidate(flag)) {
277
321
  return
278
322
  }
@@ -292,4 +336,6 @@ export function useValidation<T extends FormDataDefault, TOut = T>(
292
336
  }
293
337
  }
294
338
 
295
- export type ValidationState<T extends FormDataDefault, TOut = T> = ReturnType<typeof useValidation<T, TOut>>
339
+ export type ValidationState<T extends FormDataDefault, TOut = T> = ReturnType<
340
+ typeof useValidation<T, TOut>
341
+ >
package/src/types/form.ts CHANGED
@@ -5,11 +5,11 @@ import type { SubformOptions } from '../composables/useSubform'
5
5
  import type { ValidatorOptions } from '../composables/useValidation'
6
6
  import type { EntityPaths, Paths, PickEntity, PickProps } from './util'
7
7
  import type {
8
- ErrorBag,
9
- ValidationErrorMessage,
10
- ValidationErrors,
11
- ValidationResult,
12
- Validator,
8
+ ErrorBag,
9
+ ValidationErrorMessage,
10
+ ValidationErrors,
11
+ ValidationResult,
12
+ Validator,
13
13
  } from './validation'
14
14
 
15
15
  export type FormDataDefault = object
package/src/types/util.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type { Prop } from 'vue'
2
1
  import type { FormDataDefault } from './form'
3
2
 
4
3
  /**
@@ -5,7 +5,7 @@ import { isValidResult } from './validation'
5
5
 
6
6
  export function makeSubmitHandler<T extends FormDataDefault, TOut = T>(
7
7
  form: Form<T, TOut>,
8
- validationState: ValidationState<T, TOut>,
8
+ validationState: Pick<ValidationState<T, TOut>, 'canValidate'>,
9
9
  ) {
10
10
  return (onSubmit: (data: TOut) => Awaitable<void>) => {
11
11
  return async (event?: SubmitEvent) => {
package/src/utils/zod.ts CHANGED
@@ -1,4 +1,4 @@
1
- import z from 'zod'
1
+ import type z from 'zod'
2
2
  import type { ErrorBag } from '../types/validation'
3
3
 
4
4
  export function flattenError(error: z.ZodError): ErrorBag {
@@ -8,14 +8,17 @@ export function flattenError(error: z.ZodError): ErrorBag {
8
8
 
9
9
  const propertyErrors = error.issues
10
10
  .filter(issue => issue.path.length > 0)
11
- .reduce((acc, issue) => {
12
- const path = issue.path.join('.')
11
+ .reduce(
12
+ (acc, issue) => {
13
+ const path = issue.path.join('.')
13
14
 
14
- return {
15
- ...acc,
16
- [path]: [...(acc[path] ?? []), issue.message],
17
- }
18
- }, {} as ErrorBag['propertyErrors'])
15
+ return {
16
+ ...acc,
17
+ [path]: [...(acc[path] ?? []), issue.message],
18
+ }
19
+ },
20
+ {} as ErrorBag['propertyErrors'],
21
+ )
19
22
 
20
23
  return {
21
24
  general,
@@ -156,4 +156,3 @@ describe('Path Utilities', () => {
156
156
  })
157
157
  })
158
158
  })
159
-
@@ -397,7 +397,9 @@ describe('useForm', () => {
397
397
  },
398
398
  })
399
399
 
400
- effectScope().run(() => {
400
+ const scope = effectScope()
401
+
402
+ scope.run(() => {
401
403
  const nameField = form.defineField({ path: 'name' })
402
404
 
403
405
  expect(form.fields.value.length).toBe(1)
@@ -406,6 +408,8 @@ describe('useForm', () => {
406
408
  nameField.setData('Modified')
407
409
  })
408
410
 
411
+ scope.stop()
412
+
409
413
  expect(form.data.value.name).toBe('Modified')
410
414
  })
411
415