-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope_polyfill.js
95 lines (79 loc) · 3.22 KB
/
scope_polyfill.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
"use strict";
/**
Created by Complynx on 22.03.2019,
http://complynx.net
<[email protected]> Daniel Drizhuk
*/
/**
* if browser doesn't support `:scope` selector
*/
(function() {
if (!HTMLElement.prototype.querySelectorAll) {
throw new Error('rootedQuerySelectorAll: This polyfill can only be used with browsers that support querySelectorAll');
}
// A temporary element to query against for elements not currently in the DOM
// We'll also use this element to test for :scope support
let container = document.createElement('div');
// Check if the browser supports :scope
try {
// Browser supports :scope, do nothing
container.querySelectorAll(':scope *');
}
catch (e) {
// Match usage of scope
let rxTest = /(?:^|,)\s*:scope\s+/,
rxStart = /^\s*:scope\s+/i,
rxOthers = /,\s*:scope\s+/gi;
// Overrides
let overrideNodeMethod = (prototype, methodName)=>{
// Store the old method for use later
let oldMethod = prototype[methodName];
// Override the method
prototype[methodName] = function(query) {
let nodeList, parentNode, frag, idSelector,
gaveId = false,
gaveContainer = false,
parentIsFragment = false;
if (rxTest.test(query)) {
if (!this.parentNode) {
// Add to temporary container
container.appendChild(this);
gaveContainer = true;
}
if (this.parentNode instanceof DocumentFragment) {
frag = this.parentNode;
while (frag.firstChild) container.appendChild(frag.firstChild);
parentIsFragment = true;
}
let parentNode = this.parentNode;
if (!this.id) {
// Give temporary ID
this.id = 'rootedQuerySelector_id_'+(new Date()).getTime();
gaveId = true;
}
query = query.replace(rxStart, '#'+this.id).replace(rxOthers, ', #'+this.id);
// Find elements against parent node
nodeList = oldMethod.call(parentNode, query);
// Reset the ID
if (gaveId) {
this.id = '';
}
// Remove from temporary container
if (parentIsFragment) {
while (container.firstChild) frag.appendChild(container.firstChild);
} else if (gaveContainer) {
container.removeChild(this);
}
return nodeList;
}
else {
// No immediate child selector used
return oldMethod.call(this, query);
}
};
};
// Browser doesn't support :scope, add polyfill
overrideNodeMethod(HTMLElement.prototype, 'querySelector');
overrideNodeMethod(HTMLElement.prototype, 'querySelectorAll');
}
}());