-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvanilla-form-associated-mixin.js
575 lines (483 loc) · 17.9 KB
/
vanilla-form-associated-mixin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import { ValueMissingValidator } from "../validators/value-missing-validator.js"
import { CustomStatesMixin } from "./custom-states-mixin.js"
import { FormAssociatedMixin } from "./form-associated-mixin.js"
/**
* @template T
* @template U
* @param {T} val
* @param {U} fallback
*/
function fallbackValue (val, fallback) {
if (val !== undefined) {
return val
}
return fallback
}
/**
* @template {typeof HTMLElement} T
* @typedef {import("../../internal/form-associated-getters.js").AbstractGetters<T>} AbstractGetters
*/
/**
* @template {{ new (...args: any[]): HTMLElement }} T
* @typedef {InstanceType<T> & {
internals: ElementInternals;
validators: Array<import("../types.js").Validator>;
hasInteracted: boolean;
formControl: null | undefined | HTMLElement;
disabled: boolean;
}} FormAssociatedProperties
*/
/**
* @template {{ new (...args: any[]): HTMLElement }} T
* @param {T} superclass
*/
function _VanillaFormAssociatedGettersMixin(superclass) {
return (
/**
* @implements {AbstractGetters<T>}
*/
class extends superclass {
get allValidators () {
/**
* @type {Array<import("../types.js").Validator>}
*/
// @ts-expect-error
const staticValidators = this.constructor.validators || []
/**
* @type {Array<import("../types.js").Validator>}
*/
const validators = /** @type {FormAssociatedProperties<T>} */ (this).validators || []
return [...staticValidators, ...validators]
}
get labels () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return /** @type {NodeListOf<HTMLLabelElement>} */ (self.internals.labels)
}
get validity () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return self.internals.validity
}
get validationMessage () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return self.internals.validationMessage
}
get willValidate () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return self.internals.willValidate
}
/**
* `validationTarget` is used for displaying native validation popups as the "anchor"
* @type {null | undefined | HTMLElement}
*/
get validationTarget () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return self.formControl || undefined
}
/**
* Returns the form attached to the element
* @returns {ReturnType<ElementInternals["form"]>}
*/
get form () {
const self = /** @type {FormAssociatedProperties<T>} */ (this)
return self.internals.form
}
/**
* Tracks whether or not an element meets criteria for `:user-invalid`.
* By default, always returns false.
* @returns {boolean}
*/
get isUserInvalid () {
return /** @type {any} */ (this).hasInteracted && !this.validity.valid
}
/**
* We use a `isDisabled` that checks both `matches(":disabled")` and `this.disabled` which
* accounts for if the element is wrapped in a `<fieldset disabled>`
*/
get isDisabled () {
return Boolean(this.matches(":disabled") || /** @type {any} */ (this).disabled)
}
})
}
/**
* @template {{ new (...args: any[]): HTMLElement }} T
* @param {T} superclass
*/
export function VanillaFormAssociatedGettersMixin(superclass) {
return /** @type {T & { new (...args: any[]): AbstractGetters<T>}} */ (_VanillaFormAssociatedGettersMixin(superclass))
}
/**
* A mixin of form associated helpers that get added to a class with attachInternals.
* This opinionated version extends the above formAssociated and handles common conventions I like.
* Required properties: { value, disabled, formControl, validationTarget }
*
* @see https://webkit.org/blog/13711/elementinternals-and-form-associated-custom-elements/
* @template {{ new (...args: any[]): HTMLElement }} T
* @param {T} superclass
*/
export function VanillaFormAssociatedMixin(superclass) {
return class _VanillaFormAssociatedMixin_ extends CustomStatesMixin(VanillaFormAssociatedGettersMixin(FormAssociatedMixin(superclass))) {
static get observedAttributes () {
/**
* @type {undefined | string[]}
*/
// @ts-expect-error
const parentObservedAttributes = super.observedAttributes
const parentAttrs = new Set(parentObservedAttributes || [])
for (const validator of this.validators) {
if (!validator.observedAttributes) { continue }
for (const attr of validator.observedAttributes) {
parentAttrs.add(attr)
}
}
return [...parentAttrs]
}
/**
* Validators are static because they have `observedAttributes`, essentially attributes to "watch"
* for changes. Whenever these attributes change, we want to be notified and update the validator.
* @type {Array<import("../types.js").Validator>}
*/
static get validators () {
return [
ValueMissingValidator()
]
}
/**
* Events to listen for that will mark the element as "hasInteracted" for setting the `:state(user-valid)`
* @default ["focusout", "blur"]
* @type {string[]}
*/
static assumeInteractionOn =
/** @type {{ assumeInteractionOn: string[] }} */ (/** @type {unknown} */ (this.constructor)).assumeInteractionOn || [
"focusout",
"blur",
]
/**
* @param {...any} args
*/
constructor (...args) {
super(...args)
// We wrap it all in a `queueMicrotask` because we want this to run after the real constructor.
/**
* @type {ElementInternals["role"]}
*/
this.role = fallbackValue(this.role, this.getAttribute("role") || null)
/**
* @type {HTMLInputElement["name"]}
*/
this.name = fallbackValue(this.name, (this.getAttribute("name") || ""))
/**
* `this.type` is used by ElementInternals.
* @type {string}
*/
this.type = fallbackValue(this.type, (this.getAttribute("type") || this.localName || ""))
/**
* Make sure if you're using a library that "reflects" properties to attributes, you don't reflect this `disabled.`
* @type {boolean}
*/
this.disabled = fallbackValue(this.disabled, this.isDisabled)
/**
* Generally form controls can have "required", this may not be necessary here, but is a nice convention.
* @type {boolean}
*/
this.required = fallbackValue(this.required, this.hasAttribute("required"))
/**
* Tracks when a user blurs from a form control.
* @type {boolean}
*/
this.hasInteracted = fallbackValue(this.hasInteracted, false)
/**
* While not generally encouraged, you can add instance level validators.
* These validators should not rely on an attribute, or should already have a "watched" attribute
* to know when to re-run the validator.
* @type {Array<import("../types.js").Validator>}
*/
this.validators = fallbackValue(this.validators, [])
queueMicrotask(() => {
/**
* @protected
*/
this.__boundHandleInvalid = this.handleInvalid.bind(this)
/**
* @protected
*/
this.__boundHandleInteraction = this.handleInteraction.bind(this)
/**
* @protected
*/
this.__boundHandleSubmit = this.__handleSubmit.bind(this)
;/** @type {typeof _VanillaFormAssociatedMixin_} */(this.constructor).assumeInteractionOn.forEach((str) => {
this.addEventListener(str, this.__boundHandleInteraction)
})
this.addEventListener("invalid", this.__boundHandleInvalid)
// Private
/** These are dirty checks for custom errors. In Safari, {customError: true} always happens with `setValidity()`. This is the workaround. */
/**
* @private
*/
this.__hasCustomError = false
/**
* @private
*/
this.__customErrorMessage = ""
})
}
connectedCallback () {
// @ts-expect-error
if (typeof super.connectedCallback === "function") {
// @ts-expect-error
super.connectedCallback()
}
this.getRootNode().addEventListener("submit", this.__boundHandleSubmit)
}
disconnectedCallback () {
// @ts-expect-error
if (typeof super.disconnectedCallback === "function") {
// @ts-expect-error
super.disconnectedCallback()
}
this.getRootNode().removeEventListener("submit", this.__boundHandleSubmit)
}
/**
* Handles a submit to a form. Dont use this directly. Instead use `submitCallback (form: HTMLFormElement) {}` for reacting to when the element has been submitted by the form.
* @param {Event} e
* @private
*/
__handleSubmit (e) {
const { target } = e
if (target === this.form) {
this.submitCallback()
}
}
/**
* Use this callback for when the element has been part of a form that was attempted to be submitted.
* If a form is invalid, this will not fire.
* If someone catches the event earlier in the tree and stops propagation, you this event will not fire.
*/
submitCallback () {
this.hasInteracted = true
}
/**
* Override this to do things like emit your own `invalid` event.
* @param {Event} e
*/
handleInvalid (e) {
// invalid events could bubble from children. We only want invalid events on the parent.
if (e.target !== this) return
if (this.isDisabled) return
this.hasInteracted = true
this.updateInteractionState()
}
/**
* Sets `this.hasInteracted = true` to true when the users focus / clicks the element.
* Override this to have your own `handleInteraction` function.
* @param {Event} e
*/
handleInteraction (e) {
if (this.isDisabled) return
if (!this.matches(":focus-within")) {
this.hasInteracted = true
}
this.updateValidity()
}
/**
* This function technically does not exist with internals, but exists on native form elements.
* This is backported for users familiar with the API.
* @param {string} message
*/
setCustomValidity (message) {
if (!message) {
this.__hasCustomError = false
this.__customErrorMessage = ""
this.setValidity({})
return
}
this.__hasCustomError = true
this.__customErrorMessage = message
this.internals.setValidity({customError: true}, message)
}
/**
* @param {string} name
* @param {null | string} oldVal
* @param {null | string} newVal
*/
attributeChangedCallback(name, oldVal, newVal) {
// @ts-expect-error
if (typeof super.attributeChangedCallback === "function") {
// @ts-expect-error
super.attributeChangedCallback(name, oldVal, newVal)
}
if (newVal === oldVal) {
return
}
if (name === "role") {
this.internals.role = newVal || null
}
if (name === "disabled") {
this.disabled = Boolean(newVal)
}
this.updateValidity()
}
/**
* Called when the form is being reset. (e.g. user pressed `<input[type=reset]>` button). Custom element should clear whatever value set by the user.
* Generally it is best to call this *after* setting any properties you need as this will call `this.updateValidity()` and `this.setFormValue()`
* @example
* class MyClass extends VanillaFormAssociatedMixin(HTMLElement) {
* formResetCallback () {
* // set values first for validation
* this.value = this.defaultValue
* // call the reset handler to update validity.
* super.formResetCallback()
* }
* }
* @returns {void}
*/
formResetCallback() {
this.resetValidity()
this.updateValidity()
this.setFormValue(this.toFormValue(), /** @type {any} */ (this).value)
}
/**
* Called when the disabled state of the form changes.
* @param {boolean} isDisabled
* @returns {void}
*/
formDisabledCallback(isDisabled) {
this.disabled = isDisabled
this.resetValidity()
this.updateValidity()
}
/**
* Called when the browser is trying to restore element’s state to state in which case reason is “restore”, or when the browser is trying to fulfill autofill on behalf of user in which case reason is “autocomplete”. In the case of “restore”, state is a string, File, or FormData object previously set as the second argument to setFormValue.
* @param {unknown} state
* @param {"restore" | "autocomplete"} reason
* @returns {void}
*/
formStateRestoreCallback(state, reason) {
// Wrapped in an {any} type so it doesnt get add to the host type.
/** @type {any} */ (this).value = state
if ("formControl" in this && this.formControl) {
/** @type {HTMLElement & { value: unknown }} */ (this.formControl).value = state
}
// We don't want to reset validity on "autocomplete", jsut on `"restore"`
if (reason === "restore") {
this.resetValidity()
}
this.updateValidity()
}
// Additional things not added by the `attachInternals()` call.
/**
* This should generally not be used by end users. This is intended for custom validators.
* @param {Parameters<ElementInternals["setValidity"]>} params
*/
setValidity (...params) {
let flags = params[0]
let message = params[1]
let anchor = params[2]
if (!anchor) {
const validationTarget = this.validationTarget
anchor = validationTarget || undefined
}
this.internals.setValidity(flags, message, anchor)
this.updateInteractionState()
}
reportValidity () {
this.updateValidity()
return this.internals.reportValidity()
}
checkValidity () {
this.updateValidity()
return this.internals.checkValidity()
}
/**
* @param {Parameters<ElementInternals["setFormValue"]>} args
*/
setFormValue (...args) {
this.internals.setFormValue(...args)
this.updateValidity()
}
/**
* This function generally just returns `this.value`. Occasionally, you may want to apply transforms to your `this.value` prior to setting it on the form. This is the place to do that.
* @returns {File | null | FormData | string}
* @example
* class MyElement extends VanillaFormAssociatedMixin(HTMLElement) {
* toFormValue () {
* const elementValue = this.value // => ["1", "2", "3"]
* // Transform elementValue array into a comma separated string.
* return elementValue.join(", ")
* }
* }
*/
toFormValue () {
/**
* @type {null | File | FormData | string}
*/
const val = /** @type {any} */ (this).value
return val
}
resetValidity () {
this.hasInteracted = false
this.setCustomValidity("")
this.setValidity({})
}
updateValidity () {
if (this.isDisabled) {
this.resetValidity()
// We don't run validators on disabled thiss to be inline with native HTMLElements.
// https://codepen.io/paramagicdev/pen/PoLogeL
return
}
const validators = /** @type {{allValidators?: Array<import("../types.js").Validator>}} */ (/** @type {unknown} */ (this)).allValidators
if (!validators) {
this.setValidity({})
return
}
const customError = Boolean(this.__hasCustomError)
const flags = {
customError
}
let formControl = undefined
if ("formControl" in this && this.formControl) {
formControl = /** @type {HTMLElement} */ (this.formControl) || undefined
}
let finalMessage = ""
for (const validator of validators) {
const { isValid, message, invalidKeys } = validator.checkValidity(this)
if (isValid) { continue }
if (!finalMessage) {
finalMessage = message
}
if (invalidKeys?.length >= 0) {
// @ts-expect-error
invalidKeys.forEach((str) => flags[str] = true)
}
}
// This is a workaround for preserving custom errors
if (!finalMessage) {
finalMessage = this.validationMessage || this.__customErrorMessage
}
this.setValidity(flags, finalMessage, formControl)
}
updateInteractionState () {
if (this.isDisabled) {
this.addCustomState("disabled")
this.deleteCustomState("invalid")
this.deleteCustomState("user-invalid")
this.deleteCustomState("valid")
this.deleteCustomState("user-valid")
return
}
this.deleteCustomState("disabled")
if (this.validity.valid) {
this.deleteCustomState("invalid")
this.deleteCustomState("user-invalid")
this.addCustomState("valid")
this.toggleCustomState("user-valid", this.isUserInvalid)
} else {
this.deleteCustomState("valid")
this.deleteCustomState("user-valid")
this.addCustomState("invalid")
this.toggleCustomState("user-invalid", this.isUserInvalid)
}
}
}
}