Repository navigation
Expand file tree
/
Copy pathform-required-checkboxes.js
More file actions
303 lines (275 loc) · 7.57 KB
/
Copy pathform-required-checkboxes.js
File metadata and controls
303 lines (275 loc) · 7.57 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
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
import defaultTranslations from './translations.js';
export class FormRequiredCheckboxesElement extends HTMLElement {
#boundHandleValidation = null;
#boundResetValidity = null;
// Static property for custom translations
static customTranslations = {};
// Property reflection: observedAttributes
static get observedAttributes() {
return ['notice', 'error', 'required', 'lang'];
}
// Static method to register custom translations
static registerTranslations(translations) {
this.customTranslations = {
...this.customTranslations,
...translations,
};
}
get notice() {
return this.getAttribute('notice');
}
set notice(val) {
if (val === null || val === undefined) {
this.removeAttribute('notice');
} else {
this.setAttribute('notice', val);
}
}
get error() {
return this.getAttribute('error');
}
set error(val) {
if (val === null || val === undefined) {
this.removeAttribute('error');
} else {
this.setAttribute('error', val);
}
}
get required() {
return this.getAttribute('required');
}
set required(val) {
if (val === null || val === undefined) {
this.removeAttribute('required');
} else {
this.setAttribute('required', val);
}
}
get lang() {
return this.getAttribute('lang');
}
set lang(val) {
if (val === null || val === undefined) {
this.removeAttribute('lang');
} else {
this.setAttribute('lang', val);
}
}
// Instance helper methods below accessors
_upgradeProperty(prop) {
if (Object.prototype.hasOwnProperty.call(this, prop)) {
const value = this[prop];
delete this[prop];
this[prop] = value;
}
}
connectedCallback() {
// Upgrade properties set before element definition
this._upgradeProperty('notice');
this._upgradeProperty('error');
this._upgradeProperty('required');
this._upgradeProperty('lang');
requestAnimationFrame(() => {
this.__element_name = this.nodeName.toLowerCase();
this.__$checkboxes = this.querySelectorAll("[type='checkbox']");
this.__field_name = this.__$checkboxes[0].name;
this.__notice = this.notice;
this.__error = this.error;
this.__$fieldset = this.querySelector('fieldset');
this.__$legend = this.querySelector('legend');
this.__lang =
this.lang ||
this.closest('[lang]')?.getAttribute('lang') ||
document.documentElement.lang ||
'en';
this.__getMinMax();
this.__addDescription();
this.__setupAccessibleName();
this.__setupValidation();
});
}
disconnectedCallback() {
// Remove event listeners for cleanup
if (this.__$target && this.#boundHandleValidation) {
this.__$target.removeEventListener(
'formdata',
this.#boundHandleValidation,
);
this.__$target.removeEventListener(
'submit',
this.#boundHandleValidation,
);
}
if (this.__$checkboxes && this.#boundResetValidity) {
this.__$checkboxes.forEach((input) => {
input.removeEventListener('change', this.#boundResetValidity);
});
}
}
__getTranslations() {
// Merge default and custom translations, with custom taking precedence
const allTranslations = {
...defaultTranslations,
...FormRequiredCheckboxesElement.customTranslations,
};
// Get translations for current language, fallback to English
const langCode = this.__lang.split('-')[0]; // e.g., 'en-US' -> 'en'
return allTranslations[langCode] || allTranslations.en;
}
static __interpolate(template, values) {
return template.replace(
/\{(\w+)\}/g,
(match, key) => values[key] || match,
);
}
__getMinMax() {
const required = this.getAttribute('required');
if (!required) {
throw new Error(
'You must specify a `required` number of checkbox choices in a `form-required-checkboxes` element',
);
}
if (required.indexOf('-') > 0) {
[this.__min, this.__max] = required.split('-');
} else {
this.__min = required;
this.__max = required;
}
}
__addDescription() {
this.__$description = document.createElement('small');
this.__$description.id = `${this.__field_name.replace('[]', '')}-description`;
if (!this.__notice) {
const t = this.__getTranslations();
if (this.__min == this.__max) {
this.__notice = FormRequiredCheckboxesElement.__interpolate(
t.exact,
{ n: this.__min },
);
} else if (this.__min == 0) {
this.__notice = FormRequiredCheckboxesElement.__interpolate(
t.max,
{ n: this.__max },
);
} else {
this.__notice = FormRequiredCheckboxesElement.__interpolate(
t.range,
{
min: this.__min,
max: this.__max,
},
);
}
}
if (!this.__error) {
const t = this.__getTranslations();
if (this.__min == this.__max) {
this.__error = FormRequiredCheckboxesElement.__interpolate(
t.error_exact,
{ n: this.__min },
);
} else {
this.__error = FormRequiredCheckboxesElement.__interpolate(
t.error_range,
{
min: this.__min,
max: this.__max,
},
);
}
}
// Only update innerText if changed
if (this.__$description.innerText !== this.__notice) {
this.__$description.innerText = this.__notice;
}
// Only insert if not already present
if (this.__$legend) {
if (this.__$legend.nextSibling !== this.__$description) {
this.__$legend.after(this.__$description);
}
} else {
if (
(this.__$fieldset ? this.__$fieldset : this).lastChild !==
this.__$description
) {
(this.__$fieldset ? this.__$fieldset : this).appendChild(
this.__$description,
);
}
}
}
__setupAccessibleName() {
if (this.__$legend && !this.__$legend.id) {
this.__$legend.id = `${this.__field_name.replace('[]', '')}-legend`;
}
const labelValue = `${this.__$legend ? this.__$legend.id : ''} ${this.__$description.id}`;
const target = this.__$fieldset ? this.__$fieldset : this;
if (target.getAttribute('aria-labelledby') !== labelValue) {
target.setAttribute('aria-labelledby', labelValue);
}
}
__setupValidation() {
this.__$form = this.closest('form');
this.__$target = this.__$form || document.body;
// Bind handlers once
if (!this.#boundHandleValidation) {
this.#boundHandleValidation = this.__handleValidation.bind(this);
}
if (!this.#boundResetValidity) {
this.#boundResetValidity = this.__resetValidity.bind(this);
}
this.__$target.addEventListener(
'formdata',
this.#boundHandleValidation,
);
this.__$target.addEventListener('submit', this.#boundHandleValidation);
this.__$checkboxes.forEach((input) => {
input.addEventListener('change', this.#boundResetValidity);
});
}
__handleValidation(e) {
const total_checked = [...this.__$checkboxes].filter(
(input) => input.checked,
).length;
if (total_checked < this.__min || total_checked > this.__max) {
e.preventDefault();
this.__$checkboxes[0].setCustomValidity(
this.__error ? this.__error : this.__notice,
);
if (this.__shouldShowFieldError(this.__$checkboxes[0])) {
this.__$checkboxes[0].reportValidity();
}
}
}
__shouldShowFieldError(input) {
// If no form exists, always show the error
if (!this.__$form) {
return true;
}
const $all_fields = [...this.__$form.elements].filter((element) =>
element.matches(
'input:not([type=submit],[type=reset]),textarea,select',
),
);
let i = 0;
const length = $all_fields.length;
while (i < length) {
// this field should throw the error
if ($all_fields[i].name == input.name) {
return true;
}
// another field should throw the error
if (!$all_fields[i].validity.valid) {
return false;
}
i++;
}
return true;
}
__resetValidity() {
// Use cached checkboxes for validity reset
if (this.__$checkboxes) {
this.__$checkboxes.forEach((input) => input.setCustomValidity(''));
}
}
}