ember-headless-form 0.0.0 → 1.0.0-beta.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/README.md +16 -3
- package/dist/{components/-private → -private/components}/control/checkbox.d.ts +1 -0
- package/dist/-private/components/control/checkbox.d.ts.map +1 -0
- package/dist/-private/components/control/checkbox.js.map +1 -0
- package/dist/{components/-private → -private/components}/control/input.d.ts +17 -1
- package/dist/{components/-private → -private/components}/control/input.js +1 -1
- package/dist/-private/components/control/input.js.map +1 -0
- package/dist/-private/components/control/radio/input.js.map +1 -0
- package/dist/-private/components/control/radio.d.ts +35 -0
- package/dist/{components/-private → -private/components}/control/radio.js +1 -1
- package/dist/-private/components/control/radio.js.map +1 -0
- package/dist/-private/components/control/select/option.d.ts +18 -0
- package/dist/-private/components/control/select/option.js +15 -0
- package/dist/-private/components/control/select/option.js.map +1 -0
- package/dist/-private/components/control/select.d.ts +26 -0
- package/dist/-private/components/control/select.js +24 -0
- package/dist/-private/components/control/select.js.map +1 -0
- package/dist/-private/components/control/textarea.js.map +1 -0
- package/dist/{components/-private → -private/components}/errors.d.ts +1 -1
- package/dist/-private/components/errors.js.map +1 -0
- package/dist/-private/components/field.d.ts +146 -0
- package/dist/{components/-private → -private/components}/field.js +9 -4
- package/dist/-private/components/field.js.map +1 -0
- package/dist/-private/components/label.js.map +1 -0
- package/dist/{components/-private → -private/modifiers}/capture-events.d.ts +1 -2
- package/dist/-private/modifiers/capture-events.js.map +1 -0
- package/dist/{components/-private → -private}/types.d.ts +1 -1
- package/dist/-private/utils.js.map +1 -0
- package/dist/components/headless-form.d.ts +103 -14
- package/dist/components/headless-form.js +71 -23
- package/dist/components/headless-form.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/template-registry.d.ts +30 -0
- package/package.json +14 -10
- package/dist/components/-private/capture-events.d.ts.map +0 -1
- package/dist/components/-private/capture-events.js.map +0 -1
- package/dist/components/-private/control/checkbox.js.map +0 -1
- package/dist/components/-private/control/input.js.map +0 -1
- package/dist/components/-private/control/radio/input.js.map +0 -1
- package/dist/components/-private/control/radio.d.ts +0 -28
- package/dist/components/-private/control/radio.js.map +0 -1
- package/dist/components/-private/control/textarea.js.map +0 -1
- package/dist/components/-private/errors.js.map +0 -1
- package/dist/components/-private/field.d.ts +0 -76
- package/dist/components/-private/field.js.map +0 -1
- package/dist/components/-private/label.js.map +0 -1
- package/dist/components/-private/utils.js.map +0 -1
- /package/dist/{components/-private → -private/components}/control/checkbox.js +0 -0
- /package/dist/{components/-private → -private/components}/control/radio/input.d.ts +0 -0
- /package/dist/{components/-private → -private/components}/control/radio/input.js +0 -0
- /package/dist/{components/-private → -private/components}/control/textarea.d.ts +0 -0
- /package/dist/{components/-private → -private/components}/control/textarea.js +0 -0
- /package/dist/{components/-private → -private/components}/errors.js +0 -0
- /package/dist/{components/-private → -private/components}/label.d.ts +0 -0
- /package/dist/{components/-private → -private/components}/label.js +0 -0
- /package/dist/{components/-private → -private/modifiers}/capture-events.js +0 -0
- /package/dist/{components/-private → -private}/types.js +0 -0
- /package/dist/{components/-private → -private}/types.js.map +0 -0
- /package/dist/{components/-private → -private}/utils.d.ts +0 -0
- /package/dist/{components/-private → -private}/utils.js +0 -0
@@ -1,23 +1,70 @@
|
|
1
1
|
import Component from '@glimmer/component';
|
2
|
-
import
|
3
|
-
import
|
4
|
-
import { ErrorRecord, FieldRegistrationData, FieldValidateCallback, FormData, FormKey, FormValidateCallback, UserData } from "
|
5
|
-
import {
|
2
|
+
import { TrackedAsyncData } from 'ember-async-data';
|
3
|
+
import FieldComponent from "../-private/components/field.js";
|
4
|
+
import { ErrorRecord, FieldRegistrationData, FieldValidateCallback, FormData, FormKey, FormValidateCallback, UserData, ValidationError } from "../-private/types.js";
|
5
|
+
import { ModifierLike, WithBoundArgs } from '@glint/template';
|
6
6
|
type ValidateOn = 'change' | 'focusout' | 'submit' | 'input';
|
7
|
-
interface HeadlessFormComponentSignature<DATA extends UserData> {
|
7
|
+
interface HeadlessFormComponentSignature<DATA extends UserData, SUBMISSION_VALUE> {
|
8
8
|
Element: HTMLFormElement;
|
9
9
|
Args: {
|
10
|
+
/**
|
11
|
+
* The initial data the form will use to pre-populate the fields.
|
12
|
+
*
|
13
|
+
* Make sure the type of it matches what you expect the form to represent, i.e. the names of all form fields match the properties of the data and their respective types!
|
14
|
+
*/
|
10
15
|
data?: DATA;
|
16
|
+
/**
|
17
|
+
* By default the data you pass as `@data` is never mutated by the form component, you will only receive the updated data (a copy) on successful submission via `@onSubmit`.
|
18
|
+
* Setting this to `'mutable'` will mutate the data whenever the user updates a field. This is especially useful when the data already has some "buffering" behavior, like with `ember-changeset`.
|
19
|
+
*/
|
20
|
+
dataMode?: 'mutable' | 'immutable';
|
21
|
+
/**
|
22
|
+
* Specify when to dynamically validate a field before even submitting the whole form. By default this is `submit`, which means no dynamic validation happens. Another common setting is to validate on `focusout`.
|
23
|
+
*/
|
11
24
|
validateOn?: ValidateOn;
|
25
|
+
/**
|
26
|
+
* Specify when to revalidate a previously validated field that is invalid. By default this happens on `change`. Another common setting is to revalidate on `input`.
|
27
|
+
* Mind that text-based inputs don't emit the `change` event on every key stroke, but only on focusing out. Changing this to `input` would make text-based inputs revalidate on every key stroke.
|
28
|
+
*/
|
12
29
|
revalidateOn?: ValidateOn;
|
13
|
-
|
14
|
-
|
30
|
+
/**
|
31
|
+
* Provide a custom validation function, that operates on all fields of the form. Eventual validation errors are merged with native validation errors to determine the effective set of errors rendered in the form.
|
32
|
+
*
|
33
|
+
* Return undefined when no validation errors are present, otherwise an `ErrorRecord` mapping (one or multiple) `ValidationError`s to each invalid field.
|
34
|
+
*/
|
35
|
+
validate?: FormValidateCallback<DATA>;
|
36
|
+
/**
|
37
|
+
* Called when the user has submitted the form and no validation errors have been determined. Receives the new form data, or in case of `@dataMode="mutable"` the original data object.
|
38
|
+
*/
|
39
|
+
onSubmit?: (data: FormData<DATA>) => SUBMISSION_VALUE | Promise<SUBMISSION_VALUE>;
|
40
|
+
/**
|
41
|
+
* Called when the user tried to submit the form, but validation failed. Receives the new data (or in case of `@dataMode="mutable"` the original data object), and the record of validation errors by field.
|
42
|
+
*/
|
15
43
|
onInvalid?: (data: FormData<DATA>, errors: ErrorRecord<FormData<DATA>>) => void;
|
16
44
|
};
|
17
45
|
Blocks: {
|
18
46
|
default: [
|
19
47
|
{
|
20
|
-
|
48
|
+
/**
|
49
|
+
* Field component to define the fields of your form. It yields the further components for the form control, label and validation error.
|
50
|
+
*/
|
51
|
+
Field: WithBoundArgs<typeof FieldComponent<DATA>, 'data' | 'set' | 'errors' | 'registerField' | 'unregisterField' | 'triggerValidationFor' | 'fieldValidationEvent' | 'fieldRevalidationEvent'>;
|
52
|
+
/**
|
53
|
+
* The (async) validation state as `TrackedAsyncData`.
|
54
|
+
*
|
55
|
+
* Use derived state like `.isPending` to render the UI conditionally.
|
56
|
+
*/
|
57
|
+
validationState?: TrackedAsyncData<ErrorRecord<DATA>>;
|
58
|
+
/**
|
59
|
+
* The (async) submission state as `TrackedAsyncData`.
|
60
|
+
*
|
61
|
+
* Use derived state like `.isPending` to render the UI conditionally.
|
62
|
+
*/
|
63
|
+
submissionState?: TrackedAsyncData<SUBMISSION_VALUE>;
|
64
|
+
/**
|
65
|
+
* Will be true if at least one form field is invalid.
|
66
|
+
*/
|
67
|
+
isInvalid: boolean;
|
21
68
|
}
|
22
69
|
];
|
23
70
|
};
|
@@ -36,8 +83,51 @@ declare class FieldData<DATA extends FormData, KEY extends FormKey<DATA> = FormK
|
|
36
83
|
*/
|
37
84
|
validate?: FieldValidateCallback<DATA, KEY>;
|
38
85
|
}
|
39
|
-
|
40
|
-
|
86
|
+
/**
|
87
|
+
* Headless form component.
|
88
|
+
*
|
89
|
+
* @example
|
90
|
+
* Usage example:
|
91
|
+
*
|
92
|
+
* ```hbs
|
93
|
+
* <HeadlessForm
|
94
|
+
* @data={{this.data}}
|
95
|
+
* @validateOn="focusout"
|
96
|
+
* @revalidateOn="input"
|
97
|
+
* @onSubmit={{this.doSomething}}
|
98
|
+
* as |form|
|
99
|
+
* >
|
100
|
+
* <form.Field @name="firstName" as |field|>
|
101
|
+
* <div>
|
102
|
+
* <field.Label>First name</field.Label>
|
103
|
+
* <field.Input
|
104
|
+
* required
|
105
|
+
* />
|
106
|
+
* <field.errors />
|
107
|
+
* </div>
|
108
|
+
* </form.Field>
|
109
|
+
*
|
110
|
+
* <button
|
111
|
+
* type="submit"
|
112
|
+
* >Submit</button>
|
113
|
+
* </HeadlessForm>
|
114
|
+
* ```
|
115
|
+
*/
|
116
|
+
declare class HeadlessFormComponent<DATA extends UserData, SUBMISSION_VALUE> extends Component<HeadlessFormComponentSignature<DATA, SUBMISSION_VALUE>> {
|
117
|
+
FieldComponent: {
|
118
|
+
new (owner: unknown, args: {
|
119
|
+
name: FormKey<FormData<DATA>>;
|
120
|
+
validate?: FieldValidateCallback<FormData<DATA>, FormKey<FormData<DATA>>> | undefined;
|
121
|
+
data: FormData<DATA>;
|
122
|
+
set: (key: FormKey<FormData<DATA>>, value: DATA[FormKey<FormData<DATA>>]) => void;
|
123
|
+
errors?: Partial<Record<FormKey<FormData<DATA>>, ValidationError<DATA[FormKey<FormData<DATA>>]>[]>> | undefined;
|
124
|
+
registerField: import("../-private/types.js").RegisterFieldCallback<FormData<DATA>, FormKey<FormData<DATA>>>;
|
125
|
+
unregisterField: import("../-private/types.js").UnregisterFieldCallback<FormData<DATA>, FormKey<FormData<DATA>>>;
|
126
|
+
triggerValidationFor(name: FormKey<FormData<DATA>>): Promise<void>;
|
127
|
+
fieldValidationEvent: "focusout" | "change" | "input" | undefined;
|
128
|
+
fieldRevalidationEvent: "focusout" | "change" | "input" | undefined;
|
129
|
+
}): FieldComponent<DATA, FormKey<FormData<DATA>>>;
|
130
|
+
};
|
41
131
|
on: import("@ember/modifier").OnModifier;
|
42
132
|
formElement?: HTMLFormElement;
|
43
133
|
registerForm: ModifierLike<unknown>;
|
@@ -46,10 +136,8 @@ declare class HeadlessFormComponent<DATA extends UserData> extends Component<Hea
|
|
46
136
|
*/
|
47
137
|
internalData: DATA;
|
48
138
|
fields: Map<FormKey<FormData<DATA>>, FieldData<FormData<DATA>, FormKey<FormData<DATA>>>>;
|
49
|
-
|
50
|
-
|
51
|
-
*/
|
52
|
-
lastValidationResult?: ErrorRecord<FormData<DATA>>;
|
139
|
+
validationState?: TrackedAsyncData<ErrorRecord<DATA>>;
|
140
|
+
submissionState?: TrackedAsyncData<SUBMISSION_VALUE>;
|
53
141
|
/**
|
54
142
|
* When this is set to true by submitting the form, eventual validation errors are show for *all* field, regardless of their individual dynamic validation status in `FieldData#validationEnabled`
|
55
143
|
*/
|
@@ -75,6 +163,7 @@ declare class HeadlessFormComponent<DATA extends UserData> extends Component<Hea
|
|
75
163
|
* Call the passed validation callbacks, defined both on the whole form as well as on field level, and return the merged result for all fields.
|
76
164
|
*/
|
77
165
|
validate(): Promise<ErrorRecord<FormData<DATA>>>;
|
166
|
+
_validate(): Promise<ErrorRecord<FormData<DATA>>>;
|
78
167
|
validateNative(): ErrorRecord<FormData<DATA>> | undefined;
|
79
168
|
/**
|
80
169
|
* Return a mapping of field to validation errors, for all fields that are invalid *and* for which validation errors should be visible.
|
@@ -8,16 +8,16 @@ import Component from '@glimmer/component';
|
|
8
8
|
import { tracked } from '@glimmer/tracking';
|
9
9
|
import { assert, warn } from '@ember/debug';
|
10
10
|
import { on } from '@ember/modifier';
|
11
|
-
import { action } from '@ember/object';
|
12
|
-
import {
|
11
|
+
import { action, set } from '@ember/object';
|
12
|
+
import { TrackedAsyncData } from 'ember-async-data';
|
13
13
|
import { modifier } from 'ember-modifier';
|
14
14
|
import { TrackedObject } from 'tracked-built-ins';
|
15
|
-
import HeadlessFormFieldComponent from '
|
16
|
-
import { mergeErrorRecord } from '
|
15
|
+
import HeadlessFormFieldComponent from '../-private/components/field.js';
|
16
|
+
import { mergeErrorRecord } from '../-private/utils.js';
|
17
17
|
|
18
|
-
var TEMPLATE = precompileTemplate("<form\n novalidate\n ...attributes\n {{this.registerForm}}\n {{on \'submit\' this.onSubmit}}\n {{(if\n this.fieldValidationEvent\n (modifier this.on this.fieldValidationEvent this.handleFieldValidation)\n )}}\n {{(if\n this.fieldRevalidationEvent\n (modifier this.on this.fieldRevalidationEvent this.handleFieldRevalidation)\n )}}\n>\n {{yield\n (hash\n
|
18
|
+
var TEMPLATE = precompileTemplate("<form\n novalidate\n ...attributes\n {{this.registerForm}}\n {{on \'submit\' this.onSubmit}}\n {{(if\n this.fieldValidationEvent\n (modifier this.on this.fieldValidationEvent this.handleFieldValidation)\n )}}\n {{(if\n this.fieldRevalidationEvent\n (modifier this.on this.fieldRevalidationEvent this.handleFieldRevalidation)\n )}}\n>\n {{yield\n (hash\n Field=(component\n (ensure-safe-component this.FieldComponent)\n data=this.internalData\n set=this.set\n errors=this.visibleErrors\n registerField=this.registerField\n unregisterField=this.unregisterField\n triggerValidationFor=this.handleFieldValidation\n fieldValidationEvent=this.fieldValidationEvent\n fieldRevalidationEvent=this.fieldRevalidationEvent\n )\n validationState=this.validationState\n submissionState=this.submissionState\n isInvalid=this.hasValidationErrors\n )\n }}\n</form>");
|
19
19
|
|
20
|
-
var _class, _descriptor, _class3, _descriptor2, _descriptor3;
|
20
|
+
var _class, _descriptor, _class3, _descriptor2, _descriptor3, _descriptor4;
|
21
21
|
/**
|
22
22
|
* This internal data structure maintains information about each field that is registered to the form by `registerField`.
|
23
23
|
*/
|
@@ -39,6 +39,36 @@ let FieldData = (_class = class FieldData {
|
|
39
39
|
return false;
|
40
40
|
}
|
41
41
|
})), _class);
|
42
|
+
/**
|
43
|
+
* Headless form component.
|
44
|
+
*
|
45
|
+
* @example
|
46
|
+
* Usage example:
|
47
|
+
*
|
48
|
+
* ```hbs
|
49
|
+
* <HeadlessForm
|
50
|
+
* @data={{this.data}}
|
51
|
+
* @validateOn="focusout"
|
52
|
+
* @revalidateOn="input"
|
53
|
+
* @onSubmit={{this.doSomething}}
|
54
|
+
* as |form|
|
55
|
+
* >
|
56
|
+
* <form.Field @name="firstName" as |field|>
|
57
|
+
* <div>
|
58
|
+
* <field.Label>First name</field.Label>
|
59
|
+
* <field.Input
|
60
|
+
* required
|
61
|
+
* />
|
62
|
+
* <field.errors />
|
63
|
+
* </div>
|
64
|
+
* </form.Field>
|
65
|
+
*
|
66
|
+
* <button
|
67
|
+
* type="submit"
|
68
|
+
* >Submit</button>
|
69
|
+
* </HeadlessForm>
|
70
|
+
* ```
|
71
|
+
*/
|
42
72
|
let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Component {
|
43
73
|
constructor(...args) {
|
44
74
|
super(...args);
|
@@ -48,10 +78,11 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
48
78
|
_defineProperty(this, "registerForm", modifier((el, _p) => {
|
49
79
|
this.formElement = el;
|
50
80
|
}));
|
51
|
-
_defineProperty(this, "internalData", new TrackedObject(this.args.data ?? {}));
|
81
|
+
_defineProperty(this, "internalData", this.args.dataMode == 'mutable' && this.args.data ? this.args.data : new TrackedObject(this.args.data ?? {}));
|
52
82
|
_defineProperty(this, "fields", new Map());
|
53
|
-
_initializerDefineProperty(this, "
|
54
|
-
_initializerDefineProperty(this, "
|
83
|
+
_initializerDefineProperty(this, "validationState", _descriptor2, this);
|
84
|
+
_initializerDefineProperty(this, "submissionState", _descriptor3, this);
|
85
|
+
_initializerDefineProperty(this, "showAllValidations", _descriptor4, this);
|
55
86
|
}
|
56
87
|
get validateOn() {
|
57
88
|
return this.args.validateOn ?? 'submit';
|
@@ -91,8 +122,12 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
91
122
|
* Return true if validation has happened (by submitting or by an `@validateOn` event being triggered) and at least one field is invalid
|
92
123
|
*/
|
93
124
|
get hasValidationErrors() {
|
125
|
+
const {
|
126
|
+
validationState
|
127
|
+
} = this;
|
128
|
+
|
94
129
|
// Only consider validation errors for which we actually have a field rendered
|
95
|
-
return
|
130
|
+
return validationState?.isResolved ? Object.keys(validationState.value).some(name => this.fields.has(name)) : false;
|
96
131
|
}
|
97
132
|
|
98
133
|
/**
|
@@ -100,7 +135,7 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
100
135
|
*/
|
101
136
|
async validate() {
|
102
137
|
const nativeValidation = this.validateNative();
|
103
|
-
const customFormValidation = await this.args.validate?.(this.internalData);
|
138
|
+
const customFormValidation = await this.args.validate?.(this.internalData, Array.from(this.fields.keys()));
|
104
139
|
const customFieldValidations = [];
|
105
140
|
for (const [name, field] of this.fields) {
|
106
141
|
const fieldValidationResult = await field.validate?.(this.internalData[name], name, this.internalData);
|
@@ -112,6 +147,11 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
112
147
|
}
|
113
148
|
return mergeErrorRecord(nativeValidation, customFormValidation, ...customFieldValidations);
|
114
149
|
}
|
150
|
+
async _validate() {
|
151
|
+
const promise = this.validate();
|
152
|
+
this.validationState = new TrackedAsyncData(promise, this);
|
153
|
+
return promise;
|
154
|
+
}
|
115
155
|
validateNative() {
|
116
156
|
const form = this.formElement;
|
117
157
|
assert('Form element expected to be present. If you see this, please report it as a bug to ember-headless-form!', form);
|
@@ -147,11 +187,11 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
147
187
|
* or when that field has triggered the event given by `@validateOn` for showing validation errors before submitting, e.g. on blur.
|
148
188
|
*/
|
149
189
|
get visibleErrors() {
|
150
|
-
if (!this.
|
190
|
+
if (!this.validationState?.isResolved) {
|
151
191
|
return undefined;
|
152
192
|
}
|
153
193
|
const visibleErrors = {};
|
154
|
-
for (const [field, errors] of Object.entries(this.
|
194
|
+
for (const [field, errors] of Object.entries(this.validationState.value)) {
|
155
195
|
if (this.showErrorsFor(field)) {
|
156
196
|
visibleErrors[field] = errors;
|
157
197
|
}
|
@@ -167,13 +207,15 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
167
207
|
}
|
168
208
|
async onSubmit(e) {
|
169
209
|
e.preventDefault();
|
170
|
-
|
210
|
+
await this._validate();
|
171
211
|
this.showAllValidations = true;
|
172
212
|
if (!this.hasValidationErrors) {
|
173
|
-
this.args.onSubmit
|
213
|
+
if (this.args.onSubmit) {
|
214
|
+
this.submissionState = new TrackedAsyncData(this.args.onSubmit(this.internalData), this);
|
215
|
+
}
|
174
216
|
} else {
|
175
|
-
assert('Validation errors expected to be present. If you see this, please report it as a bug to ember-headless-form!', this.
|
176
|
-
this.args.onInvalid?.(this.internalData, this.
|
217
|
+
assert('Validation errors expected to be present. If you see this, please report it as a bug to ember-headless-form!', this.validationState?.isResolved);
|
218
|
+
this.args.onInvalid?.(this.internalData, this.validationState.value);
|
177
219
|
}
|
178
220
|
}
|
179
221
|
registerField(name, field) {
|
@@ -184,7 +226,8 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
184
226
|
this.fields.delete(name);
|
185
227
|
}
|
186
228
|
set(key, value) {
|
187
|
-
|
229
|
+
// when @mutableData is set, our internalData is something we don't control, i.e. might require old-school set() to be on the safe side
|
230
|
+
set(this.internalData, key, value);
|
188
231
|
}
|
189
232
|
|
190
233
|
/**
|
@@ -205,7 +248,7 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
205
248
|
if (name) {
|
206
249
|
const field = this.fields.get(name);
|
207
250
|
if (field) {
|
208
|
-
|
251
|
+
await this._validate();
|
209
252
|
field.validationEnabled = true;
|
210
253
|
}
|
211
254
|
} else if (e instanceof Event) {
|
@@ -231,7 +274,7 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
231
274
|
} = target;
|
232
275
|
if (name) {
|
233
276
|
if (this.showErrorsFor(name)) {
|
234
|
-
|
277
|
+
await this._validate();
|
235
278
|
}
|
236
279
|
} else {
|
237
280
|
warn(`An event of type "${e.type}" was received by headless-form, which is supposed to trigger validations for a certain field. But the name of that field could not be determined. Make sure that your control element has a \`name\` attribute matching the field, or use the yielded \`{{field.captureEvents}}\` to capture the events.`, {
|
@@ -239,19 +282,24 @@ let HeadlessFormComponent = (_class3 = class HeadlessFormComponent extends Compo
|
|
239
282
|
});
|
240
283
|
}
|
241
284
|
}
|
242
|
-
}, (_descriptor2 = _applyDecoratedDescriptor(_class3.prototype, "
|
285
|
+
}, (_descriptor2 = _applyDecoratedDescriptor(_class3.prototype, "validationState", [tracked], {
|
286
|
+
configurable: true,
|
287
|
+
enumerable: true,
|
288
|
+
writable: true,
|
289
|
+
initializer: null
|
290
|
+
}), _descriptor3 = _applyDecoratedDescriptor(_class3.prototype, "submissionState", [tracked], {
|
243
291
|
configurable: true,
|
244
292
|
enumerable: true,
|
245
293
|
writable: true,
|
246
294
|
initializer: null
|
247
|
-
}),
|
295
|
+
}), _descriptor4 = _applyDecoratedDescriptor(_class3.prototype, "showAllValidations", [tracked], {
|
248
296
|
configurable: true,
|
249
297
|
enumerable: true,
|
250
298
|
writable: true,
|
251
299
|
initializer: function () {
|
252
300
|
return false;
|
253
301
|
}
|
254
|
-
}), _applyDecoratedDescriptor(_class3.prototype, "
|
302
|
+
}), _applyDecoratedDescriptor(_class3.prototype, "onSubmit", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "onSubmit"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "registerField", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "registerField"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "unregisterField", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "unregisterField"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "set", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "set"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "handleFieldValidation", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "handleFieldValidation"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "handleFieldRevalidation", [action], Object.getOwnPropertyDescriptor(_class3.prototype, "handleFieldRevalidation"), _class3.prototype)), _class3);
|
255
303
|
setComponentTemplate(TEMPLATE, HeadlessFormComponent);
|
256
304
|
|
257
305
|
export { HeadlessFormComponent as default };
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"headless-form.js","sources":["../../src/components/headless-form.hbs.js","../../src/components/headless-form.ts"],"sourcesContent":["import { precompileTemplate } from \"@ember/template-compilation\";\nexport default precompileTemplate(\"<form\\n novalidate\\n ...attributes\\n {{this.registerForm}}\\n {{on \\'submit\\' this.onSubmit}}\\n {{(if\\n this.fieldValidationEvent\\n (modifier this.on this.fieldValidationEvent this.handleFieldValidation)\\n )}}\\n {{(if\\n this.fieldRevalidationEvent\\n (modifier this.on this.fieldRevalidationEvent this.handleFieldRevalidation)\\n )}}\\n>\\n {{yield\\n (hash\\n field=(component\\n (ensure-safe-component this.FieldComponent)\\n data=this.internalData\\n set=this.set\\n errors=this.visibleErrors\\n registerField=this.registerField\\n unregisterField=this.unregisterField\\n triggerValidationFor=this.handleFieldValidation\\n fieldValidationEvent=this.fieldValidationEvent\\n fieldRevalidationEvent=this.fieldRevalidationEvent\\n )\\n )\\n }}\\n</form>\")","import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { assert, warn } from '@ember/debug';\nimport { on } from '@ember/modifier';\nimport { action } from '@ember/object';\nimport { waitFor } from '@ember/test-waiters';\n\nimport { modifier } from 'ember-modifier';\nimport { TrackedObject } from 'tracked-built-ins';\n\nimport FieldComponent from './-private/field';\nimport { mergeErrorRecord } from './-private/utils';\n\nimport type { HeadlessFormFieldComponentSignature } from './-private/field';\nimport type {\n ErrorRecord,\n FieldRegistrationData,\n FieldValidateCallback,\n FormData,\n FormKey,\n FormValidateCallback,\n UserData,\n ValidationError,\n} from './-private/types';\nimport type {\n ComponentLike,\n ModifierLike,\n WithBoundArgs,\n} from '@glint/template';\n\ntype ValidateOn = 'change' | 'focusout' | 'submit' | 'input';\n\nexport interface HeadlessFormComponentSignature<DATA extends UserData> {\n Element: HTMLFormElement;\n Args: {\n data?: DATA;\n validateOn?: ValidateOn;\n revalidateOn?: ValidateOn;\n validate?: FormValidateCallback<FormData<DATA>>;\n onSubmit?: (data: FormData<DATA>) => void;\n onInvalid?: (\n data: FormData<DATA>,\n errors: ErrorRecord<FormData<DATA>>\n ) => void;\n };\n Blocks: {\n default: [\n {\n field: WithBoundArgs<\n typeof FieldComponent<DATA>,\n | 'data'\n | 'set'\n | 'errors'\n | 'registerField'\n | 'unregisterField'\n | 'triggerValidationFor'\n | 'fieldValidationEvent'\n | 'fieldRevalidationEvent'\n >;\n }\n ];\n };\n}\n\n/**\n * This internal data structure maintains information about each field that is registered to the form by `registerField`.\n */\nclass FieldData<\n DATA extends FormData,\n KEY extends FormKey<DATA> = FormKey<DATA>\n> {\n constructor(fieldRegistration: FieldRegistrationData<DATA, KEY>) {\n this.validate = fieldRegistration.validate;\n }\n\n /**\n * tracked state that enabled a dynamic validation of a field *before* the whole form is submitted, e.g. by `@validateOn=\"blur\" and the blur event being triggered for that particular field.\n */\n @tracked validationEnabled = false;\n\n /**\n * The *field* level validation callback passed to the field as in `<form.field @name=\"foo\" @validate={{this.validateCallback}}>`\n */\n validate?: FieldValidateCallback<DATA, KEY>;\n}\n\nexport default class HeadlessFormComponent<\n DATA extends UserData\n> extends Component<HeadlessFormComponentSignature<DATA>> {\n FieldComponent: ComponentLike<HeadlessFormFieldComponentSignature<DATA>> =\n FieldComponent;\n\n // we cannot use (modifier \"on\") directly in the template due to https://github.com/emberjs/ember.js/issues/19869\n on = on;\n\n formElement?: HTMLFormElement;\n\n registerForm = modifier((el: HTMLFormElement, _p: []) => {\n this.formElement = el;\n }) as unknown as ModifierLike<unknown>; // @todo getting Glint errors without this. Try again with Glint 1.0 (beta)!\n\n /**\n * A copy of the passed `@data` stored internally, which is only passed back to the component consumer after a (successful) form submission.\n */\n internalData: DATA = new TrackedObject(this.args.data ?? {}) as DATA;\n\n fields = new Map<FormKey<FormData<DATA>>, FieldData<FormData<DATA>>>();\n\n /**\n * The last result of calling `this.validate()`.\n */\n @tracked lastValidationResult?: ErrorRecord<FormData<DATA>>;\n\n /**\n * When this is set to true by submitting the form, eventual validation errors are show for *all* field, regardless of their individual dynamic validation status in `FieldData#validationEnabled`\n */\n @tracked showAllValidations = false;\n\n get validateOn(): ValidateOn {\n return this.args.validateOn ?? 'submit';\n }\n\n get revalidateOn(): ValidateOn {\n return this.args.revalidateOn ?? 'change';\n }\n\n /**\n * Return the event type that will be listened on for dynamic validation (i.e. *before* submitting)\n */\n get fieldValidationEvent(): 'focusout' | 'change' | 'input' | undefined {\n const { validateOn } = this;\n\n return validateOn === 'submit'\n ? // no need for dynamic validation, as validation always happens on submit\n undefined\n : validateOn;\n }\n\n /**\n * Return the event type that will be listened on for dynamic *re*validation, i.e. updating the validation status of a field that has been previously marked as invalid\n */\n get fieldRevalidationEvent(): 'focusout' | 'change' | 'input' | undefined {\n const { validateOn, revalidateOn } = this;\n\n return revalidateOn === 'submit'\n ? // no need for dynamic validation, as validation always happens on submit\n undefined\n : // when validation happens more frequently than revalidation, then we can ignore revalidation, because the validation handler will already cover us\n validateOn === 'input' ||\n (validateOn === 'change' && revalidateOn === 'focusout') ||\n validateOn === revalidateOn\n ? undefined\n : revalidateOn;\n }\n\n /**\n * Return true if validation has happened (by submitting or by an `@validateOn` event being triggered) and at least one field is invalid\n */\n get hasValidationErrors(): boolean {\n // Only consider validation errors for which we actually have a field rendered\n return this.lastValidationResult\n ? Object.keys(this.lastValidationResult).some((name) =>\n this.fields.has(name as FormKey<FormData<DATA>>)\n )\n : false;\n }\n\n /**\n * Call the passed validation callbacks, defined both on the whole form as well as on field level, and return the merged result for all fields.\n */\n @waitFor\n async validate(): Promise<ErrorRecord<FormData<DATA>>> {\n const nativeValidation = this.validateNative();\n const customFormValidation = await this.args.validate?.(this.internalData);\n const customFieldValidations: ErrorRecord<FormData<DATA>>[] = [];\n\n for (const [name, field] of this.fields) {\n const fieldValidationResult = await field.validate?.(\n this.internalData[name],\n name,\n this.internalData\n );\n\n if (fieldValidationResult) {\n customFieldValidations.push({\n [name]: fieldValidationResult,\n } as ErrorRecord<FormData<DATA>>);\n }\n }\n\n return mergeErrorRecord(\n nativeValidation,\n customFormValidation,\n ...customFieldValidations\n );\n }\n\n validateNative(): ErrorRecord<FormData<DATA>> | undefined {\n const form = this.formElement;\n\n assert(\n 'Form element expected to be present. If you see this, please report it as a bug to ember-headless-form!',\n form\n );\n\n if (form.checkValidity()) {\n return;\n }\n\n const errors: ErrorRecord<FormData<DATA>> = {};\n\n for (const el of form.elements) {\n // This is just to make TS happy, as we need to access properties on el that only form elements have, but elements in `form.elements` are just typed as plain `Element`. Should never occur in reality.\n assert(\n 'Unexpected form element. If you see this, please report it as a bug to ember-headless-form!',\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLButtonElement ||\n el instanceof HTMLFieldSetElement ||\n el instanceof HTMLObjectElement ||\n el instanceof HTMLOutputElement\n );\n\n if (el.validity.valid) {\n continue;\n }\n\n const name = el.name as FormKey<FormData<DATA>>;\n\n if (this.fields.has(name)) {\n errors[name] = [\n {\n type: 'native',\n value: this.internalData[name],\n message: el.validationMessage,\n },\n ];\n } else {\n warn(\n `An invalid form element with name \"${name}\" was detected, but this name is not used as a form field. It will be ignored for validation. Make sure to apply the correct name to custom form elements that participate in form validation!`,\n { id: 'headless-form.invalid-control-for-unknown-field' }\n );\n }\n }\n\n return errors;\n }\n\n /**\n * Return a mapping of field to validation errors, for all fields that are invalid *and* for which validation errors should be visible.\n * Validation errors will be visible for a certain field, if validation errors for *all* fields are visible, which is the case when trying to submit the form,\n * or when that field has triggered the event given by `@validateOn` for showing validation errors before submitting, e.g. on blur.\n */\n get visibleErrors(): ErrorRecord<FormData<DATA>> | undefined {\n if (!this.lastValidationResult) {\n return undefined;\n }\n\n const visibleErrors: ErrorRecord<FormData<DATA>> = {};\n\n for (const [field, errors] of Object.entries(this.lastValidationResult) as [\n FormKey<FormData<DATA>>,\n ValidationError<FormData<DATA>[FormKey<FormData<DATA>>]>[]\n ][]) {\n if (this.showErrorsFor(field)) {\n visibleErrors[field] = errors;\n }\n }\n\n return visibleErrors;\n }\n\n /**\n * Given a field name, return if eventual errors for the field should be visible. See `visibleErrors` for further details.\n */\n showErrorsFor(field: FormKey<FormData<DATA>>): boolean {\n return (\n this.showAllValidations ||\n (this.fields.get(field)?.validationEnabled ?? false)\n );\n }\n\n @action\n async onSubmit(e: Event): Promise<void> {\n e.preventDefault();\n\n this.lastValidationResult = await this.validate();\n this.showAllValidations = true;\n\n if (!this.hasValidationErrors) {\n this.args.onSubmit?.(this.internalData);\n } else {\n assert(\n 'Validation errors expected to be present. If you see this, please report it as a bug to ember-headless-form!',\n this.lastValidationResult\n );\n this.args.onInvalid?.(this.internalData, this.lastValidationResult);\n }\n }\n\n @action\n registerField(\n name: FormKey<FormData<DATA>>,\n field: FieldRegistrationData<FormData<DATA>>\n ): void {\n assert(\n `You passed @name=\"${String(\n name\n )}\" to the form field, but this is already in use. Names of form fields must be unique!`,\n !this.fields.has(name)\n );\n this.fields.set(name, new FieldData(field));\n }\n\n @action\n unregisterField(name: FormKey<FormData<DATA>>): void {\n this.fields.delete(name);\n }\n\n @action\n set<KEY extends FormKey<FormData<DATA>>>(key: KEY, value: DATA[KEY]): void {\n this.internalData[key] = value;\n }\n\n /**\n * Handle the `@validateOn` event for a certain field, e.g. \"blur\".\n * Associating the event with a field is done by looking at the event target's `name` attribute, which must match one of the `<form.field @name=\"...\">` invocations by the user's template.\n * Validation will be triggered, and the particular field will be marked to show eventual validation errors.\n */\n @action\n async handleFieldValidation(e: Event | string): Promise<void> {\n let name: string;\n\n if (typeof e === 'string') {\n name = e;\n } else {\n const { target } = e;\n\n name = (target as HTMLInputElement).name;\n }\n\n if (name) {\n const field = this.fields.get(name as FormKey<FormData<DATA>>);\n\n if (field) {\n this.lastValidationResult = await this.validate();\n field.validationEnabled = true;\n }\n } else if (e instanceof Event) {\n warn(\n `An event of type \"${e.type}\" was received by headless-form, which is supposed to trigger validations for a certain field. But the name of that field could not be determined. Make sure that your control element has a \\`name\\` attribute matching the field, or use the yielded \\`{{field.captureEvents}}\\` to capture the events.`,\n { id: 'headless-form.validation-event-for-unknown-field' }\n );\n }\n }\n\n /**\n * Handle the `@revalidateOn` event for a certain field, e.g. \"blur\".\n * Associating the event with a field is done by looking at the event target's `name` attribute, which must match one of the `<form.field @name=\"...\">` invocations by the user's template.\n * When a field has been already marked to show validation errors by `@validateOn`, then for revalidation another validation will be triggered.\n *\n * The use case here is to allow this to happen more frequently than the initial validation, e.g. `@validateOn=\"blur\" @revalidateOn=\"change\"`.\n */\n @action\n async handleFieldRevalidation(e: Event): Promise<void> {\n const { target } = e;\n const { name } = target as HTMLInputElement;\n\n if (name) {\n if (this.showErrorsFor(name as FormKey<FormData<DATA>>)) {\n this.lastValidationResult = await this.validate();\n }\n } else {\n warn(\n `An event of type \"${e.type}\" was received by headless-form, which is supposed to trigger validations for a certain field. But the name of that field could not be determined. Make sure that your control element has a \\`name\\` attribute matching the field, or use the yielded \\`{{field.captureEvents}}\\` to capture the events.`,\n { id: 'headless-form.validation-event-for-unknown-field' }\n );\n }\n }\n}\n"],"names":["precompileTemplate","FieldData","constructor","fieldRegistration","validate","tracked","HeadlessFormComponent","Component","FieldComponent","on","modifier","el","_p","formElement","TrackedObject","args","data","Map","validateOn","revalidateOn","fieldValidationEvent","undefined","fieldRevalidationEvent","hasValidationErrors","lastValidationResult","Object","keys","some","name","fields","has","nativeValidation","validateNative","customFormValidation","internalData","customFieldValidations","field","fieldValidationResult","push","mergeErrorRecord","form","assert","checkValidity","errors","elements","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFieldSetElement","HTMLObjectElement","HTMLOutputElement","validity","valid","type","value","message","validationMessage","warn","id","visibleErrors","entries","showErrorsFor","showAllValidations","get","validationEnabled","onSubmit","e","preventDefault","onInvalid","registerField","String","set","unregisterField","delete","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,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,UAAA,EAAA,CAiHPC,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,UAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,eAAA,EAAA,CAkBNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,eAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,iBAAA,EAAA,CAcNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,iBAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,KAAA,EAAA,CAKNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,KAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,uBAAA,EAAA,CAUNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,uBAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,yBAAA,EAAA,CAkCNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,yBAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,GAAA,OAAA,EAAA;AAtRiC,oBAAA,CAAA,QAAA,EAAA,qBAAA,CAAA;;;;"}
|
1
|
+
{"version":3,"file":"headless-form.js","sources":["../../src/components/headless-form.hbs.js","../../src/components/headless-form.ts"],"sourcesContent":["import { precompileTemplate } from \"@ember/template-compilation\";\nexport default precompileTemplate(\"<form\\n novalidate\\n ...attributes\\n {{this.registerForm}}\\n {{on \\'submit\\' this.onSubmit}}\\n {{(if\\n this.fieldValidationEvent\\n (modifier this.on this.fieldValidationEvent this.handleFieldValidation)\\n )}}\\n {{(if\\n this.fieldRevalidationEvent\\n (modifier this.on this.fieldRevalidationEvent this.handleFieldRevalidation)\\n )}}\\n>\\n {{yield\\n (hash\\n Field=(component\\n (ensure-safe-component this.FieldComponent)\\n data=this.internalData\\n set=this.set\\n errors=this.visibleErrors\\n registerField=this.registerField\\n unregisterField=this.unregisterField\\n triggerValidationFor=this.handleFieldValidation\\n fieldValidationEvent=this.fieldValidationEvent\\n fieldRevalidationEvent=this.fieldRevalidationEvent\\n )\\n validationState=this.validationState\\n submissionState=this.submissionState\\n isInvalid=this.hasValidationErrors\\n )\\n }}\\n</form>\")","import Component from '@glimmer/component';\nimport { tracked } from '@glimmer/tracking';\nimport { assert, warn } from '@ember/debug';\nimport { on } from '@ember/modifier';\nimport { action, set } from '@ember/object';\n\nimport { TrackedAsyncData } from 'ember-async-data';\nimport { modifier } from 'ember-modifier';\nimport { TrackedObject } from 'tracked-built-ins';\n\nimport FieldComponent from '../-private/components/field';\nimport { mergeErrorRecord } from '../-private/utils';\n\nimport type {\n ErrorRecord,\n FieldRegistrationData,\n FieldValidateCallback,\n FormData,\n FormKey,\n FormValidateCallback,\n UserData,\n ValidationError,\n} from '../-private/types';\nimport type { ModifierLike, WithBoundArgs } from '@glint/template';\n\ntype ValidateOn = 'change' | 'focusout' | 'submit' | 'input';\n\nexport interface HeadlessFormComponentSignature<\n DATA extends UserData,\n SUBMISSION_VALUE\n> {\n Element: HTMLFormElement;\n Args: {\n /**\n * The initial data the form will use to pre-populate the fields.\n *\n * Make sure the type of it matches what you expect the form to represent, i.e. the names of all form fields match the properties of the data and their respective types!\n */\n data?: DATA;\n\n /**\n * By default the data you pass as `@data` is never mutated by the form component, you will only receive the updated data (a copy) on successful submission via `@onSubmit`.\n * Setting this to `'mutable'` will mutate the data whenever the user updates a field. This is especially useful when the data already has some \"buffering\" behavior, like with `ember-changeset`.\n */\n dataMode?: 'mutable' | 'immutable';\n\n /**\n * Specify when to dynamically validate a field before even submitting the whole form. By default this is `submit`, which means no dynamic validation happens. Another common setting is to validate on `focusout`.\n */\n validateOn?: ValidateOn;\n\n /**\n * Specify when to revalidate a previously validated field that is invalid. By default this happens on `change`. Another common setting is to revalidate on `input`.\n * Mind that text-based inputs don't emit the `change` event on every key stroke, but only on focusing out. Changing this to `input` would make text-based inputs revalidate on every key stroke.\n */\n revalidateOn?: ValidateOn;\n\n /**\n * Provide a custom validation function, that operates on all fields of the form. Eventual validation errors are merged with native validation errors to determine the effective set of errors rendered in the form.\n *\n * Return undefined when no validation errors are present, otherwise an `ErrorRecord` mapping (one or multiple) `ValidationError`s to each invalid field.\n */\n validate?: FormValidateCallback<DATA>;\n\n /**\n * Called when the user has submitted the form and no validation errors have been determined. Receives the new form data, or in case of `@dataMode=\"mutable\"` the original data object.\n */\n onSubmit?: (\n data: FormData<DATA>\n ) => SUBMISSION_VALUE | Promise<SUBMISSION_VALUE>;\n\n /**\n * Called when the user tried to submit the form, but validation failed. Receives the new data (or in case of `@dataMode=\"mutable\"` the original data object), and the record of validation errors by field.\n */\n onInvalid?: (\n data: FormData<DATA>,\n errors: ErrorRecord<FormData<DATA>>\n ) => void;\n };\n Blocks: {\n default: [\n {\n /**\n * Field component to define the fields of your form. It yields the further components for the form control, label and validation error.\n */\n Field: WithBoundArgs<\n typeof FieldComponent<DATA>,\n | 'data'\n | 'set'\n | 'errors'\n | 'registerField'\n | 'unregisterField'\n | 'triggerValidationFor'\n | 'fieldValidationEvent'\n | 'fieldRevalidationEvent'\n >;\n\n /**\n * The (async) validation state as `TrackedAsyncData`.\n *\n * Use derived state like `.isPending` to render the UI conditionally.\n */\n validationState?: TrackedAsyncData<ErrorRecord<DATA>>;\n\n /**\n * The (async) submission state as `TrackedAsyncData`.\n *\n * Use derived state like `.isPending` to render the UI conditionally.\n */\n submissionState?: TrackedAsyncData<SUBMISSION_VALUE>;\n\n /**\n * Will be true if at least one form field is invalid.\n */\n isInvalid: boolean;\n }\n ];\n };\n}\n\n/**\n * This internal data structure maintains information about each field that is registered to the form by `registerField`.\n */\nclass FieldData<\n DATA extends FormData,\n KEY extends FormKey<DATA> = FormKey<DATA>\n> {\n constructor(fieldRegistration: FieldRegistrationData<DATA, KEY>) {\n this.validate = fieldRegistration.validate;\n }\n\n /**\n * tracked state that enabled a dynamic validation of a field *before* the whole form is submitted, e.g. by `@validateOn=\"blur\" and the blur event being triggered for that particular field.\n */\n @tracked validationEnabled = false;\n\n /**\n * The *field* level validation callback passed to the field as in `<form.field @name=\"foo\" @validate={{this.validateCallback}}>`\n */\n validate?: FieldValidateCallback<DATA, KEY>;\n}\n\n/**\n * Headless form component.\n *\n * @example\n * Usage example:\n *\n * ```hbs\n * <HeadlessForm\n * @data={{this.data}}\n * @validateOn=\"focusout\"\n * @revalidateOn=\"input\"\n * @onSubmit={{this.doSomething}}\n * as |form|\n * >\n * <form.Field @name=\"firstName\" as |field|>\n * <div>\n * <field.Label>First name</field.Label>\n * <field.Input\n * required\n * />\n * <field.errors />\n * </div>\n * </form.Field>\n *\n * <button\n * type=\"submit\"\n * >Submit</button>\n * </HeadlessForm>\n * ```\n */\nexport default class HeadlessFormComponent<\n DATA extends UserData,\n SUBMISSION_VALUE\n> extends Component<HeadlessFormComponentSignature<DATA, SUBMISSION_VALUE>> {\n FieldComponent = FieldComponent<DATA>;\n\n // we cannot use (modifier \"on\") directly in the template due to https://github.com/emberjs/ember.js/issues/19869\n on = on;\n\n formElement?: HTMLFormElement;\n\n registerForm = modifier((el: HTMLFormElement, _p: []) => {\n this.formElement = el;\n }) as unknown as ModifierLike<unknown>; // @todo getting Glint errors without this. Try again with Glint 1.0 (beta)!\n\n /**\n * A copy of the passed `@data` stored internally, which is only passed back to the component consumer after a (successful) form submission.\n */\n internalData: DATA =\n this.args.dataMode == 'mutable' && this.args.data\n ? this.args.data\n : (new TrackedObject(this.args.data ?? {}) as DATA);\n\n fields = new Map<FormKey<FormData<DATA>>, FieldData<FormData<DATA>>>();\n\n @tracked validationState?: TrackedAsyncData<ErrorRecord<DATA>>;\n @tracked submissionState?: TrackedAsyncData<SUBMISSION_VALUE>;\n\n /**\n * When this is set to true by submitting the form, eventual validation errors are show for *all* field, regardless of their individual dynamic validation status in `FieldData#validationEnabled`\n */\n @tracked showAllValidations = false;\n\n get validateOn(): ValidateOn {\n return this.args.validateOn ?? 'submit';\n }\n\n get revalidateOn(): ValidateOn {\n return this.args.revalidateOn ?? 'change';\n }\n\n /**\n * Return the event type that will be listened on for dynamic validation (i.e. *before* submitting)\n */\n get fieldValidationEvent(): 'focusout' | 'change' | 'input' | undefined {\n const { validateOn } = this;\n\n return validateOn === 'submit'\n ? // no need for dynamic validation, as validation always happens on submit\n undefined\n : validateOn;\n }\n\n /**\n * Return the event type that will be listened on for dynamic *re*validation, i.e. updating the validation status of a field that has been previously marked as invalid\n */\n get fieldRevalidationEvent(): 'focusout' | 'change' | 'input' | undefined {\n const { validateOn, revalidateOn } = this;\n\n return revalidateOn === 'submit'\n ? // no need for dynamic validation, as validation always happens on submit\n undefined\n : // when validation happens more frequently than revalidation, then we can ignore revalidation, because the validation handler will already cover us\n validateOn === 'input' ||\n (validateOn === 'change' && revalidateOn === 'focusout') ||\n validateOn === revalidateOn\n ? undefined\n : revalidateOn;\n }\n\n /**\n * Return true if validation has happened (by submitting or by an `@validateOn` event being triggered) and at least one field is invalid\n */\n get hasValidationErrors(): boolean {\n const { validationState } = this;\n\n // Only consider validation errors for which we actually have a field rendered\n return validationState?.isResolved\n ? Object.keys(validationState.value).some((name) =>\n this.fields.has(name as FormKey<FormData<DATA>>)\n )\n : false;\n }\n\n /**\n * Call the passed validation callbacks, defined both on the whole form as well as on field level, and return the merged result for all fields.\n */\n async validate(): Promise<ErrorRecord<FormData<DATA>>> {\n const nativeValidation = this.validateNative();\n const customFormValidation = await this.args.validate?.(\n this.internalData,\n Array.from(this.fields.keys())\n );\n const customFieldValidations: ErrorRecord<FormData<DATA>>[] = [];\n\n for (const [name, field] of this.fields) {\n const fieldValidationResult = await field.validate?.(\n this.internalData[name],\n name,\n this.internalData\n );\n\n if (fieldValidationResult) {\n customFieldValidations.push({\n [name]: fieldValidationResult,\n } as ErrorRecord<FormData<DATA>>);\n }\n }\n\n return mergeErrorRecord(\n nativeValidation,\n customFormValidation,\n ...customFieldValidations\n );\n }\n\n async _validate(): Promise<ErrorRecord<FormData<DATA>>> {\n const promise = this.validate();\n\n this.validationState = new TrackedAsyncData(promise, this);\n\n return promise;\n }\n\n validateNative(): ErrorRecord<FormData<DATA>> | undefined {\n const form = this.formElement;\n\n assert(\n 'Form element expected to be present. If you see this, please report it as a bug to ember-headless-form!',\n form\n );\n\n if (form.checkValidity()) {\n return;\n }\n\n const errors: ErrorRecord<FormData<DATA>> = {};\n\n for (const el of form.elements) {\n // This is just to make TS happy, as we need to access properties on el that only form elements have, but elements in `form.elements` are just typed as plain `Element`. Should never occur in reality.\n assert(\n 'Unexpected form element. If you see this, please report it as a bug to ember-headless-form!',\n el instanceof HTMLInputElement ||\n el instanceof HTMLTextAreaElement ||\n el instanceof HTMLSelectElement ||\n el instanceof HTMLButtonElement ||\n el instanceof HTMLFieldSetElement ||\n el instanceof HTMLObjectElement ||\n el instanceof HTMLOutputElement\n );\n\n if (el.validity.valid) {\n continue;\n }\n\n const name = el.name as FormKey<FormData<DATA>>;\n\n if (this.fields.has(name)) {\n errors[name] = [\n {\n type: 'native',\n value: this.internalData[name],\n message: el.validationMessage,\n },\n ];\n } else {\n warn(\n `An invalid form element with name \"${name}\" was detected, but this name is not used as a form field. It will be ignored for validation. Make sure to apply the correct name to custom form elements that participate in form validation!`,\n { id: 'headless-form.invalid-control-for-unknown-field' }\n );\n }\n }\n\n return errors;\n }\n\n /**\n * Return a mapping of field to validation errors, for all fields that are invalid *and* for which validation errors should be visible.\n * Validation errors will be visible for a certain field, if validation errors for *all* fields are visible, which is the case when trying to submit the form,\n * or when that field has triggered the event given by `@validateOn` for showing validation errors before submitting, e.g. on blur.\n */\n get visibleErrors(): ErrorRecord<FormData<DATA>> | undefined {\n if (!this.validationState?.isResolved) {\n return undefined;\n }\n\n const visibleErrors: ErrorRecord<FormData<DATA>> = {};\n\n for (const [field, errors] of Object.entries(\n this.validationState.value\n ) as [\n FormKey<FormData<DATA>>,\n ValidationError<FormData<DATA>[FormKey<FormData<DATA>>]>[]\n ][]) {\n if (this.showErrorsFor(field)) {\n visibleErrors[field] = errors;\n }\n }\n\n return visibleErrors;\n }\n\n /**\n * Given a field name, return if eventual errors for the field should be visible. See `visibleErrors` for further details.\n */\n showErrorsFor(field: FormKey<FormData<DATA>>): boolean {\n return (\n this.showAllValidations ||\n (this.fields.get(field)?.validationEnabled ?? false)\n );\n }\n\n @action\n async onSubmit(e: Event): Promise<void> {\n e.preventDefault();\n\n await this._validate();\n this.showAllValidations = true;\n\n if (!this.hasValidationErrors) {\n if (this.args.onSubmit) {\n this.submissionState = new TrackedAsyncData(\n this.args.onSubmit(this.internalData),\n this\n );\n }\n } else {\n assert(\n 'Validation errors expected to be present. If you see this, please report it as a bug to ember-headless-form!',\n this.validationState?.isResolved\n );\n this.args.onInvalid?.(this.internalData, this.validationState.value);\n }\n }\n\n @action\n registerField(\n name: FormKey<FormData<DATA>>,\n field: FieldRegistrationData<FormData<DATA>>\n ): void {\n assert(\n `You passed @name=\"${String(\n name\n )}\" to the form field, but this is already in use. Names of form fields must be unique!`,\n !this.fields.has(name)\n );\n this.fields.set(name, new FieldData(field));\n }\n\n @action\n unregisterField(name: FormKey<FormData<DATA>>): void {\n this.fields.delete(name);\n }\n\n @action\n set<KEY extends FormKey<FormData<DATA>>>(key: KEY, value: DATA[KEY]): void {\n // when @mutableData is set, our internalData is something we don't control, i.e. might require old-school set() to be on the safe side\n set(this.internalData, key, value);\n }\n\n /**\n * Handle the `@validateOn` event for a certain field, e.g. \"blur\".\n * Associating the event with a field is done by looking at the event target's `name` attribute, which must match one of the `<form.field @name=\"...\">` invocations by the user's template.\n * Validation will be triggered, and the particular field will be marked to show eventual validation errors.\n */\n @action\n async handleFieldValidation(e: Event | string): Promise<void> {\n let name: string;\n\n if (typeof e === 'string') {\n name = e;\n } else {\n const { target } = e;\n\n name = (target as HTMLInputElement).name;\n }\n\n if (name) {\n const field = this.fields.get(name as FormKey<FormData<DATA>>);\n\n if (field) {\n await this._validate();\n field.validationEnabled = true;\n }\n } else if (e instanceof Event) {\n warn(\n `An event of type \"${e.type}\" was received by headless-form, which is supposed to trigger validations for a certain field. But the name of that field could not be determined. Make sure that your control element has a \\`name\\` attribute matching the field, or use the yielded \\`{{field.captureEvents}}\\` to capture the events.`,\n { id: 'headless-form.validation-event-for-unknown-field' }\n );\n }\n }\n\n /**\n * Handle the `@revalidateOn` event for a certain field, e.g. \"blur\".\n * Associating the event with a field is done by looking at the event target's `name` attribute, which must match one of the `<form.field @name=\"...\">` invocations by the user's template.\n * When a field has been already marked to show validation errors by `@validateOn`, then for revalidation another validation will be triggered.\n *\n * The use case here is to allow this to happen more frequently than the initial validation, e.g. `@validateOn=\"blur\" @revalidateOn=\"change\"`.\n */\n @action\n async handleFieldRevalidation(e: Event): Promise<void> {\n const { target } = e;\n const { name } = target as HTMLInputElement;\n\n if (name) {\n if (this.showErrorsFor(name as FormKey<FormData<DATA>>)) {\n await this._validate();\n }\n } else {\n warn(\n `An event of type \"${e.type}\" was received by headless-form, which is supposed to trigger validations for a certain field. But the name of that field could not be determined. Make sure that your control element has a \\`name\\` attribute matching the field, or use the yielded \\`{{field.captureEvents}}\\` to capture the events.`,\n { id: 'headless-form.validation-event-for-unknown-field' }\n );\n }\n }\n}\n"],"names":["precompileTemplate","FieldData","constructor","fieldRegistration","validate","tracked","HeadlessFormComponent","Component","FieldComponent","on","modifier","el","_p","formElement","args","dataMode","data","TrackedObject","Map","validateOn","revalidateOn","fieldValidationEvent","undefined","fieldRevalidationEvent","hasValidationErrors","validationState","isResolved","Object","keys","value","some","name","fields","has","nativeValidation","validateNative","customFormValidation","internalData","Array","from","customFieldValidations","field","fieldValidationResult","push","mergeErrorRecord","_validate","promise","TrackedAsyncData","form","assert","checkValidity","errors","elements","HTMLInputElement","HTMLTextAreaElement","HTMLSelectElement","HTMLButtonElement","HTMLFieldSetElement","HTMLObjectElement","HTMLOutputElement","validity","valid","type","message","validationMessage","warn","id","visibleErrors","entries","showErrorsFor","showAllValidations","get","validationEnabled","onSubmit","e","preventDefault","submissionState","onInvalid","registerField","String","set","unregisterField","delete","key","handleFieldValidation","target","Event","handleFieldRevalidation","action"],"mappings":";;;;;;;;;;;;;;;;;AACA,eAAeA,kBAAkB,CAAC,q8BAAq8B,CAAC;;;ACuHx+B;AACA;AACA;AAFA,IAGMC,SAAS,IAAA,MAAA,GAAf,MAAMA,SAAS,CAGb;EACAC,WAAW,CAACC,iBAAmD,EAAE;AAAA,IAAA,0BAAA,CAAA,IAAA,EAAA,mBAAA,EAAA,WAAA,EAAA,IAAA,CAAA,CAAA;AAAA,IAAA,eAAA,CAAA,IAAA,EAAA,UAAA,EAAA,KAAA,CAAA,CAAA,CAAA;AAC/D,IAAA,IAAI,CAACC,QAAQ,GAAGD,iBAAiB,CAACC,QAAQ,CAAA;AAC5C,GAAA;;AAEA;AACF;AACA;AAOA,CAAC,mFANEC,OAAO,CAAA,EAAA;AAAA,EAAA,YAAA,EAAA,IAAA;AAAA,EAAA,UAAA,EAAA,IAAA;AAAA,EAAA,QAAA,EAAA,IAAA;AAAA,EAAA,WAAA,EAAA,YAAA;AAAA,IAAA,OAAqB,KAAK,CAAA;AAAA,GAAA;AAAA,CAAA,CAAA,GAAA,MAAA,CAAA,CAAA;AAQpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA7BA,IA8BqBC,qBAAq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AAAA,SAAAA,EAAAA,UAAAA,EAAAA,CAAAA,MAAM,CAuBNA,EAAAA,MAAAA,CAAAA,wBAAAA,CAAAA,OAAAA,CAAAA,SAAAA,EAAAA,UAAAA,CAAAA,EAAAA,OAAAA,CAAAA,SAAAA,CAAAA,EAAAA,yBAAAA,CAAAA,OAAAA,CAAAA,SAAAA,EAAAA,eAAAA,EAAAA,CAAAA,MAAM,CAcNA,EAAAA,MAAAA,CAAAA,wBAAAA,CAAAA,OAAAA,CAAAA,SAAAA,EAAAA,eAAAA,CAAAA,EAAAA,OAAAA,CAAAA,SAAAA,CAAAA,EAAAA,yBAAAA,CAAAA,OAAAA,CAAAA,SAAAA,EAAAA,iBAAAA,EAAAA,CAAAA,MAAM,mJAKNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,KAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,uBAAA,EAAA,CAWNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,uBAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,EAAA,yBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,yBAAA,EAAA,CAkCNA,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,OAAA,CAAA,SAAA,EAAA,yBAAA,CAAA,EAAA,OAAA,CAAA,SAAA,CAAA,GAAA,OAAA,EAAA;AA3SiC,oBAAA,CAAA,QAAA,EAAA,qBAAA,CAAA;;;;"}
|
package/dist/index.d.ts
CHANGED
@@ -1 +1,3 @@
|
|
1
|
-
export type { InputType } from "
|
1
|
+
export type { InputType } from "./-private/components/control/input.js";
|
2
|
+
export type { ErrorRecord, FieldValidateCallback, FormData, FormKey, FormValidateCallback, ValidationError } from "./-private/types.js";
|
3
|
+
export { default as HeadlessForm } from "./components/headless-form.js";
|
package/dist/index.js
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
|
1
|
+
export { default as HeadlessForm } from './components/headless-form.js';
|
2
2
|
//# sourceMappingURL=index.js.map
|
@@ -1,5 +1,35 @@
|
|
1
1
|
import HeadlessFormComponent from "./components/headless-form.js";
|
2
2
|
interface Registry {
|
3
|
+
/**
|
4
|
+
* Headless form component.
|
5
|
+
*
|
6
|
+
* @example
|
7
|
+
* Usage example:
|
8
|
+
*
|
9
|
+
* ```hbs
|
10
|
+
* <HeadlessForm
|
11
|
+
* @data={{this.data}}
|
12
|
+
* @validateOn="focusout"
|
13
|
+
* @revalidateOn="input"
|
14
|
+
* @onSubmit={{this.doSomething}}
|
15
|
+
* as |form|
|
16
|
+
* >
|
17
|
+
* <form.Field @name="firstName" as |field|>
|
18
|
+
* <div>
|
19
|
+
* <field.Label>First name</field.Label>
|
20
|
+
* <field.Input
|
21
|
+
* required
|
22
|
+
* />
|
23
|
+
* <field.errors />
|
24
|
+
* </div>
|
25
|
+
* </form.Field>
|
26
|
+
*
|
27
|
+
* <button
|
28
|
+
* type="submit"
|
29
|
+
* >Submit</button>
|
30
|
+
* </HeadlessForm>
|
31
|
+
* ```
|
32
|
+
*/
|
3
33
|
HeadlessForm: typeof HeadlessFormComponent;
|
4
34
|
}
|
5
35
|
export { Registry as default };
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "ember-headless-form",
|
3
|
-
"version": "0.0.0",
|
3
|
+
"version": "1.0.0-beta.0",
|
4
4
|
"description": "The default blueprint for Embroider v2 addons.",
|
5
5
|
"keywords": [
|
6
6
|
"ember-addon"
|
@@ -15,14 +15,15 @@
|
|
15
15
|
"dependencies": {
|
16
16
|
"@babel/runtime": "^7.20.7",
|
17
17
|
"@embroider/addon-shim": "^1.0.0",
|
18
|
-
"@
|
19
|
-
"
|
20
|
-
"ember-modifier": "^4.
|
18
|
+
"@embroider/util": "^1.10.0",
|
19
|
+
"ember-async-data": "^0.7.0",
|
20
|
+
"ember-modifier": "^4.1.0",
|
21
21
|
"tracked-built-ins": "^3.1.0"
|
22
22
|
},
|
23
23
|
"peerDependencies": {
|
24
24
|
"@glimmer/component": "^1.1.2",
|
25
|
-
"@glimmer/tracking": "^1.1.2"
|
25
|
+
"@glimmer/tracking": "^1.1.2",
|
26
|
+
"ember-source": ">=4.4.0"
|
26
27
|
},
|
27
28
|
"devDependencies": {
|
28
29
|
"@babel/core": "^7.17.0",
|
@@ -33,9 +34,9 @@
|
|
33
34
|
"@embroider/addon-dev": "^3.0.0",
|
34
35
|
"@glimmer/component": "^1.1.2",
|
35
36
|
"@glimmer/tracking": "^1.1.2",
|
36
|
-
"@glint/core": "^0.
|
37
|
-
"@glint/environment-ember-loose": "^0.
|
38
|
-
"@glint/template": "^0.
|
37
|
+
"@glint/core": "^1.0.0-beta.3",
|
38
|
+
"@glint/environment-ember-loose": "^1.0.0-beta.3",
|
39
|
+
"@glint/template": "^1.0.0-beta.3",
|
39
40
|
"@nullvoxpopuli/eslint-configs": "^3.0.2",
|
40
41
|
"@tsconfig/ember": "^1.0.0",
|
41
42
|
"@types/ember": "^4.0.0",
|
@@ -59,6 +60,7 @@
|
|
59
60
|
"@typescript-eslint/eslint-plugin": "^5.30.5",
|
60
61
|
"@typescript-eslint/parser": "^5.30.5",
|
61
62
|
"concurrently": "^7.2.1",
|
63
|
+
"ember-source": "^4.4.0",
|
62
64
|
"ember-template-lint": "^4.0.0",
|
63
65
|
"eslint": "^7.32.0",
|
64
66
|
"eslint-config-prettier": "^8.3.0",
|
@@ -69,7 +71,8 @@
|
|
69
71
|
"rollup": "^2.67.0",
|
70
72
|
"rollup-plugin-copy": "^3.4.0",
|
71
73
|
"rollup-plugin-ts": "^3.2.0",
|
72
|
-
"typescript": "^4.7.4"
|
74
|
+
"typescript": "^4.7.4",
|
75
|
+
"webpack": "^5.75.0"
|
73
76
|
},
|
74
77
|
"publishConfig": {
|
75
78
|
"registry": "https://registry.npmjs.org"
|
@@ -91,7 +94,8 @@
|
|
91
94
|
"types": "./dist/*.d.ts",
|
92
95
|
"default": "./dist/*.js"
|
93
96
|
},
|
94
|
-
"./addon-main.js": "./addon-main.js"
|
97
|
+
"./addon-main.js": "./addon-main.js",
|
98
|
+
"./-private/*": null
|
95
99
|
},
|
96
100
|
"typesVersions": {
|
97
101
|
"*": {
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"components/-private/capture-events.d.ts","sourceRoot":"","sources":["../src/components/-private/capture-events.ts"],"names":[],"mappings":"AAEA,UAAiB,8BAA8B;IAC7C,OAAO,EAAE,WAAW,CAAC;IACrB,IAAI,EAAE;QACJ,KAAK,EAAE;YACL,KAAK,EAAE,UAAU,GAAG,QAAQ,CAAC;YAC7B,iBAAiB,IAAI,IAAI,CAAC;SAC3B,CAAC;KACH,CAAC;CACH;AAED,QAAA,MAAM,qBAAqB;;;;mBANd,UAAU,GAAG,QAAQ;iCACP,IAAI;;;;EAa9B,CAAC"}
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"capture-events.js","sources":["../../../src/components/-private/capture-events.ts"],"sourcesContent":["import { modifier } from 'ember-modifier';\n\nexport interface CaptureEventsModifierSignature {\n Element: HTMLElement;\n Args: {\n Named: {\n event: 'focusout' | 'change';\n triggerValidation(): void;\n };\n };\n}\n\nconst CaptureEventsModifier = modifier<CaptureEventsModifierSignature>(\n (element, _pos, { event, triggerValidation }) => {\n element.addEventListener(event, triggerValidation, { passive: true });\n\n return () => {\n element.removeEventListener(event, triggerValidation);\n };\n }\n);\n\nexport default CaptureEventsModifier;\n"],"names":["CaptureEventsModifier","modifier","element","_pos","event","triggerValidation","addEventListener","passive","removeEventListener"],"mappings":";;AAYMA,MAAAA,qBAAqB,GAAGC,QAAQ,CACpC,CAACC,OAAO,EAAEC,IAAI,EAAE;EAAEC,KAAK;AAAEC,EAAAA,iBAAAA;AAAkB,CAAC,KAAK;AAC/CH,EAAAA,OAAO,CAACI,gBAAgB,CAACF,KAAK,EAAEC,iBAAiB,EAAE;AAAEE,IAAAA,OAAO,EAAE,IAAA;AAAK,GAAC,CAAC,CAAA;AAErE,EAAA,OAAO,MAAM;AACXL,IAAAA,OAAO,CAACM,mBAAmB,CAACJ,KAAK,EAAEC,iBAAiB,CAAC,CAAA;GACtD,CAAA;AACH,CAAC;;;;"}
|
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"file":"checkbox.js","sources":["../../../../src/components/-private/control/checkbox.hbs.js","../../../../src/components/-private/control/checkbox.ts"],"sourcesContent":["import { precompileTemplate } from \"@ember/template-compilation\";\nexport default precompileTemplate(\"<input\\n name={{@name}}\\n type=\\'checkbox\\'\\n checked={{@value}}\\n id={{@fieldId}}\\n aria-invalid={{if @invalid \\'true\\'}}\\n ...attributes\\n {{on \\'click\\' this.handleInput}}\\n/>\")","import Component from '@glimmer/component';\nimport { action } from '@ember/object';\n\nexport interface HeadlessFormControlCheckboxComponentSignature {\n Element: HTMLInputElement;\n Args: {\n value: boolean;\n name: string;\n fieldId: string;\n setValue: (value: boolean) => void;\n invalid: boolean;\n errorId: string;\n };\n}\n\nexport default class HeadlessFormControlCheckboxComponent extends Component<HeadlessFormControlCheckboxComponentSignature> {\n @action\n handleInput(e: Event | InputEvent): void {\n this.args.setValue((e.target as HTMLInputElement).checked);\n }\n}\n"],"names":["precompileTemplate","HeadlessFormControlCheckboxComponent","Component","handleInput","e","args","setValue","target","checked","action"],"mappings":";;;;;;AACA,eAAeA,kBAAkB,CAAC,2LAA2L,CAAC;;;ACAvL,IAclBC,oCAAoC,IAA1C,MAAA,GAAA,MAAMA,oCAAoC,SAASC,SAAS,CAAgD;EAEzHC,WAAW,CAACC,CAAqB,EAAQ;IACvC,IAAI,CAACC,IAAI,CAACC,QAAQ,CAAEF,CAAC,CAACG,MAAM,CAAsBC,OAAO,CAAC,CAAA;AAC5D,GAAA;AACF,CAAC,+DAJEC,MAAM,CAAA,EAAA,MAAA,CAAA,wBAAA,CAAA,MAAA,CAAA,SAAA,EAAA,aAAA,CAAA,EAAA,MAAA,CAAA,SAAA,CAAA,GAAA,MAAA,EAAA;AADgD,oBAAA,CAAA,QAAA,EAAA,oCAAA,CAAA;;;;"}
|