-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathsuperForm.ts
2186 lines (1858 loc) · 65.4 KB
/
superForm.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable dci-lint/atomic-role-binding */
import type { TaintedFields, SuperFormValidated, SuperValidated } from '$lib/superValidate.js';
import type { ActionResult, BeforeNavigate, Page, SubmitFunction } from '@sveltejs/kit';
import {
derived,
get,
readonly,
writable,
type Readable,
type Writable,
type Updater
} from 'svelte/store';
import { navigating, page } from '$app/stores';
import { clone } from '$lib/utils.js';
import { browser } from '$app/environment';
import { onDestroy, tick } from 'svelte';
import { comparePaths, pathExists, setPaths, traversePath, traversePaths } from '$lib/traversal.js';
import {
splitPath,
type FormPathType,
mergePath,
type FormPath,
type FormPathLeaves
} from '$lib/stringPath.js';
import { beforeNavigate, goto, invalidateAll } from '$app/navigation';
import { SuperFormError, flattenErrors, mapErrors, updateErrors } from '$lib/errors.js';
import { cancelFlash, shouldSyncFlash } from './flash.js';
import { applyAction, deserialize, enhance as kitEnhance } from '$app/forms';
import { setCustomValidityForm, updateCustomValidity } from './customValidity.js';
import { inputInfo } from './elements.js';
import { Form as HtmlForm, scrollToFirstError } from './form.js';
import { stringify } from 'devalue';
import type { ValidationErrors } from '$lib/superValidate.js';
import type { MaybePromise } from '$lib/utils.js';
import type {
ClientValidationAdapter,
ValidationAdapter,
ValidationResult
} from '$lib/adapters/adapters.js';
import type { InputConstraints } from '$lib/jsonSchema/constraints.js';
import { fieldProxy, type ProxyOptions } from './proxies.js';
import { shapeFromObject } from '$lib/jsonSchema/schemaShape.js';
export type SuperFormEvents<T extends Record<string, unknown>, M> = Pick<
FormOptions<T, M>,
'onError' | 'onResult' | 'onSubmit' | 'onUpdate' | 'onUpdated'
>;
export type SuperFormEventList<T extends Record<string, unknown>, M> = {
[Property in keyof SuperFormEvents<T, M>]-?: NonNullable<SuperFormEvents<T, M>[Property]>[];
};
type FilterType<T, Check> = {
[K in keyof NonNullable<T> as NonNullable<NonNullable<T>[K]> extends Check
? never
: K]: NonNullable<T>[K];
};
/**
* Helper type for making ActionResult data strongly typed in onUpdate.
* @example const action : FormResult<ActionData> = result.data;
*/
export type FormResult<T extends Record<string, unknown> | null | undefined> = FilterType<
T,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
SuperValidated<Record<string, unknown>, any, Record<string, unknown>>
>;
export type TaintOption = boolean | 'untaint' | 'untaint-all' | 'untaint-form';
type ValidatorsOption<T extends Record<string, unknown>> =
| ValidationAdapter<Partial<T>, Record<string, unknown>>
| false
| 'clear';
// Need to distribute T with "T extends T",
// since SuperForm<A|B> is not the same as SuperForm<A> | SuperForm<B>
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
export type FormOptions<
T extends Record<string, unknown> = Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = any,
In extends Record<string, unknown> = T
> = Partial<{
id: string;
applyAction: boolean;
invalidateAll: boolean | 'force';
resetForm: boolean | (() => boolean);
scrollToError: 'auto' | 'smooth' | 'off' | boolean | ScrollIntoViewOptions;
autoFocusOnError: boolean | 'detect';
errorSelector: string;
selectErrorText: boolean;
stickyNavbar: string;
taintedMessage: string | boolean | null | (() => MaybePromise<boolean>);
SPA: true | { failStatus?: number } | string;
onSubmit: (
input: Parameters<SubmitFunction>[0] & {
/**
* If dataType: 'json' is set, send this data instead of $form when posting,
* and client-side validation for $form passes.
* @param data An object that can be serialized with devalue.
*/
jsonData: (data: Record<string, unknown>) => void;
/**
* Override client validation temporarily for this form submission.
*/
validators: (validators: Exclude<ValidatorsOption<T>, 'clear'>) => void;
/**
* Use a custom fetch or XMLHttpRequest implementation for this form submission. It must return an ActionResult in the response body.
* If the request is using a XMLHttprequest, the promise must be resolved when the request is complete.
*/
customRequest: (
validators: (input: Parameters<SubmitFunction>[0]) => Promise<Response | XMLHttpRequest>
) => void;
}
) => MaybePromise<unknown | void>;
onResult: (event: {
result: ActionResult;
/**
* @deprecated Use formElement instead
*/
formEl: HTMLFormElement;
formElement: HTMLFormElement;
cancel: () => void;
}) => MaybePromise<unknown | void>;
onUpdate: (event: {
form: SuperValidated<T, M, In>;
/**
* @deprecated Use formElement instead
*/
formEl: HTMLFormElement;
formElement: HTMLFormElement;
cancel: () => void;
result: Required<Extract<ActionResult, { type: 'success' | 'failure' }>>;
}) => MaybePromise<unknown | void>;
onUpdated: (event: { form: Readonly<SuperValidated<T, M, In>> }) => MaybePromise<unknown | void>;
onError:
| 'apply'
| ((event: {
result: {
type: 'error';
status?: number;
error: App.Error | Error | { message: string };
};
}) => MaybePromise<unknown | void>);
onChange: (event: ChangeEvent<T>) => void;
dataType: 'form' | 'json';
jsonChunkSize: number;
// TODO: Use NoInfer<T> on ClientValidationAdapter when available, so T can be used instead of Partial<T>
validators: ClientValidationAdapter<Partial<T>, Record<string, unknown>> | ValidatorsOption<T>;
validationMethod: 'auto' | 'oninput' | 'onblur' | 'onsubmit' | 'submit-only';
customValidity: boolean;
clearOnSubmit: 'errors' | 'message' | 'errors-and-message' | 'none';
delayMs: number;
timeoutMs: number;
multipleSubmits: 'prevent' | 'allow' | 'abort';
syncFlashMessage?: boolean;
flashMessage: {
module: {
getFlash(page: Readable<Page>): Writable<App.PageData['flash']>;
updateFlash(page: Readable<Page>, update?: () => Promise<void>): Promise<boolean>;
};
onError?: (event: {
result: {
type: 'error';
status?: number;
error: App.Error;
};
flashMessage: Writable<App.PageData['flash']>;
}) => MaybePromise<unknown | void>;
cookiePath?: string;
cookieName?: string;
};
warnings: {
duplicateId?: boolean;
};
/**
* Version 1 compatibilty mode if true.
* Sets resetForm = false and taintedMessage = true.
* Add define: { SUPERFORMS_LEGACY: true } to vite.config.ts to enable globally.
*/
legacy: boolean;
}>;
export type SuperFormSnapshot<
T extends Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = App.Superforms.Message extends never ? any : App.Superforms.Message,
In extends Record<string, unknown> = T
> = SuperFormValidated<T, M, In> & { tainted: TaintedFields<T> | undefined };
type SuperFormData<T extends Record<string, unknown>> = {
subscribe: Readable<T>['subscribe'];
set(this: void, value: T, options?: { taint?: TaintOption }): void;
update(this: void, updater: Updater<T>, options?: { taint?: TaintOption }): void;
};
type SuperFormErrors<T extends Record<string, unknown>> = {
subscribe: Writable<ValidationErrors<T>>['subscribe'];
set(this: void, value: ValidationErrors<T>, options?: { force?: boolean }): void;
update(this: void, updater: Updater<ValidationErrors<T>>, options?: { force?: boolean }): void;
clear: () => void;
};
type ResetOptions<T extends Record<string, unknown>> = {
keepMessage?: boolean;
data?: Partial<T>;
newState?: Partial<T>;
id?: string;
};
// Brackets are required: https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
type Capture<
T extends Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = App.Superforms.Message extends never ? any : App.Superforms.Message
> = [T] extends [T] ? () => SuperFormSnapshot<T, M> : never;
type Restore<
T extends Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = App.Superforms.Message extends never ? any : App.Superforms.Message
> = (snapshot: SuperFormSnapshot<T, M>) => void;
export type SuperForm<
T extends Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = App.Superforms.Message extends never ? any : App.Superforms.Message
> = {
form: SuperFormData<T>;
formId: Writable<string>;
errors: SuperFormErrors<T>;
constraints: Writable<InputConstraints<T>>;
message: Writable<M | undefined>;
tainted: Writable<TaintedFields<T> | undefined>;
submitting: Readable<boolean>;
delayed: Readable<boolean>;
timeout: Readable<boolean>;
/**
* @deprecated posted is inconsistent between server and client validation, and SPA mode. Will be removed in v3. Use a status message or return your own data in the form action to handle form post status.
*/
posted: Readable<boolean>;
allErrors: Readable<{ path: string; messages: string[] }[]>;
options: T extends T ? FormOptions<T, M> : never; // Need this to distribute T so it works with unions
enhance: (el: HTMLFormElement, events?: SuperFormEvents<T, M>) => ReturnType<typeof kitEnhance>;
isTainted: (path?: FormPath<T> | Record<string, unknown> | boolean | undefined) => boolean;
reset: (options?: ResetOptions<T>) => void;
submit: (submitter?: HTMLElement | Event | EventTarget | null) => void;
capture: Capture<T, M>;
restore: T extends T ? Restore<T, M> : never;
validate: <
Out extends Partial<T> = T,
Path extends FormPathLeaves<T> = FormPathLeaves<T>,
In extends Record<string, unknown> = Record<string, unknown>
>(
path: Path,
opts?: ValidateOptions<FormPathType<T, Path>, Out, In>
) => Promise<string[] | undefined>;
validateForm: <
Out extends Partial<T> = T,
In extends Record<string, unknown> = Record<string, unknown>
>(opts?: {
update?: boolean;
schema?: ValidationAdapter<Out, In>;
focusOnError?: boolean;
}) => Promise<SuperFormValidated<T, M, In>>;
};
export type ValidateOptions<
Value,
Out extends Record<string, unknown>,
In extends Record<string, unknown>
> = Partial<{
value: Value;
update: boolean | 'errors' | 'value';
taint: TaintOption;
errors: string | string[];
schema: ValidationAdapter<Out, In>;
}>;
export type ChangeEvent<T extends Record<string, unknown>> =
| {
path: FormPath<T>;
paths: FormPath<T>[];
formElement: HTMLFormElement;
target: Element;
set: <Path extends FormPath<T>>(
path: Path,
value: FormPathType<T, Path>,
options?: ProxyOptions
) => void;
get: <Path extends FormPath<T>>(path: Path) => FormPathType<T, Path>;
}
| {
target: undefined;
paths: FormPath<T>[];
set: <Path extends FormPath<T>>(
path: Path,
value: FormPathType<T, Path>,
options?: ProxyOptions
) => void;
get: <Path extends FormPath<T>>(path: Path) => FormPathType<T, Path>;
};
type FullChangeEvent = {
paths: (string | number | symbol)[][];
immediate?: boolean;
multiple?: boolean;
type?: 'input' | 'blur';
formElement?: HTMLFormElement;
target?: EventTarget;
};
type FormDataOptions = Partial<{
taint: TaintOption | 'ignore';
keepFiles: boolean;
}>;
const formIds = new WeakMap<Page, Set<string | undefined>>();
const initialForms = new WeakMap<
object,
SuperValidated<Record<string, unknown>, unknown, Record<string, unknown>>
>();
const defaultOnError = (event: { result: { error: unknown } }) => {
console.warn(
'Unhandled error caught by Superforms, use onError event to handle it:',
event.result.error
);
};
const defaultFormOptions = {
applyAction: true,
invalidateAll: true,
resetForm: true,
autoFocusOnError: 'detect',
scrollToError: 'smooth',
errorSelector: '[aria-invalid="true"],[data-invalid]',
selectErrorText: false,
stickyNavbar: undefined,
taintedMessage: false,
onSubmit: undefined,
onResult: undefined,
onUpdate: undefined,
onUpdated: undefined,
onError: defaultOnError,
dataType: 'form',
validators: undefined,
customValidity: false,
clearOnSubmit: 'message',
delayMs: 500,
timeoutMs: 8000,
multipleSubmits: 'prevent',
SPA: undefined,
validationMethod: 'auto'
} satisfies FormOptions;
function multipleFormIdError(id: string | undefined) {
return (
`Duplicate form id's found: "${id}". ` +
'Multiple forms will receive the same data. Use the id option to differentiate between them, ' +
'or if this is intended, set the warnings.duplicateId option to false in superForm to disable this warning. ' +
'More information: https://superforms.rocks/concepts/multiple-forms'
);
}
/////////////////////////////////////////////////////////////////////
/**
* V1 compatibilty. resetForm = false and taintedMessage = true
*/
let LEGACY_MODE = false;
try {
// @ts-expect-error Vite define check
if (SUPERFORMS_LEGACY) LEGACY_MODE = true;
} catch {
// No legacy mode defined
}
/**
* Storybook compatibility mode, basically disables the navigating store.
*/
let STORYBOOK_MODE = false;
try {
// @ts-expect-error Storybook check
if (globalThis.STORIES) STORYBOOK_MODE = true;
} catch {
// No Storybook
}
/////////////////////////////////////////////////////////////////////
/**
* Initializes a SvelteKit form, for convenient handling of values, errors and sumbitting data.
* @param {SuperValidated} form Usually data.form from PageData or defaults, but can also be an object with default values, but then constraints won't be available.
* @param {FormOptions} formOptions Configuration for the form.
* @returns {SuperForm} A SuperForm object that can be used in a Svelte component.
* @DCI-context
*/
export function superForm<
T extends Record<string, unknown> = Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
M = App.Superforms.Message extends never ? any : App.Superforms.Message,
In extends Record<string, unknown> = T
>(form: SuperValidated<T, M, In> | T, formOptions?: FormOptions<T, M, In>): SuperForm<T, M> {
// Used in reset
let initialForm: SuperValidated<T, M, In>;
let options = formOptions ?? ({} as FormOptions<T, M, In>);
// To check if a full validator is used when switching options.validators dynamically
let initialValidator: FormOptions<T, M, In>['validators'] | undefined = undefined;
{
if (options.legacy ?? LEGACY_MODE) {
if (options.resetForm === undefined) options.resetForm = false;
if (options.taintedMessage === undefined) options.taintedMessage = true;
}
if (STORYBOOK_MODE) {
if (options.applyAction === undefined) options.applyAction = false;
}
if (typeof options.SPA === 'string') {
// SPA action mode is "passive", no page updates are made.
if (options.invalidateAll === undefined) options.invalidateAll = false;
if (options.applyAction === undefined) options.applyAction = false;
}
initialValidator = options.validators;
options = {
...defaultFormOptions,
...options
};
if (
(options.SPA === true || typeof options.SPA === 'object') &&
options.validators === undefined
) {
console.warn(
'No validators set for superForm in SPA mode. ' +
'Add a validation adapter to the validators option, or set it to false to disable this warning.'
);
}
if (!form) {
throw new SuperFormError(
'No form data sent to superForm. ' +
"Make sure the output from superValidate is used (usually data.form) and that it's not null or undefined. " +
"Alternatively, an object with default values for the form can also be used, but then constraints won't be available."
);
}
if (Context_isValidationObject(form) === false) {
form = {
id: options.id ?? Math.random().toString(36).slice(2, 10),
valid: false,
posted: false,
errors: {},
data: form as T,
shape: shapeFromObject(form)
} satisfies SuperValidated<T, M, In>;
}
form = form as SuperValidated<T, M, In>;
// Assign options.id to form, if it exists
const _initialFormId = (form.id = options.id ?? form.id);
const _currentPage = get(page) ?? (STORYBOOK_MODE ? {} : undefined);
// Check multiple id's
if (browser && options.warnings?.duplicateId !== false) {
if (!formIds.has(_currentPage)) {
formIds.set(_currentPage, new Set([_initialFormId]));
} else {
const currentForms = formIds.get(_currentPage);
if (currentForms?.has(_initialFormId)) {
console.warn(multipleFormIdError(_initialFormId));
} else {
currentForms?.add(_initialFormId);
}
}
}
/**
* Need to clone the form data, in case it's used to populate multiple forms
* and in components that are mounted and destroyed multiple times.
* This also means that it needs to be set here, before it's cloned further below.
*/
if (!initialForms.has(form)) {
initialForms.set(form, form);
}
initialForm = initialForms.get(form) as SuperValidated<T, M, In>;
// Detect if a form is posted without JavaScript.
if (!browser && _currentPage.form && typeof _currentPage.form === 'object') {
const postedData = _currentPage.form;
for (const postedForm of Context_findValidationForms(postedData).reverse()) {
if (postedForm.id == _initialFormId && !initialForms.has(postedForm)) {
// Prevent multiple "posting" that can happen when components are recreated.
initialForms.set(postedData, postedData);
const pageDataForm = form as SuperValidated<T, M, In>;
// Add the missing fields from the page data form
form = postedForm as SuperValidated<T, M, In>;
form.constraints = pageDataForm.constraints;
form.shape = pageDataForm.shape;
// Reset the form if option set and form is valid.
if (
form.valid &&
options.resetForm &&
(options.resetForm === true || options.resetForm())
) {
form = clone(pageDataForm);
form.message = clone(postedForm.message);
}
break;
}
}
} else {
form = clone(initialForm);
}
///// From here, form is properly initialized /////
onDestroy(() => {
Unsubscriptions_unsubscribe();
NextChange_clear();
EnhancedForm_destroy();
for (const events of Object.values(formEvents)) {
events.length = 0;
}
formIds.get(_currentPage)?.delete(_initialFormId);
});
// Check for nested objects, throw if datatype isn't json
if (options.dataType !== 'json') {
const checkForNestedData = (key: string, value: unknown) => {
if (!value || typeof value !== 'object') return;
if (Array.isArray(value)) {
if (value.length > 0) checkForNestedData(key, value[0]);
} else if (
!(value instanceof Date) &&
!(value instanceof File) &&
(!browser || !(value instanceof FileList))
) {
throw new SuperFormError(
`Object found in form field "${key}". ` +
`Set the dataType option to "json" and add use:enhance to use nested data structures. ` +
`More information: https://superforms.rocks/concepts/nested-data`
);
}
};
for (const [key, value] of Object.entries(form.data)) {
checkForNestedData(key, value);
}
}
}
///// Roles ///////////////////////////////////////////////////////
//#region Data
/**
* Container for store data, subscribed to with Unsubscriptions
* to avoid "get" usage.
*/
const __data = {
formId: form.id,
form: clone(form.data),
constraints: form.constraints ?? {},
posted: form.posted,
errors: clone(form.errors),
message: clone(form.message),
tainted: undefined as TaintedFields<T> | undefined,
valid: form.valid,
submitting: false,
shape: form.shape
};
const Data: Readonly<typeof __data> = __data;
//#endregion
//#region FormId
const FormId = writable<string>(options.id ?? form.id);
//#endregion
//#region Context
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const Context = {};
function Context_findValidationForms(data: Record<string, unknown>) {
const forms = Object.values(data).filter(
(v) => Context_isValidationObject(v) !== false
) as SuperValidated<Record<string, unknown>>[];
return forms;
}
/**
* Return false if object isn't a validation object, otherwise the form id,
* which can be an empty string, so always check with === false
*/
function Context_isValidationObject(object: unknown): string | false {
if (!object || typeof object !== 'object') return false;
if (!('valid' in object && 'errors' in object && typeof object.valid === 'boolean')) {
return false;
}
return 'id' in object && typeof object.id === 'string' ? object.id : false;
}
//#endregion
//#region Form
// eslint-disable-next-line dci-lint/grouped-rolemethods
const _formData = writable(form.data);
const Form = {
subscribe: _formData.subscribe,
set: (value: Parameters<typeof _formData.set>[0], options: FormDataOptions = {}) => {
// Need to clone the value, so it won't refer to $page for example.
const newData = clone(value);
Tainted_update(newData, options.taint ?? true);
return _formData.set(newData);
},
update: (updater: Parameters<typeof _formData.update>[0], options: FormDataOptions = {}) => {
return _formData.update((value) => {
// No cloning here, since it's an update
const newData = updater(value);
Tainted_update(newData, options.taint ?? true);
return newData;
});
}
};
function Form_isSPA() {
return options.SPA === true || typeof options.SPA === 'object';
}
async function Form_validate(
opts: {
adapter?: FormOptions<T, M>['validators'];
recheckValidData?: boolean;
formData?: Record<string, unknown>;
} = {}
): Promise<SuperFormValidated<T, M, In>> {
const dataToValidate = opts.formData ?? Data.form;
let errors: ValidationErrors<T> = {};
let status: ValidationResult<Partial<T>>;
const validator = opts.adapter ?? options.validators;
if (typeof validator == 'object') {
// Checking for full validation with the jsonSchema field (doesn't exist in client validators).
if (validator != initialValidator && !('jsonSchema' in validator)) {
throw new SuperFormError(
'Client validation adapter found in options.validators. ' +
'A full adapter must be used when changing validators dynamically, for example "zod" instead of "zodClient".'
);
}
status = await /* @__PURE__ */ validator.validate(dataToValidate);
if (!status.success) {
errors = mapErrors(
status.issues,
validator.shape ?? Data.shape ?? {}
) as ValidationErrors<T>;
} else if (opts.recheckValidData !== false) {
// need to make an additional validation, in case the data has been transformed
return Form_validate({ ...opts, recheckValidData: false });
}
} else {
status = { success: true, data: {} };
}
const data: T = { ...Data.form, ...dataToValidate, ...(status.success ? status.data : {}) };
return {
valid: status.success,
posted: false,
errors,
data,
constraints: Data.constraints,
message: undefined,
id: Data.formId,
shape: Data.shape
};
}
function Form__changeEvent(event: FullChangeEvent) {
if (!options.onChange || !event.paths.length || event.type == 'blur') return;
let changeEvent: ChangeEvent<T>;
const paths = event.paths.map(mergePath) as FormPath<T>[];
if (
event.type &&
event.paths.length == 1 &&
event.formElement &&
event.target instanceof Element
) {
changeEvent = {
path: paths[0],
paths,
formElement: event.formElement,
target: event.target,
set(path, value, options?) {
// Casting trick to make it think it's a SuperForm
fieldProxy({ form: Form } as SuperForm<T>, path, options).set(value);
},
get(path) {
return get(fieldProxy<T, typeof path>(Form, path));
}
};
} else {
changeEvent = {
paths,
target: undefined,
set(path, value, options?) {
// Casting trick to make it think it's a SuperForm
fieldProxy({ form: Form } as SuperForm<T>, path, options).set(value);
},
get(path) {
return get(fieldProxy<T, typeof path>(Form, path));
}
};
}
options.onChange(changeEvent);
}
/**
* Make a client-side validation, updating the form data if successful.
* @param event A change event, from html input or programmatically
* @param force Is true if called from validateForm with update: true
* @param adapter ValidationAdapter, if called from validateForm with schema set
* @returns SuperValidated, or undefined if options prevented validation.
*/
async function Form_clientValidation(
event: FullChangeEvent | null,
force = false,
adapter?: ValidationAdapter<Partial<T>>
) {
if (event) {
if (options.validators == 'clear') {
Errors.update(($errors) => {
setPaths($errors, event.paths, undefined);
return $errors;
});
}
setTimeout(() => Form__changeEvent(event));
}
let skipValidation = false;
if (!force) {
if (options.validationMethod == 'onsubmit' || options.validationMethod == 'submit-only') {
skipValidation = true;
} else if (options.validationMethod == 'onblur' && event?.type == 'input')
skipValidation = true;
else if (options.validationMethod == 'oninput' && event?.type == 'blur')
skipValidation = true;
}
if (skipValidation || !event || !options.validators || options.validators == 'clear') {
if (event?.paths) {
const formElement = event?.formElement ?? EnhancedForm_get();
if (formElement) Form__clearCustomValidity(formElement);
}
return;
}
const result = await Form_validate({ adapter });
// TODO: Add option for always setting result.data?
if (result.valid && (event.immediate || event.type != 'input')) {
Form.set(result.data, { taint: 'ignore' });
}
// Wait for tainted, so object errors can be displayed
await tick();
Form__displayNewErrors(result.errors, event, force);
return result;
}
function Form__clearCustomValidity(formElement: HTMLFormElement) {
const validity = new Map<string, { el: HTMLElement; message: string }>();
if (options.customValidity && formElement) {
for (const el of formElement.querySelectorAll<HTMLElement & { name: string }>(`[name]`)) {
if (typeof el.name !== 'string' || !el.name.length) continue;
const message = 'validationMessage' in el ? String(el.validationMessage) : '';
validity.set(el.name, { el, message });
updateCustomValidity(el, undefined);
}
}
return validity;
}
async function Form__displayNewErrors(
errors: ValidationErrors<T>,
event: FullChangeEvent,
force: boolean
) {
const { type, immediate, multiple, paths } = event;
const previous = Data.errors;
const output: Record<string, unknown> = {};
let validity = new Map<string, { el: HTMLElement; message: string }>();
const formElement = event.formElement ?? EnhancedForm_get();
if (formElement) validity = Form__clearCustomValidity(formElement);
traversePaths(errors, (error) => {
if (!Array.isArray(error.value)) return;
const currentPath = [...error.path];
if (currentPath[currentPath.length - 1] == '_errors') {
currentPath.pop();
}
const joinedPath = currentPath.join('.');
function addError() {
//console.log('Adding error', `[${error.path.join('.')}]`, error.value); //debug
setPaths(output, [error.path], error.value);
if (options.customValidity && isEventError && validity.has(joinedPath)) {
const { el, message } = validity.get(joinedPath)!;
if (message != error.value) {
setTimeout(() => updateCustomValidity(el, error.value));
// Only need one error to display
validity.clear();
}
}
}
if (force) return addError();
const lastPath = error.path[error.path.length - 1];
const isObjectError = lastPath == '_errors';
const isEventError =
error.value &&
paths.some((path) => {
// If array/object, any part of the path can match. If not, exact match is required
return isObjectError
? currentPath && path && currentPath.length > 0 && currentPath[0] == path[0]
: joinedPath == path.join('.');
});
if (isEventError && options.validationMethod == 'oninput') return addError();
// Immediate, non-multiple input should display the errors
if (immediate && !multiple && isEventError) return addError();
// Special case for multiple, which should display errors on blur
// or if any error has existed previously. Tricky UX.
if (multiple) {
// For multi-select, if any error has existed, display all errors
const errorPath = pathExists(get(Errors), error.path.slice(0, -1));
if (errorPath?.value && typeof errorPath?.value == 'object') {
for (const errors of Object.values(errorPath.value)) {
if (Array.isArray(errors)) {
return addError();
}
}
}
}
// If previous error exist, always display
const previousError = pathExists(previous, error.path);
if (previousError && previousError.key in previousError.parent) {
return addError();
}
if (isObjectError) {
// New object errors should be displayed on blur events,
// or the (parent) path is or has been tainted.
if (
options.validationMethod == 'oninput' ||
(type == 'blur' &&
Tainted_hasBeenTainted(mergePath(error.path.slice(0, -1)) as FormPath<T>))
) {
return addError();
}
} else {
// Display text errors on blur, if the event matches the error path
// Also, display errors if the error is in an array an it has been tainted.
if (
type == 'blur' &&
isEventError
//|| (isErrorInArray && Tainted_hasBeenTainted(mergePath(error.path.slice(0, -1)) as FormPath<T>))
) {
return addError();
}
}
});
Errors.set(output as ValidationErrors<T>);
}
function Form_set(data: T, options: FormDataOptions = {}) {
// Check if file fields should be kept, usually when the server returns them as undefined.
// in that case remove the undefined field from the new data.
if (options.keepFiles) {
traversePaths(Data.form, (info) => {
if (
(!browser || !(info.parent instanceof FileList)) &&
(info.value instanceof File || (browser && info.value instanceof FileList))
) {
const dataPath = pathExists(data, info.path);
if (!dataPath || !(dataPath.key in dataPath.parent)) {
setPaths(data, [info.path], info.value);
}
}
});
}
return Form.set(data, options);
}
function Form_shouldReset(validForm: boolean, successActionResult: boolean) {
return (
validForm &&
successActionResult &&
options.resetForm &&
(options.resetForm === true || options.resetForm())
);
}
async function Form_updateFromValidation(form: SuperValidated<T, M, In>, successResult: boolean) {
if (form.valid && successResult && Form_shouldReset(form.valid, successResult)) {
Form_reset({ message: form.message, posted: true });
} else {
rebind({
form,
untaint: successResult,
keepFiles: true,
// Check if the form data should be used for updating, or if the invalidateAll load function should be used:
skipFormData: options.invalidateAll == 'force'
});
}
// onUpdated may check stores, so need to wait for them to update.
if (formEvents.onUpdated.length) {
await tick();
}
// But do not await on onUpdated itself, since we're already finished with the request
for (const event of formEvents.onUpdated) {
event({ form });
}
}
function Form_reset(
opts: Omit<ResetOptions<T>, 'keepMessage'> & {
message?: M;
posted?: boolean;
} = {}
) {
if (opts.newState) initialForm.data = { ...initialForm.data, ...opts.newState };
const resetData = clone(initialForm);
resetData.data = { ...resetData.data, ...opts.data };
if (opts.id !== undefined) resetData.id = opts.id;
rebind({
form: resetData,
untaint: true,
message: opts.message,
keepFiles: false,
posted: opts.posted,
resetted: true
});
}