-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormStore.svelte.ts
55 lines (46 loc) · 1.62 KB
/
FormStore.svelte.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
type FormStoreSanitizer<FD, Sanitized> = (fd: FD) => Sanitized;
type FormStoreErrorLogger = (key: string, msg: string) => void;
type FormStoreValidator<Sanitized> = (fd: Sanitized, err: FormStoreErrorLogger) => void;
type FormStoreConfig<FD, Sanitized> = {
initialState: FD
sanitizer: FormStoreSanitizer<FD, Sanitized>
validator: FormStoreValidator<Sanitized>
}
class FormStore<FD, Sanitized = FD> {
state: FD = $state({}) as FD;
errors: Map<string, string> = $state(new Map());
sanitized: Sanitized = $state({}) as Sanitized;
valid: boolean = true;
static sanitizeString(str: string): string {
return str.trim().replaceAll(/\s+/gm, " ")
}
constructor(config: FormStoreConfig<FD, Sanitized>) {
this.state = config.initialState
$effect(() => {
this.#resetErrors()
this.sanitized = config.sanitizer(this.state)
config.validator(this.sanitized, this.err.bind(this))
if (Object.keys(this.errors).length === 0) this.valid = true;
})
}
checkUnique(arr: any[], key: string, onMatch: (indices: [number, number], items: [any, any]) => void) {
arr.forEach((a, i) => {
arr.forEach((b, j) => {
if ((a !== b) && (a[key] === b[key])) {
onMatch([i, j], [a, b])
}
})
})
}
#resetErrors() {
this.errors = new Map();
this.valid = false;
}
err(key: string, msg: string) {
this.errors.set(key, msg)
}
errMsg(key: string): string {
return this.errors.get(key) || ""
}
}
export default FormStore