-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathbrowser.js
269 lines (231 loc) · 8.97 KB
/
browser.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
import '@mrhenry/core-web/modules/~element-qsa-has.js';
import extractEncodedSelectors from './encode/extract.mjs';
import encodeCSS from './encode/encode.mjs';
function hasNativeSupport() {
try {
if (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {
return false;
}
} catch (_) {
return false;
}
return true;
}
export default function cssHasPseudo(document, options) {
// OPTIONS
{
if (!options) {
options = {};
}
options = {
hover: (!!options.hover) || false,
debug: (!!options.debug) || false,
observedAttributes: options.observedAttributes || [],
forcePolyfill: (!!options.forcePolyfill) || false,
};
options.mustPolyfill = options.forcePolyfill || !hasNativeSupport();
if (!Array.isArray(options.observedAttributes)) {
options.observedAttributes = [];
}
options.observedAttributes = options.observedAttributes.filter((x) => {
return (typeof x === 'string');
});
// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
// `data-*` and `style` were omitted
options.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);
}
const observedItems = [];
// document.createAttribute() doesn't support `:` in the name. innerHTML does
const attributeElement = document.createElement('x');
// walk all stylesheets to collect observed css rules
[].forEach.call(document.styleSheets, walkStyleSheet);
if (!options.mustPolyfill) {
// Cleanup of rules will have happened in `walkStyleSheet`
// Native support will take over from here
return;
}
transformObservedItemsThrottled();
// observe DOM modifications that affect selectors
if ('MutationObserver' in self) {
const mutationObserver = new MutationObserver((mutationsList) => {
mutationsList.forEach(mutation => {
[].forEach.call(mutation.addedNodes || [], node => {
// walk stylesheets to collect observed css rules
if (node.nodeType === 1 && node.sheet) {
walkStyleSheet(node.sheet);
}
});
// transform observed css rules
cleanupObservedCssRules();
transformObservedItemsThrottled();
});
});
mutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });
}
// observe DOM events that affect pseudo-selectors
document.addEventListener('focus', transformObservedItemsThrottled, true);
document.addEventListener('blur', transformObservedItemsThrottled, true);
document.addEventListener('input', transformObservedItemsThrottled);
document.addEventListener('change', transformObservedItemsThrottled, true);
if (options.hover) {
if ('onpointerenter' in document) {
document.addEventListener('pointerenter', transformObservedItemsThrottled, true);
document.addEventListener('pointerleave', transformObservedItemsThrottled, true);
} else {
document.addEventListener('mouseover', transformObservedItemsThrottled, true);
document.addEventListener('mouseout', transformObservedItemsThrottled, true);
}
}
// observe Javascript setters that effect pseudo-selectors
if ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {
try {
function observeProperty(proto, property) {
// eslint-disable-next-line no-prototype-builtins
if (proto.hasOwnProperty(property)) {
const descriptor = Object.getOwnPropertyDescriptor(proto, property);
if (descriptor && descriptor.configurable && 'set' in descriptor) {
Object.defineProperty(proto, property, {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
get: function () {
return descriptor.get.apply(this, arguments);
},
set: function () {
descriptor.set.apply(this, arguments);
try {
transformObservedItemsThrottled();
} catch (_) {
// should never happen as there is an inner try/catch
// but just in case
}
},
});
}
}
}
if ('HTMLElement' in self && HTMLElement.prototype) {
observeProperty(HTMLElement.prototype, 'disabled');
}
// Not all of these elements have all of these properties.
// But the code above checks if they exist first.
['checked', 'selected', 'readOnly', 'required'].forEach((property) => {
[
'HTMLButtonElement',
'HTMLFieldSetElement',
'HTMLInputElement',
'HTMLMeterElement',
'HTMLOptGroupElement',
'HTMLOptionElement',
'HTMLOutputElement',
'HTMLProgressElement',
'HTMLSelectElement',
'HTMLTextAreaElement',
].forEach((elementName) => {
if (elementName in self && self[elementName].prototype) {
observeProperty(self[elementName].prototype, property);
}
});
});
} catch (e) {
if (options.debug) {
console.error(e);
}
}
}
let transformObservedItemsThrottledBusy = false;
function transformObservedItemsThrottled() {
if (transformObservedItemsThrottledBusy) {
cancelAnimationFrame(transformObservedItemsThrottledBusy);
}
transformObservedItemsThrottledBusy = requestAnimationFrame(() => {
transformObservedItems();
});
}
// transform observed css rules
function transformObservedItems() {
observedItems.forEach((item) => {
const nodes = [];
let matches = [];
try {
matches = document.querySelectorAll(item.selector);
} catch (e) {
if (options.debug) {
console.error(e);
}
return;
}
[].forEach.call(matches, (element) => {
// memorize the node
nodes.push(element);
// set an attribute with an irregular attribute name
// document.createAttribute() doesn't support special characters
attributeElement.innerHTML = '<x ' + item.attributeName + '>';
element.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());
// trigger a style refresh in IE and Edge
document.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;
});
// remove the encoded attribute from all nodes that no longer match them
item.nodes.forEach(node => {
if (nodes.indexOf(node) === -1) {
node.removeAttribute(item.attributeName);
// trigger a style refresh in IE and Edge
document.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;
}
});
// update the
item.nodes = nodes;
});
}
// remove any observed cssrules that no longer apply
function cleanupObservedCssRules() {
[].push.apply(
observedItems,
observedItems.splice(0).filter((item) => {
return item.rule.parentStyleSheet &&
item.rule.parentStyleSheet.ownerNode &&
document.documentElement.contains(item.rule.parentStyleSheet.ownerNode);
}),
);
}
// walk a stylesheet to collect observed css rules
function walkStyleSheet(styleSheet) {
try {
// walk a css rule to collect observed css rules
[].forEach.call(styleSheet.cssRules || [], (rule, index) => {
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(/\.js-has-pseudo\s/g, '');
try {
// decode the selector text in all browsers to:
const hasSelectors = extractEncodedSelectors(rule.selectorText.toString());
if (hasSelectors.length === 0) {
return;
}
if (!options.mustPolyfill) {
styleSheet.deleteRule(index);
return;
}
for (let i = 0; i < hasSelectors.length; i++) {
const hasSelector = hasSelectors[i];
observedItems.push({
rule: rule,
selector: hasSelector,
attributeName: encodeCSS(hasSelector),
nodes: [],
});
}
} catch (e) {
if (options.debug) {
console.error(e);
}
}
} else {
walkStyleSheet(rule);
}
});
} catch (e) {
if (options.debug) {
console.error(e);
}
}
}
}