UNPKG

2.43 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2021 Google LLC
4 * SPDX-License-Identifier: Apache-2.0
5 */
6import { __decorate, __metadata } from "tslib";
7import { bound } from '@material/web/decorators/bound.js';
8/**
9 * A unique symbol key for `FormController` elements to implement their
10 * `getFormValue()` function.
11 */
12export const getFormValue = Symbol('getFormValue');
13/**
14 * A `ReactiveController` that adds `<form>` support to an element.
15 */
16export class FormController {
17 /**
18 * Creates a new `FormController` for the given element.
19 *
20 * @param element The element to add `<form>` support to.
21 */
22 constructor(element) {
23 this.element = element;
24 }
25 hostConnected() {
26 // If the component internals are not in Shadow DOM, subscribing to form
27 // data events could lead to duplicated data, which may not work correctly
28 // on the server side.
29 if (!this.element.shadowRoot || window.ShadyDOM?.inUse) {
30 return;
31 }
32 // Preserve a reference to the form, since on hostDisconnected it may be
33 // null if the child was removed.
34 this.form = this.element.form;
35 this.form?.addEventListener('formdata', this.formDataListener);
36 }
37 hostDisconnected() {
38 this.form?.removeEventListener('formdata', this.formDataListener);
39 }
40 formDataListener(event) {
41 if (this.element.disabled) {
42 // Check for truthiness since some elements may not support disabling.
43 return;
44 }
45 const value = this.element[getFormValue]();
46 // If given a `FormData` instance, append all values to the form. This
47 // allows elements to customize what is added beyond a single name/value
48 // pair.
49 if (value instanceof FormData) {
50 for (const [key, dataValue] of value) {
51 event.formData.append(key, dataValue);
52 }
53 return;
54 }
55 // Do not associate the value with the form if there is no value or no name.
56 if (value === null || !this.element.name) {
57 return;
58 }
59 event.formData.append(this.element.name, value);
60 }
61}
62__decorate([
63 bound,
64 __metadata("design:type", Function),
65 __metadata("design:paramtypes", [FormDataEvent]),
66 __metadata("design:returntype", void 0)
67], FormController.prototype, "formDataListener", null);
68//# sourceMappingURL=form-controller.js.map
\No newline at end of file