MCPcopy Create free account
hub / github.com/dfinity/orbit / useForm

Function useForm

apps/wallet/src/composables/forms.composable.ts:15–163  ·  view source on GitHub ↗
(opts: {
  /**
   * The model to use for the form.
   */
  model: Ref<T>;
  /**
   * The submit function to call when the form is valid and submitted.
   *
   * @param model the model to submit
   * @returns
   */
  submit: (model: T) => Promise<void>;
  /**
   * Take a snapshot of the model for comparison.
   *
   * If not provided, the model will be stringified.
   */
  takeModelSnapshot?: (model: T) => string;
  /**
   * The form template ref to use for validation.
   *
   * If not provided, defaults to 'form'.
   */
  formTemplateRef?: string;
  /**
   * Additional validation rules to apply to the form.
   *
   * If not provided, only the form's built-in validation will be used.
   */
  isValid?: (model: T) => Promise<FieldWithError[]> | FieldWithError[];
})

Source from the content-addressed store, hash-verified

13}
14
15export const useForm = <T>(opts: {
16 /**
17 * The model to use for the form.
18 */
19 model: Ref<T>;
20 /**
21 * The submit function to call when the form is valid and submitted.
22 *
23 * @param model the model to submit
24 * @returns
25 */
26 submit: (model: T) => Promise<void>;
27 /**
28 * Take a snapshot of the model for comparison.
29 *
30 * If not provided, the model will be stringified.
31 */
32 takeModelSnapshot?: (model: T) => string;
33 /**
34 * The form template ref to use for validation.
35 *
36 * If not provided, defaults to 'form'.
37 */
38 formTemplateRef?: string;
39 /**
40 * Additional validation rules to apply to the form.
41 *
42 * If not provided, only the form's built-in validation will be used.
43 */
44 isValid?: (model: T) => Promise<FieldWithError[]> | FieldWithError[];
45}) => {
46 const form = useTemplateRef<VFormValidation>(opts.formTemplateRef ?? 'form');
47 const valid = ref(true);
48 const fieldsWithErrors = ref<Array<FieldWithError>>([]);
49 const modelSnapshot = ref<string>('');
50 const submitting = ref(false);
51 const edited = ref(false);
52 const submitted = ref(false);
53 const initialModel = ref(deepClone(opts.model.value)) as Ref<T>;
54
55 const model = computed({
56 get: () => opts.model.value,
57 set: value => {
58 opts.model.value = value;
59 },
60 });
61
62 const additionalValidationCheck = opts.isValid ?? (() => Promise.resolve([]));
63
64 const takeModelSnapshot =
65 opts.takeModelSnapshot ??
66 function (model: T) {
67 return JSON.stringify(transformData(model));
68 };
69
70 const additionalFieldErrors = computed(() => {
71 return fieldsWithErrors.value.filter(field => field.isCustomValidation);
72 });

Callers

nothing calls this directly

Calls 3

deepCloneFunction · 0.90
transformDataFunction · 0.90
mapMethod · 0.80

Tested by

no test coverage detected