@frontile/forms 0.17.0-beta.25 → 0.17.0-beta.26
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/declarations/components/checkbox-group.d.ts +3 -1
- package/declarations/components/checkbox.d.ts +2 -0
- package/declarations/components/field-types.d.ts +14 -0
- package/declarations/components/field.d.ts +85 -0
- package/declarations/components/form-control.d.ts +1 -0
- package/declarations/components/form.d.ts +244 -8
- package/declarations/components/input.d.ts +5 -0
- package/declarations/components/radio-group.d.ts +1 -1
- package/declarations/components/radio.d.ts +2 -0
- package/declarations/components/select.d.ts +211 -5
- package/declarations/components/switch.d.ts +21 -16
- package/declarations/components/textarea.d.ts +2 -0
- package/declarations/index.d.ts +3 -0
- package/declarations/utils/index.d.ts +1 -0
- package/declarations/utils/nested-data.d.ts +44 -0
- package/declarations/utils/standard-validator.d.ts +151 -0
- package/dist/_app_/components/field-types.js +1 -0
- package/dist/_app_/components/field.js +1 -0
- package/dist/components/checkbox-group.js +1 -1
- package/dist/components/checkbox-group.js.map +1 -1
- package/dist/components/checkbox.js +8 -2
- package/dist/components/checkbox.js.map +1 -1
- package/dist/components/field-types.js +2 -0
- package/dist/components/field-types.js.map +1 -0
- package/dist/components/field.js +103 -0
- package/dist/components/field.js.map +1 -0
- package/dist/components/form-control.js.map +1 -1
- package/dist/components/form.js +12 -29
- package/dist/components/form.js.map +1 -1
- package/dist/components/input.js +8 -2
- package/dist/components/input.js.map +1 -1
- package/dist/components/native-select.js +1 -1
- package/dist/components/radio-group.js +1 -1
- package/dist/components/radio-group.js.map +1 -1
- package/dist/components/radio.js +8 -2
- package/dist/components/radio.js.map +1 -1
- package/dist/components/select.js +159 -18
- package/dist/components/select.js.map +1 -1
- package/dist/components/switch.js +5 -2
- package/dist/components/switch.js.map +1 -1
- package/dist/components/textarea.js +8 -2
- package/dist/components/textarea.js.map +1 -1
- package/dist/form-CVuJDJUq.js +726 -0
- package/dist/form-CVuJDJUq.js.map +1 -0
- package/dist/form-Dzyb1-8B.js +623 -0
- package/dist/form-Dzyb1-8B.js.map +1 -0
- package/dist/index-CeaQc-U7.js.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/runtime-BPCpkOf1-B5Lbloj7.js +67 -0
- package/dist/runtime-BPCpkOf1-B5Lbloj7.js.map +1 -0
- package/dist/test-support.js +2 -2
- package/dist/test-support.js.map +1 -1
- package/package.json +10 -7
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
import Component from '@glimmer/component';
|
|
2
|
+
import { tracked } from '@glimmer/tracking';
|
|
3
|
+
import { action } from '@ember/object';
|
|
4
|
+
import { hash } from '@ember/helper';
|
|
5
|
+
import { on } from '@ember/modifier';
|
|
6
|
+
import { ref } from '@frontile/utilities';
|
|
7
|
+
import { dataFrom } from 'form-data-utils';
|
|
8
|
+
import { Field } from './components/field.js';
|
|
9
|
+
import { precompileTemplate } from '@ember/template-compilation';
|
|
10
|
+
import { setComponentTemplate } from '@ember/component';
|
|
11
|
+
import { d as decorateFieldV2, i as initializeDeferredDecorator, a as decorateMethodV2 } from './runtime-BPCpkOf1-B5Lbloj7.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Utility functions for working with nested data structures in forms.
|
|
15
|
+
* These functions convert between nested objects and flat dotted-path notation.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Type guard to check if a value is a plain object (not an array, Date, File, etc.)
|
|
20
|
+
*/
|
|
21
|
+
function isPlainObject(value) {
|
|
22
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof File) && !(value instanceof FileList);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Flattens a nested object into a flat object with dotted-path keys.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* flattenData({name: {first: 'John', last: 'Doe'}, email: 'john@example.com'})
|
|
30
|
+
* // Returns: {'name.first': 'John', 'name.last': 'Doe', 'email': 'john@example.com'}
|
|
31
|
+
*
|
|
32
|
+
* @param data - The nested data object to flatten
|
|
33
|
+
* @param prefix - Internal parameter for recursion (parent path)
|
|
34
|
+
* @returns A flat object with dotted-path keys
|
|
35
|
+
*/
|
|
36
|
+
function flattenData(data, prefix = '') {
|
|
37
|
+
const result = {};
|
|
38
|
+
for (const key in data) {
|
|
39
|
+
if (!Object.prototype.hasOwnProperty.call(data, key)) {
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const value = data[key];
|
|
43
|
+
const fullPath = prefix ? `${prefix}.${key}` : key;
|
|
44
|
+
if (isPlainObject(value)) {
|
|
45
|
+
// Recursively flatten nested objects
|
|
46
|
+
Object.assign(result, flattenData(value, fullPath));
|
|
47
|
+
} else {
|
|
48
|
+
// Store primitive values, arrays, and special objects as-is
|
|
49
|
+
result[fullPath] = value;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Unflattens a flat object with dotted-path keys into a nested object structure.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* unflattenData({'name.first': 'John', 'name.last': 'Doe', 'email': 'john@example.com'})
|
|
60
|
+
* // Returns: {name: {first: 'John', last: 'Doe'}, email: 'john@example.com'}
|
|
61
|
+
*
|
|
62
|
+
* @param data - The flat data object with dotted-path keys
|
|
63
|
+
* @returns A nested object structure
|
|
64
|
+
*/
|
|
65
|
+
function unflattenData(data) {
|
|
66
|
+
const result = {};
|
|
67
|
+
for (const path in data) {
|
|
68
|
+
if (!Object.prototype.hasOwnProperty.call(data, path)) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const value = data[path];
|
|
72
|
+
const keys = path.split('.');
|
|
73
|
+
let current = result;
|
|
74
|
+
|
|
75
|
+
// Navigate/create nested structure
|
|
76
|
+
for (let i = 0; i < keys.length - 1; i++) {
|
|
77
|
+
const key = keys[i];
|
|
78
|
+
if (!key) continue;
|
|
79
|
+
if (!isPlainObject(current[key])) {
|
|
80
|
+
current[key] = {};
|
|
81
|
+
}
|
|
82
|
+
current = current[key];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Set the final value
|
|
86
|
+
const lastKey = keys[keys.length - 1];
|
|
87
|
+
if (lastKey) {
|
|
88
|
+
current[lastKey] = value;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return result;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Checks if the data structure contains any nested objects.
|
|
96
|
+
* If true, we need to handle it as nested data.
|
|
97
|
+
*
|
|
98
|
+
* @param data - The data object to check
|
|
99
|
+
* @returns True if the data contains nested plain objects
|
|
100
|
+
*/
|
|
101
|
+
function hasNestedData(data) {
|
|
102
|
+
for (const key in data) {
|
|
103
|
+
if (Object.prototype.hasOwnProperty.call(data, key)) {
|
|
104
|
+
if (isPlainObject(data[key])) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Deep equality comparison for nested objects.
|
|
114
|
+
* Handles primitives, arrays, and nested objects.
|
|
115
|
+
*
|
|
116
|
+
* @param a - First value to compare
|
|
117
|
+
* @param b - Second value to compare
|
|
118
|
+
* @returns True if values are deeply equal
|
|
119
|
+
*/
|
|
120
|
+
function deepEqual(a, b) {
|
|
121
|
+
// Handle primitives and same reference
|
|
122
|
+
if (a === b) return true;
|
|
123
|
+
|
|
124
|
+
// Handle null/undefined
|
|
125
|
+
if (a == null || b == null) return a === b;
|
|
126
|
+
|
|
127
|
+
// Handle different types
|
|
128
|
+
if (typeof a !== typeof b) return false;
|
|
129
|
+
|
|
130
|
+
// Handle arrays
|
|
131
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
132
|
+
if (a.length !== b.length) return false;
|
|
133
|
+
return a.every((item, index) => deepEqual(item, b[index]));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Handle plain objects
|
|
137
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
138
|
+
const keysA = Object.keys(a);
|
|
139
|
+
const keysB = Object.keys(b);
|
|
140
|
+
if (keysA.length !== keysB.length) return false;
|
|
141
|
+
return keysA.every(key => deepEqual(a[key], b[key]));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Handle special objects (Date, File, etc.) - compare by reference
|
|
145
|
+
return a === b;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The issues collection returned by a Standard Schema validation failure.
|
|
150
|
+
*/
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The return type of a validator function.
|
|
154
|
+
* Resolves to the issues (when validation fails) or undefined
|
|
155
|
+
* (when it succeeds).
|
|
156
|
+
*/
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* StandardSchemaV1 issues as either a promise or synchronous. If there are
|
|
160
|
+
* no issues, `undefined` is returned.
|
|
161
|
+
*/
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A custom validator function.
|
|
165
|
+
* If there are errors, they are returned by the validator as
|
|
166
|
+
* StandardSchemaV1 issues. If there are no errors, nothing is returned.
|
|
167
|
+
*/
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Provides convenience methods for validating data using Standard Schema.
|
|
171
|
+
* Also supports custom validator functions that return issues in the
|
|
172
|
+
* Standard Schema format.
|
|
173
|
+
*
|
|
174
|
+
* Most of the time you should use `validateAll` or `validateFieldAll` to
|
|
175
|
+
* validate data. Schema and custom validation are optional arguments
|
|
176
|
+
* to these methods. This is useful because schema and custom validation
|
|
177
|
+
* must both be optional in the form component, which is the primary use
|
|
178
|
+
* case for this class.
|
|
179
|
+
*
|
|
180
|
+
* Note: all methods are static, so you do not need to instantiate
|
|
181
|
+
* this class.
|
|
182
|
+
*
|
|
183
|
+
* @see https://standardschema.dev/
|
|
184
|
+
*/
|
|
185
|
+
class StandardValidator {
|
|
186
|
+
constructor() {
|
|
187
|
+
throw new Error('StandardValidator is static and cannot be instantiated');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Validates data against the provided standard schema.
|
|
192
|
+
* If there are errors, they are returned. Otherwise, nothing is returned.
|
|
193
|
+
* This provides a boolean indication of outcome: if there is a return
|
|
194
|
+
* value, validation failed. Otherwise, validation succeeded.
|
|
195
|
+
* @see https://standardschema.dev/
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* const input = …; // your data to validate
|
|
199
|
+
* const schema = …; // your standard schema
|
|
200
|
+
* const issues = await StandardValidator.validate(input, schema);
|
|
201
|
+
*
|
|
202
|
+
* @param input The input to validate.
|
|
203
|
+
* @param schema The standard schema to validate against.
|
|
204
|
+
* @return The issues if validation failed, otherwise undefined.
|
|
205
|
+
*/
|
|
206
|
+
static async validate(input, schema) {
|
|
207
|
+
const result = await schema['~standard'].validate(input);
|
|
208
|
+
return result.issues;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Validates a single field within the input data using the provided
|
|
213
|
+
* standard schema. If there are issues related to the specified field,
|
|
214
|
+
* they are returned. Otherwise, nothing is returned.
|
|
215
|
+
*
|
|
216
|
+
* Note: because standard schema does not provide a way to validate
|
|
217
|
+
* individual fields, this method filters the issues returned by the
|
|
218
|
+
* schema validation to find those related to the specified field.
|
|
219
|
+
* @see https://standardschema.dev/
|
|
220
|
+
*
|
|
221
|
+
* @param input The input data to validate.
|
|
222
|
+
* @param fieldName The name of the field to validate.
|
|
223
|
+
* @param schema The standard schema to validate against.
|
|
224
|
+
* @returns The issues related to the specified field if validation failed,
|
|
225
|
+
* otherwise undefined.
|
|
226
|
+
*/
|
|
227
|
+
static async validateField(input, fieldName, schema) {
|
|
228
|
+
const issues = await StandardValidator.validate(input, schema);
|
|
229
|
+
if (issues) {
|
|
230
|
+
return StandardValidator.filterFieldIssues(issues, fieldName);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Validates input using a custom validator function.
|
|
236
|
+
* If there are errors, they are returned by the validator as
|
|
237
|
+
* StandardSchemaV1 issues. If there are no errors, nothing is returned.
|
|
238
|
+
* @see https://standardschema.dev/
|
|
239
|
+
*
|
|
240
|
+
* @param input The input data to validate.
|
|
241
|
+
* @param customValidator The custom validator function to use.
|
|
242
|
+
* @returns The issues if validation failed, otherwise undefined.
|
|
243
|
+
*/
|
|
244
|
+
static async validateCustom(input, customValidator) {
|
|
245
|
+
return await customValidator(input);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Validates a single field within the input data using a custom validator
|
|
250
|
+
* function. If there are issues related to the specified field, they are
|
|
251
|
+
* returned. Otherwise, nothing is returned.
|
|
252
|
+
*
|
|
253
|
+
* Note: because custom validators may return issues for multiple fields,
|
|
254
|
+
* this method filters the issues returned by the custom validator to find
|
|
255
|
+
* those related to the specified field.
|
|
256
|
+
* @see https://standardschema.dev/
|
|
257
|
+
*
|
|
258
|
+
* @param input The input data to validate.
|
|
259
|
+
* @param fieldName The name of the field to validate.
|
|
260
|
+
* @param customValidator The custom validator function to use.
|
|
261
|
+
* @returns The issues related to the specified field if validation failed,
|
|
262
|
+
* otherwise undefined.
|
|
263
|
+
*/
|
|
264
|
+
static async validateFieldCustom(input, fieldName, customValidator) {
|
|
265
|
+
const issues = await StandardValidator.validateCustom(input, customValidator);
|
|
266
|
+
if (issues) {
|
|
267
|
+
return StandardValidator.filterFieldIssues(issues, fieldName);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Validates input data using both a standard schema and a custom validator
|
|
273
|
+
* function, merging any issues found by either method. If there are issues,
|
|
274
|
+
* they are returned. Otherwise, nothing is returned. This method runs both
|
|
275
|
+
* validations in parallel.
|
|
276
|
+
*
|
|
277
|
+
* Note: `schema` and `customValidator` are both optional. If either the
|
|
278
|
+
* schema or custom validator is not provided, that validation is skipped.
|
|
279
|
+
* @see https://standardschema.dev/
|
|
280
|
+
*
|
|
281
|
+
* @param input The input data to validate.
|
|
282
|
+
* @param schema Optional standard schema to validate against.
|
|
283
|
+
* @param customValidator Optional custom validator function to use.
|
|
284
|
+
* @returns issues if validation failed, otherwise undefined.
|
|
285
|
+
*/
|
|
286
|
+
static async validateAll(input, schema, customValidator) {
|
|
287
|
+
const standardIssues = schema && StandardValidator.validate(input, schema);
|
|
288
|
+
const customIssues = customValidator && StandardValidator.validateCustom(input, customValidator);
|
|
289
|
+
const [s, c] = await Promise.all([standardIssues, customIssues]);
|
|
290
|
+
if (s || c) {
|
|
291
|
+
return [...(s ?? []), ...(c ?? [])];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Validates a single field within the input data using both a standard
|
|
297
|
+
* schema and a custom validator function, merging any issues found by
|
|
298
|
+
* either method. If there are issues related to the specified field,
|
|
299
|
+
* they are returned. Otherwise, nothing is returned. This method runs
|
|
300
|
+
* both validations in parallel.
|
|
301
|
+
*
|
|
302
|
+
* Note: `schema` and `customValidator` are both optional. If either the
|
|
303
|
+
* schema or custom validator is not provided, that validation is skipped.
|
|
304
|
+
* @see https://standardschema.dev/
|
|
305
|
+
*
|
|
306
|
+
* @param input The input data to validate.
|
|
307
|
+
* @param fieldName The name of the field to validate.
|
|
308
|
+
* @param schema Optional standard schema to validate against.
|
|
309
|
+
* @param customValidator Optional custom validator function to use.
|
|
310
|
+
* @returns The issues related to the specified field if validation failed,
|
|
311
|
+
* otherwise undefined.
|
|
312
|
+
*/
|
|
313
|
+
static async validateFieldAll(input, fieldName, schema, customValidator) {
|
|
314
|
+
const standardIssues = schema && StandardValidator.validateField(input, fieldName, schema);
|
|
315
|
+
const customIssues = customValidator && StandardValidator.validateFieldCustom(input, fieldName, customValidator);
|
|
316
|
+
const [s, c] = await Promise.all([standardIssues, customIssues]);
|
|
317
|
+
if (s || c) {
|
|
318
|
+
return [...(s ?? []), ...(c ?? [])];
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Filters issues to those related to the specified field name.
|
|
324
|
+
* Supports both simple field names and dotted notation for nested fields.
|
|
325
|
+
*
|
|
326
|
+
* @param issues The issues to filter.
|
|
327
|
+
* @param fieldName The name of the field to filter by (e.g., "email" or
|
|
328
|
+
* "profile.contact.email").
|
|
329
|
+
* @returns The issues related to the specified field, or undefined if
|
|
330
|
+
* there are none.
|
|
331
|
+
*/
|
|
332
|
+
static filterFieldIssues(issues, fieldName) {
|
|
333
|
+
const fieldParts = fieldName.split('.');
|
|
334
|
+
const fieldIssues = issues.filter(issue => {
|
|
335
|
+
if (!issue.path) return false;
|
|
336
|
+
|
|
337
|
+
// Extract keys from path segments
|
|
338
|
+
const pathKeys = issue.path.map(s => typeof s === 'object' && 'key' in s ? s.key : s).filter(Boolean);
|
|
339
|
+
|
|
340
|
+
// For exact path matching:
|
|
341
|
+
// The paths must be the same length and match exactly
|
|
342
|
+
return pathKeys.length === fieldParts.length && pathKeys.every((key, i) => key === fieldParts[i]);
|
|
343
|
+
});
|
|
344
|
+
return fieldIssues.length > 0 ? fieldIssues : undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* A form component that handles form submissions and input changes.
|
|
350
|
+
*
|
|
351
|
+
* @example
|
|
352
|
+
* ```hbs
|
|
353
|
+
* <Form
|
|
354
|
+
* @data={{this.formData}}
|
|
355
|
+
* @schema={{this.schema}}
|
|
356
|
+
* @validate={{this.customValidator}}
|
|
357
|
+
* @onSubmit={{this.onSubmit}}
|
|
358
|
+
* @onChange={{this.onChange}}
|
|
359
|
+
* as |form|
|
|
360
|
+
* >
|
|
361
|
+
* <form.Field name="firstName" as |field|>
|
|
362
|
+
* <field.Input />
|
|
363
|
+
* </form.Field>
|
|
364
|
+
* <form.Field name="lastName" as |field|>
|
|
365
|
+
* <field.Input />
|
|
366
|
+
* </form.Field>
|
|
367
|
+
* <button type="submit" disabled={{form.isLoading}}>
|
|
368
|
+
* {{#if form.isLoading}}Submitting...{{else}}Submit{{/if}}
|
|
369
|
+
* </button>
|
|
370
|
+
* </Form>
|
|
371
|
+
* ```
|
|
372
|
+
*/
|
|
373
|
+
class Form extends Component {
|
|
374
|
+
static {
|
|
375
|
+
decorateFieldV2(this.prototype, "isLoading", [tracked], function () {
|
|
376
|
+
return false;
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
#isLoading = (initializeDeferredDecorator(this, "isLoading"), void 0);
|
|
380
|
+
/** Whether the form is currently submitting. */
|
|
381
|
+
static {
|
|
382
|
+
decorateFieldV2(this.prototype, "errors", [tracked], function () {
|
|
383
|
+
return {};
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
#errors = (initializeDeferredDecorator(this, "errors"), void 0);
|
|
387
|
+
/** The current form validation errors. */
|
|
388
|
+
static {
|
|
389
|
+
decorateFieldV2(this.prototype, "uncontrolledData", [tracked]);
|
|
390
|
+
}
|
|
391
|
+
#uncontrolledData = (initializeDeferredDecorator(this, "uncontrolledData"), void 0);
|
|
392
|
+
/** The current uncontrolled form data. */
|
|
393
|
+
static {
|
|
394
|
+
decorateFieldV2(this.prototype, "initialDataSnapshot", [tracked]);
|
|
395
|
+
}
|
|
396
|
+
#initialDataSnapshot = (initializeDeferredDecorator(this, "initialDataSnapshot"), void 0);
|
|
397
|
+
/**
|
|
398
|
+
* Flattened snapshot of initial data for dirty field comparison.
|
|
399
|
+
* Stored in flattened form regardless of whether source data is nested or flat.
|
|
400
|
+
*/
|
|
401
|
+
static {
|
|
402
|
+
decorateFieldV2(this.prototype, "dirty", [tracked], function () {
|
|
403
|
+
return new Set();
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
#dirty = (initializeDeferredDecorator(this, "dirty"), void 0);
|
|
407
|
+
/**
|
|
408
|
+
* The set of fields that have changed from their initial values.
|
|
409
|
+
* For flat data structures: contains top-level keys (e.g., "firstName", "email")
|
|
410
|
+
* For nested data structures: contains dotted paths (e.g., "user.name.first", "profile.email")
|
|
411
|
+
*/
|
|
412
|
+
/** Reference to the form element. */element = ref();
|
|
413
|
+
/**
|
|
414
|
+
* Creates a new instance of the Form component.
|
|
415
|
+
* Initializes internal state based on provided args.
|
|
416
|
+
* @param owner - The owner of the component.
|
|
417
|
+
* @param args - The arguments passed to the component.
|
|
418
|
+
*/
|
|
419
|
+
constructor(owner, args) {
|
|
420
|
+
super(owner, args);
|
|
421
|
+
// Create copy of initial data
|
|
422
|
+
if (args.data) {
|
|
423
|
+
// Always store flattened snapshot for dirty tracking
|
|
424
|
+
// This ensures consistent comparison regardless of initial structure
|
|
425
|
+
this.initialDataSnapshot = flattenData(args.data);
|
|
426
|
+
// Keep uncontrolled data in original structure
|
|
427
|
+
this.uncontrolledData = {
|
|
428
|
+
...args.data
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/** Whether the form is valid (i.e. has no validation errors). */
|
|
433
|
+
get isValid() {
|
|
434
|
+
return Object.keys(this.errors).length === 0;
|
|
435
|
+
}
|
|
436
|
+
/** Whether the form is invalid (i.e. has validation errors). */
|
|
437
|
+
get isInvalid() {
|
|
438
|
+
return !this.isValid;
|
|
439
|
+
}
|
|
440
|
+
/** Whether the form is controlled (`onChange` is provided). */
|
|
441
|
+
get isControlled() {
|
|
442
|
+
return !!this.args.onChange;
|
|
443
|
+
}
|
|
444
|
+
/** The events on which validation should run. */
|
|
445
|
+
get validateOn() {
|
|
446
|
+
return this.args.validateOn ?? ['change', 'blur', 'submit'];
|
|
447
|
+
}
|
|
448
|
+
/** The events on which field-level validation should run. */
|
|
449
|
+
get fieldValidateOn() {
|
|
450
|
+
return this.validateOn.filter(e => e !== 'submit');
|
|
451
|
+
}
|
|
452
|
+
/** The current form data, from args if controlled, or internal state if uncontrolled. */
|
|
453
|
+
get currentData() {
|
|
454
|
+
if (this.isControlled) {
|
|
455
|
+
return this.args.data;
|
|
456
|
+
}
|
|
457
|
+
return this.uncontrolledData;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Validates data against the provided schema using StandardValidator.
|
|
461
|
+
* Updates the `errors` property with any validation errors found.
|
|
462
|
+
*
|
|
463
|
+
* @param data - The form data to validate.
|
|
464
|
+
* @returns A promise that resolves to the validation errors, if any.
|
|
465
|
+
*/
|
|
466
|
+
async validate(data) {
|
|
467
|
+
// Run validator and get issues
|
|
468
|
+
const errors = await StandardValidator.validateAll(data, this.args.schema, this.args.validate);
|
|
469
|
+
// Convert validator errors to FormErrors
|
|
470
|
+
if (errors) {
|
|
471
|
+
const formErrors = validatorToFormErrors(errors);
|
|
472
|
+
this.errors = formErrors;
|
|
473
|
+
return formErrors;
|
|
474
|
+
}
|
|
475
|
+
// Clear errors if no issues
|
|
476
|
+
this.errors = {};
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Validates a single field against the provided schema using
|
|
480
|
+
* StandardValidator. Updates the `errors` property with any validation
|
|
481
|
+
* errors found for the field. If the field had previous errors but
|
|
482
|
+
* is now valid, those errors are cleared.
|
|
483
|
+
*
|
|
484
|
+
* @param data - The form data to validate against.
|
|
485
|
+
* @param name - The name of the field to validate.
|
|
486
|
+
* @returns A promise that resolves to errors for the field, if any.
|
|
487
|
+
*/
|
|
488
|
+
async validateField(data, name) {
|
|
489
|
+
if (!this.args.schema && !this.args.validate) {
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
// Run validator and get issues
|
|
493
|
+
const errors = await StandardValidator.validateFieldAll(data, name, this.args.schema, this.args.validate);
|
|
494
|
+
// Convert validator errors to FormErrors
|
|
495
|
+
if (errors) {
|
|
496
|
+
const formErrors = validatorToFormErrors(errors);
|
|
497
|
+
if (formErrors[name]) {
|
|
498
|
+
// Merge with existing errors immutably
|
|
499
|
+
this.errors = {
|
|
500
|
+
...this.errors,
|
|
501
|
+
[name]: formErrors[name]
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
return {
|
|
505
|
+
[name]: formErrors[name]
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
// Clear field error if no issues
|
|
509
|
+
// Remove field error using immutable pattern:
|
|
510
|
+
// 1. Use destructuring to extract the field we want to remove
|
|
511
|
+
// (assigned to '_' since unused)
|
|
512
|
+
// 2. Capture all remaining fields in 'rest' using the spread operator
|
|
513
|
+
// 3. Reassign this.errors to the 'rest' object, effectively removing
|
|
514
|
+
// the field
|
|
515
|
+
// This approach maintains immutability by creating a new object rather than
|
|
516
|
+
// mutating the existing errors object with 'delete'
|
|
517
|
+
if (this.errors[name]) {
|
|
518
|
+
const {
|
|
519
|
+
[name]: _,
|
|
520
|
+
...rest
|
|
521
|
+
} = this.errors;
|
|
522
|
+
this.errors = rest;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Computes which fields have changed from their initial values.
|
|
527
|
+
* Uses deep comparison for consistency across flat and nested structures.
|
|
528
|
+
* This is a pure function with no side effects.
|
|
529
|
+
*
|
|
530
|
+
* @param data - The current form data.
|
|
531
|
+
* @returns A set of field names that have changed.
|
|
532
|
+
*/
|
|
533
|
+
static {
|
|
534
|
+
decorateMethodV2(this.prototype, "validateField", [action]);
|
|
535
|
+
}
|
|
536
|
+
computeDirtyFields(data) {
|
|
537
|
+
const dirty = new Set();
|
|
538
|
+
if (!this.initialDataSnapshot) {
|
|
539
|
+
return dirty;
|
|
540
|
+
}
|
|
541
|
+
// Flatten current data to same representation as snapshot
|
|
542
|
+
const currentFlat = flattenData(data);
|
|
543
|
+
// Compare all keys in current data
|
|
544
|
+
for (const key in currentFlat) {
|
|
545
|
+
if (!deepEqual(currentFlat[key], this.initialDataSnapshot[key])) {
|
|
546
|
+
dirty.add(key);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
// Check for keys in initial data that are missing in current data
|
|
550
|
+
for (const key in this.initialDataSnapshot) {
|
|
551
|
+
if (!(key in currentFlat) && this.initialDataSnapshot[key] !== undefined) {
|
|
552
|
+
dirty.add(key);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return dirty;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Builds the form result data object to pass to callbacks.
|
|
559
|
+
* Also updates the dirty state as a side effect.
|
|
560
|
+
*
|
|
561
|
+
* @param data - The current form data.
|
|
562
|
+
* @returns The form result data object.
|
|
563
|
+
*/
|
|
564
|
+
buildFormResultData(data) {
|
|
565
|
+
const {
|
|
566
|
+
isValid,
|
|
567
|
+
isInvalid,
|
|
568
|
+
errors
|
|
569
|
+
} = this;
|
|
570
|
+
const dirty = this.computeDirtyFields(data);
|
|
571
|
+
this.dirty = dirty; // Update tracked state
|
|
572
|
+
return {
|
|
573
|
+
data,
|
|
574
|
+
isValid,
|
|
575
|
+
isInvalid,
|
|
576
|
+
errors,
|
|
577
|
+
dirty
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Handles the `input` event on the form element.
|
|
582
|
+
* Calls the `onChange` callback with the current form data if provided.
|
|
583
|
+
* Automatically unflattens dotted field names to nested structure.
|
|
584
|
+
*/
|
|
585
|
+
handleInput(event) {
|
|
586
|
+
const form = event.currentTarget;
|
|
587
|
+
if (form instanceof HTMLFormElement) {
|
|
588
|
+
let data = dataFrom(event);
|
|
589
|
+
// Always unflatten form data to handle dotted field names
|
|
590
|
+
// This is safe for flat data too - keys without dots remain unchanged
|
|
591
|
+
data = unflattenData(data);
|
|
592
|
+
const resultData = this.buildFormResultData(data);
|
|
593
|
+
this.uncontrolledData = data;
|
|
594
|
+
this.args.onChange?.(resultData, event);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* Handles the `submit` event on the form element.
|
|
599
|
+
* Prevents the default form submission and calls the `onSubmit` callback
|
|
600
|
+
* with the current form data. Manages the `isLoading` state during the
|
|
601
|
+
* submission process. Automatically unflattens dotted field names to nested structure.
|
|
602
|
+
*/
|
|
603
|
+
static {
|
|
604
|
+
decorateMethodV2(this.prototype, "handleInput", [action]);
|
|
605
|
+
}
|
|
606
|
+
async handleSubmit(event) {
|
|
607
|
+
event.preventDefault();
|
|
608
|
+
const form = event.currentTarget;
|
|
609
|
+
if (form instanceof HTMLFormElement) {
|
|
610
|
+
this.isLoading = true;
|
|
611
|
+
let data = dataFrom(event);
|
|
612
|
+
// Always unflatten form data to handle dotted field names
|
|
613
|
+
// This is safe for flat data too - keys without dots remain unchanged
|
|
614
|
+
data = unflattenData(data);
|
|
615
|
+
let errors;
|
|
616
|
+
if (this.validateOn.includes('submit')) {
|
|
617
|
+
errors = await this.validate(data);
|
|
618
|
+
}
|
|
619
|
+
const resultData = this.buildFormResultData(data);
|
|
620
|
+
this.uncontrolledData = data;
|
|
621
|
+
try {
|
|
622
|
+
if (errors && this.args.onError) {
|
|
623
|
+
// Call onError handler when there are validation errors
|
|
624
|
+
await this.args.onError(errors, data, event);
|
|
625
|
+
} else if (!errors && this.args.onSubmit) {
|
|
626
|
+
// Run `onSubmit` if validation was skipped OR if validation passed
|
|
627
|
+
await this.args.onSubmit(resultData, event);
|
|
628
|
+
// Update snapshot on successful submit (new baseline)
|
|
629
|
+
this.initialDataSnapshot = flattenData(data);
|
|
630
|
+
// Clear dirty state since we've updated the baseline
|
|
631
|
+
this.dirty = new Set();
|
|
632
|
+
}
|
|
633
|
+
} finally {
|
|
634
|
+
this.isLoading = false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Handles the `reset` event on the form element.
|
|
640
|
+
* Clears validation errors and dirty tracking.
|
|
641
|
+
* Restores the form data to its initial state.
|
|
642
|
+
* Calls `onChange` if the form is controlled to let parent update state.
|
|
643
|
+
*/
|
|
644
|
+
static {
|
|
645
|
+
decorateMethodV2(this.prototype, "handleSubmit", [action]);
|
|
646
|
+
}
|
|
647
|
+
handleReset(event) {
|
|
648
|
+
// Clear state
|
|
649
|
+
this.errors = {};
|
|
650
|
+
this.dirty = new Set();
|
|
651
|
+
// Restore initial data
|
|
652
|
+
if (this.initialDataSnapshot) {
|
|
653
|
+
// Unflatten data if it was nested
|
|
654
|
+
const restoredData = unflattenData(this.initialDataSnapshot);
|
|
655
|
+
// For controlled forms, call onChange to let parent update state
|
|
656
|
+
if (this.isControlled && this.args.onChange) {
|
|
657
|
+
const resultData = this.buildFormResultData(restoredData);
|
|
658
|
+
this.args.onChange(resultData, event);
|
|
659
|
+
} else {
|
|
660
|
+
// For uncontrolled forms, update internal state
|
|
661
|
+
this.uncontrolledData = restoredData;
|
|
662
|
+
}
|
|
663
|
+
} else {
|
|
664
|
+
// No initial data, just clear uncontrolled data
|
|
665
|
+
this.uncontrolledData = undefined;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Resets the form to its initial state.
|
|
670
|
+
* This method calls the native form reset() to clear all form controls,
|
|
671
|
+
* triggering a `reset` event that is handled in `handleReset`.
|
|
672
|
+
*/
|
|
673
|
+
static {
|
|
674
|
+
decorateMethodV2(this.prototype, "handleReset", [action]);
|
|
675
|
+
}
|
|
676
|
+
reset() {
|
|
677
|
+
this.element?.current?.reset();
|
|
678
|
+
}
|
|
679
|
+
static {
|
|
680
|
+
decorateMethodV2(this.prototype, "reset", [action]);
|
|
681
|
+
}
|
|
682
|
+
static {
|
|
683
|
+
setComponentTemplate(precompileTemplate("\n {{!-- @glint-nocheck component generics (field) trigger: type instantiation is excessively deep and possibly infinite --}}\n <form {{this.element.setup}} {{on \"input\" this.handleInput}} {{on \"submit\" this.handleSubmit}} {{on \"reset\" this.handleReset}} ...attributes>\n {{yield (hash data=this.currentData isLoading=this.isLoading isValid=this.isValid isInvalid=this.isInvalid errors=this.errors dirty=this.dirty reset=this.reset Field=(component Field errors=this.errors formData=this.currentData disabled=@disabled validateOn=this.fieldValidateOn validateField=this.validateField)) to=\"default\"}}\n </form>\n ", {
|
|
684
|
+
strictMode: true,
|
|
685
|
+
scope: () => ({
|
|
686
|
+
on,
|
|
687
|
+
hash,
|
|
688
|
+
Field
|
|
689
|
+
})
|
|
690
|
+
}), this);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Helper function.
|
|
695
|
+
* Converts validation type `Issues` from StandardValidator into a format
|
|
696
|
+
* suitable for the form component, type `FormErrors`.
|
|
697
|
+
*
|
|
698
|
+
* For example, an issue with path `['email']` will be converted
|
|
699
|
+
* to a form error for the field `email`, `{"email": "error message" }`.
|
|
700
|
+
*
|
|
701
|
+
* @param errors - The validation issues to convert.
|
|
702
|
+
* @returns A mapping of field names to their validation error messages.
|
|
703
|
+
*/
|
|
704
|
+
function validatorToFormErrors(errors) {
|
|
705
|
+
const formErrors = {};
|
|
706
|
+
for (const issue of errors) {
|
|
707
|
+
if (!issue.path || issue.path.length === 0) continue;
|
|
708
|
+
// Extract keys from path segments to build field name
|
|
709
|
+
const pathKeys = issue.path.map(s => typeof s === 'object' && 'key' in s ? s.key : s).filter(Boolean);
|
|
710
|
+
const fieldName = pathKeys.join('.');
|
|
711
|
+
const message = issue.message;
|
|
712
|
+
// Add message to the field's errors
|
|
713
|
+
const existing = formErrors[fieldName];
|
|
714
|
+
if (existing === undefined) {
|
|
715
|
+
formErrors[fieldName] = message;
|
|
716
|
+
} else if (Array.isArray(existing)) {
|
|
717
|
+
existing.push(message);
|
|
718
|
+
} else {
|
|
719
|
+
formErrors[fieldName] = [existing, message];
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return formErrors;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
export { Form as F, StandardValidator as S, deepEqual as d, flattenData as f, hasNestedData as h, unflattenData as u };
|
|
726
|
+
//# sourceMappingURL=form-CVuJDJUq.js.map
|