-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelement.js
391 lines (339 loc) · 10.8 KB
/
element.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
import { aria } from './aom.js';
import { polyfillGetterSetter, polyfillMethod, overwriteMethod } from './utils.js';
import { getHTML, setHTMLUnsafe } from './methods/dom.js';
import './sanitizer.js';
polyfillMethod(Element.prototype, 'setHTMLUnsafe', setHTMLUnsafe);
polyfillMethod(Element.prototype, 'getHTML', getHTML);
if ('CustomElementRegistry' in globalThis && ! (CustomElementRegistry.prototype.getName instanceof Function)) {
const registry = new Map();
overwriteMethod(CustomElementRegistry.prototype, 'define', original => {
return (tag, proto, opts) => {
original.call(customElements, tag,proto, opts);
registry.set(proto, typeof opts.extends === 'string' ? opts.extends : tag);
};
});
polyfillMethod(CustomElementRegistry.prototype, 'getName', proto => {
if (typeof proto === 'function') {
return registry.get(proto) ?? null;
} else if (typeof proto === 'object' && proto !== null) {
// Unnecessary, but just to be sure the same errors are thrown.
throw new TypeError('CustomElementRegistry.getName: Argument 1 is not callable.');
} else {
throw new TypeError('CustomElementRegistry.getName: Argument 1 is not an object.');
}
});
}
function handlePopover({ currentTarget }) {
switch(currentTarget.popoverTargetAction) {
case 'show':
currentTarget.popoverTargetElement.showPopover();
break;
case 'hide':
currentTarget.popoverTargetElement.hidePopover();
break;
default:
currentTarget.popoverTargetElement.togglePopover();
}
}
export function initPopover(target = document.body) {
target.querySelectorAll('button[popovertarget], input[type="button"][popovertarget]')
.forEach(el => el.addEventListener('click', handlePopover));
}
if (! (globalThis.ToggleEvent instanceof Function)) {
class ToggleEvent extends Event {
#newState;
#oldState;
constructor(type, { newState, oldState }) {
super(type, { bubbles: true });
this.#newState = newState;
this.#oldState = oldState;
}
get newState() {
return this.#newState;
}
get oldState() {
return this.#oldState;
}
}
globalThis.ToggleEvent = ToggleEvent;
}
if (! (HTMLElement.prototype.showPopover instanceof Function)) {
const isPopoverOpen = el => el.classList.contains('_popover-open');
Object.defineProperties(HTMLElement.prototype, {
showPopover: {
value: function showPopover() {
if (! isPopoverOpen(this)) {
this.dispatchEvent(new ToggleEvent('beforetoggle', { oldState: 'closed', newState: 'open' }));
if (this.getAttribute('popover') === 'auto') {
const controller = new AbortController();
document.body.addEventListener('click', ({ target }) => {
if (! this.contains(target) && ! this.isSameNode(target.popoverTargetElement)) {
controller.abort();
this.hidePopover();
}
}, { signal: controller.signal, capture: true });
document.body.addEventListener('keydown', ({ key }) => {
if (key === 'Escape') {
controller.abort();
this.hidePopover();
}
}, { signal: controller.signal, capture: true });
document.addEventListener('beforetoggle', ({ target }) => {
if (! target.isSameNode(this) && target.getAttribute('popover') === 'auto') {
controller.abort();
this.hidePopover();
}
}, { signal: controller.signal });
}
this.classList.add('_popover-open');
this.dispatchEvent(new ToggleEvent('toggle', { oldState: 'closed', newState: 'open' }));
}
}
},
hidePopover: {
value: function hidePopover() {
if (isPopoverOpen(this)) {
this.dispatchEvent(new ToggleEvent('beforetoggle', { oldState: 'open', newState: 'closed' }));
queueMicrotask(() => this.classList.remove('_popover-open'));
this.dispatchEvent(new ToggleEvent('toggle', { oldState: 'open', newState: 'closed' }));
}
}
},
togglePopover: {
value: function togglePopover() {
isPopoverOpen(this) ? this.hidePopover() : this.showPopover();
}
}
});
Object.defineProperties(HTMLButtonElement.prototype, {
popoverTargetElement: {
get() {
return document.getElementById(this.getAttribute('popovertarget'));
}
},
popoverTargetAction: {
get() {
return this.getAttribute('popovertargetaction') || 'toggle';
},
set(val) {
this.setAttribute('popovertargetaction', val);
}
}
});
initPopover();
}
if (! (HTMLScriptElement.supports instanceof Function)) {
HTMLScriptElement.supports = function supports(type) {
switch(type.toLowerCase()) {
case 'classic':
return true;
case 'module':
return 'noModule' in HTMLScriptElement.prototype;
case 'importmap':
return false;
case 'speculationrules':
return false;
default:
return false;
}
};
}
if (! Element.prototype.hasOwnProperty(aria.role)) {
const enumerable = true;
const configurable = true;
const props = Object.fromEntries(Object.entries(aria).map(([prop, attr]) => [prop, {
get: function() {
return this.getAttribute(attr);
},
set: function(val) {
if (typeof val === 'string') {
this.setAttribute(attr, val);
} else {
this.removeAttribute(attr);
}
},
enumerable, configurable,
}]));
Object.defineProperties(Element.prototype, props);
}
if (! HTMLElement.prototype.hasOwnProperty('inert')) {
// CSS will handle pointer events
const previous = new WeakMap();
const restoreTabIndex = el => {
if (previous.has(el)) {
el.tabIndex = previous.get(el);
}
if (el.hasChildNodes()) {
[...el.children].forEach(restoreTabIndex);
}
};
const setTabIndex = el => {
if (el.tabIndex !== -1) {
previous.set(el, el.tabIndex);
el.tabIndex = -1;
}
if (el.hasChildNodes()) {
[...el.children].forEach(setTabIndex);
}
};
Object.defineProperty(HTMLElement.prototype, 'inert', {
get: function() {
return this.hasAttribute('inert');
},
set: function(val) {
if (val) {
this.setAttribute('aria-hidden', 'true');
this.setAttribute('inert', '');
setTabIndex(this);
} else {
this.removeAttribute('aria-hidden');
this.removeAttribute('inert');
restoreTabIndex(this);
}
},
enumerable: true, configurable: true,
});
}
if (! HTMLImageElement.prototype.hasOwnProperty('complete')) {
/**
* Note: This shim cannot detect if an image has an error while loading
* and will return false on an invalid URL, for example. It also does not
* work for 0-sized images, if such a thing is possible.
*/
Object.defineProperty(HTMLImageElement.prototype, 'complete', {
get: function() {
return this.src === '' || this.naturalHeight > 0;
}
});
}
if (! (HTMLImageElement.prototype.decode instanceof Function)) {
HTMLImageElement.prototype.decode = function () {
if (this.complete) {
return Promise.resolve();
} else {
return new Promise((resolve, reject) => {
const load = () => {
this.removeEventListener('error', error);
this.removeEventListener('load', load);
resolve();
};
const error = (err) => {
this.removeEventListener('error', error);
this.removeEventListener('load', load);
reject(err);
};
this.addEventListener('load', load);
this.addEventListener('error', error);
});
}
};
}
if (! HTMLTemplateElement.prototype.hasOwnProperty('shadowRootMode')) {
const attachedShadows = new WeakMap();
polyfillGetterSetter(HTMLTemplateElement.prototype, 'shadowRootMode', {
get() {
return this.getAttribute('shadowrootmode');
},
set(val) {
this.setAttribute('shadowrootmode', val);
}
});
polyfillGetterSetter(HTMLTemplateElement.prototype, 'shadowRootDelegatesFocus', {
get() {
return this.hasAttribute('shadowrootdelegatesfocus');
},
set(val) {
this.toggleAttribute('shadowrootdelegatesfocus', val);
}
});
polyfillGetterSetter(HTMLTemplateElement.prototype, 'shadowRootClonable', {
get() {
return this.hasAttribute('shadowrootclonable');
},
set(val) {
this.toggleAttribute('shadowrootclonable', val);
}
});
polyfillGetterSetter(HTMLTemplateElement.prototype, 'shadowRootSerializable', {
get() {
return this.hasAttribute('shadowrootserializable');
},
set(val) {
this.toggleAttribute('shadowrootserializable', val);
}
});
const attachShadows = (base = document) => {
base.querySelectorAll('template[shadowrootmode]').forEach(tmp => {
const shadow = tmp.parentElement.attachShadow({
mode: tmp.shadowRootMode,
clonable: tmp.shadowRootClonable,
delegatesFocus: tmp.shadowRootDelegatesFocus,
serializable: tmp.shadowRootSerializable,
});
shadow.append(tmp.content);
tmp.remove();
attachShadows(shadow);
attachedShadows.set(shadow.host, shadow);
});
};
overwriteMethod(HTMLElement.prototype, 'attachShadow', function(attach) {
return ({ mode, clonable = false, delegatesFocus = false, serializable = false, slotAssignment = 'auto' }) => {
if (! attachedShadows.has(this)) {
return attach.call(this, { mode, clonable, delegatesFocus, serializable, slotAssignment });
} else {
const shadow = attachedShadows.get(this);
if (mode === shadow.shadowRootMode) {
attachShadows.remove(this);
return shadow;
} else {
throw new DOMException('Element.attachShadow: Unable to re-attach to existing ShadowDOM');
}
}
};
});
if (document.readyState === 'loading') {
document.addEventListener('readystatechange', () => attachShadows(document), { once: true });
} else {
attachShadows(document);
}
}
if (! (HTMLFormElement.prototype.requestSubmit instanceof Function)) {
HTMLFormElement.prototype.requestSubmit = function(submitter) {
if (typeof submitter === 'undefined') {
const btn = document.createElement('button');
btn.type = 'submit';
btn.hidden = true;
this.append(btn);
this.requestSubmit(btn);
setTimeout(() => btn.remove(), 100);
} else if (! (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement)) {
throw new TypeError('HTMLFormElement.requestSubmit: The submitter is not a submit button.');
} else if (submitter.type !== 'submit' && ! (submitter instanceof HTMLInputElement && submitter.type === 'image')) {
throw new TypeError('HTMLFormElement.requestSubmit: The submitter is not a submit button.');
} else if (! this.isSameNode(submitter.form)) {
throw new DOMException('HTMLFormElement.requestSubmit: The submitter is not owned by this form.', 'NotFoundError');
} else {
submitter.click();
}
};
}
if (! ('loading' in HTMLIFrameElement.prototype)) {
polyfillGetterSetter(HTMLIFrameElement.prototype, 'loading', {
get: function() {
return this.getAttribute('loading') || 'auto';
},
set: function(val) {
this.setAttribute('loading', val);
}
});
}
if (! ('credentialless' in HTMLIFrameElement.prototype)) {
polyfillGetterSetter(HTMLIFrameElement.prototype, 'credentialless', {
get: function() {
return this.hasAttribute('credentialless');
},
set: function(val) {
this.toggleAttribute('credentialless', val);
}
});
}