@clarity-js/forms 0.0.0-stage → 1.0.1
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 +48 -2
- package/index.d.ts +92 -0
- package/index.js +357 -0
- package/package.json +20 -4
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/forms
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Forms on signals for [Clarity.js](https://clarity-js.com). Each field is a signal you bind to an input, with
|
|
4
|
+
its error, whether it was touched or changed, and whether an async rule is still checking. The form adds them
|
|
5
|
+
up: values, errors, valid, dirty, and the state of a submit. No dependencies.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @clarity-js/forms
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```clarity
|
|
12
|
+
import { createForm, required, email, minLength } from '@clarity-js/forms'
|
|
13
|
+
|
|
14
|
+
component SignIn() {
|
|
15
|
+
const form = createForm({
|
|
16
|
+
fields: {
|
|
17
|
+
email: { initial: '', rules: [required(), email()] },
|
|
18
|
+
password: { initial: '', rules: [required(), minLength(8)] },
|
|
19
|
+
},
|
|
20
|
+
onSubmit: (values) => signIn(values),
|
|
21
|
+
})
|
|
22
|
+
const mail = form.fields.email
|
|
23
|
+
render {
|
|
24
|
+
<form on:submit={ form.submit }>
|
|
25
|
+
<label for="email">Email</label>
|
|
26
|
+
<input id="email" type="email" bind:value={ mail.value } on:blur={ mail.touch() } aria-invalid={ mail.invalid.get() } />
|
|
27
|
+
<when test={ mail.shownError.get() }><p id="email-error">{ mail.shownError.get() }</p></when>
|
|
28
|
+
<button disabled={ form.submitting.get() }>Sign in</button>
|
|
29
|
+
</form>
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- **Errors show when they should.** A field is checked from the start, so `form.valid` is always true to
|
|
35
|
+
the values, but its `shownError` stays empty until the field was touched or the form submitted. After a
|
|
36
|
+
field has shown an error it is checked on every change, so the message goes away as soon as it is right.
|
|
37
|
+
`validateOn: 'input' | 'blur' | 'submit'` sets when a field is first checked.
|
|
38
|
+
- **Rules are functions** of the value and the other values: `required`, `minLength`, `maxLength`, `email`,
|
|
39
|
+
`url`, `pattern`, `min`, `max`, `matches('password')`, `custom(test, message)`.
|
|
40
|
+
- **Async rules without races.** `asyncRule(test, message, { debounce })` runs after the plain rules pass;
|
|
41
|
+
an answer that comes back after the value changed again is thrown away. `field.pending` says it is running.
|
|
42
|
+
- **Schemas.** `schema:` takes any [Standard Schema](https://standardschema.dev) (Zod 3.24+, Valibot, ArkType),
|
|
43
|
+
or a Zod or Yup schema by their own methods. `validateSchema(schema, values)` on its own gives
|
|
44
|
+
`{ field: message }`.
|
|
45
|
+
- **Server answers.** If `onSubmit` returns `{ errors: { field: message } }` (a server action's answer), the
|
|
46
|
+
messages land on the fields at once. `form.setErrors()` does the same by hand.
|
|
47
|
+
- **Lists of forms:** `createFormArray({ factory, initial })` with `append`, `remove`, `move`, `values`, `valid`.
|
|
48
|
+
|
|
49
|
+
Docs: <https://clarity-js.com/docs/packages#forms>. MIT.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// @clarity-js/forms — types
|
|
2
|
+
export interface ReadSignal<T> { get(): T; peek(): T }
|
|
3
|
+
export interface Signal<T> extends ReadSignal<T> { set(value: T): T; update(fn: (value: T) => T): T }
|
|
4
|
+
|
|
5
|
+
/** A rule: an error message for a value, or null when it is fine. It sees the other values too. */
|
|
6
|
+
export type Rule<V = any, Values = Record<string, any>> = ((value: V, values: Values) => string | null | undefined)
|
|
7
|
+
export interface AsyncRule<V = any, Values = Record<string, any>> {
|
|
8
|
+
(value: V, values: Values): Promise<true | string | null | undefined | false>
|
|
9
|
+
async: true; message: string; debounce: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface FieldDefinition<V = any> { initial?: V; rules?: Array<Rule<V> | AsyncRule<V>>; label?: string }
|
|
13
|
+
|
|
14
|
+
export interface Field<V = any> {
|
|
15
|
+
readonly name: string
|
|
16
|
+
readonly label: string
|
|
17
|
+
value: Signal<V>
|
|
18
|
+
error: Signal<string | null>
|
|
19
|
+
touched: Signal<boolean>
|
|
20
|
+
pending: Signal<boolean>
|
|
21
|
+
dirty: ReadSignal<boolean>
|
|
22
|
+
/** The error to show: once the field was touched or the form submitted. */
|
|
23
|
+
shownError: ReadSignal<string | null>
|
|
24
|
+
invalid: ReadSignal<boolean>
|
|
25
|
+
touch(): void
|
|
26
|
+
reset(initial?: V): void
|
|
27
|
+
setError(message: string | null): void
|
|
28
|
+
validate(options?: { immediate?: boolean }): Promise<string | null>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Anything Standard Schema v1, a Zod schema (safeParseAsync) or a Yup schema (validate). */
|
|
32
|
+
export type Schema = { '~standard': { validate(value: unknown): any } } | { safeParseAsync(value: unknown): Promise<any> } | { validate(value: unknown, options?: any): Promise<any> }
|
|
33
|
+
|
|
34
|
+
export interface FormOptions<F extends Record<string, FieldDefinition>> {
|
|
35
|
+
fields: F
|
|
36
|
+
schema?: Schema
|
|
37
|
+
onSubmit?: (values: Values<F>, form: Form<F>) => unknown
|
|
38
|
+
validateOn?: 'blur' | 'input' | 'submit'
|
|
39
|
+
}
|
|
40
|
+
export type Values<F extends Record<string, FieldDefinition>> = { [K in keyof F]: F[K] extends FieldDefinition<infer V> ? V : any }
|
|
41
|
+
|
|
42
|
+
export interface Form<F extends Record<string, FieldDefinition> = Record<string, FieldDefinition>> {
|
|
43
|
+
fields: { [K in keyof F]: Field<F[K] extends FieldDefinition<infer V> ? V : any> }
|
|
44
|
+
values: ReadSignal<Values<F>>
|
|
45
|
+
errors: ReadSignal<Partial<Record<keyof F, string>>>
|
|
46
|
+
valid: ReadSignal<boolean>
|
|
47
|
+
dirty: ReadSignal<boolean>
|
|
48
|
+
touched: ReadSignal<boolean>
|
|
49
|
+
pending: ReadSignal<boolean>
|
|
50
|
+
submitting: Signal<boolean>
|
|
51
|
+
submitCount: Signal<number>
|
|
52
|
+
submitError: Signal<string | null>
|
|
53
|
+
/** on:submit={ form.submit } */
|
|
54
|
+
submit(event?: Event): Promise<boolean>
|
|
55
|
+
handleSubmit(handler?: (values: Values<F>, form: Form<F>) => unknown): (event?: Event) => Promise<boolean>
|
|
56
|
+
validate(): Promise<boolean>
|
|
57
|
+
reset(values?: Partial<Values<F>>): void
|
|
58
|
+
setValues(values: Partial<Values<F>>): void
|
|
59
|
+
setErrors(errors: Partial<Record<keyof F, string | null>>): void
|
|
60
|
+
field<K extends keyof F>(name: K): Form<F>['fields'][K]
|
|
61
|
+
attrs(name: keyof F): { id: string; name: string; 'aria-invalid': ReadSignal<boolean>; 'aria-describedby': string }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function createForm<F extends Record<string, FieldDefinition>>(options: FormOptions<F>): Form<F>
|
|
65
|
+
export function useField<F extends Record<string, FieldDefinition>, K extends keyof F>(form: Form<F>, name: K): Form<F>['fields'][K]
|
|
66
|
+
export function validateSchema(schema: Schema, values: unknown): Promise<Record<string, string>>
|
|
67
|
+
|
|
68
|
+
export function required(message?: string): Rule
|
|
69
|
+
export function minLength(n: number, message?: string): Rule
|
|
70
|
+
export function maxLength(n: number, message?: string): Rule
|
|
71
|
+
export function email(message?: string): Rule
|
|
72
|
+
export function url(message?: string): Rule
|
|
73
|
+
export function pattern(re: RegExp, message?: string): Rule
|
|
74
|
+
export function min(n: number, message?: string): Rule
|
|
75
|
+
export function max(n: number, message?: string): Rule
|
|
76
|
+
export function matches(field: string, message?: string): Rule
|
|
77
|
+
export function custom<V = any>(test: (value: V, values: Record<string, any>) => boolean, message?: string): Rule<V>
|
|
78
|
+
export function asyncRule<V = any>(test: (value: V, values: Record<string, any>) => Promise<boolean | string>, message?: string, options?: { debounce?: number }): AsyncRule<V>
|
|
79
|
+
|
|
80
|
+
export interface FormArray<F extends Record<string, FieldDefinition>> {
|
|
81
|
+
forms: Signal<Form<F>[]>
|
|
82
|
+
values: ReadSignal<Values<F>[]>
|
|
83
|
+
valid: ReadSignal<boolean>
|
|
84
|
+
dirty: ReadSignal<boolean>
|
|
85
|
+
append(values?: Partial<Values<F>>): Form<F>
|
|
86
|
+
remove(index: number): void
|
|
87
|
+
move(from: number, to: number): void
|
|
88
|
+
validate(): Promise<boolean>
|
|
89
|
+
getValues(): Values<F>[]
|
|
90
|
+
reset(): void
|
|
91
|
+
}
|
|
92
|
+
export function createFormArray<F extends Record<string, FieldDefinition>>(options: { factory: () => Form<F>; initial?: number }): FormArray<F>
|
package/index.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/forms — forms on signals.
|
|
3
|
+
*
|
|
4
|
+
* Every field is a signal you can bind (`bind:value={ form.fields.email.value }`), with its error, whether it
|
|
5
|
+
* was touched or changed, and whether an async rule is still running. The form adds up its fields: values,
|
|
6
|
+
* errors, valid, dirty, and the state of a submit. Rules are plain functions; a schema can be given instead —
|
|
7
|
+
* any Standard Schema (Zod 3.24+, Valibot, ArkType), or Zod and Yup by their own methods.
|
|
8
|
+
*
|
|
9
|
+
* import { createForm, required, email, minLength } from '@clarity-js/forms'
|
|
10
|
+
*
|
|
11
|
+
* const form = createForm({
|
|
12
|
+
* fields: {
|
|
13
|
+
* email: { initial: '', rules: [required(), email()] },
|
|
14
|
+
* password: { initial: '', rules: [required(), minLength(8)] },
|
|
15
|
+
* },
|
|
16
|
+
* onSubmit: async (values) => { await login(values) },
|
|
17
|
+
* })
|
|
18
|
+
*
|
|
19
|
+
* <form on:submit={ form.submit }>
|
|
20
|
+
* <input bind:value={ form.fields.email.value } on:blur={ form.fields.email.touch() } />
|
|
21
|
+
* <when test={ form.fields.email.shownError.get() }><p>{ form.fields.email.shownError.get() }</p></when>
|
|
22
|
+
* <button disabled={ form.submitting.get() }>Sign in</button>
|
|
23
|
+
* </form>
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { signal, computed, effect, batch, untrack } from '@ozsarman/clarityjs/runtime';
|
|
27
|
+
|
|
28
|
+
// ─── Rules ────────────────────────────────────────────────────────────────────
|
|
29
|
+
// A rule takes (value, values) and returns an error message, or null when the value is fine.
|
|
30
|
+
|
|
31
|
+
const empty = (v) => v == null || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0);
|
|
32
|
+
|
|
33
|
+
export const required = (message = 'This field is required') =>
|
|
34
|
+
(v) => (empty(v) || v === false ? message : null);
|
|
35
|
+
|
|
36
|
+
export const minLength = (n, message) =>
|
|
37
|
+
(v) => (!empty(v) && String(v).length < n ? (message ?? `At least ${n} characters`) : null);
|
|
38
|
+
|
|
39
|
+
export const maxLength = (n, message) =>
|
|
40
|
+
(v) => (!empty(v) && String(v).length > n ? (message ?? `At most ${n} characters`) : null);
|
|
41
|
+
|
|
42
|
+
export const email = (message = 'Enter a valid email address') =>
|
|
43
|
+
(v) => (!empty(v) && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v)) ? message : null);
|
|
44
|
+
|
|
45
|
+
export const url = (message = 'Enter a valid web address') =>
|
|
46
|
+
(v) => {
|
|
47
|
+
if (empty(v)) return null;
|
|
48
|
+
try { const u = new URL(String(v)); return u.protocol === 'http:' || u.protocol === 'https:' ? null : message; }
|
|
49
|
+
catch { return message; }
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export const pattern = (re, message = 'This does not match the expected format') =>
|
|
53
|
+
(v) => (!empty(v) && !re.test(String(v)) ? message : null);
|
|
54
|
+
|
|
55
|
+
export const min = (n, message) =>
|
|
56
|
+
(v) => (!empty(v) && Number(v) < n ? (message ?? `At least ${n}`) : null);
|
|
57
|
+
|
|
58
|
+
export const max = (n, message) =>
|
|
59
|
+
(v) => (!empty(v) && Number(v) > n ? (message ?? `At most ${n}`) : null);
|
|
60
|
+
|
|
61
|
+
/** The value must equal another field's (a password confirmed, an email typed twice). */
|
|
62
|
+
export const matches = (field, message = 'The two values do not match') =>
|
|
63
|
+
(v, values) => (v !== values?.[field] ? message : null);
|
|
64
|
+
|
|
65
|
+
/** A rule from a test: `custom(v => v % 2 === 0, 'Even numbers only')`. */
|
|
66
|
+
export const custom = (test, message = 'This value is not allowed') =>
|
|
67
|
+
(v, values) => (test(v, values) ? null : message);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A rule that has to ask someone (is this user name free?). `test` returns true when the value is fine, or an
|
|
71
|
+
* error message. It runs after the plain rules pass, `debounce` ms after the last change; an answer that comes
|
|
72
|
+
* back after the value changed again is thrown away.
|
|
73
|
+
*/
|
|
74
|
+
export const asyncRule = (test, message = 'This value is not allowed', { debounce = 250 } = {}) =>
|
|
75
|
+
Object.assign((v, values) => test(v, values), { async: true, message, debounce });
|
|
76
|
+
|
|
77
|
+
/** @deprecated the 0.x name of asyncRule */
|
|
78
|
+
export const asyncValidator = (fn, message) => asyncRule(fn, message);
|
|
79
|
+
|
|
80
|
+
// ─── Schemas ──────────────────────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
function pathOf(issue) {
|
|
83
|
+
const p = issue?.path;
|
|
84
|
+
if (!p) return null;
|
|
85
|
+
const parts = Array.isArray(p) ? p.map((s) => (typeof s === 'object' && s !== null ? s.key : s)) : String(p).split('.');
|
|
86
|
+
return parts.length ? String(parts[0]) : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Runs a schema over the values and returns { field: message } for the first problem of each field. */
|
|
90
|
+
export async function validateSchema(schema, values) {
|
|
91
|
+
const errors = {};
|
|
92
|
+
const note = (issues) => {
|
|
93
|
+
for (const issue of issues ?? []) {
|
|
94
|
+
const name = pathOf(issue);
|
|
95
|
+
if (name != null && !(name in errors)) errors[name] = issue.message;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
if (schema?.['~standard']?.validate) { // Standard Schema v1
|
|
99
|
+
const result = await schema['~standard'].validate(values);
|
|
100
|
+
if (result.issues) note(result.issues);
|
|
101
|
+
return errors;
|
|
102
|
+
}
|
|
103
|
+
if (typeof schema?.safeParseAsync === 'function') { // Zod
|
|
104
|
+
const result = await schema.safeParseAsync(values);
|
|
105
|
+
if (!result.success) note(result.error?.issues ?? result.error?.errors);
|
|
106
|
+
return errors;
|
|
107
|
+
}
|
|
108
|
+
if (typeof schema?.validate === 'function') { // Yup
|
|
109
|
+
try { await schema.validate(values, { abortEarly: false }); }
|
|
110
|
+
catch (err) { note(err?.inner?.length ? err.inner : [err]); }
|
|
111
|
+
return errors;
|
|
112
|
+
}
|
|
113
|
+
throw new TypeError('[forms] schema: expected a Standard Schema, a Zod schema or a Yup schema');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ─── Fields ───────────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
class Field {
|
|
119
|
+
constructor(name, def, form) {
|
|
120
|
+
this.name = name;
|
|
121
|
+
this.label = def.label ?? name;
|
|
122
|
+
this._form = form;
|
|
123
|
+
this._rules = def.rules ?? [];
|
|
124
|
+
this._initial = def.initial ?? '';
|
|
125
|
+
this._run = 0;
|
|
126
|
+
this._timer = null;
|
|
127
|
+
|
|
128
|
+
this.value = signal(this._initial);
|
|
129
|
+
this.error = signal(null);
|
|
130
|
+
this.touched = signal(false);
|
|
131
|
+
this.pending = signal(false);
|
|
132
|
+
this.dirty = computed(() => !same(this.value.get(), this._initial));
|
|
133
|
+
/** The error to show: once the field was touched or the form was submitted. */
|
|
134
|
+
this.shownError = computed(() => ((this.touched.get() || form.submitCount.get() > 0) ? this.error.get() : null));
|
|
135
|
+
/** For aria-invalid. */
|
|
136
|
+
this.invalid = computed(() => this.shownError.get() !== null);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Mark it touched (on blur) and check it. */
|
|
140
|
+
touch() {
|
|
141
|
+
this.touched.set(true);
|
|
142
|
+
if (this._form._mode !== 'submit') this.validate();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Back to its first value (or a new one), untouched and without error. */
|
|
146
|
+
reset(initial) {
|
|
147
|
+
if (initial !== undefined) this._initial = initial;
|
|
148
|
+
clearTimeout(this._timer);
|
|
149
|
+
this._run++;
|
|
150
|
+
batch(() => {
|
|
151
|
+
this.value.set(this._initial);
|
|
152
|
+
this.touched.set(false);
|
|
153
|
+
this.pending.set(false);
|
|
154
|
+
this.error.set(this._syncError(this._initial));
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Set an error from outside (a server's answer); cleared by the next check. */
|
|
159
|
+
setError(message) { this.error.set(message ?? null); }
|
|
160
|
+
|
|
161
|
+
_syncError(value) {
|
|
162
|
+
const values = untrack(() => this._form.values.get());
|
|
163
|
+
for (const rule of this._rules) {
|
|
164
|
+
if (rule.async) continue;
|
|
165
|
+
const out = rule(value, values);
|
|
166
|
+
if (out) return out;
|
|
167
|
+
}
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Check every rule now; resolves to the error, or null. */
|
|
172
|
+
async validate({ immediate = true } = {}) {
|
|
173
|
+
const value = this.value.peek();
|
|
174
|
+
const run = ++this._run;
|
|
175
|
+
clearTimeout(this._timer);
|
|
176
|
+
const syncError = this._syncError(value);
|
|
177
|
+
const asyncRules = this._rules.filter((r) => r.async);
|
|
178
|
+
if (syncError || !asyncRules.length) {
|
|
179
|
+
batch(() => { this.error.set(syncError); this.pending.set(false); });
|
|
180
|
+
return syncError;
|
|
181
|
+
}
|
|
182
|
+
this.pending.set(true);
|
|
183
|
+
if (!immediate) {
|
|
184
|
+
const wait = Math.max(...asyncRules.map((r) => r.debounce ?? 0));
|
|
185
|
+
if (wait > 0) await new Promise((done) => { this._timer = setTimeout(done, wait); });
|
|
186
|
+
if (run !== this._run) return this.error.peek();
|
|
187
|
+
}
|
|
188
|
+
const values = untrack(() => this._form.values.get());
|
|
189
|
+
let found = null;
|
|
190
|
+
for (const rule of asyncRules) {
|
|
191
|
+
let out;
|
|
192
|
+
try { out = await rule(value, values); } catch { out = false; }
|
|
193
|
+
if (run !== this._run) return this.error.peek(); // the value changed meanwhile
|
|
194
|
+
if (out !== true && out != null) { found = typeof out === 'string' ? out : rule.message; break; }
|
|
195
|
+
}
|
|
196
|
+
batch(() => { this.error.set(found); this.pending.set(false); });
|
|
197
|
+
return found;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function same(a, b) {
|
|
202
|
+
if (Object.is(a, b)) return true;
|
|
203
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => Object.is(x, b[i]));
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ─── Forms ────────────────────────────────────────────────────────────────────
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* @param {object} opts
|
|
211
|
+
* @param {Record<string, {initial?: any, rules?: Function[], label?: string}>} opts.fields
|
|
212
|
+
* @param {object} [opts.schema] a Standard Schema, Zod or Yup schema, checked with the rules
|
|
213
|
+
* @param {(values: object, form: object) => any} [opts.onSubmit]
|
|
214
|
+
* @param {'blur'|'input'|'submit'} [opts.validateOn='blur'] when a field is first checked; once it has shown an
|
|
215
|
+
* error it is checked on every change until it is right
|
|
216
|
+
*/
|
|
217
|
+
export function createForm({ fields = {}, schema = null, onSubmit = null, validateOn = 'blur', options } = {}) {
|
|
218
|
+
if (options && options.validateOnChange === false) validateOn = options.validateOnBlur === false ? 'submit' : 'blur';
|
|
219
|
+
const form = {
|
|
220
|
+
_mode: validateOn,
|
|
221
|
+
_schema: schema,
|
|
222
|
+
fields: {},
|
|
223
|
+
submitting: signal(false),
|
|
224
|
+
submitCount: signal(0),
|
|
225
|
+
submitError: signal(null),
|
|
226
|
+
};
|
|
227
|
+
for (const [name, def] of Object.entries(fields)) form.fields[name] = new Field(name, def, form);
|
|
228
|
+
const list = Object.values(form.fields);
|
|
229
|
+
|
|
230
|
+
form.values = computed(() => Object.fromEntries(list.map((f) => [f.name, f.value.get()])));
|
|
231
|
+
form.errors = computed(() => Object.fromEntries(list.filter((f) => f.error.get()).map((f) => [f.name, f.error.get()])));
|
|
232
|
+
form.valid = computed(() => list.every((f) => f.error.get() === null && !f.pending.get()));
|
|
233
|
+
form.dirty = computed(() => list.some((f) => f.dirty.get()));
|
|
234
|
+
form.touched = computed(() => list.some((f) => f.touched.get()));
|
|
235
|
+
form.pending = computed(() => list.some((f) => f.pending.get()));
|
|
236
|
+
|
|
237
|
+
// Each field: checked silently at first (so `valid` is true only when it is), then as `validateOn` says.
|
|
238
|
+
for (const field of list) {
|
|
239
|
+
field.error.set(field._syncError(field.value.peek()));
|
|
240
|
+
let first = true;
|
|
241
|
+
effect(() => {
|
|
242
|
+
field.value.get();
|
|
243
|
+
if (first) { first = false; return; }
|
|
244
|
+
untrack(() => {
|
|
245
|
+
const shown = field.shownError.peek() !== null || field.error.peek() !== null && field.touched.peek();
|
|
246
|
+
if (form._mode === 'input' || shown || (form._mode === 'blur' && field.touched.peek())) field.validate({ immediate: false });
|
|
247
|
+
else field.error.set(field._syncError(field.value.peek()));
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Check every field (and the schema); resolves to true when the form is valid. */
|
|
253
|
+
form.validate = async () => {
|
|
254
|
+
await Promise.all(list.map((f) => f.validate()));
|
|
255
|
+
if (schema) {
|
|
256
|
+
const errors = await validateSchema(schema, form.values.peek());
|
|
257
|
+
batch(() => { for (const f of list) if (errors[f.name] && !f.error.peek()) f.error.set(errors[f.name]); });
|
|
258
|
+
}
|
|
259
|
+
return form.valid.peek();
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
/** A submit handler; `on:submit={ form.submit }`. Checks everything, then calls onSubmit with the values. */
|
|
263
|
+
form.handleSubmit = (handler = onSubmit) => async (event) => {
|
|
264
|
+
event?.preventDefault?.();
|
|
265
|
+
batch(() => { for (const f of list) f.touched.set(true); form.submitCount.update((n) => n + 1); });
|
|
266
|
+
if (!(await form.validate()) || !handler) return false;
|
|
267
|
+
batch(() => { form.submitting.set(true); form.submitError.set(null); });
|
|
268
|
+
try {
|
|
269
|
+
const result = await handler(form.values.peek(), form);
|
|
270
|
+
if (result && typeof result === 'object' && result.errors && typeof result.errors === 'object') {
|
|
271
|
+
form.setErrors(result.errors); // a server action's answer
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
return true;
|
|
275
|
+
} catch (err) {
|
|
276
|
+
form.submitError.set(err?.message ?? String(err));
|
|
277
|
+
return false;
|
|
278
|
+
} finally {
|
|
279
|
+
form.submitting.set(false);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
form.submit = form.handleSubmit();
|
|
283
|
+
|
|
284
|
+
/** Back to the first values (or new ones). */
|
|
285
|
+
form.reset = (values = {}) => batch(() => {
|
|
286
|
+
for (const f of list) f.reset(values[f.name]);
|
|
287
|
+
form.submitCount.set(0);
|
|
288
|
+
form.submitError.set(null);
|
|
289
|
+
form.submitting.set(false);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
form.setValues = (values = {}) => batch(() => {
|
|
293
|
+
for (const [name, value] of Object.entries(values)) form.fields[name]?.value.set(value);
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
/** Errors from outside, e.g. a server: { email: 'This address is taken' }. They show at once. */
|
|
297
|
+
form.setErrors = (errors = {}) => batch(() => {
|
|
298
|
+
for (const [name, message] of Object.entries(errors)) {
|
|
299
|
+
const f = form.fields[name];
|
|
300
|
+
if (!f) continue;
|
|
301
|
+
f.touched.set(true);
|
|
302
|
+
f.error.set(message ?? null);
|
|
303
|
+
}
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
form.field = (name) => {
|
|
307
|
+
const f = form.fields[name];
|
|
308
|
+
if (!f) throw new Error(`[forms] no field "${name}"`);
|
|
309
|
+
return f;
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
/** Attributes for an input, to spread: `<input {...form.attrs('email')} />` (id, name, aria-*). */
|
|
313
|
+
form.attrs = (name) => {
|
|
314
|
+
const f = form.field(name);
|
|
315
|
+
return { id: name, name, 'aria-invalid': f.invalid, 'aria-describedby': name + '-error' };
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
// 0.x names, kept working
|
|
319
|
+
form.isValid = form.valid;
|
|
320
|
+
form.isDirty = form.dirty;
|
|
321
|
+
form.isTouched = form.touched;
|
|
322
|
+
form.isSubmitting = form.submitting;
|
|
323
|
+
for (const f of list) { f.isTouched = f.touched; f.isDirty = f.dirty; }
|
|
324
|
+
return form;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** @deprecated the 0.x name of createForm */
|
|
328
|
+
export const useForm = createForm;
|
|
329
|
+
|
|
330
|
+
/** A field of a form, for a child component. */
|
|
331
|
+
export function useField(form, name) { return form.field(name); }
|
|
332
|
+
|
|
333
|
+
// ─── Lists of forms ───────────────────────────────────────────────────────────
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* A list of sub-forms (rows of an invoice, addresses):
|
|
337
|
+
* const rows = createFormArray({ factory: () => createForm({ fields: { item: { initial: '' } } }), initial: 1 })
|
|
338
|
+
* rows.append(); rows.remove(0); rows.forms.get()
|
|
339
|
+
*/
|
|
340
|
+
export function createFormArray({ factory, initial = 0 } = {}) {
|
|
341
|
+
if (typeof factory !== 'function') throw new TypeError('[forms] createFormArray needs a factory');
|
|
342
|
+
const forms = signal(Array.from({ length: initial }, () => factory()));
|
|
343
|
+
return {
|
|
344
|
+
forms,
|
|
345
|
+
append(values = {}) { const f = factory(); f.setValues(values); forms.update((a) => [...a, f]); return f; },
|
|
346
|
+
remove(index) { forms.update((a) => a.filter((_, i) => i !== index)); },
|
|
347
|
+
move(from, to) { forms.update((a) => { const c = [...a]; const [x] = c.splice(from, 1); c.splice(to, 0, x); return c; }); },
|
|
348
|
+
async validate() { return (await Promise.all(forms.peek().map((f) => f.validate()))).every(Boolean); },
|
|
349
|
+
values: computed(() => forms.get().map((f) => f.values.get())),
|
|
350
|
+
getValues() { return forms.peek().map((f) => f.values.peek()); },
|
|
351
|
+
reset() { for (const f of forms.peek()) f.reset(); },
|
|
352
|
+
valid: computed(() => forms.get().every((f) => f.valid.get())),
|
|
353
|
+
dirty: computed(() => forms.get().some((f) => f.dirty.get())),
|
|
354
|
+
get isValid() { return this.valid; },
|
|
355
|
+
get isDirty() { return this.dirty; },
|
|
356
|
+
};
|
|
357
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/forms",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Forms on signals for Clarity.js: fields you bind, errors shown when they should be, async rules without races, Standard Schema (Zod, Valibot, ArkType) or Yup, and server-action answers on the fields. No dependencies.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.js",
|
|
7
|
+
"module": "./index.js",
|
|
8
|
+
"types": "./index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": { "types": "./index.d.ts", "import": "./index.js", "default": "./index.js" },
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": ["index.js", "index.d.ts", "README.md"],
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"keywords": ["clarity", "@ozsarman/clarityjs", "forms", "validation", "signals", "standard-schema", "zod", "valibot", "yup"],
|
|
16
|
+
"author": "Özdemir Şarman",
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"peerDependencies": { "@ozsarman/clarityjs": ">=1.10.0" },
|
|
19
|
+
"homepage": "https://clarity-js.com/docs/packages#forms",
|
|
20
|
+
"repository": { "type": "git", "url": "git+https://github.com/ozdemirsarman/clarity.js.git", "directory": "packages/clarity-forms" },
|
|
21
|
+
"engines": { "node": ">=18.0.0" }
|
|
22
|
+
}
|