apply.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /* eslint no-var: 0 */
  2. 'use strict';
  3. (() => {
  4. var ID_PREFIX = 'stylus-';
  5. var ROOT = document.documentElement;
  6. var isOwnPage = location.protocol.endsWith('-extension:');
  7. var disableAll = false;
  8. var exposeIframes = false;
  9. var styleElements = new Map();
  10. var disabledElements = new Map();
  11. var retiredStyleTimers = new Map();
  12. var docRewriteObserver;
  13. var docRootObserver;
  14. requestStyles();
  15. chrome.runtime.onMessage.addListener(applyOnMessage);
  16. window.applyOnMessage = applyOnMessage;
  17. if (!isOwnPage) {
  18. window.dispatchEvent(new CustomEvent(chrome.runtime.id));
  19. window.addEventListener(chrome.runtime.id, orphanCheck, true);
  20. }
  21. function requestStyles(options, callback = applyStyles) {
  22. var matchUrl = location.href;
  23. if (!matchUrl.match(/^(http|file|chrome|ftp)/)) {
  24. // dynamic about: and javascript: iframes don't have an URL yet
  25. // so we'll try the parent frame which is guaranteed to have a real URL
  26. try {
  27. if (window !== parent) {
  28. matchUrl = parent.location.href;
  29. }
  30. } catch (e) {}
  31. }
  32. const request = Object.assign({
  33. method: 'getStyles',
  34. matchUrl,
  35. enabled: true,
  36. asHash: true,
  37. }, options);
  38. // On own pages we request the styles directly to minimize delay and flicker
  39. if (typeof getStylesSafe === 'function') {
  40. getStylesSafe(request).then(callback);
  41. } else {
  42. chrome.runtime.sendMessage(request, callback);
  43. }
  44. }
  45. function applyOnMessage(request, sender, sendResponse) {
  46. if (request.styles === 'DIY') {
  47. // Do-It-Yourself tells our built-in pages to fetch the styles directly
  48. // which is faster because IPC messaging JSON-ifies everything internally
  49. requestStyles({}, styles => {
  50. request.styles = styles;
  51. applyOnMessage(request);
  52. });
  53. return;
  54. }
  55. switch (request.method) {
  56. case 'styleDeleted':
  57. removeStyle(request);
  58. break;
  59. case 'styleUpdated':
  60. if (request.codeIsUpdated === false) {
  61. applyStyleState(request.style);
  62. break;
  63. }
  64. if (request.style.enabled) {
  65. removeStyle({id: request.style.id, retire: true});
  66. requestStyles({id: request.style.id});
  67. } else {
  68. removeStyle(request.style);
  69. }
  70. break;
  71. case 'styleAdded':
  72. if (request.style.enabled) {
  73. requestStyles({id: request.style.id});
  74. }
  75. break;
  76. case 'styleApply':
  77. applyStyles(request.styles);
  78. break;
  79. case 'styleReplaceAll':
  80. replaceAll(request.styles);
  81. break;
  82. case 'prefChanged':
  83. if ('disableAll' in request.prefs) {
  84. doDisableAll(request.prefs.disableAll);
  85. }
  86. if ('exposeIframes' in request.prefs) {
  87. doExposeIframes(request.prefs.exposeIframes);
  88. }
  89. break;
  90. case 'ping':
  91. sendResponse(true);
  92. break;
  93. }
  94. }
  95. function doDisableAll(disable = disableAll) {
  96. if (!disable === !disableAll) {
  97. return;
  98. }
  99. disableAll = disable;
  100. Array.prototype.forEach.call(document.styleSheets, stylesheet => {
  101. if (stylesheet.ownerNode.matches(`style.stylus[id^="${ID_PREFIX}"]`)
  102. && stylesheet.disabled !== disable) {
  103. stylesheet.disabled = disable;
  104. }
  105. });
  106. }
  107. function doExposeIframes(state = exposeIframes) {
  108. if (state === exposeIframes || window === parent) {
  109. return;
  110. }
  111. exposeIframes = state;
  112. const attr = document.documentElement.getAttribute('stylus-iframe');
  113. if (state && attr !== '') {
  114. document.documentElement.setAttribute('stylus-iframe', '');
  115. } else if (!state && attr === '') {
  116. document.documentElement.removeAttribute('stylus-iframe');
  117. }
  118. }
  119. function applyStyleState({id, enabled}) {
  120. const inCache = disabledElements.get(id) || styleElements.get(id);
  121. const inDoc = document.getElementById(ID_PREFIX + id);
  122. if (enabled) {
  123. if (inDoc) {
  124. return;
  125. } else if (inCache) {
  126. addStyleElement(inCache);
  127. disabledElements.delete(id);
  128. } else {
  129. requestStyles({id});
  130. }
  131. } else {
  132. if (inDoc) {
  133. disabledElements.set(id, inDoc);
  134. docRootObserver.stop();
  135. inDoc.remove();
  136. docRootObserver.start();
  137. }
  138. }
  139. }
  140. function removeStyle({id, retire = false}) {
  141. const el = document.getElementById(ID_PREFIX + id);
  142. if (el) {
  143. if (retire) {
  144. // to avoid page flicker when the style is updated
  145. // instead of removing it immediately we rename its ID and queue it
  146. // to be deleted in applyStyles after a new version is fetched and applied
  147. const deadID = 'ghost-' + id;
  148. el.id = ID_PREFIX + deadID;
  149. // in case something went wrong and new style was never applied
  150. retiredStyleTimers.set(deadID, setTimeout(removeStyle, 1000, {id: deadID}));
  151. } else {
  152. el.remove();
  153. }
  154. }
  155. styleElements.delete(ID_PREFIX + id);
  156. disabledElements.delete(id);
  157. retiredStyleTimers.delete(id);
  158. }
  159. function applyStyles(styles) {
  160. if (!styles) {
  161. // Chrome is starting up
  162. requestStyles();
  163. return;
  164. }
  165. if ('disableAll' in styles) {
  166. doDisableAll(styles.disableAll);
  167. delete styles.disableAll;
  168. }
  169. if ('exposeIframes' in styles) {
  170. doExposeIframes(styles.exposeIframes);
  171. delete styles.exposeIframes;
  172. }
  173. const gotNewStyles = Object.keys(styles).length || styles.needTransitionPatch;
  174. if (gotNewStyles) {
  175. if (docRootObserver) {
  176. docRootObserver.stop();
  177. } else {
  178. initDocRootObserver();
  179. }
  180. }
  181. if (styles.needTransitionPatch) {
  182. // CSS transition bug workaround: since we insert styles asynchronously,
  183. // the browsers, especially Firefox, may apply all transitions on page load
  184. delete styles.needTransitionPatch;
  185. const className = chrome.runtime.id + '-transition-bug-fix';
  186. const docId = document.documentElement.id ? '#' + document.documentElement.id : '';
  187. document.documentElement.classList.add(className);
  188. applySections(0, `
  189. ${docId}.${className}:root * {
  190. transition: none !important;
  191. }
  192. `);
  193. setTimeout(() => {
  194. removeStyle({id: 0});
  195. document.documentElement.classList.remove(className);
  196. });
  197. }
  198. if (gotNewStyles) {
  199. for (const id in styles) {
  200. applySections(id, styles[id].map(section => section.code).join('\n'));
  201. }
  202. docRootObserver.start({sort: true});
  203. }
  204. if (!isOwnPage && !docRewriteObserver && styleElements.size) {
  205. initDocRewriteObserver();
  206. }
  207. if (retiredStyleTimers.size) {
  208. setTimeout(() => {
  209. for (const [id, timer] of retiredStyleTimers.entries()) {
  210. removeStyle({id});
  211. clearTimeout(timer);
  212. }
  213. });
  214. }
  215. }
  216. function applySections(styleId, code) {
  217. const id = ID_PREFIX + styleId;
  218. let el = styleElements.get(id) || document.getElementById(id);
  219. if (!el) {
  220. if (document.documentElement instanceof SVGSVGElement) {
  221. // SVG document style
  222. el = document.createElementNS('http://www.w3.org/2000/svg', 'style');
  223. } else if (document instanceof XMLDocument) {
  224. // XML document style
  225. el = document.createElementNS('http://www.w3.org/1999/xhtml', 'style');
  226. } else {
  227. // HTML document style; also works on HTML-embedded SVG
  228. el = document.createElement('style');
  229. }
  230. Object.assign(el, {
  231. id,
  232. type: 'text/css',
  233. textContent: code,
  234. });
  235. // SVG className is not a string, but an instance of SVGAnimatedString
  236. el.classList.add('stylus');
  237. addStyleElement(el);
  238. }
  239. styleElements.set(id, el);
  240. disabledElements.delete(Number(styleId));
  241. return el;
  242. }
  243. function addStyleElement(newElement) {
  244. if (!ROOT) {
  245. return;
  246. }
  247. let next;
  248. const newStyleId = getStyleId(newElement);
  249. for (const el of styleElements.values()) {
  250. if (el.parentNode && !el.id.endsWith('-ghost') && getStyleId(el) > newStyleId) {
  251. next = el.parentNode === ROOT ? el : null;
  252. break;
  253. }
  254. }
  255. if (next === newElement.nextElementSibling) {
  256. return;
  257. }
  258. docRootObserver.stop();
  259. ROOT.insertBefore(newElement, next || null);
  260. if (disableAll) {
  261. newElement.disabled = true;
  262. }
  263. docRootObserver.start();
  264. }
  265. function replaceAll(newStyles) {
  266. const oldStyles = Array.prototype.slice.call(
  267. document.querySelectorAll(`style.stylus[id^="${ID_PREFIX}"]`));
  268. oldStyles.forEach(el => (el.id += '-ghost'));
  269. styleElements.clear();
  270. disabledElements.clear();
  271. [...retiredStyleTimers.values()].forEach(clearTimeout);
  272. retiredStyleTimers.clear();
  273. applyStyles(newStyles);
  274. oldStyles.forEach(el => el.remove());
  275. }
  276. function getStyleId(el) {
  277. return parseInt(el.id.substr(ID_PREFIX.length));
  278. }
  279. function orphanCheck() {
  280. if (chrome.i18n && chrome.i18n.getUILanguage()) {
  281. return true;
  282. }
  283. // In Chrome content script is orphaned on an extension update/reload
  284. // so we need to detach event listeners
  285. [docRewriteObserver, docRootObserver].forEach(ob => ob && ob.takeRecords() && ob.disconnect());
  286. window.removeEventListener(chrome.runtime.id, orphanCheck, true);
  287. }
  288. function initDocRewriteObserver() {
  289. // detect documentElement being rewritten from inside the script
  290. docRewriteObserver = new MutationObserver(mutations => {
  291. for (let m = mutations.length; --m >= 0;) {
  292. const added = mutations[m].addedNodes;
  293. for (let n = added.length; --n >= 0;) {
  294. if (added[n].localName === 'html') {
  295. reinjectStyles();
  296. return;
  297. }
  298. }
  299. }
  300. });
  301. docRewriteObserver.observe(document, {childList: true});
  302. // detect dynamic iframes rewritten after creation by the embedder i.e. externally
  303. setTimeout(() => {
  304. if (document.documentElement !== ROOT) {
  305. reinjectStyles();
  306. }
  307. });
  308. // re-add styles if we detect documentElement being recreated
  309. function reinjectStyles() {
  310. if (!styleElements) {
  311. orphanCheck();
  312. return;
  313. }
  314. ROOT = document.documentElement;
  315. docRootObserver.stop();
  316. const imported = [];
  317. for (const [id, el] of styleElements.entries()) {
  318. const copy = document.importNode(el, true);
  319. el.textContent += ' '; // invalidate CSSOM cache
  320. imported.push([id, copy]);
  321. addStyleElement(copy);
  322. }
  323. docRootObserver.start();
  324. styleElements = new Map(imported);
  325. }
  326. }
  327. function initDocRootObserver() {
  328. let lastRestorationTime = 0;
  329. let restorationCounter = 0;
  330. let observing = false;
  331. let sorting = false;
  332. // allow any types of elements between ours, except for the following:
  333. const ORDERED_TAGS = ['head', 'body', 'frameset', 'style', 'link'];
  334. init();
  335. return;
  336. function init() {
  337. docRootObserver = new MutationObserver(sortStyleElements);
  338. Object.assign(docRootObserver, {start, stop});
  339. setTimeout(sortStyleElements);
  340. }
  341. function start({sort = false} = {}) {
  342. if (sort && sortStyleMap()) {
  343. sortStyleElements();
  344. }
  345. if (!observing && ROOT) {
  346. docRootObserver.observe(ROOT, {childList: true});
  347. observing = true;
  348. }
  349. }
  350. function stop() {
  351. if (observing) {
  352. docRootObserver.disconnect();
  353. observing = false;
  354. }
  355. }
  356. function sortStyleMap() {
  357. const list = [];
  358. let prevStyleId = 0;
  359. let needsSorting = false;
  360. for (const entry of styleElements.entries()) {
  361. list.push(entry);
  362. const el = entry[1];
  363. const styleId = getStyleId(el);
  364. el.styleId = styleId;
  365. needsSorting |= styleId < prevStyleId;
  366. prevStyleId = styleId;
  367. }
  368. if (needsSorting) {
  369. styleElements = new Map(list.sort((a, b) => a[1].styleId - b[1].styleId));
  370. return true;
  371. }
  372. }
  373. function sortStyleElements() {
  374. let prevExpected = document.documentElement.lastElementChild;
  375. while (prevExpected && isSkippable(prevExpected, true)) {
  376. prevExpected = prevExpected.previousElementSibling;
  377. }
  378. if (!prevExpected) {
  379. return;
  380. }
  381. for (const el of styleElements.values()) {
  382. if (!isMovable(el)) {
  383. continue;
  384. }
  385. while (true) {
  386. const next = prevExpected.nextElementSibling;
  387. if (next && isSkippable(next)) {
  388. prevExpected = next;
  389. } else if (
  390. next === el ||
  391. next === el.previousElementSibling ||
  392. moveAfter(el, next || prevExpected)) {
  393. prevExpected = el;
  394. break;
  395. } else {
  396. return;
  397. }
  398. }
  399. }
  400. if (sorting) {
  401. sorting = false;
  402. docRootObserver.takeRecords();
  403. if (!restorationLimitExceeded()) {
  404. start();
  405. } else {
  406. setTimeout(start, 1000);
  407. }
  408. }
  409. }
  410. function isMovable(el) {
  411. return el.parentNode || !disabledElements.has(getStyleId(el));
  412. }
  413. function isSkippable(el, skipOwnStyles) {
  414. return !ORDERED_TAGS.includes(el.localName) ||
  415. el.id.startsWith(ID_PREFIX) &&
  416. (skipOwnStyles || el.id.endsWith('-ghost')) &&
  417. el.localName === 'style' &&
  418. el.className === 'stylus';
  419. }
  420. function moveAfter(el, expected) {
  421. if (!sorting) {
  422. sorting = true;
  423. docRootObserver.stop();
  424. }
  425. expected.insertAdjacentElement('afterend', el);
  426. if (el.disabled !== disableAll) {
  427. // moving an element resets its 'disabled' state
  428. el.disabled = disableAll;
  429. }
  430. return true;
  431. }
  432. function restorationLimitExceeded() {
  433. const t = performance.now();
  434. if (t - lastRestorationTime > 1000) {
  435. restorationCounter = 0;
  436. }
  437. lastRestorationTime = t;
  438. return ++restorationCounter > 2;
  439. }
  440. }
  441. })();