@codual/react-native-ui 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +18 -2
- package/dist/announce.d.ts +2 -0
- package/dist/announce.js +8 -0
- package/dist/charts/data.d.ts +32 -0
- package/dist/charts/data.js +13 -0
- package/dist/charts/labels.d.ts +54 -0
- package/dist/charts/labels.js +91 -0
- package/dist/charts/machine.d.ts +62 -0
- package/dist/charts/machine.js +144 -0
- package/dist/charts/points.d.ts +23 -0
- package/dist/charts/points.js +46 -0
- package/dist/charts/summary.d.ts +29 -0
- package/dist/charts/summary.js +45 -0
- package/dist/charts/use-chart-interaction.d.ts +62 -0
- package/dist/charts/use-chart-interaction.js +79 -0
- package/dist/forms/async-checks.d.ts +34 -0
- package/dist/forms/async-checks.js +77 -0
- package/dist/forms/field-errors.d.ts +8 -0
- package/dist/forms/field-errors.js +16 -0
- package/dist/forms/form-types.d.ts +43 -0
- package/dist/forms/form-types.js +2 -0
- package/dist/forms/machine.d.ts +63 -0
- package/dist/forms/machine.js +251 -0
- package/dist/forms/numbers.d.ts +5 -0
- package/dist/forms/numbers.js +83 -0
- package/dist/forms/rules.d.ts +47 -0
- package/dist/forms/rules.js +72 -0
- package/dist/forms/server-errors.d.ts +17 -0
- package/dist/forms/server-errors.js +22 -0
- package/dist/forms/use-form.d.ts +49 -0
- package/dist/forms/use-form.js +61 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +94 -0
- package/dist/lists/PagedList.d.ts +47 -0
- package/dist/lists/PagedList.js +81 -0
- package/dist/lists/controller.d.ts +23 -0
- package/dist/lists/controller.js +20 -0
- package/dist/lists/inverted-list.d.ts +23 -0
- package/dist/lists/inverted-list.js +60 -0
- package/dist/lists/machine.d.ts +81 -0
- package/dist/lists/machine.js +252 -0
- package/dist/lists/newest-end.d.ts +30 -0
- package/dist/lists/newest-end.js +58 -0
- package/dist/lists/paged-content.d.ts +46 -0
- package/dist/lists/paged-content.js +65 -0
- package/dist/lists/paged-list-types.d.ts +56 -0
- package/dist/lists/paged-list-types.js +2 -0
- package/dist/lists/system-footer.d.ts +28 -0
- package/dist/lists/system-footer.js +50 -0
- package/dist/lists/use-paged-list.d.ts +25 -0
- package/dist/lists/use-paged-list.js +34 -0
- package/dist/permissions/access.d.ts +30 -0
- package/dist/permissions/access.js +2 -0
- package/dist/permissions/android-permission.d.ts +52 -0
- package/dist/permissions/android-permission.js +143 -0
- package/dist/permissions/permission.d.ts +69 -0
- package/dist/permissions/permission.js +201 -0
- package/dist/permissions/setup.d.ts +25 -0
- package/dist/permissions/setup.js +41 -0
- package/dist/permissions/status.d.ts +29 -0
- package/dist/permissions/status.js +18 -0
- package/dist/permissions/use-permission.d.ts +23 -0
- package/dist/permissions/use-permission.js +29 -0
- package/dist/purchases/Paywall.d.ts +27 -0
- package/dist/purchases/Paywall.js +28 -0
- package/dist/purchases/paywall-content.d.ts +20 -0
- package/dist/purchases/paywall-content.js +34 -0
- package/dist/purchases/purchases.d.ts +92 -0
- package/dist/purchases/purchases.js +236 -0
- package/dist/purchases/status.d.ts +62 -0
- package/dist/purchases/status.js +25 -0
- package/dist/purchases/store.d.ts +71 -0
- package/dist/purchases/store.js +2 -0
- package/dist/purchases/system-views.d.ts +49 -0
- package/dist/purchases/system-views.js +91 -0
- package/dist/purchases/use-purchases.d.ts +3 -0
- package/dist/purchases/use-purchases.js +8 -0
- package/dist/react-native-iap/iap-purchases.d.ts +24 -0
- package/dist/react-native-iap/iap-purchases.js +90 -0
- package/dist/react-native-iap/iap-store.d.ts +56 -0
- package/dist/react-native-iap/iap-store.js +249 -0
- package/dist/react-native-iap/iap-types.d.ts +12 -0
- package/dist/react-native-iap/iap-types.js +11 -0
- package/dist/react-native-iap/index.d.ts +31 -0
- package/dist/react-native-iap/index.js +24 -0
- package/dist/react-native-permissions/index.d.ts +24 -0
- package/dist/react-native-permissions/index.js +88 -0
- package/dist/screen-states/ScreenStates.d.ts +38 -0
- package/dist/screen-states/ScreenStates.js +69 -0
- package/dist/screen-states/errors.d.ts +9 -0
- package/dist/screen-states/errors.js +24 -0
- package/dist/screen-states/machine.d.ts +97 -0
- package/dist/screen-states/machine.js +172 -0
- package/dist/screen-states/system-views.d.ts +40 -0
- package/dist/screen-states/system-views.js +66 -0
- package/dist/screen-states/use-screen-states.d.ts +23 -0
- package/dist/screen-states/use-screen-states.js +41 -0
- package/dist/search/SearchResults.d.ts +22 -0
- package/dist/search/SearchResults.js +25 -0
- package/dist/search/announcements.d.ts +17 -0
- package/dist/search/announcements.js +31 -0
- package/dist/search/labels.d.ts +15 -0
- package/dist/search/labels.js +14 -0
- package/dist/search/machine.d.ts +65 -0
- package/dist/search/machine.js +241 -0
- package/dist/search/recent-search-sync.d.ts +32 -0
- package/dist/search/recent-search-sync.js +87 -0
- package/dist/search/recent-searches.d.ts +22 -0
- package/dist/search/recent-searches.js +40 -0
- package/dist/search/system-views.d.ts +11 -0
- package/dist/search/system-views.js +16 -0
- package/dist/search/types.d.ts +51 -0
- package/dist/search/types.js +2 -0
- package/dist/search/use-search.d.ts +73 -0
- package/dist/search/use-search.js +123 -0
- package/dist/selection/config.d.ts +34 -0
- package/dist/selection/config.js +13 -0
- package/dist/selection/labels.d.ts +19 -0
- package/dist/selection/labels.js +23 -0
- package/dist/selection/machine.d.ts +80 -0
- package/dist/selection/machine.js +274 -0
- package/dist/selection/snapshot.d.ts +54 -0
- package/dist/selection/snapshot.js +45 -0
- package/dist/selection/state.d.ts +25 -0
- package/dist/selection/state.js +24 -0
- package/dist/selection/system-views.d.ts +11 -0
- package/dist/selection/system-views.js +22 -0
- package/dist/selection/use-selection.d.ts +73 -0
- package/dist/selection/use-selection.js +100 -0
- package/dist/sheets/machine.d.ts +101 -0
- package/dist/sheets/machine.js +213 -0
- package/dist/sheets/use-sheet.d.ts +78 -0
- package/dist/sheets/use-sheet.js +103 -0
- package/dist/victory-native/index.d.ts +37 -0
- package/dist/victory-native/index.js +41 -0
- package/package.json +94 -4
- package/react-native-iap/package.json +4 -0
- package/react-native-permissions/package.json +4 -0
- package/victory-native/package.json +4 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FormMachine = void 0;
|
|
4
|
+
const errors_1 = require("../screen-states/errors");
|
|
5
|
+
const async_checks_1 = require("./async-checks");
|
|
6
|
+
const field_errors_1 = require("./field-errors");
|
|
7
|
+
const server_errors_1 = require("./server-errors");
|
|
8
|
+
/**
|
|
9
|
+
* The state machine behind `useForm`. `source` is read whenever a rule runs, so rules can change between renders;
|
|
10
|
+
* the fields and their order can't.
|
|
11
|
+
*/
|
|
12
|
+
class FormMachine {
|
|
13
|
+
source;
|
|
14
|
+
order;
|
|
15
|
+
snapshot;
|
|
16
|
+
listeners = new Set();
|
|
17
|
+
focused = new Set();
|
|
18
|
+
inputs = new Map();
|
|
19
|
+
refs = new Map();
|
|
20
|
+
checks;
|
|
21
|
+
/** Counts submits and resets, so a reset drops the answer of a submit still running. */
|
|
22
|
+
submits = 0;
|
|
23
|
+
constructor(source, order, initialValues) {
|
|
24
|
+
this.source = source;
|
|
25
|
+
this.order = order;
|
|
26
|
+
const values = Object.fromEntries(order.map((field) => [field, initialValues?.[field] ?? ""]));
|
|
27
|
+
const startingValues = values;
|
|
28
|
+
this.snapshot = {
|
|
29
|
+
values: startingValues,
|
|
30
|
+
startingValues,
|
|
31
|
+
touched: new Set(),
|
|
32
|
+
isSubmitAttempted: false,
|
|
33
|
+
isSubmitting: false,
|
|
34
|
+
submitError: undefined,
|
|
35
|
+
serverErrors: new Map(),
|
|
36
|
+
answers: new Map(),
|
|
37
|
+
};
|
|
38
|
+
this.checks = new async_checks_1.AsyncChecks({
|
|
39
|
+
asyncRule: (field) => this.options(field).asyncRule,
|
|
40
|
+
needsCheck: (field) => this.needsCheck(field),
|
|
41
|
+
checkedValue: (field) => this.checkedValue(field, this.snapshot.values),
|
|
42
|
+
answer: (field, value, message) => this.update({ answers: new Map([...this.snapshot.answers, [field, { value, message }]]) }),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
subscribe = (listener) => {
|
|
46
|
+
this.listeners.add(listener);
|
|
47
|
+
return () => this.listeners.delete(listener);
|
|
48
|
+
};
|
|
49
|
+
getSnapshot = () => this.snapshot;
|
|
50
|
+
/** Stops every async check, as the form unmounts. A running submit carries on. */
|
|
51
|
+
disappear = () => {
|
|
52
|
+
this.checks.cancelAll(this.order);
|
|
53
|
+
};
|
|
54
|
+
setValue = (field, value) => {
|
|
55
|
+
const serverErrors = new Map(this.snapshot.serverErrors);
|
|
56
|
+
serverErrors.delete(field);
|
|
57
|
+
this.update({ values: { ...this.snapshot.values, [field]: value }, serverErrors });
|
|
58
|
+
this.checks.changed(field);
|
|
59
|
+
this.syncChecks();
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Starts the checks other fields now need (a rule matching this one may pass now) and cancels the ones they no
|
|
63
|
+
* longer need (an inactive field). Call after anything that changes which fields need a check.
|
|
64
|
+
*/
|
|
65
|
+
syncChecks = () => {
|
|
66
|
+
for (const field of this.order) {
|
|
67
|
+
const isNeeded = this.needsCheck(field);
|
|
68
|
+
if (isNeeded !== this.checks.isPending(field))
|
|
69
|
+
this.checks.changed(field);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
/** The error to show under the field now, or undefined. */
|
|
73
|
+
error = (field) => {
|
|
74
|
+
if (!this.isActive(field))
|
|
75
|
+
return undefined;
|
|
76
|
+
const serverError = this.snapshot.serverErrors.get(field);
|
|
77
|
+
if (!this.snapshot.isSubmitAttempted && !this.snapshot.touched.has(field))
|
|
78
|
+
return serverError;
|
|
79
|
+
return this.ruleError(field) ?? this.asyncError(field) ?? serverError;
|
|
80
|
+
};
|
|
81
|
+
/** Whether the field's async rule hasn't answered for its value yet: waiting for typing to pause, or running. */
|
|
82
|
+
isChecking = (field) => this.needsCheck(field);
|
|
83
|
+
isValid = () => this.firstInvalid() === undefined;
|
|
84
|
+
isDirty = () => {
|
|
85
|
+
const { values, startingValues } = this.snapshot;
|
|
86
|
+
return this.order.some((field) => this.isActive(field) && this.checkedValue(field, values) !== this.checkedValue(field, startingValues));
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Checks every field, waiting for async rules, and runs `action` with the values as checked if they all pass.
|
|
90
|
+
* Does nothing while a submit runs. Resolves with whether the action ran and succeeded.
|
|
91
|
+
*/
|
|
92
|
+
submit = async (action) => {
|
|
93
|
+
if (this.snapshot.isSubmitting)
|
|
94
|
+
return false;
|
|
95
|
+
this.update({ isSubmitting: true, isSubmitAttempted: true, submitError: undefined });
|
|
96
|
+
const submit = ++this.submits;
|
|
97
|
+
await this.finishChecks();
|
|
98
|
+
if (submit !== this.submits)
|
|
99
|
+
return false;
|
|
100
|
+
const invalid = this.firstInvalid();
|
|
101
|
+
if (invalid !== undefined) {
|
|
102
|
+
this.update({ isSubmitting: false });
|
|
103
|
+
this.focusAndAnnounce(invalid);
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
const submitted = this.snapshot.values;
|
|
107
|
+
try {
|
|
108
|
+
await action(this.checkedValues(submitted));
|
|
109
|
+
if (submit !== this.submits)
|
|
110
|
+
return false;
|
|
111
|
+
this.update({ startingValues: submitted, isSubmitting: false });
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
// A reset while the action ran drops its answer.
|
|
116
|
+
if (submit !== this.submits)
|
|
117
|
+
return false;
|
|
118
|
+
this.update({ isSubmitting: false, ...this.failure(error, submitted) });
|
|
119
|
+
this.focusFirstServerError();
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
/** Puts the starting values back and clears every error, check and the submit error. */
|
|
124
|
+
reset = () => {
|
|
125
|
+
this.checks.cancelAll(this.order);
|
|
126
|
+
this.submits += 1;
|
|
127
|
+
this.update({
|
|
128
|
+
isSubmitting: false,
|
|
129
|
+
values: this.snapshot.startingValues,
|
|
130
|
+
touched: new Set(),
|
|
131
|
+
isSubmitAttempted: false,
|
|
132
|
+
submitError: undefined,
|
|
133
|
+
serverErrors: new Map(),
|
|
134
|
+
answers: new Map(),
|
|
135
|
+
});
|
|
136
|
+
};
|
|
137
|
+
focusChanged(field, isFocused) {
|
|
138
|
+
if (isFocused) {
|
|
139
|
+
this.focused.add(field);
|
|
140
|
+
}
|
|
141
|
+
else if (this.focused.delete(field)) {
|
|
142
|
+
this.leave(field);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Return on the field: Next focuses the next field; Done, on the last, runs `onDone`. Both leave the field. */
|
|
146
|
+
submitEditing(field, onDone) {
|
|
147
|
+
this.leave(field);
|
|
148
|
+
const next = this.fieldAfter(field);
|
|
149
|
+
if (next === undefined)
|
|
150
|
+
onDone?.();
|
|
151
|
+
else
|
|
152
|
+
this.inputs.get(next)?.focus();
|
|
153
|
+
}
|
|
154
|
+
/** The next active field in keyboard order, or undefined for the last. */
|
|
155
|
+
fieldAfter(field) {
|
|
156
|
+
return this.order.slice(this.order.indexOf(field) + 1).find((next) => this.isActive(next));
|
|
157
|
+
}
|
|
158
|
+
/** The field's ref callback, the same one on every render. */
|
|
159
|
+
ref(field) {
|
|
160
|
+
let ref = this.refs.get(field);
|
|
161
|
+
if (ref === undefined) {
|
|
162
|
+
ref = (input) => {
|
|
163
|
+
if (input === null)
|
|
164
|
+
this.inputs.delete(field);
|
|
165
|
+
else
|
|
166
|
+
this.inputs.set(field, input);
|
|
167
|
+
};
|
|
168
|
+
this.refs.set(field, ref);
|
|
169
|
+
}
|
|
170
|
+
return ref;
|
|
171
|
+
}
|
|
172
|
+
/** Runs every check a field needs now, again while edits replace them, until none is needed. */
|
|
173
|
+
async finishChecks() {
|
|
174
|
+
while (this.order.some((field) => this.needsCheck(field))) {
|
|
175
|
+
await Promise.all(this.order.map((field) => this.checks.now(field)));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
leave(field) {
|
|
179
|
+
if (!this.snapshot.touched.has(field))
|
|
180
|
+
this.update({ touched: new Set([...this.snapshot.touched, field]) });
|
|
181
|
+
void this.checks.now(field);
|
|
182
|
+
}
|
|
183
|
+
failure(error, submitted) {
|
|
184
|
+
if ((0, errors_1.isAbortError)(error))
|
|
185
|
+
return {};
|
|
186
|
+
if (!(error instanceof field_errors_1.FormFieldErrors))
|
|
187
|
+
return { submitError: { error } };
|
|
188
|
+
const { serverErrors, leftover } = (0, server_errors_1.serverErrorsFor)(error.messages, {
|
|
189
|
+
fields: this.order.filter((field) => this.isActive(field)),
|
|
190
|
+
isUnchanged: (field) => this.snapshot.values[field] === submitted[field],
|
|
191
|
+
});
|
|
192
|
+
return { serverErrors, ...(leftover === undefined ? {} : { submitError: { error: leftover } }) };
|
|
193
|
+
}
|
|
194
|
+
focusFirstServerError() {
|
|
195
|
+
const field = this.order.find((candidate) => this.snapshot.serverErrors.has(candidate));
|
|
196
|
+
if (field !== undefined)
|
|
197
|
+
this.focusAndAnnounce(field);
|
|
198
|
+
}
|
|
199
|
+
focusAndAnnounce(field) {
|
|
200
|
+
this.inputs.get(field)?.focus();
|
|
201
|
+
const message = this.error(field);
|
|
202
|
+
if (message !== undefined)
|
|
203
|
+
this.source().announce(message);
|
|
204
|
+
}
|
|
205
|
+
firstInvalid() {
|
|
206
|
+
return this.order.find((field) => this.isActive(field) &&
|
|
207
|
+
(this.snapshot.serverErrors.has(field) ||
|
|
208
|
+
this.ruleError(field) !== undefined ||
|
|
209
|
+
this.asyncError(field) !== undefined ||
|
|
210
|
+
this.needsCheck(field)));
|
|
211
|
+
}
|
|
212
|
+
isActive(field) {
|
|
213
|
+
return this.options(field).active !== false;
|
|
214
|
+
}
|
|
215
|
+
ruleError(field) {
|
|
216
|
+
const values = this.checkedValues(this.snapshot.values);
|
|
217
|
+
const value = values[field];
|
|
218
|
+
return this.options(field).rules?.find((rule) => !rule.isValid(value, values))?.message;
|
|
219
|
+
}
|
|
220
|
+
asyncError(field) {
|
|
221
|
+
const answer = this.snapshot.answers.get(field);
|
|
222
|
+
return answer?.value === this.checkedValue(field, this.snapshot.values) ? answer.message : undefined;
|
|
223
|
+
}
|
|
224
|
+
needsCheck(field) {
|
|
225
|
+
if (!this.isActive(field) || this.options(field).asyncRule === undefined)
|
|
226
|
+
return false;
|
|
227
|
+
if (this.ruleError(field) !== undefined)
|
|
228
|
+
return false;
|
|
229
|
+
const value = this.checkedValue(field, this.snapshot.values);
|
|
230
|
+
if (value === this.checkedValue(field, this.snapshot.startingValues))
|
|
231
|
+
return false;
|
|
232
|
+
return this.snapshot.answers.get(field)?.value !== value;
|
|
233
|
+
}
|
|
234
|
+
checkedValues(values) {
|
|
235
|
+
const checked = Object.fromEntries(this.order.map((field) => [field, this.checkedValue(field, values)]));
|
|
236
|
+
return checked;
|
|
237
|
+
}
|
|
238
|
+
checkedValue(field, values) {
|
|
239
|
+
const value = values[field];
|
|
240
|
+
return this.options(field).trim === false ? value : value.trim();
|
|
241
|
+
}
|
|
242
|
+
options(field) {
|
|
243
|
+
return this.source().fields[field];
|
|
244
|
+
}
|
|
245
|
+
update(change) {
|
|
246
|
+
this.snapshot = { ...this.snapshot, ...change };
|
|
247
|
+
for (const listener of this.listeners)
|
|
248
|
+
listener();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
exports.FormMachine = FormMachine;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The number `text` writes in `locale` (the device's by default): "1,200.5" in English and "1.200,5" in German
|
|
3
|
+
* are both 1200.5. Undefined for anything else, a grouping separator in the wrong place ("1,5" in English) included.
|
|
4
|
+
*/
|
|
5
|
+
export declare function parseNumber(text: string, locale?: string): number | undefined;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseNumber = parseNumber;
|
|
4
|
+
const DIGITS = /^[0-9]+$/;
|
|
5
|
+
const SIGNS = new Set(["-", "+", "−"]);
|
|
6
|
+
const SPACE_LIKE = [" ", "\u00a0", "\u202f"];
|
|
7
|
+
const APOSTROPHE_LIKE = ["'", "’"];
|
|
8
|
+
const SAMPLE = 12345.6;
|
|
9
|
+
const FALLBACK = { decimal: ".", grouping: [","] };
|
|
10
|
+
// Every group after the first has three digits, so "1,5" is never 15.
|
|
11
|
+
const GROUP_LENGTH = 3;
|
|
12
|
+
const separatorsByLocale = new Map();
|
|
13
|
+
/**
|
|
14
|
+
* The number `text` writes in `locale` (the device's by default): "1,200.5" in English and "1.200,5" in German
|
|
15
|
+
* are both 1200.5. Undefined for anything else, a grouping separator in the wrong place ("1,5" in English) included.
|
|
16
|
+
*/
|
|
17
|
+
function parseNumber(text, locale) {
|
|
18
|
+
const trimmed = text.trim();
|
|
19
|
+
const sign = SIGNS.has(trimmed.charAt(0)) ? trimmed.charAt(0) : "";
|
|
20
|
+
const unsigned = trimmed.slice(sign.length);
|
|
21
|
+
const separators = localeSeparators(locale);
|
|
22
|
+
const [integer = "", fraction, ...rest] = unsigned.split(separators.decimal);
|
|
23
|
+
if (rest.length > 0)
|
|
24
|
+
return undefined;
|
|
25
|
+
const integerDigits = groupedDigits(integer, separators.grouping);
|
|
26
|
+
if (integerDigits === undefined)
|
|
27
|
+
return undefined;
|
|
28
|
+
if (fraction !== undefined && !DIGITS.test(fraction))
|
|
29
|
+
return undefined;
|
|
30
|
+
if (integerDigits === "" && fraction === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
const magnitude = Number(`${integerDigits || "0"}.${fraction ?? "0"}`);
|
|
33
|
+
return sign === "-" || sign === "−" ? -magnitude : magnitude;
|
|
34
|
+
}
|
|
35
|
+
/** The digits of an integer part, with its grouping separators checked and removed; "" for none. */
|
|
36
|
+
function groupedDigits(integer, grouping) {
|
|
37
|
+
if (integer === "")
|
|
38
|
+
return "";
|
|
39
|
+
const groups = splitOnAny(integer, grouping);
|
|
40
|
+
if (!groups.every((group) => DIGITS.test(group)))
|
|
41
|
+
return undefined;
|
|
42
|
+
if (groups.length === 1)
|
|
43
|
+
return integer;
|
|
44
|
+
const [first = "", ...rest] = groups;
|
|
45
|
+
if (first.length === 0 || first.length > GROUP_LENGTH)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (rest.some((group) => group.length !== GROUP_LENGTH))
|
|
48
|
+
return undefined;
|
|
49
|
+
return groups.join("");
|
|
50
|
+
}
|
|
51
|
+
function splitOnAny(text, separators) {
|
|
52
|
+
let groups = [text];
|
|
53
|
+
for (const separator of separators)
|
|
54
|
+
groups = groups.flatMap((group) => group.split(separator));
|
|
55
|
+
return groups;
|
|
56
|
+
}
|
|
57
|
+
function localeSeparators(locale) {
|
|
58
|
+
const key = locale ?? "";
|
|
59
|
+
const cached = separatorsByLocale.get(key);
|
|
60
|
+
if (cached !== undefined)
|
|
61
|
+
return cached;
|
|
62
|
+
const separators = readSeparators(locale);
|
|
63
|
+
separatorsByLocale.set(key, separators);
|
|
64
|
+
return separators;
|
|
65
|
+
}
|
|
66
|
+
/** The locale's separators, from `Intl` where the JavaScript engine has it; "." and "," otherwise. */
|
|
67
|
+
function readSeparators(locale) {
|
|
68
|
+
if (typeof Intl === "undefined" || typeof Intl.NumberFormat.prototype.formatToParts !== "function") {
|
|
69
|
+
return FALLBACK;
|
|
70
|
+
}
|
|
71
|
+
const parts = new Intl.NumberFormat(locale).formatToParts(SAMPLE);
|
|
72
|
+
const decimal = parts.find((part) => part.type === "decimal")?.value ?? FALLBACK.decimal;
|
|
73
|
+
const grouping = parts.find((part) => part.type === "group")?.value;
|
|
74
|
+
return { decimal, grouping: grouping === undefined ? [] : equivalentSeparators(grouping) };
|
|
75
|
+
}
|
|
76
|
+
/** People type a plain space for a non-breaking one, and `'` for `’`. */
|
|
77
|
+
function equivalentSeparators(grouping) {
|
|
78
|
+
if (SPACE_LIKE.includes(grouping))
|
|
79
|
+
return SPACE_LIKE;
|
|
80
|
+
if (APOSTROPHE_LIKE.includes(grouping))
|
|
81
|
+
return APOSTROPHE_LIKE;
|
|
82
|
+
return [grouping];
|
|
83
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Every field's value, as checked: trimmed unless the field keeps spaces. */
|
|
2
|
+
export type FormValues<F extends string> = Readonly<Record<F, string>>;
|
|
3
|
+
/** A rule a field's value must pass, and the message shown under the field when it doesn't. */
|
|
4
|
+
export interface FormRule<F extends string> {
|
|
5
|
+
readonly message: string;
|
|
6
|
+
/** Gets the field's value and every field's value, as checked. */
|
|
7
|
+
readonly isValid: (value: string, values: FormValues<F>) => boolean;
|
|
8
|
+
}
|
|
9
|
+
/** A rule that asks something else, such as the server, whether a value is fine. */
|
|
10
|
+
export interface AsyncFormRule {
|
|
11
|
+
/** Resolves with the message to show, or undefined when the value is fine. Abort the work when `signal` aborts. */
|
|
12
|
+
readonly check: (value: string, signal: AbortSignal) => Promise<string | undefined>;
|
|
13
|
+
/** How long typing must pause before the check runs. */
|
|
14
|
+
readonly debounceMs: number;
|
|
15
|
+
}
|
|
16
|
+
export interface AsyncFormRuleOptions {
|
|
17
|
+
/** How long typing must pause before the check runs, in milliseconds: 500 by default. */
|
|
18
|
+
readonly debounceMs?: number;
|
|
19
|
+
}
|
|
20
|
+
/** The app's own rule. It runs on an empty value too. Name the fields, `rule<Field>(…)`, to type `values`. */
|
|
21
|
+
export declare function rule<F extends string = string>(message: string, isValid: (value: string, values: FormValues<F>) => boolean): FormRule<F>;
|
|
22
|
+
/** Fails on an empty value, and on one that is only spaces or new lines, even in a field that keeps spaces. */
|
|
23
|
+
export declare function required(message: string): FormRule<never>;
|
|
24
|
+
/** At least `length` characters, as people see them. An empty value passes. */
|
|
25
|
+
export declare function minLength(length: number, message: string): FormRule<never>;
|
|
26
|
+
/** At most `length` characters, as people see them. An empty value passes. */
|
|
27
|
+
export declare function maxLength(length: number, message: string): FormRule<never>;
|
|
28
|
+
/** `regex` matches the whole value. An empty value passes. */
|
|
29
|
+
export declare function pattern(regex: RegExp, message: string): FormRule<never>;
|
|
30
|
+
/** One `@`, a name before it, and a domain with a dot after it. An empty value passes. */
|
|
31
|
+
export declare function email(message: string): FormRule<never>;
|
|
32
|
+
export interface NumberRuleOptions {
|
|
33
|
+
/** The lowest value allowed, inclusive. */
|
|
34
|
+
readonly min?: number;
|
|
35
|
+
/** The highest value allowed, inclusive. */
|
|
36
|
+
readonly max?: number;
|
|
37
|
+
/** The locale the number is written in; the device's by default. */
|
|
38
|
+
readonly locale?: string;
|
|
39
|
+
}
|
|
40
|
+
/** A number as `locale` writes it ("1,200.5" in English), within `min` and `max`. An empty value passes. */
|
|
41
|
+
export declare function number(message: string, options?: NumberRuleOptions): FormRule<never>;
|
|
42
|
+
/** The same value as the field `other`, as each is checked. Empty doesn't pass unless `other` is empty too. */
|
|
43
|
+
export declare function matches<F extends string>(other: F, message: string): FormRule<F>;
|
|
44
|
+
/** A rule checked by `check`, after typing pauses (500 ms by default) and only once the field's rules pass. */
|
|
45
|
+
export declare function asyncRule(check: (value: string, signal: AbortSignal) => Promise<string | undefined>, options?: AsyncFormRuleOptions): AsyncFormRule;
|
|
46
|
+
/** Characters as people see them, with `Intl.Segmenter` where the engine has it; code points otherwise. */
|
|
47
|
+
export declare function characterCount(value: string): number;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.rule = rule;
|
|
4
|
+
exports.required = required;
|
|
5
|
+
exports.minLength = minLength;
|
|
6
|
+
exports.maxLength = maxLength;
|
|
7
|
+
exports.pattern = pattern;
|
|
8
|
+
exports.email = email;
|
|
9
|
+
exports.number = number;
|
|
10
|
+
exports.matches = matches;
|
|
11
|
+
exports.asyncRule = asyncRule;
|
|
12
|
+
exports.characterCount = characterCount;
|
|
13
|
+
const numbers_1 = require("./numbers");
|
|
14
|
+
const DEFAULT_DEBOUNCE_MS = 500;
|
|
15
|
+
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s.]+$/;
|
|
16
|
+
const DISALLOWED_PATTERN_FLAGS = /[gmy]/g;
|
|
17
|
+
/** The app's own rule. It runs on an empty value too. Name the fields, `rule<Field>(…)`, to type `values`. */
|
|
18
|
+
function rule(message, isValid) {
|
|
19
|
+
return { message, isValid };
|
|
20
|
+
}
|
|
21
|
+
/** Fails on an empty value, and on one that is only spaces or new lines, even in a field that keeps spaces. */
|
|
22
|
+
function required(message) {
|
|
23
|
+
return rule(message, (value) => value.trim() !== "");
|
|
24
|
+
}
|
|
25
|
+
/** At least `length` characters, as people see them. An empty value passes. */
|
|
26
|
+
function minLength(length, message) {
|
|
27
|
+
return unlessEmpty(message, (value) => characterCount(value) >= length);
|
|
28
|
+
}
|
|
29
|
+
/** At most `length` characters, as people see them. An empty value passes. */
|
|
30
|
+
function maxLength(length, message) {
|
|
31
|
+
return unlessEmpty(message, (value) => characterCount(value) <= length);
|
|
32
|
+
}
|
|
33
|
+
/** `regex` matches the whole value. An empty value passes. */
|
|
34
|
+
function pattern(regex, message) {
|
|
35
|
+
// A global or sticky regex keeps its place between tests, and a multiline one anchors at each line.
|
|
36
|
+
const whole = new RegExp(`^(?:${regex.source})$`, regex.flags.replace(DISALLOWED_PATTERN_FLAGS, ""));
|
|
37
|
+
return unlessEmpty(message, (value) => whole.test(value));
|
|
38
|
+
}
|
|
39
|
+
/** One `@`, a name before it, and a domain with a dot after it. An empty value passes. */
|
|
40
|
+
function email(message) {
|
|
41
|
+
return unlessEmpty(message, (value) => EMAIL.test(value));
|
|
42
|
+
}
|
|
43
|
+
/** A number as `locale` writes it ("1,200.5" in English), within `min` and `max`. An empty value passes. */
|
|
44
|
+
function number(message, options = {}) {
|
|
45
|
+
const { min = -Infinity, max = Infinity, locale } = options;
|
|
46
|
+
return unlessEmpty(message, (value) => {
|
|
47
|
+
const parsed = (0, numbers_1.parseNumber)(value, locale);
|
|
48
|
+
return parsed !== undefined && parsed >= min && parsed <= max;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** The same value as the field `other`, as each is checked. Empty doesn't pass unless `other` is empty too. */
|
|
52
|
+
function matches(other, message) {
|
|
53
|
+
return rule(message, (value, values) => value === values[other]);
|
|
54
|
+
}
|
|
55
|
+
/** A rule checked by `check`, after typing pauses (500 ms by default) and only once the field's rules pass. */
|
|
56
|
+
function asyncRule(check, options = {}) {
|
|
57
|
+
return { check, debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS };
|
|
58
|
+
}
|
|
59
|
+
function unlessEmpty(message, isValid) {
|
|
60
|
+
return rule(message, (value) => value === "" || isValid(value));
|
|
61
|
+
}
|
|
62
|
+
let segmenter;
|
|
63
|
+
/** Characters as people see them, with `Intl.Segmenter` where the engine has it; code points otherwise. */
|
|
64
|
+
function characterCount(value) {
|
|
65
|
+
if (typeof Intl === "undefined" || typeof Intl.Segmenter !== "function")
|
|
66
|
+
return Array.from(value).length;
|
|
67
|
+
segmenter ??= new Intl.Segmenter();
|
|
68
|
+
let count = 0;
|
|
69
|
+
for (const _ of segmenter.segment(value))
|
|
70
|
+
count += 1;
|
|
71
|
+
return count;
|
|
72
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { FormFieldErrors } from "./field-errors";
|
|
2
|
+
export interface ServerErrorFields<F extends string> {
|
|
3
|
+
/** The fields that can show an error, in keyboard order: the active ones. */
|
|
4
|
+
readonly fields: readonly F[];
|
|
5
|
+
/** Whether the field still has the value the server answered for. */
|
|
6
|
+
readonly isUnchanged: (field: F) => boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface MappedServerErrors<F extends string> {
|
|
9
|
+
readonly serverErrors: ReadonlyMap<F, string>;
|
|
10
|
+
/** The messages for no field that can show one, as the submit error; undefined when there are none. */
|
|
11
|
+
readonly leftover: FormFieldErrors<string> | undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Splits the server's field errors into those shown under their fields and the rest, which become the submit
|
|
15
|
+
* error so none is lost. An error for a field changed while the submit ran is dropped: its value is new.
|
|
16
|
+
*/
|
|
17
|
+
export declare function serverErrorsFor<F extends string>(messages: Readonly<Partial<Record<string, string>>>, { fields, isUnchanged }: ServerErrorFields<F>): MappedServerErrors<F>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.serverErrorsFor = serverErrorsFor;
|
|
4
|
+
const field_errors_1 = require("./field-errors");
|
|
5
|
+
/**
|
|
6
|
+
* Splits the server's field errors into those shown under their fields and the rest, which become the submit
|
|
7
|
+
* error so none is lost. An error for a field changed while the submit ran is dropped: its value is new.
|
|
8
|
+
*/
|
|
9
|
+
function serverErrorsFor(messages, { fields, isUnchanged }) {
|
|
10
|
+
const shown = new Set(fields);
|
|
11
|
+
const serverErrors = new Map();
|
|
12
|
+
for (const field of fields) {
|
|
13
|
+
const message = messages[field];
|
|
14
|
+
if (message !== undefined && isUnchanged(field))
|
|
15
|
+
serverErrors.set(field, message);
|
|
16
|
+
}
|
|
17
|
+
const rest = Object.entries(messages).filter((entry) => entry[1] !== undefined && !shown.has(entry[0]));
|
|
18
|
+
return {
|
|
19
|
+
serverErrors,
|
|
20
|
+
leftover: rest.length === 0 ? undefined : new field_errors_1.FormFieldErrors(Object.fromEntries(rest)),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Focusable, FormFields, SubmitAction, SubmitError } from "./form-types";
|
|
2
|
+
export interface FormOptions<F extends string> {
|
|
3
|
+
/** Every field with its rules, in keyboard order. The fields can't change; their rules can. */
|
|
4
|
+
readonly fields: FormFields<F>;
|
|
5
|
+
/** The values the fields start with, such as the profile being edited. Others start empty. */
|
|
6
|
+
readonly initialValues?: Readonly<Partial<Record<NoInfer<F>, string>>>;
|
|
7
|
+
}
|
|
8
|
+
export interface FormFieldHelperOptions {
|
|
9
|
+
/** Runs when Done is pressed on the last field: usually the submit. */
|
|
10
|
+
readonly onDone?: () => void;
|
|
11
|
+
}
|
|
12
|
+
/** Spread on a `TextInput`: `<TextInput {...form.field("email")} />`. */
|
|
13
|
+
export interface FormTextInputProps {
|
|
14
|
+
readonly ref: (input: Focusable | null) => void;
|
|
15
|
+
readonly value: string;
|
|
16
|
+
readonly onChangeText: (text: string) => void;
|
|
17
|
+
readonly onFocus: () => void;
|
|
18
|
+
readonly onBlur: () => void;
|
|
19
|
+
readonly returnKeyType: "next" | "done";
|
|
20
|
+
readonly submitBehavior: "submit" | "blurAndSubmit";
|
|
21
|
+
readonly onSubmitEditing: () => void;
|
|
22
|
+
/** The field's shown error, read by screen readers with the field. */
|
|
23
|
+
readonly accessibilityHint?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface FormController<F extends string> {
|
|
26
|
+
/** What is in each field, as typed. */
|
|
27
|
+
readonly values: Readonly<Record<F, string>>;
|
|
28
|
+
readonly isSubmitting: boolean;
|
|
29
|
+
/** The last submit's failure, when it wasn't for a field; cleared by the next submit. */
|
|
30
|
+
readonly submitError: SubmitError | undefined;
|
|
31
|
+
/** Every field passes, and no async rule is still checking. */
|
|
32
|
+
readonly isValid: boolean;
|
|
33
|
+
/** A value differs from its starting one (as checked). */
|
|
34
|
+
readonly isDirty: boolean;
|
|
35
|
+
/** Dirty and not submitting: ask before closing the screen only when this is true. */
|
|
36
|
+
readonly shouldConfirmDiscard: boolean;
|
|
37
|
+
readonly error: (field: F) => string | undefined;
|
|
38
|
+
readonly isChecking: (field: F) => boolean;
|
|
39
|
+
readonly setValue: (field: F, value: string) => void;
|
|
40
|
+
/** Runs `action` once, with the values as checked, if every field passes; resolves with whether it succeeded. */
|
|
41
|
+
readonly submit: (action: SubmitAction<F>) => Promise<boolean>;
|
|
42
|
+
readonly reset: () => void;
|
|
43
|
+
readonly field: (field: F, options?: FormFieldHelperOptions) => FormTextInputProps;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A form's values, errors and submit, for the app's own `TextInput`s, error texts and buttons. Errors show once a
|
|
47
|
+
* field is left or a submit is tried; a submit runs once at a time. Async checks stop on unmount.
|
|
48
|
+
*/
|
|
49
|
+
export declare function useForm<F extends string>(options: FormOptions<F>): FormController<F>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useForm = useForm;
|
|
4
|
+
const react_1 = require("react");
|
|
5
|
+
const react_native_1 = require("react-native");
|
|
6
|
+
const machine_1 = require("./machine");
|
|
7
|
+
/**
|
|
8
|
+
* A form's values, errors and submit, for the app's own `TextInput`s, error texts and buttons. Errors show once a
|
|
9
|
+
* field is left or a submit is tried; a submit runs once at a time. Async checks stop on unmount.
|
|
10
|
+
*/
|
|
11
|
+
function useForm(options) {
|
|
12
|
+
const source = {
|
|
13
|
+
fields: options.fields,
|
|
14
|
+
// Queued on iOS, after whatever VoiceOver is saying; Android's TalkBack queues announcements anyway.
|
|
15
|
+
announce: (message) => react_native_1.AccessibilityInfo.announceForAccessibilityWithOptions(message, { queue: true }),
|
|
16
|
+
};
|
|
17
|
+
const latest = (0, react_1.useRef)(source);
|
|
18
|
+
// Set while rendering, not after: what this render shows (errors, validity, return keys) reads this render's
|
|
19
|
+
// rules and active fields.
|
|
20
|
+
latest.current = source;
|
|
21
|
+
const [machine] = (0, react_1.useState)(() => new machine_1.FormMachine(() => latest.current, fieldOrder(options.fields), options.initialValues));
|
|
22
|
+
const snapshot = (0, react_1.useSyncExternalStore)(machine.subscribe, machine.getSnapshot);
|
|
23
|
+
(0, react_1.useEffect)(() => machine.disappear, [machine]);
|
|
24
|
+
const activeFields = machine.order.filter((field) => options.fields[field].active !== false).join("\n");
|
|
25
|
+
(0, react_1.useEffect)(() => machine.syncChecks(), [machine, activeFields]);
|
|
26
|
+
const isDirty = machine.isDirty();
|
|
27
|
+
return {
|
|
28
|
+
values: snapshot.values,
|
|
29
|
+
isSubmitting: snapshot.isSubmitting,
|
|
30
|
+
submitError: snapshot.submitError,
|
|
31
|
+
isValid: machine.isValid(),
|
|
32
|
+
isDirty,
|
|
33
|
+
shouldConfirmDiscard: isDirty && !snapshot.isSubmitting,
|
|
34
|
+
error: machine.error,
|
|
35
|
+
isChecking: machine.isChecking,
|
|
36
|
+
setValue: machine.setValue,
|
|
37
|
+
submit: machine.submit,
|
|
38
|
+
reset: machine.reset,
|
|
39
|
+
field: (field, helperOptions = {}) => textInputProps(machine, field, helperOptions),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function fieldOrder(fields) {
|
|
43
|
+
const keys = Object.keys(fields);
|
|
44
|
+
return keys.filter((key) => key in fields);
|
|
45
|
+
}
|
|
46
|
+
function textInputProps(machine, field, { onDone }) {
|
|
47
|
+
const isLast = machine.fieldAfter(field) === undefined;
|
|
48
|
+
const error = machine.error(field);
|
|
49
|
+
return {
|
|
50
|
+
ref: machine.ref(field),
|
|
51
|
+
value: machine.getSnapshot().values[field],
|
|
52
|
+
onChangeText: (text) => machine.setValue(field, text),
|
|
53
|
+
onFocus: () => machine.focusChanged(field, true),
|
|
54
|
+
onBlur: () => machine.focusChanged(field, false),
|
|
55
|
+
returnKeyType: isLast ? "done" : "next",
|
|
56
|
+
// "submit" keeps the keyboard up on Next while focus moves; the last field closes it.
|
|
57
|
+
submitBehavior: isLast ? "blurAndSubmit" : "submit",
|
|
58
|
+
onSubmitEditing: () => machine.submitEditing(field, onDone),
|
|
59
|
+
...(error === undefined ? {} : { accessibilityHint: error }),
|
|
60
|
+
};
|
|
61
|
+
}
|