-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation-output.ts
More file actions
217 lines (179 loc) · 7.12 KB
/
validation-output.ts
File metadata and controls
217 lines (179 loc) · 7.12 KB
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
// The lib.dom.d.ts is not complete for the CustomStateSet interface
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface CustomStateSet {
add(token: string): void;
delete(token: string): void;
has(token: string): boolean;
}
class ValidationOutput extends HTMLElement {
#template: DocumentFragment | null = null;
#for!: HTMLInputElement;
#internals: ElementInternals;
#interacted = false;
#serverError: string | undefined = undefined;
#serverErrorValue: string | undefined = undefined;
constructor() {
super();
this.#internals = this.attachInternals();
}
connectedCallback() {
this.#initializeInput();
this.#initializeUsability();
this.#initializeTemplate();
this.#initializeServerError();
this.#for.addEventListener("input", this.#handleInput);
this.#for.addEventListener("change", this.#handleChange);
this.#for.addEventListener("invalid", this.#handleInvalid);
}
disconnectedCallback() {
this.#for.removeEventListener("input", this.#handleInput);
this.#for.removeEventListener("change", this.#handleChange);
this.#for.removeEventListener("invalid", this.#handleInvalid);
}
#initializeServerError() {
if (!this.innerHTML.trim()) return;
// Flag is interacted so that the user can remove the error message on input.
this.#interacted = true;
this.#serverError = this.innerHTML;
this.#serverErrorValue = this.#for.value;
// We only set the custom validity if the element is persistent.
// If we set this while not persistent, the client will not be able to submit the form
if (this.hasAttribute("persistent")) {
this.#for.setCustomValidity(this.#serverError);
}
// If the element is added to the DOM, we need to wait until the element is rendered.
// Otherwise, transitions/animations will not work correctly.
requestAnimationFrame(() => {
this.#internals.states.add("has-error");
});
// This is a hack to make the server-side validation error stylable in the input element.
this.#for.setAttribute("data-server-invalid", "true");
}
#initializeInput() {
if (!this.hasAttribute("for")) {
throw new Error('ValidationOutput: Missing "for" attribute');
}
const _for = document.getElementById(
this.getAttribute("for") as string,
);
if (!_for) {
throw new Error(
"ValidationOutput: No element with ID " +
this.getAttribute("for"),
);
}
this.#for = _for as HTMLInputElement;
}
#initializeUsability() {
// Add reasonable defaults for screen readers
if (!this.hasAttribute("aria-live")) {
this.setAttribute("aria-live", "polite");
}
if (!this.hasAttribute("role")) {
this.setAttribute("role", "alert");
}
}
#initializeTemplate() {
if (!this.hasAttribute("template")) return;
const template = document.getElementById(
this.getAttribute("template") as string,
);
if (!(template instanceof HTMLTemplateElement)) {
throw new Error("Target template must be a <template> element");
}
this.#template = template.content.cloneNode(true) as DocumentFragment;
}
#handleInput = () => {
// The form could be tried to be submitted but failed on other inputs.
// In this case, our #for target is flagged as "interacted" and gets the :user-invalid state.
if (this.#for.matches(":user-invalid")) {
this.#interacted = true;
}
// User did not interact yet with the input element; this means that :user-invalid state is not applied yet.
if (!this.#interacted) {
return;
}
this.#validate();
};
#handleChange = () => {
this.#interacted = true;
this.#validate();
};
#handleInvalid = (e: Event) => {
this.#interacted = true;
this.#validate();
// Prevent the default validation message from being displayed
e.preventDefault();
};
#validate() {
this.#for.setCustomValidity("");
// Remove the server-side validation error fix, from this point we can use the `:user-invalid` state.`
if (this.#for.hasAttribute("data-server-invalid")) {
this.#for.removeAttribute("data-server-invalid");
}
// Check if the user reverted to the original server-rejected value
if (
this.#serverError &&
this.#for.value === this.#serverErrorValue &&
this.hasAttribute("persistent")
) {
this.#for.setCustomValidity(this.#serverError);
this.#setErrorMessage(this.#serverError);
return;
}
// The first :user-invalid state is applied on the "change" event.
// After the first :user-invalid state is applied, the state can be reapplied from the "input" event.
// E.g.: It starts functioning as the :invalid state.
if (this.#for.matches(":user-invalid")) {
this.#setErrorMessage(
this.#getCustomValidationMessage(this.#for.validity) ??
this.#for.validationMessage,
);
return;
}
// We don't remove the error message if there is a transition, we just remove the `has-error` state.
// It will trigger the transition, and after the transition, the error message will be removed.
// This makes it easier to style and animate the error message.
if (!this.#internals.states.has("has-error")) return;
const transitionDuration = parseFloat(
getComputedStyle(this).transitionDuration,
);
this.#internals.states.delete("has-error");
if (transitionDuration === 0) {
this.innerHTML = "";
return;
}
const handleTransitionEnd = () => {
if (this.matches(":user-invalid")) return;
this.innerHTML = "";
};
this.addEventListener("transitionend", handleTransitionEnd, {
once: true,
});
}
#setErrorMessage(message: string | DocumentFragment) {
this.innerHTML = "";
if (message instanceof DocumentFragment) {
this.appendChild(message);
} else {
this.innerHTML = message;
}
this.#internals.states.add("has-error");
}
#getCustomValidationMessage(
validity: ValidityState,
): DocumentFragment | null {
if (!this.#template) return null;
for (const key in validity) {
if (!validity[key as keyof ValidityState]) continue;
const template = this.#template.querySelector(
`template[data-validity="${key}"]`,
) as HTMLTemplateElement | null;
if (template) {
return template.content.cloneNode(true) as DocumentFragment;
}
}
return null;
}
}
customElements.define("validation-output", ValidationOutput);