-
Notifications
You must be signed in to change notification settings - Fork 0
/
listField.ts
272 lines (235 loc) · 8.92 KB
/
listField.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
import { computed, makeAutoObservable, observable, reaction } from "mobx";
import { ListFieldConfig, ObjectConfig } from "src/config";
import { createObjectState, newObjectState, ObjectState, ObjectStateInternal } from "src/fields/objectField";
import { FieldState, InternalSetOpts } from "src/fields/valueField";
import { required, Rule } from "src/rules";
import { fail, isNotUndefined } from "src/utils";
/** Form state for list of children, i.e. `U` is a `Book` in a form with a `books: Book[]`. */
export interface ListFieldState<T, U> extends Omit<FieldState<U[]>, "originalValue"> {
readonly rows: ReadonlyArray<ObjectState<U>>;
add(value: U, index?: number): void;
remove(indexOrValue: number | U): void;
}
export function newListFieldState<T, K extends keyof T, U>(
parentInstance: T,
parentState: () => ObjectState<T>,
key: K,
rules: Rule<readonly ObjectState<U>[]>[],
listConfig: ListFieldConfig<T, U>,
config: ObjectConfig<U>,
maybeAutoSave: () => void,
): ListFieldState<T, U> {
// Keep a map of "item in the parent list" -> "that item's ObjectState"
const rowMap = new Map<U, ObjectStateInternal<U>>();
const _tick = observable({ value: 1 });
const _childTick = observable({ value: 1 });
// this is for dirty checking, not object identity
let originalCopy = [...((parentInstance[key] as any) || [])];
const list = {
key: key as string,
// Our fundamental state of wrapped Us
get value() {
return _tick.value > 0 && _childTick.value > 0 ? ((parentInstance[key] as any) as U[]) : fail();
},
_focused: false,
_readOnly: false,
_loading: false,
get readOnly(): boolean {
return this._readOnly || parentState().readOnly;
},
set readOnly(readOnly: boolean) {
this._readOnly = readOnly;
},
get loading(): boolean {
return this._loading || parentState().loading;
},
set loading(loading: boolean) {
this._loading = loading;
},
set value(v: U[]) {
this.set(v);
},
get dirty(): boolean {
return this.rows.some((r) => r.dirty) || this.hasNewItems();
},
get required(): boolean {
return this.rules.some((rule) => rule === required);
},
get isNewEntity(): boolean {
return parentState().isNewEntity;
},
// private
hasNewItems(): boolean {
const [current, original] = [this.value || [], originalCopy || []];
// Instead of relying on just object identities, we look up each child's state
// in rowMap, because we already dedup/check object identity (i.e. look for id fields)
// when create object states.
const a = current.every((e: any) => {
const state = rowMap.get(e);
return original.some((e) => rowMap.get(e) === state);
});
const b = original.every((e: any) => {
const state = rowMap.get(e);
return current.some((e) => rowMap.get(e) === state);
});
const isSame = a && b;
return !isSame;
},
// And we can derive each value's ObjectState wrapper as needed from the rowMap cache
get rows(): readonly ObjectState<U>[] {
// It's unclear why we need to access _tick.value here, b/c calling `this.value` should
// transitively register us as a dependency on it
if (_tick.value < 0) fail();
// Avoid using `this.value` to avoid registering `_childTick` as a dependency
const value = (parentInstance[key] as any) as U[];
return (value || []).map((child) => {
// Because we're reading from this.value, child will be the proxy version
let childState = rowMap.get(child);
if (!childState) {
childState = newObjectState<U>(
config,
parentState as any,
(list as any) as FieldState<any>,
child,
undefined,
maybeAutoSave,
);
rowMap.set(child, childState);
}
return childState;
});
},
// TODO Should this be true when all rows are touched?
get touched() {
return this.rows.some((r) => r.touched) || this.hasNewItems();
},
set touched(touched: boolean) {
this.rows.forEach((r) => (r.touched = touched));
},
rules,
get valid(): boolean {
const value = this.rows;
// TODO Passing `originalCopy || []` is probably not 100% right
const opts = { value, key: key as string, originalValue: originalCopy || [], object: parentState() };
const collectionValid = this.rules.every((r) => r(opts as any) === undefined);
const entriesValid = this.rows.filter((r) => !(r as any)._considerDeleted()).every((r) => r.valid);
return collectionValid && entriesValid;
},
get errors(): string[] {
if (_tick.value < 0) fail();
const opts = { value: this.rows, key: key as string, originalValue: originalCopy || [], object: parentState() };
return this.rules.map((r) => r(opts as any)).filter(isNotUndefined);
},
get changedValue() {
const result = [] as any;
const hasOpKey = Object.keys(listConfig.config).includes("op");
const hasLegacyOpKey = Object.keys(listConfig.config).some((key) => key === "delete" || key === "remove");
const incremental =
listConfig.update === "incremental" ||
// Implicitly enable incremental mode if we see an op key
(listConfig.update === undefined && (hasOpKey || hasLegacyOpKey));
const exhaustive = !incremental;
this.rows.forEach((r) => {
if (exhaustive || r.dirty || r.isNewEntity) {
const changed = r.changedValue;
// Ensure we have an `op: include` key, following https://joist-orm.io/docs/features/partial-update-apis
if (incremental && hasOpKey) {
(changed as any).op ??= "include";
}
result.push(changed);
}
});
return result;
},
focus() {
this._focused = true;
},
blur() {
this._focused = false;
this.maybeAutoSave();
},
maybeAutoSave() {
this.touched = true;
maybeAutoSave();
},
set(values: U[], opts: InternalSetOpts = {}) {
if (this.readOnly && !opts.resetting && !opts.refreshing) {
throw new Error(`${key} is currently readOnly`);
}
// We should be passed values that are non-proxies.
parentInstance[key] = (values.map((value) => {
let childState = rowMap.get(value);
if (!childState) {
// Look for an existing child (requires having an id key configured)
for (const [, otherState] of rowMap.entries()) {
if ((otherState as any).isSameEntity(value)) {
otherState.set(value, opts);
rowMap.set(value, otherState);
return otherState.value;
}
}
// If we didn't have an existing child, just make a new object state
childState = createObjectState(config, value, { maybeAutoSave });
rowMap.set(value, childState);
}
// Return the already-observable'd value so that our `parent.value[key] = values` doesn't re-proxy things
return childState.value;
}) as any) as T[K];
// Reset originalCopy so that our dirty checks have the right # of rows.
if (opts.refreshing) {
originalCopy = [...((parentInstance[key] as any) || [])];
}
_tick.value++;
},
add(value: U, spliceIndex?: number): void {
// This is called by the user, so value should be a non-proxy value we should keep
const childState = createObjectState(config, value, { maybeAutoSave });
rowMap.set(value, childState);
this.ensureSet();
this.value.splice(typeof spliceIndex === "number" ? spliceIndex : this.value.length, 0, childState.value);
_tick.value++;
maybeAutoSave();
},
remove(indexOrValue: number | U): void {
this.ensureSet();
if (typeof indexOrValue === "number") {
this.value.splice(indexOrValue, 1);
} else {
const index = this.value.findIndex((v) => v === indexOrValue);
if (index > -1) {
this.value.splice(index, 1);
}
}
_tick.value++;
maybeAutoSave();
},
revertChanges() {
if (originalCopy) {
this.set(originalCopy, { resetting: true });
this.rows.forEach((r) => r.revertChanges());
}
},
commitChanges() {
this.rows.forEach((r) => r.commitChanges());
originalCopy = [...((parentInstance[key] as any) || [])];
_tick.value++;
},
ensureSet() {
if (!parentInstance[key]) {
(parentInstance as any)[key] = [];
}
_tick.value++;
},
};
const proxy = makeAutoObservable(list, {
// See other makeAutoObservable comment
value: computed({ equals: () => false }),
}) as any;
// Any time a row's value changes, percolate that to our `.value` (so the callers to our
// `.value` will rerun given the value they saw has deeply changed.)
reaction(
() => proxy.rows.map((r: any) => r.value),
() => _childTick.value++,
);
return proxy;
}