group all style management stuff in injector

This commit is contained in:
tophf 2020-02-11 15:19:59 +03:00
parent cb4f875fe1
commit e9584b2cab
2 changed files with 244 additions and 282 deletions

View File

@ -10,25 +10,12 @@ self.INJECTED !== 1 && (() => {
self.INJECTED = 1; self.INJECTED = 1;
const STYLE_VIA_API = !chrome.app && document instanceof XMLDocument; const STYLE_VIA_API = !chrome.app && document instanceof XMLDocument;
const IS_OWN_PAGE = Boolean(chrome.tabs);
const styleInjector = createStyleInjector({ const styleInjector = createStyleInjector({
compare: (a, b) => a.id - b.id, compare: (a, b) => a.id - b.id,
onUpdate: onInjectorUpdate onUpdate: onInjectorUpdate,
});
const docRootObserver = createDocRootObserver({
onChange: () => {
if (styleInjector.outOfOrder()) {
styleInjector.sort();
return true;
}
}
});
const docRewriteObserver = createDocRewriteObserver({
onChange: () => {
docRootObserver.evade(styleInjector.sort);
}
}); });
const initializing = init(); const initializing = init();
// save it now because chrome.runtime will be unavailable in the orphaned script // save it now because chrome.runtime will be unavailable in the orphaned script
const orphanEventId = chrome.runtime.id; const orphanEventId = chrome.runtime.id;
let isOrphaned; let isOrphaned;
@ -37,7 +24,7 @@ self.INJECTED !== 1 && (() => {
msg.onTab(applyOnMessage); msg.onTab(applyOnMessage);
if (!IS_OWN_PAGE) { if (!chrome.tabs) {
window.dispatchEvent(new CustomEvent(orphanEventId)); window.dispatchEvent(new CustomEvent(orphanEventId));
window.addEventListener(orphanEventId, orphanCheck, true); window.addEventListener(orphanEventId, orphanCheck, true);
} }
@ -50,22 +37,16 @@ self.INJECTED !== 1 && (() => {
} }
function onInjectorUpdate() { function onInjectorUpdate() {
if (!IS_OWN_PAGE && styleInjector.list.length) { if (!isOrphaned) {
docRewriteObserver.start(); updateCount();
docRootObserver.start(); updateExposeIframes();
} else {
docRewriteObserver.stop();
docRootObserver.stop();
} }
if (isOrphaned) return;
updateCount();
updateExposeIframes();
} }
function init() { function init() {
return STYLE_VIA_API ? return STYLE_VIA_API ?
API.styleViaAPI({method: 'styleApply'}) : API.styleViaAPI({method: 'styleApply'}) :
API.getSectionsByUrl(getMatchUrl()).then(applyStyles); API.getSectionsByUrl(getMatchUrl()).then(styleInjector.apply);
} }
function getMatchUrl() { function getMatchUrl() {
@ -108,7 +89,7 @@ self.INJECTED !== 1 && (() => {
if (!sections[request.style.id]) { if (!sections[request.style.id]) {
styleInjector.remove(request.style.id); styleInjector.remove(request.style.id);
} else { } else {
applyStyles(sections); styleInjector.apply(sections);
} }
}); });
} else { } else {
@ -119,13 +100,13 @@ self.INJECTED !== 1 && (() => {
case 'styleAdded': case 'styleAdded':
if (request.style.enabled) { if (request.style.enabled) {
API.getSectionsByUrl(getMatchUrl(), request.style.id) API.getSectionsByUrl(getMatchUrl(), request.style.id)
.then(applyStyles); .then(styleInjector.apply);
} }
break; break;
case 'urlChanged': case 'urlChanged':
API.getSectionsByUrl(getMatchUrl()) API.getSectionsByUrl(getMatchUrl())
.then(replaceAll); .then(styleInjector.replace);
break; break;
case 'backgroundReady': case 'backgroundReady':
@ -197,31 +178,6 @@ self.INJECTED !== 1 && (() => {
}).catch(console.error); }).catch(console.error);
} }
function applyStyles(sections) {
return new Promise(resolve => {
const styles = styleMapToArray(sections);
if (styles.length) {
docRootObserver.evade(() => {
styleInjector.addMany(styles);
resolve();
});
} else {
resolve();
}
});
}
function replaceAll(newStyles) {
styleInjector.replaceAll(styleMapToArray(newStyles));
}
function styleMapToArray(styleMap) {
return Object.values(styleMap).map(s => ({
id: s.id,
code: s.code.join(''),
}));
}
function orphanCheck() { function orphanCheck() {
try { try {
if (chrome.i18n.getUILanguage()) return; if (chrome.i18n.getUILanguage()) return;
@ -235,93 +191,4 @@ self.INJECTED !== 1 && (() => {
msg.off(applyOnMessage); msg.off(applyOnMessage);
} catch (e) {} } catch (e) {}
} }
function createDocRewriteObserver({onChange}) {
// detect documentElement being rewritten from inside the script
let root;
let observing = false;
let timer;
const observer = new MutationObserver(check);
return {start, stop};
function start() {
if (observing) return;
// detect dynamic iframes rewritten after creation by the embedder i.e. externally
root = document.documentElement;
timer = setTimeout(check);
observer.observe(document, {childList: true});
observing = true;
}
function stop() {
if (!observing) return;
clearTimeout(timer);
observer.disconnect();
observing = false;
}
function check() {
if (root !== document.documentElement) {
root = document.documentElement;
onChange();
}
}
}
function createDocRootObserver({onChange}) {
let digest = 0;
let lastCalledTime = NaN;
let observing = false;
const observer = new MutationObserver(() => {
if (digest) {
if (performance.now() - lastCalledTime > 1000) {
digest = 0;
} else if (digest > 5) {
throw new Error('The page keeps generating mutations. Skip the event.');
}
}
if (onChange()) {
digest++;
lastCalledTime = performance.now();
}
});
return {start, stop, evade};
function start() {
if (observing) return;
observer.observe(document.documentElement, {childList: true});
observing = true;
}
function stop() {
if (!observing) return;
// FIXME: do we need this?
observer.takeRecords();
observer.disconnect();
observing = false;
}
function evade(fn) {
if (observing) {
stop();
_run(fn);
start();
} else {
_run(fn);
}
}
function _run(fn) {
if (document.documentElement) {
fn();
} else {
new MutationObserver((mutations, observer) => {
if (document.documentElement) {
observer.disconnect();
fn();
}
}).observe(document, {childList: true});
}
}
}
})(); })();

View File

@ -8,8 +8,11 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
const PATCH_ID = 'transition-patch'; const PATCH_ID = 'transition-patch';
// styles are out of order if any of these elements is injected between them // styles are out of order if any of these elements is injected between them
const ORDERED_TAGS = new Set(['head', 'body', 'frameset', 'style', 'link']); const ORDERED_TAGS = new Set(['head', 'body', 'frameset', 'style', 'link']);
const IS_OWN_PAGE = Boolean(chrome.tabs);
// detect Chrome 65 via a feature it added since browser version can be spoofed // detect Chrome 65 via a feature it added since browser version can be spoofed
const isChromePre65 = chrome.app && typeof Worklet !== 'function'; const isChromePre65 = chrome.app && typeof Worklet !== 'function';
const docRewriteObserver = RewriteObserver(_sort);
const docRootObserver = RootObserver(_sortIfNeeded);
const list = []; const list = [];
const table = new Map(); const table = new Map();
let isEnabled = true; let isEnabled = true;
@ -17,78 +20,74 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
// will store the original method refs because the page can override them // will store the original method refs because the page can override them
let creationDoc, createElement, createElementNS; let creationDoc, createElement, createElementNS;
return { return {
// manipulation apply,
addMany,
remove,
clear, clear,
clearOrphans, clearOrphans,
replaceAll, remove,
replace,
// method
toggle, toggle,
sort,
// state
outOfOrder,
list, list,
// static util
createStyle
}; };
/* function apply(styleMap) {
FF59+ workaround: allow the page to read our sheets, https://github.com/openstyles/stylus/issues/461 const styles = _styleMapToArray(styleMap);
First we're trying the page context document where inline styles may be forbidden by CSP return !styles.length ?
https://bugzilla.mozilla.org/show_bug.cgi?id=1579345#c3 Promise.resolve([]) :
and since userAgent.navigator can be spoofed via about:config or devtools, docRootObserver.evade(() => {
we're checking for getPreventDefault that was removed in FF59 if (!isTransitionPatched) _applyTransitionPatch(styles);
*/ const els = styles.map(_apply);
function _initCreationDoc() { _emitUpdate();
creationDoc = !Event.prototype.getPreventDefault && document.wrappedJSObject; return els;
if (creationDoc) { });
({createElement, createElementNS} = creationDoc);
const el = document.documentElement.appendChild(createStyle());
const isApplied = el.sheet;
el.remove();
if (isApplied) return;
}
creationDoc = document;
({createElement, createElementNS} = document);
} }
function outOfOrder() { function clear() {
if (!list.length) { for (const style of list) {
return false; style.el.remove();
} }
let el = list[0].el; list.length = 0;
if (el.parentNode !== creationDoc.documentElement) { table.clear();
return true; _emitUpdate();
} }
let i = 0;
while (el) { function clearOrphans() {
if (i < list.length && el === list[i].el) { for (const el of document.querySelectorAll(`style[id^="${PREFIX}"].stylus`)) {
i++; const id = el.id.slice(PREFIX.length);
} else if (ORDERED_TAGS.has(el.localName)) { if (/^\d+$/.test(id) || id === PATCH_ID) {
return true; el.remove();
} }
el = el.nextElementSibling;
} }
// some styles are not injected to the document
return i < list.length;
} }
function addMany(styles) { function remove(id) {
if (!isTransitionPatched) _applyTransitionPatch(styles); _remove(id);
const els = styles.map(_add); _emitUpdate();
onUpdate(); }
return els;
function replace(styleMap) {
const styles = _styleMapToArray(styleMap);
const added = new Set(styles.map(s => s.id));
const removed = [];
for (const style of list) {
if (!added.has(style.id)) {
removed.push(style.id);
}
}
styles.forEach(_apply);
removed.forEach(_remove);
_emitUpdate();
}
function toggle(_enabled) {
if (isEnabled === _enabled) return;
isEnabled = _enabled;
for (const style of list) {
style.el.disabled = !isEnabled;
}
} }
function _add(style) { function _add(style) {
if (table.has(style.id)) { const el = style.el = _createStyle(style.id, style.code);
return _update(style);
}
const el = style.el = createStyle(style.id, style.code);
table.set(style.id, style); table.set(style.id, style);
const nextIndex = list.findIndex(i => compare(i, style) > 0); const nextIndex = list.findIndex(i => compare(i, style) > 0);
if (nextIndex < 0) { if (nextIndex < 0) {
@ -103,14 +102,18 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
return el; return el;
} }
// CSS transition bug workaround: since we insert styles asynchronously, function _apply(style) {
// the browsers, especially Firefox, may apply all transitions on page load return table.has(style.id) ? _update(style) : _add(style);
}
function _applyTransitionPatch(styles) { function _applyTransitionPatch(styles) {
// CSS transition bug workaround: since we insert styles asynchronously,
// the browsers, especially Firefox, may apply all transitions on page load
isTransitionPatched = document.readyState === 'complete'; isTransitionPatched = document.readyState === 'complete';
if (isTransitionPatched || !styles.some(s => s.code.includes('transition'))) { if (isTransitionPatched || !styles.some(s => s.code.includes('transition'))) {
return; return;
} }
const el = createStyle(PATCH_ID, ` const el = _createStyle(PATCH_ID, `
:root:not(#\\0):not(#\\0) * { :root:not(#\\0):not(#\\0) * {
transition: none !important; transition: none !important;
} }
@ -121,50 +124,7 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
requestAnimationFrame(() => setTimeout(() => el.remove())); requestAnimationFrame(() => setTimeout(() => el.remove()));
} }
function remove(id) { function _createStyle(id, code = '') {
_remove(id);
onUpdate();
}
function _remove(id) {
const style = table.get(id);
if (!style) return;
table.delete(id);
list.splice(list.indexOf(style), 1);
style.el.remove();
}
function _update({id, code}) {
const style = table.get(id);
if (style.code === code) return;
style.code = code;
// workaround for Chrome devtools bug fixed in v65
if (isChromePre65) {
const oldEl = style.el;
style.el = createStyle(id, code);
oldEl.parentNode.insertBefore(style.el, oldEl.nextSibling);
oldEl.remove();
} else {
style.el.textContent = code;
}
// https://github.com/openstyles/stylus/issues/693
style.el.disabled = !isEnabled;
}
function _supersede(domId) {
const el = document.getElementById(domId);
if (el) {
// remove if it looks like our style that wasn't cleaned up in orphanCheck
// (note, Firefox doesn't orphanize content scripts at all so orphanCheck will never run)
if (el.localName === 'style' && el.classList.contains('stylus')) {
el.remove();
} else {
el.id += ' superseded by Stylus';
}
}
}
function createStyle(id, code = '') {
if (!creationDoc) _initCreationDoc(); if (!creationDoc) _initCreationDoc();
let el; let el;
if (document.documentElement instanceof SVGSVGElement) { if (document.documentElement instanceof SVGSVGElement) {
@ -179,7 +139,8 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
} }
if (id) { if (id) {
el.id = `${PREFIX}${id}`; el.id = `${PREFIX}${id}`;
_supersede(el.id); const oldEl = document.getElementById(el.id);
if (oldEl) oldEl.id += '-superseded-by-Stylus';
} }
el.type = 'text/css'; el.type = 'text/css';
// SVG className is not a string, but an instance of SVGAnimatedString // SVG className is not a string, but an instance of SVGAnimatedString
@ -188,54 +149,188 @@ self.createStyleInjector = self.INJECTED === 1 ? self.createStyleInjector : ({
return el; return el;
} }
function clear() { function _emitUpdate() {
for (const style of list) { if (!IS_OWN_PAGE && list.length) {
style.el.remove(); docRewriteObserver.start();
docRootObserver.start();
} else {
docRewriteObserver.stop();
docRootObserver.stop();
} }
list.length = 0;
table.clear();
onUpdate(); onUpdate();
} }
function clearOrphans() { /*
for (const el of document.querySelectorAll(`style[id^="${PREFIX}-"].stylus`)) { FF59+ workaround: allow the page to read our sheets, https://github.com/openstyles/stylus/issues/461
const id = el.id.slice(PREFIX.length + 1); First we're trying the page context document where inline styles may be forbidden by CSP
if (/^\d+$/.test(id) || id === PATCH_ID) { https://bugzilla.mozilla.org/show_bug.cgi?id=1579345#c3
el.remove(); and since userAgent.navigator can be spoofed via about:config or devtools,
we're checking for getPreventDefault that was removed in FF59
*/
function _initCreationDoc() {
creationDoc = !Event.prototype.getPreventDefault && document.wrappedJSObject;
if (creationDoc) {
({createElement, createElementNS} = creationDoc);
const el = document.documentElement.appendChild(_createStyle());
const isApplied = el.sheet;
el.remove();
if (isApplied) return;
}
creationDoc = document;
({createElement, createElementNS} = document);
}
function _remove(id) {
const style = table.get(id);
if (!style) return;
table.delete(id);
list.splice(list.indexOf(style), 1);
style.el.remove();
}
function _sort() {
docRootObserver.evade(() => {
list.sort(compare);
for (const style of list) {
// moving an element resets its 'disabled' state
document.documentElement.appendChild(style.el);
style.el.disabled = !isEnabled;
}
});
}
function _sortIfNeeded() {
let needsSort;
let el = list.length && list[0].el;
if (!el) {
needsSort = false;
} else if (el.parentNode !== creationDoc.documentElement) {
needsSort = true;
} else {
let i = 0;
while (el) {
if (i < list.length && el === list[i].el) {
i++;
} else if (ORDERED_TAGS.has(el.localName)) {
needsSort = true;
break;
}
el = el.nextElementSibling;
}
// some styles are not injected to the document
if (i < list.length) needsSort = true;
}
if (needsSort) _sort();
return needsSort;
}
function _styleMapToArray(styleMap) {
return Object.values(styleMap).map(s => ({
id: s.id,
code: s.code.join(''),
}));
}
function _update({id, code}) {
const style = table.get(id);
if (style.code === code) return;
style.code = code;
// workaround for Chrome devtools bug fixed in v65
if (isChromePre65) {
const oldEl = style.el;
style.el = _createStyle(id, code);
oldEl.parentNode.insertBefore(style.el, oldEl.nextSibling);
oldEl.remove();
} else {
style.el.textContent = code;
}
// https://github.com/openstyles/stylus/issues/693
style.el.disabled = !isEnabled;
}
function RewriteObserver(onChange) {
// detect documentElement being rewritten from inside the script
let root;
let observing = false;
let timer;
const observer = new MutationObserver(_check);
return {start, stop};
function start() {
if (observing) return;
// detect dynamic iframes rewritten after creation by the embedder i.e. externally
root = document.documentElement;
timer = setTimeout(_check);
observer.observe(document, {childList: true});
observing = true;
}
function stop() {
if (!observing) return;
clearTimeout(timer);
observer.disconnect();
observing = false;
}
function _check() {
if (root !== document.documentElement) {
root = document.documentElement;
onChange();
} }
} }
} }
function toggle(_enabled) { function RootObserver(onChange) {
if (isEnabled === _enabled) return; let digest = 0;
isEnabled = _enabled; let lastCalledTime = NaN;
for (const style of list) { let observing = false;
style.el.disabled = !isEnabled; const observer = new MutationObserver(() => {
} if (digest) {
} if (performance.now() - lastCalledTime > 1000) {
digest = 0;
} else if (digest > 5) {
throw new Error('The page keeps generating mutations. Skip the event.');
}
}
if (onChange()) {
digest++;
lastCalledTime = performance.now();
}
});
return {evade, start, stop};
function sort() { function evade(fn) {
list.sort(compare); const restore = observing && start;
for (const style of list) { stop();
return new Promise(resolve => _run(fn, resolve, _waitForRoot))
.then(restore);
}
function start() {
if (observing) return;
observer.observe(document.documentElement, {childList: true});
observing = true;
}
function stop() {
if (!observing) return;
// FIXME: do we need this? // FIXME: do we need this?
// const copy = document.importNode(el, true); observer.takeRecords();
// el.textContent += ' '; // invalidate CSSOM cache observer.disconnect();
document.documentElement.appendChild(style.el); observing = false;
// moving an element resets its 'disabled' state
style.el.disabled = !isEnabled;
} }
}
function replaceAll(styles) { function _run(fn, resolve, wait) {
const added = new Set(styles.map(s => s.id)); if (document.documentElement) {
const removed = []; resolve(fn());
for (const style of list) { return true;
if (!added.has(style.id)) {
removed.push(style.id);
} }
if (wait) wait(fn, resolve);
}
function _waitForRoot(...args) {
new MutationObserver((_, observer) => _run(...args) && observer.disconnect())
.observe(document, {childList: true});
} }
styles.forEach(_add);
removed.forEach(_remove);
onUpdate();
} }
}; };