-
Notifications
You must be signed in to change notification settings - Fork 3
/
listAtom.ts
371 lines (323 loc) · 9.47 KB
/
listAtom.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
import {
FieldAtomConfig,
FormAtom,
FormFields,
Validate,
ValidateOn,
ValidateStatus,
formAtom,
walkFields,
} from "form-atoms";
import { Atom, Getter, PrimitiveAtom, Setter, WritableAtom, atom } from "jotai";
import { RESET, atomWithReset, splitAtom } from "jotai/utils";
import {
type ListAtomItems,
type ListAtomValue,
listBuilder,
} from "./listBuilder";
import { ExtendFieldAtom } from "../extendFieldAtom";
// copied from jotai/utils
type SplitAtomAction<Item> =
| {
type: "remove";
atom: PrimitiveAtom<Item>;
}
| {
type: "insert";
value: Item;
before?: PrimitiveAtom<Item>;
}
| {
type: "move";
atom: PrimitiveAtom<Item>;
before?: PrimitiveAtom<Item>;
};
export type ListAtom<
Fields extends ListAtomItems,
Value extends ListAtomValue<Fields>,
> = ExtendFieldAtom<
Value[],
{
empty: Atom<boolean>;
buildItem(): FormAtom<{
fields: Fields;
}>;
_formFields: Atom<Fields[]>;
_formList: PrimitiveAtom<
FormAtom<{
fields: Fields;
}>[]
>;
/**
* A splitAtom() managing adding, removing and moving items in the list.
*/
_splitList: WritableAtom<
PrimitiveAtom<
FormAtom<{
fields: Fields;
}>
>[],
[
SplitAtomAction<
FormAtom<{
fields: Fields;
}>
>,
],
void
>;
}
>;
/**
* @private
*/
export function listAtom<
Fields extends ListAtomItems,
Value extends ListAtomValue<Fields>,
>(
config: {
builder: (value: Value) => Fields;
invalidItemError?: string;
} & Pick<FieldAtomConfig<Value[]>, "name" | "validate" | "value">,
): ListAtom<Fields, Value> {
const nameAtom = atomWithReset(config.name);
const initialValueAtom = atomWithReset<Value | undefined>(undefined);
const formBuilder = listBuilder(config.builder);
function buildItem(): FormAtom<{
fields: Fields;
}> {
return formAtom({ fields: formBuilder() });
}
const _formListAtom = atomWithReset(
formBuilder(config.value).map((fields) => formAtom({ fields })),
);
const _splitListAtom = splitAtom(_formListAtom);
/**
* Unwraps the list of formAtoms, into list of fields of each form.
*/
const _formFieldsAtom = atom((get) => {
const formLists = get(_formListAtom);
return formLists.map((formAtom) => {
const formAtoms = get(formAtom);
const { fields } = get(formAtoms.fields);
return fields;
});
});
const touchedAtom = atomWithReset(false);
const dirtyAtom = atom(false);
const listErrorsAtom = atom<string[]>([]);
const itemErrorsAtom = atom((get) => {
// get errors from the nested forms
const hasInvalidForm = get(_formListAtom)
.map((formAtom) => {
const form = get(formAtom);
let invalid = false;
walkFields(get(form.fields), (field) => {
const atoms = get(field);
const errors = get(atoms.errors);
if (errors.length) {
invalid = true;
return false;
}
});
// does not work with async
// state.get(form.validateStatus) === "invalid";
return invalid;
})
.some((invalid) => invalid);
return hasInvalidForm
? [config.invalidItemError ?? "Some list items contain errors."]
: [];
});
const errorsAtom = atom(
(get) => [...get(listErrorsAtom), ...get(itemErrorsAtom)],
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(_get, _set, _value: string[]) => {
// intentional NO-OP
// the errors atom must be writable, as the `validateAtoms` will write the errors returned from `_validateCallback`
// but we ignore it, as we already manage the `listErrors` internally
},
);
const validateCountAtom = atom(0);
const validateResultAtom = atom<ValidateStatus>("valid");
const refAtom = atom<HTMLFieldSetElement | null>(null);
const emptyAtom = atom((get) => get(_formListAtom).length === 0);
const valueAtom = atom(
(get) => {
const formLists = get(_formListAtom);
return formLists.map((formAtom) => {
const formAtoms = get(formAtom);
const { fields } = get(formAtoms.values);
return fields as Value;
});
},
(
get,
set,
value: Value[] | typeof RESET | ((prev: Value[]) => Value[]), // the function is here just to match the type of FieldAtom!
) => {
if (value === RESET) {
set(_formListAtom, value);
const forms = get(_formListAtom);
for (const form of forms) {
const { reset } = get(form);
set(reset);
}
} else if (Array.isArray(value)) {
set(
_formListAtom,
formBuilder(value).map((fields) => formAtom({ fields })),
);
} else {
throw Error("Writing unsupported value to listFieldAtom value!");
}
},
);
const resetAtom = atom<null, [void], void>(null, (get, set) => {
set(errorsAtom, []);
set(listErrorsAtom, []);
set(touchedAtom, RESET);
set(valueAtom, get(initialValueAtom) ?? RESET);
// Need to set a new pointer to prevent stale validation results
// from being set to state after this invocation.
set(validateCountAtom, (count) => ++count);
set(validateResultAtom, "valid");
});
const validateAtom = atom<null, [] | [ValidateOn], void>(
null,
(get, set, event = "user") => {
async function resolveErrors() {
if (!event) return;
// This pointer prevents a stale validation result from being
// set to state after the most recent invocation of validate.
const ptr = get(validateCountAtom) + 1;
set(validateCountAtom, ptr);
const dirty = get(dirtyAtom);
const value = get(valueAtom);
if (event === "user" || event === "submit") {
set(touchedAtom, true);
}
let errors: string[] = [];
const maybeValidatePromise = config.validate?.({
get,
set,
dirty,
touched: get(touchedAtom),
value,
event: event,
});
if (isPromise(maybeValidatePromise)) {
ptr === get(validateCountAtom) &&
set(validateResultAtom, "validating");
errors = (await maybeValidatePromise) ?? get(errorsAtom);
} else {
errors = maybeValidatePromise ?? get(errorsAtom);
}
if (ptr === get(validateCountAtom)) {
set(errorsAtom, errors);
set(validateResultAtom, errors.length > 0 ? "invalid" : "valid");
}
}
resolveErrors();
},
);
const validateCallback: Validate<Value> = async (state) => {
// run validation for nested forms
await Promise.all(
state
.get(_formListAtom)
.map((formAtom) =>
validateFormFields(
formAtom as any,
state.get,
state.set,
state.event,
),
),
);
// validate the listAtom itself
const listValidate = config.validate?.(state);
const listError = isPromise(listValidate)
? await listValidate
: listValidate;
state.set(listErrorsAtom, listError ?? []);
return state.get(errorsAtom);
};
const listAtoms = {
name: nameAtom,
value: valueAtom,
empty: emptyAtom,
validateStatus: validateResultAtom,
touched: touchedAtom,
dirty: dirtyAtom,
errors: errorsAtom,
reset: resetAtom,
validate: validateAtom,
ref: refAtom,
buildItem,
_validateCount: validateCountAtom,
_validateCallback: validateCallback,
/**
* List private atoms
*/
_splitList: _splitListAtom,
_formList: _formListAtom,
_formFields: _formFieldsAtom,
_initialValue: initialValueAtom,
};
// @ts-expect-error ref with HTMLFieldset is ok
return atom(listAtoms);
}
function isPromise(value: any): value is Promise<any> {
return typeof value === "object" && typeof value.then === "function";
}
// TODO: reuse from formAtoms._validateFields
async function validateFormFields(
formAtom: FormAtom<FormFields>,
get: Getter,
set: Setter,
event: ValidateOn,
) {
const form = get(formAtom);
const fields = get(form.fields);
const promises: Promise<boolean>[] = [];
walkFields(fields, (nextField) => {
async function validate(field: typeof nextField) {
const fieldAtom = get(field);
const value = get(fieldAtom.value);
const dirty = get(fieldAtom.dirty);
// This pointer prevents a stale validation result from being
// set after the most recent validation has been performed.
const ptr = get(fieldAtom._validateCount) + 1;
set(fieldAtom._validateCount, ptr);
if (event === "user" || event === "submit") {
set(fieldAtom.touched, true);
}
const maybePromise = fieldAtom._validateCallback?.({
get,
set,
value,
dirty,
touched: get(fieldAtom.touched),
event,
});
let errors: string[];
if (isPromise(maybePromise)) {
set(fieldAtom.validateStatus, "validating");
errors = (await maybePromise) ?? get(fieldAtom.errors);
} else {
errors = maybePromise ?? get(fieldAtom.errors);
}
if (ptr === get(fieldAtom._validateCount)) {
set(fieldAtom.errors, errors);
set(fieldAtom.validateStatus, errors.length > 0 ? "invalid" : "valid");
}
if (errors && errors.length) {
return false;
}
return true;
}
promises.push(validate(nextField));
});
await Promise.all(promises);
}