-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathform-mixin.js
194 lines (168 loc) · 5.74 KB
/
form-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
import './form-errory-summary.js';
import '../tooltip/tooltip.js';
import '../link/link.js';
import { isCustomFormElement, isNativeFormElement } from './form-helper.js';
import { getComposedActiveElement } from '../../helpers/focus.js';
import { getUniqueId } from '../../helpers/uniqueId.js';
import { LocalizeCoreElement } from '../../helpers/localize-core-element.js';
import { localizeFormElement } from './form-element-localize-helper.js';
export const FormMixin = superclass => class extends LocalizeCoreElement(superclass) {
static get properties() {
return {
/**
* Indicates that the form should interrupt and warn on navigation if the user has unsaved changes on native elements.
* @type {boolean}
*/
trackChanges: { type: Boolean, attribute: 'track-changes', reflect: true },
_errors: { type: Object }
};
}
constructor() {
super();
this._onUnload = this._onUnload.bind(this);
this._onNativeSubmit = this._onNativeSubmit.bind(this);
this.trackChanges = false;
this._errors = new Map();
this._firstUpdateResolve = null;
this._firstUpdatePromise = new Promise((resolve) => {
this._firstUpdateResolve = resolve;
});
this._tooltips = new Map();
this._validationCustoms = new Set();
this.addEventListener('d2l-form-errors-change', this._onErrorsChange);
this.addEventListener('d2l-form-element-errors-change', this._onErrorsChange);
this.addEventListener('d2l-validation-custom-connected', this._validationCustomConnected);
}
connectedCallback() {
super.connectedCallback();
window.addEventListener('beforeunload', this._onUnload);
}
disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener('beforeunload', this._onUnload);
}
firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this.addEventListener('change', this._onFormElementChange);
this.addEventListener('input', this._onFormElementChange);
this.addEventListener('focusout', this._onFormElementChange);
this._firstUpdateResolve();
}
// eslint-disable-next-line no-unused-vars
async requestSubmit(submitter) {
throw new Error('FormMixin.requestSubmit must be overridden');
}
async submit() {
throw new Error('FormMixin.submit must be overridden');
}
async validate() {
throw new Error('FormMixin.validate must be overridden');
}
_displayInvalid(ele, message) {
let tooltip = this._tooltips.get(ele);
if (!tooltip) {
tooltip = document.createElement('d2l-tooltip');
tooltip.for = ele.id;
tooltip.align = 'start';
tooltip.state = 'error';
ele.parentNode.append(tooltip);
this._tooltips.set(ele, tooltip);
tooltip.appendChild(document.createTextNode(message));
} else if (tooltip.innerText.trim() !== message.trim()) {
tooltip.textContent = '';
tooltip.appendChild(document.createTextNode(message));
tooltip.updatePosition();
}
ele.setAttribute('aria-invalid', 'true');
}
_displayValid(ele) {
const tooltip = this._tooltips.get(ele);
if (tooltip) {
this._tooltips.delete(ele);
tooltip.remove();
}
ele.setAttribute('aria-invalid', 'false');
}
_onErrorsChange(e) {
if (e.target === this) {
return;
}
e.stopPropagation();
this._updateErrors(e.target, e.detail.errors);
}
async _onFormElementChange(e) {
const ele = e.target;
if ((isNativeFormElement(ele) || isCustomFormElement(ele)) && e.type !== 'focusout') {
this._dirty = true;
/** Dispatched whenever any form element fires an `input` or `change` event. Can be used to track whether the form is dirty or not. */
this.dispatchEvent(new CustomEvent('d2l-form-dirty'));
}
if (!isNativeFormElement(ele)) {
return;
}
e.stopPropagation();
const errors = await this._validateFormElement(ele, e.type === 'focusout');
this._updateErrors(ele, errors);
}
_onNativeSubmit(e) {
e.preventDefault();
e.stopPropagation();
const submitter = e.submitter || getComposedActiveElement();
this.requestSubmit(submitter);
}
_onUnload(e) {
if (this.trackChanges && this._dirty) {
e.preventDefault();
e.returnValue = false;
}
}
_updateErrors(ele, errors) {
if (!this._errors.has(ele)) {
return false;
}
if (Array.from(errors).length === 0) {
this._errors.delete(ele);
} else {
this._errors.set(ele, errors);
}
const detail = { bubbles: true, composed: true, detail: { errors: this._errors } };
/** @ignore */
this.dispatchEvent(new CustomEvent('d2l-form-errors-change', detail));
this.requestUpdate('_errors');
return true;
}
async _validateFormElement(ele, showNewErrors) {
// if validation occurs before we've rendered,
// localization may not have loaded yet
await this._firstUpdatePromise;
ele.id = ele.id || getUniqueId();
if (isCustomFormElement(ele)) {
return ele.validate(showNewErrors);
} else if (isNativeFormElement(ele)) {
const customs = [...this._validationCustoms].filter(custom => custom.forElement === ele);
const results = await Promise.all(customs.map(custom => custom.validate()));
const errors = customs.map(custom => custom.failureText).filter((_, i) => !results[i]);
if (!ele.checkValidity()) {
const validationMessage = localizeFormElement(this.localize.bind(this), ele);
errors.unshift(validationMessage);
}
if (errors.length > 0 && (showNewErrors || ele.getAttribute('aria-invalid') === 'true')) {
this._displayInvalid(ele, errors[0]);
} else {
this._displayValid(ele);
}
return errors;
}
return [];
}
_validationCustomConnected(e) {
e.stopPropagation();
const custom = e.composedPath()[0];
this._validationCustoms.add(custom);
const onDisconnect = () => {
custom.removeEventListener('d2l-validation-custom-disconnected', onDisconnect);
this._validationCustoms.delete(custom);
};
custom.addEventListener('d2l-validation-custom-disconnected', onDisconnect);
}
};