@conform-to/react 0.4.0-pre.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,10 +11,9 @@
11
11
  - [useFieldList](#usefieldlist)
12
12
  - [useControlledInput](#usecontrolledinput)
13
13
  - [conform](#conform)
14
+ - [getFormElements](#getformelements)
14
15
  - [hasError](#haserror)
15
- - [isFieldElement](#isfieldelement)
16
16
  - [parse](#parse)
17
- - [setFormError](#setformerror)
18
17
  - [shouldValidate](#shouldvalidate)
19
18
 
20
19
  <!-- /aside -->
@@ -295,33 +294,6 @@ function Fieldset() {
295
294
  }
296
295
  ```
297
296
 
298
- <details>
299
- <summary>Is it required to provide the FieldsetConfig to `useFieldset`?</summary>
300
-
301
- No. The only thing required is the ref object. All the config is optional. You can always pass them to each fields manually.
302
-
303
- ```tsx
304
- import { useForm, useFieldset } from '@conform-to/react';
305
-
306
- function SubscriptionForm() {
307
- const formProps = useForm();
308
- const { email } = useFieldset(formProps.ref);
309
-
310
- return (
311
- <form {...formProps}>
312
- <input
313
- type="email"
314
- name={email.config.name}
315
- defaultValue="support@conform.dev"
316
- required
317
- />
318
- </form>
319
- );
320
- }
321
- ```
322
-
323
- </details>
324
-
325
297
  <details>
326
298
  <summary>Why does `useFieldset` require a ref object of the form or fieldset?</summary>
327
299
 
@@ -352,7 +324,7 @@ function ExampleForm() {
352
324
 
353
325
  ### useFieldList
354
326
 
355
- It returns a list of key and config, with a group of helpers configuring buttons for list manipulation
327
+ It returns a list of key and config, with helpers to configure command buttons with [list command](/docs/submission.md#list-command).
356
328
 
357
329
  ```tsx
358
330
  import { useFieldset, useFieldList } from '@conform-to/react';
@@ -373,7 +345,7 @@ type Collection = {
373
345
  function CollectionFieldset() {
374
346
  const ref = useRef();
375
347
  const { books } = useFieldset<Collection>(ref);
376
- const [bookList, control] = useFieldList(ref, books.config);
348
+ const [bookList, command] = useFieldList(ref, books.config);
377
349
 
378
350
  return (
379
351
  <fieldset ref={ref}>
@@ -390,12 +362,12 @@ function CollectionFieldset() {
390
362
  />
391
363
 
392
364
  {/* To setup a delete button */}
393
- <button {...control.remove({ index })}>Delete</button>
365
+ <button {...command.remove({ index })}>Delete</button>
394
366
  </div>
395
367
  ))}
396
368
 
397
369
  {/* To setup a button that can append a new row with optional default value */}
398
- <button {...control.append({ defaultValue: { name: '', isbn: '' } })}>
370
+ <button {...command.append({ defaultValue: { name: '', isbn: '' } })}>
399
371
  add
400
372
  </button>
401
373
  </fieldset>
@@ -412,7 +384,7 @@ import { useRef } from 'react';
412
384
  function CollectionFieldset() {
413
385
  const ref = useRef();
414
386
  const { books } = useFieldset<Collection>(ref);
415
- const [bookList, control] = useFieldList(ref, books.config);
387
+ const [bookList, command] = useFieldList(ref, books.config);
416
388
 
417
389
  return (
418
390
  <fieldset ref={ref}>
@@ -422,12 +394,12 @@ function CollectionFieldset() {
422
394
  <BookFieldset {...book.config} />
423
395
 
424
396
  {/* To setup a delete button */}
425
- <button {...control.remove({ index })}>Delete</button>
397
+ <button {...command.remove({ index })}>Delete</button>
426
398
  </div>
427
399
  ))}
428
400
 
429
401
  {/* To setup a button that can append a new row */}
430
- <button {...control.append()}>add</button>
402
+ <button {...command.append()}>add</button>
431
403
  </fieldset>
432
404
  );
433
405
  }
@@ -582,74 +554,43 @@ function RandomForm() {
582
554
  }
583
555
  ```
584
556
 
585
- ### hasError
586
-
587
- This helper checks if there is any message defined in error array with the provided name.
588
-
589
- ```ts
590
- import { hasError } from '@conform-to/react';
591
-
592
- /**
593
- * Assume the error looks like this:
594
- */
595
- const error = [['email', 'Email is required']];
596
-
597
- // This will log `true`
598
- console.log(hasError(error, 'email'));
599
-
600
- // This will log `false`
601
- console.log(hasError(error, 'password'));
602
- ```
603
-
604
557
  ---
605
558
 
606
- ### isFieldElement
559
+ ### getFormElements
607
560
 
608
- This checks if the provided element is an `input` / `select` / `textarea` or `button` HTML element with type guard. Useful when you need to access the validityState of the fields and modify the validation message manually.
561
+ It returns all _input_ / _select_ / _textarea_ or _button_ in the forms. Useful when looping through the form elements to validate each field.
609
562
 
610
563
  ```tsx
611
- import { isFieldElement } from '@conform-to/react';
564
+ import { useForm, parse, getFormElements } from '@conform-to/react';
612
565
 
613
- export default function SignupForm() {
566
+ export default function LoginForm() {
614
567
  const form = useForm({
615
- onValidate({ form }) {
616
- for (const element of form.elements) {
617
- if (isFieldElement(element)) {
618
- switch (field.name) {
619
- case 'email':
620
- if (field.validity.valueMissing) {
621
- field.setCustomValidity('Email is required');
622
- } else if (field.validity.typeMismatch) {
623
- field.setCustomValidity('Please enter a valid email');
624
- } else {
625
- field.setCustomValidity('');
626
- }
627
- break;
628
- case 'password':
629
- if (field.validity.valueMissing) {
630
- field.setCustomValidity('Password is required');
631
- } else if (field.validity.tooShort) {
632
- field.setCustomValidity(
633
- 'The password should be at least 10 characters long',
634
- );
635
- } else {
636
- field.setCustomValidity('');
637
- }
638
- break;
639
- case 'confirm-password': {
640
- if (field.validity.valueMissing) {
641
- field.setCustomValidity('Confirm Password is required');
642
- } else if (field.value !== formData.get('password')) {
643
- field.setCustomValidity('The password does not match');
644
- } else {
645
- field.setCustomValidity('');
646
- }
647
- break;
568
+ onValidate({ form, formData }) {
569
+ const submission = parse(formData);
570
+
571
+ for (const element of getFormElements(form)) {
572
+ switch (element.name) {
573
+ case 'email': {
574
+ if (element.validity.valueMissing) {
575
+ submission.error.push([element.name, 'Email is required']);
576
+ } else if (element.validity.typeMismatch) {
577
+ submission.error.push([element.name, 'Email is invalid']);
578
+ }
579
+ break;
580
+ }
581
+ case 'password': {
582
+ if (element.validity.valueMissing) {
583
+ submission.error.push([element.name, 'Password is required']);
648
584
  }
585
+ break;
649
586
  }
650
587
  }
651
588
  }
589
+
590
+ return submission;
652
591
  },
592
+
593
+ // ....
653
594
  });
654
595
 
655
596
  // ...
@@ -658,42 +599,38 @@ export default function SignupForm() {
658
599
 
659
600
  ---
660
601
 
661
- ### parse
602
+ ### hasError
662
603
 
663
- It parses the formData based on the [naming convention](/docs/submission).
604
+ This helper checks if there is any message defined in error array with the provided name.
664
605
 
665
- ```tsx
666
- import { parse } from '@conform-to/react';
606
+ ```ts
607
+ import { hasError } from '@conform-to/react';
667
608
 
668
- const formData = new FormData(formElement);
669
- const submission = parse(formData);
609
+ /**
610
+ * Assume the error looks like this:
611
+ */
612
+ const error = [['email', 'Email is required']];
670
613
 
671
- console.log(submission);
614
+ // This will log `true`
615
+ console.log(hasError(error, 'email'));
616
+
617
+ // This will log `false`
618
+ console.log(hasError(error, 'password'));
672
619
  ```
673
620
 
674
621
  ---
675
622
 
676
- ### setFormError
623
+ ### parse
677
624
 
678
- This helpers updates the form error based on the submission result by looping through all elements in the form and update the error with the [setCustomValidity](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setCustomValidity) API.
625
+ It parses the formData based on the [naming convention](/docs/submission).
679
626
 
680
627
  ```tsx
681
- import { setFormError } from '@conform-to/react';
682
-
683
- function ExampleForm() {
684
- const form = useForm({
685
- onValidate({ form, submission }) {
686
- const error = validate(submission);
628
+ import { parse } from '@conform-to/react';
687
629
 
688
- setFormError(form, {
689
- ...submission,
690
- error,
691
- });
692
- },
693
- });
630
+ const formData = new FormData();
631
+ const submission = parse(formData);
694
632
 
695
- // ...
696
- }
633
+ console.log(submission);
697
634
  ```
698
635
 
699
636
  ---
@@ -706,14 +643,13 @@ This helper checks if the scope of validation includes a specific field by check
706
643
  import { shouldValidate } from '@conform-to/react';
707
644
 
708
645
  /**
709
- * The submission type and metadata give us hint on what should be valdiated.
646
+ * The submission type and intent give us hint on what should be valdiated.
710
647
  * If the type is 'validate', only the field with name matching the metadata must be validated.
711
- *
712
- * However, if the type is `undefined`, both will log true (Default submission)
648
+ * If the type is 'submit', everything should be validated (Default submission)
713
649
  */
714
650
  const submission = {
715
- type: 'validate',
716
- metadata: 'email',
651
+ context: 'validate',
652
+ intent: 'email',
717
653
  value: {},
718
654
  error: [],
719
655
  };
@@ -4,17 +4,14 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  function ownKeys(object, enumerableOnly) {
6
6
  var keys = Object.keys(object);
7
-
8
7
  if (Object.getOwnPropertySymbols) {
9
8
  var symbols = Object.getOwnPropertySymbols(object);
10
9
  enumerableOnly && (symbols = symbols.filter(function (sym) {
11
10
  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
12
11
  })), keys.push.apply(keys, symbols);
13
12
  }
14
-
15
13
  return keys;
16
14
  }
17
-
18
15
  function _objectSpread2(target) {
19
16
  for (var i = 1; i < arguments.length; i++) {
20
17
  var source = null != arguments[i] ? arguments[i] : {};
@@ -24,10 +21,8 @@ function _objectSpread2(target) {
24
21
  Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
25
22
  });
26
23
  }
27
-
28
24
  return target;
29
25
  }
30
-
31
26
  function _defineProperty(obj, key, value) {
32
27
  if (key in obj) {
33
28
  Object.defineProperty(obj, key, {
@@ -39,7 +34,6 @@ function _defineProperty(obj, key, value) {
39
34
  } else {
40
35
  obj[key] = value;
41
36
  }
42
-
43
37
  return obj;
44
38
  }
45
39
 
package/helpers.js CHANGED
@@ -21,23 +21,19 @@ function input(config) {
21
21
  pattern: config.pattern,
22
22
  multiple: config.multiple
23
23
  };
24
-
25
24
  if (config.initialError && config.initialError.length > 0) {
26
25
  attributes.autoFocus = true;
27
26
  }
28
-
29
27
  if (isCheckboxOrRadio) {
30
28
  attributes.value = value !== null && value !== void 0 ? value : 'on';
31
29
  attributes.defaultChecked = config.defaultValue === attributes.value;
32
30
  } else {
33
31
  attributes.defaultValue = config.defaultValue;
34
32
  }
35
-
36
33
  return attributes;
37
34
  }
38
35
  function select(config) {
39
36
  var _config$defaultValue;
40
-
41
37
  var attributes = {
42
38
  name: config.name,
43
39
  form: config.form,
@@ -45,16 +41,13 @@ function select(config) {
45
41
  required: config.required,
46
42
  multiple: config.multiple
47
43
  };
48
-
49
44
  if (config.initialError && config.initialError.length > 0) {
50
45
  attributes.autoFocus = true;
51
46
  }
52
-
53
47
  return attributes;
54
48
  }
55
49
  function textarea(config) {
56
50
  var _config$defaultValue2;
57
-
58
51
  var attributes = {
59
52
  name: config.name,
60
53
  form: config.form,
@@ -64,11 +57,9 @@ function textarea(config) {
64
57
  maxLength: config.maxLength,
65
58
  autoFocus: Boolean(config.initialError)
66
59
  };
67
-
68
60
  if (config.initialError && config.initialError.length > 0) {
69
61
  attributes.autoFocus = true;
70
62
  }
71
-
72
63
  return attributes;
73
64
  }
74
65
 
package/hooks.d.ts CHANGED
@@ -1,10 +1,5 @@
1
1
  import { type FieldConfig, type FieldElement, type FieldValue, type FieldsetConstraint, type ListCommand, type Primitive, type Submission } from '@conform-to/dom';
2
2
  import { type InputHTMLAttributes, type FormEvent, type RefObject } from 'react';
3
- interface FormContext<Schema extends Record<string, any>> {
4
- form: HTMLFormElement;
5
- formData: FormData;
6
- submission: Submission<Schema>;
7
- }
8
3
  export interface FormConfig<Schema extends Record<string, any>> {
9
4
  /**
10
5
  * Validation mode. Default to `client-only`.
@@ -40,12 +35,18 @@ export interface FormConfig<Schema extends Record<string, any>> {
40
35
  /**
41
36
  * A function to be called when the form should be (re)validated.
42
37
  */
43
- onValidate?: (context: FormContext<Schema>) => Array<[string, string]>;
38
+ onValidate?: ({ form, formData, }: {
39
+ form: HTMLFormElement;
40
+ formData: FormData;
41
+ }) => Submission<Schema>;
44
42
  /**
45
43
  * The submit event handler of the form. It will be called
46
44
  * only when the form is considered valid.
47
45
  */
48
- onSubmit?: (event: FormEvent<HTMLFormElement>, context: FormContext<Schema>) => void;
46
+ onSubmit?: (event: FormEvent<HTMLFormElement>, context: {
47
+ formData: FormData;
48
+ submission: Submission<Schema>;
49
+ }) => void;
49
50
  }
50
51
  /**
51
52
  * Properties to be applied to the form element
@@ -65,7 +66,7 @@ interface Form<Schema extends Record<string, any>> {
65
66
  * Returns properties required to hook into form events.
66
67
  * Applied custom validation and define when error should be reported.
67
68
  *
68
- * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.2/packages/conform-react/README.md#useform
69
+ * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.3/packages/conform-react/README.md#useform
69
70
  */
70
71
  export declare function useForm<Schema extends Record<string, any>>(config?: FormConfig<Schema>): Form<Schema>;
71
72
  /**
@@ -106,41 +107,37 @@ export interface FieldsetConfig<Schema extends Record<string, any>> {
106
107
  /**
107
108
  * Returns all the information about the fieldset.
108
109
  *
109
- * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.2/packages/conform-react/README.md#usefieldset
110
+ * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.3/packages/conform-react/README.md#usefieldset
110
111
  */
111
- export declare function useFieldset<Schema extends Record<string, any>>(ref: RefObject<HTMLFormElement | HTMLFieldSetElement>, config?: FieldsetConfig<Schema>): Fieldset<Schema>;
112
- export declare function useFieldset<Schema extends Record<string, any>>(ref: RefObject<HTMLFormElement | HTMLFieldSetElement>, config?: FieldConfig<Schema>): Fieldset<Schema>;
113
- interface ControlButtonProps {
112
+ export declare function useFieldset<Schema extends Record<string, any>>(ref: RefObject<HTMLFormElement | HTMLFieldSetElement>, config: FieldsetConfig<Schema>): Fieldset<Schema>;
113
+ export declare function useFieldset<Schema extends Record<string, any>>(ref: RefObject<HTMLFormElement | HTMLFieldSetElement>, config: FieldConfig<Schema>): Fieldset<Schema>;
114
+ interface CommandButtonProps {
114
115
  name?: string;
115
116
  value?: string;
116
117
  form?: string;
117
118
  formNoValidate: true;
118
119
  }
119
- declare type CommandPayload<Schema, Type extends ListCommand<FieldValue<Schema>>['type']> = Extract<ListCommand<FieldValue<Schema>>, {
120
+ declare type ListCommandPayload<Schema, Type extends ListCommand<FieldValue<Schema>>['type']> = Extract<ListCommand<FieldValue<Schema>>, {
120
121
  type: Type;
121
122
  }>['payload'];
122
- /**
123
- * A group of helpers for configuring a list control button
124
- */
125
- interface ListControl<Schema> {
126
- prepend(payload?: CommandPayload<Schema, 'prepend'>): ControlButtonProps;
127
- append(payload?: CommandPayload<Schema, 'append'>): ControlButtonProps;
128
- replace(payload: CommandPayload<Schema, 'replace'>): ControlButtonProps;
129
- remove(payload: CommandPayload<Schema, 'remove'>): ControlButtonProps;
130
- reorder(payload: CommandPayload<Schema, 'reorder'>): ControlButtonProps;
131
- }
132
123
  /**
133
124
  * Returns a list of key and config, with a group of helpers
134
125
  * configuring buttons for list manipulation
135
126
  *
136
- * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.2/packages/conform-react/README.md#usefieldlist
127
+ * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.3/packages/conform-react/README.md#usefieldlist
137
128
  */
138
129
  export declare function useFieldList<Payload = any>(ref: RefObject<HTMLFormElement | HTMLFieldSetElement>, config: FieldConfig<Array<Payload>>): [
139
130
  Array<{
140
131
  key: string;
141
132
  config: FieldConfig<Payload>;
142
133
  }>,
143
- ListControl<Payload>
134
+ {
135
+ prepend(payload?: ListCommandPayload<Payload, 'prepend'>): CommandButtonProps;
136
+ append(payload?: ListCommandPayload<Payload, 'append'>): CommandButtonProps;
137
+ replace(payload: ListCommandPayload<Payload, 'replace'>): CommandButtonProps;
138
+ remove(payload: ListCommandPayload<Payload, 'remove'>): CommandButtonProps;
139
+ reorder(payload: ListCommandPayload<Payload, 'reorder'>): CommandButtonProps;
140
+ }
144
141
  ];
145
142
  interface ShadowInputProps extends InputHTMLAttributes<HTMLInputElement> {
146
143
  ref: RefObject<HTMLInputElement>;
@@ -163,7 +160,7 @@ interface InputControl<Element extends {
163
160
  * This is particular useful when integrating dropdown and datepicker whichs
164
161
  * introduces custom input mode.
165
162
  *
166
- * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.2/packages/conform-react/README.md#usecontrolledinput
163
+ * @see https://github.com/edmundhung/conform/tree/v0.4.0-pre.3/packages/conform-react/README.md#usecontrolledinput
167
164
  */
168
165
  export declare function useControlledInput<Element extends {
169
166
  focus: () => void;