render.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* global $ $$ animateElement scrollElementIntoView */// dom.js
  2. /* global API */// msg.js
  3. /* global URLS debounce isEmptyObj sessionStore */// toolbox.js
  4. /* global filterAndAppend */// filters.js
  5. /* global installed newUI */// manage.js
  6. /* global prefs */
  7. /* global sorter */
  8. /* global t */// localization.js
  9. 'use strict';
  10. const ENTRY_ID_PREFIX_RAW = 'style-';
  11. const TARGET_TYPES = ['domains', 'urls', 'urlPrefixes', 'regexps'];
  12. const GET_FAVICON_URL = 'https://www.google.com/s2/favicons?domain=';
  13. const OWN_ICON = chrome.runtime.getManifest().icons['16'];
  14. const AGES = [
  15. [24, 'h', t('dateAbbrHour', '\x01')],
  16. [30, 'd', t('dateAbbrDay', '\x01')],
  17. [12, 'm', t('dateAbbrMonth', '\x01')],
  18. [Infinity, 'y', t('dateAbbrYear', '\x01')],
  19. ];
  20. let elementParts;
  21. function $entry(styleOrId, root = installed) {
  22. return $(`#${ENTRY_ID_PREFIX_RAW}${styleOrId.id || styleOrId}`, root);
  23. }
  24. function createAgeText(el, style) {
  25. let val = style.updateDate || style.installDate;
  26. if (val) {
  27. val = (Date.now() - val) / 3600e3; // age in hours
  28. for (const [max, unit, text] of AGES) {
  29. const rounded = Math.round(val);
  30. if (rounded < max) {
  31. el.textContent = text.replace('\x01', rounded);
  32. el.dataset.value = padLeft(Math.round(rounded), 2) + unit;
  33. break;
  34. }
  35. val /= max;
  36. }
  37. } else if (el.firstChild) {
  38. el.textContent = '';
  39. delete el.dataset.value;
  40. }
  41. }
  42. function createStyleElement({style, name: nameLC}) {
  43. // query the sub-elements just once, then reuse the references
  44. if ((elementParts || {}).newUI !== newUI.enabled) {
  45. const entry = t.template[newUI.enabled ? 'styleNewUI' : 'style'].cloneNode(true);
  46. elementParts = {
  47. newUI: newUI.enabled,
  48. entry,
  49. entryClassBase: entry.className,
  50. checker: $('input', entry) || {},
  51. nameLink: $('.style-name-link', entry),
  52. editLink: $('.style-edit-link', entry) || {},
  53. editHrefBase: 'edit.html?id=',
  54. homepage: $('.homepage', entry),
  55. homepageIcon: t.template[`homepageIcon${newUI.enabled ? 'Small' : 'Big'}`],
  56. infoAge: $('[data-type=age]', entry),
  57. infoVer: $('[data-type=version]', entry),
  58. appliesTo: $('.applies-to', entry),
  59. targets: $('.targets', entry),
  60. expander: $('.expander', entry),
  61. decorations: {
  62. urlPrefixesAfter: '*',
  63. regexpsBefore: '/',
  64. regexpsAfter: '/',
  65. },
  66. oldConfigure: !newUI.enabled && $('.configure-usercss', entry),
  67. oldCheckUpdate: !newUI.enabled && $('.check-update', entry),
  68. oldUpdate: !newUI.enabled && $('.update', entry),
  69. };
  70. }
  71. const parts = elementParts;
  72. const ud = style.usercssData;
  73. const configurable = ud && ud.vars && !isEmptyObj(ud.vars);
  74. const name = style.customName || style.name;
  75. parts.checker.checked = style.enabled;
  76. parts.nameLink.firstChild.textContent = t.breakWord(name);
  77. parts.nameLink.href = parts.editLink.href = parts.editHrefBase + style.id;
  78. parts.homepage.href = parts.homepage.title = style.url || '';
  79. parts.infoVer.textContent = ud ? ud.version : '';
  80. parts.infoVer.dataset.value = ud ? ud.version : '';
  81. if (URLS.extractUsoArchiveId(style.updateUrl)) {
  82. parts.infoVer.dataset.isDate = '';
  83. } else {
  84. delete parts.infoVer.dataset.isDate;
  85. }
  86. if (newUI.enabled) {
  87. createAgeText(parts.infoAge, style);
  88. } else {
  89. parts.oldConfigure.classList.toggle('hidden', !configurable);
  90. parts.oldCheckUpdate.classList.toggle('hidden', !style.updateUrl);
  91. parts.oldUpdate.classList.toggle('hidden', !style.updateUrl);
  92. }
  93. // clear the code to free up some memory
  94. // (note, style is already a deep copy)
  95. style.sourceCode = null;
  96. style.sections.forEach(section => (section.code = null));
  97. const entry = parts.entry.cloneNode(true);
  98. entry.id = ENTRY_ID_PREFIX_RAW + style.id;
  99. entry.styleId = style.id;
  100. entry.styleNameLowerCase = nameLC || name.toLocaleLowerCase() + '\n' + name;
  101. entry.styleMeta = style;
  102. entry.className = parts.entryClassBase + ' ' +
  103. (style.enabled ? 'enabled' : 'disabled') +
  104. (style.updateUrl ? ' updatable' : '') +
  105. (ud ? ' usercss' : '');
  106. if (style.url) {
  107. $('.homepage', entry).appendChild(parts.homepageIcon.cloneNode(true));
  108. }
  109. if (style.updateUrl && newUI.enabled) {
  110. $('.actions', entry).appendChild(t.template.updaterIcons.cloneNode(true));
  111. }
  112. if (configurable && newUI.enabled) {
  113. $('.actions', entry).appendChild(t.template.configureIcon.cloneNode(true));
  114. }
  115. createTargetsElement({entry, style});
  116. return entry;
  117. }
  118. function createTargetsElement({entry, expanded, style = entry.styleMeta}) {
  119. const entryTargets = $('.targets', entry);
  120. const expanderCls = $('.applies-to', entry).classList;
  121. const targets = elementParts.targets.cloneNode(true);
  122. let container = targets;
  123. let el = entryTargets.firstElementChild;
  124. let numTargets = 0;
  125. let allTargetsRendered = true;
  126. const maxTargets = expanded ? 1000 : newUI.enabled ? newUI.targets : 10;
  127. const displayed = new Set();
  128. for (const type of TARGET_TYPES) {
  129. for (const section of style.sections) {
  130. for (const targetValue of section[type] || []) {
  131. if (displayed.has(targetValue)) {
  132. continue;
  133. }
  134. if (++numTargets > maxTargets) {
  135. allTargetsRendered = expanded;
  136. break;
  137. }
  138. displayed.add(targetValue);
  139. const text =
  140. (elementParts.decorations[type + 'Before'] || '') +
  141. targetValue +
  142. (elementParts.decorations[type + 'After'] || '');
  143. if (el && el.dataset.type === type && el.lastChild.textContent === text) {
  144. const next = el.nextElementSibling;
  145. container.appendChild(el);
  146. el = next;
  147. continue;
  148. }
  149. const element = t.template.appliesToTarget.cloneNode(true);
  150. if (!newUI.enabled) {
  151. if (numTargets === maxTargets) {
  152. container = container.appendChild(t.template.extraAppliesTo.cloneNode(true));
  153. } else if (numTargets > 1) {
  154. container.appendChild(t.template.appliesToSeparator.cloneNode(true));
  155. }
  156. }
  157. element.dataset.type = type;
  158. element.appendChild(document.createTextNode(text));
  159. container.appendChild(element);
  160. }
  161. }
  162. }
  163. if (newUI.enabled && numTargets > newUI.targets) {
  164. expanderCls.add('has-more');
  165. }
  166. if (numTargets) {
  167. entryTargets.parentElement.replaceChild(targets, entryTargets);
  168. } else if (
  169. !entry.classList.contains('global') ||
  170. !entryTargets.firstElementChild
  171. ) {
  172. if (entryTargets.firstElementChild) {
  173. entryTargets.textContent = '';
  174. }
  175. entryTargets.appendChild(t.template.appliesToEverything.cloneNode(true));
  176. }
  177. entry.classList.toggle('global', !numTargets);
  178. entry._allTargetsRendered = allTargetsRendered;
  179. entry._numTargets = numTargets;
  180. }
  181. function getFaviconSrc(container = installed) {
  182. if (!newUI.enabled || !newUI.favicons) return;
  183. const regexpRemoveNegativeLookAhead = /(\?!([^)]+\))|\(\?![\w(]+[^)]+[\w|)]+)/g;
  184. // replace extra characters & all but the first group entry "(abc|def|ghi)xyz" => abcxyz
  185. const regexpReplaceExtraCharacters = /[\\(]|((\|\w+)+\))/g;
  186. const regexpMatchRegExp = /[\w-]+[.(]+(com|org|co|net|im|io|edu|gov|biz|info|de|cn|uk|nl|eu|ru)\b/g;
  187. const regexpMatchDomain = /^.*?:\/\/([^/]+)/;
  188. for (const target of $$('.target', container)) {
  189. const type = target.dataset.type;
  190. const targetValue = target.textContent;
  191. if (!targetValue) continue;
  192. let favicon = '';
  193. if (type === 'domains') {
  194. favicon = GET_FAVICON_URL + targetValue;
  195. } else if (targetValue.includes('chrome-extension:') || targetValue.includes('moz-extension:')) {
  196. favicon = OWN_ICON;
  197. } else if (type === 'regexps') {
  198. favicon = targetValue
  199. .replace(regexpRemoveNegativeLookAhead, '')
  200. .replace(regexpReplaceExtraCharacters, '')
  201. .match(regexpMatchRegExp);
  202. favicon = favicon ? GET_FAVICON_URL + favicon.shift() : '';
  203. } else {
  204. favicon = targetValue.includes('://') && targetValue.match(regexpMatchDomain);
  205. favicon = favicon ? GET_FAVICON_URL + favicon[1] : '';
  206. }
  207. if (favicon) {
  208. const img = target.children[0];
  209. if (!img || img.localName !== 'img') {
  210. target.insertAdjacentElement('afterbegin', document.createElement('img'))
  211. .dataset.src = favicon;
  212. } else if ((img.dataset.src || img.src) !== favicon) {
  213. img.src = '';
  214. img.dataset.src = favicon;
  215. }
  216. }
  217. }
  218. loadFavicons();
  219. }
  220. function fitSelectBox(...elems) {
  221. const data = [];
  222. for (const el of elems) {
  223. const sel = el.selectedOptions[0];
  224. if (!sel) continue;
  225. const oldWidth = parseFloat(el.style.width);
  226. const text = [];
  227. data.push({el, text, oldWidth});
  228. for (const elOpt of el.options) {
  229. text.push(elOpt.textContent);
  230. if (elOpt !== sel) elOpt.textContent = '';
  231. }
  232. el.style.width = 'min-content';
  233. }
  234. for (const {el, text, oldWidth} of data) {
  235. const w = el.offsetWidth;
  236. if (w && oldWidth !== w) el.style.width = w + 'px';
  237. text.forEach((t, i) => (el.options[i].textContent = t));
  238. }
  239. }
  240. /* exported fitSelectBoxesIn */
  241. /**
  242. * @param {HTMLDetailsElement} el
  243. * @param {string} targetSel
  244. */
  245. function fitSelectBoxesIn(el, targetSel = 'select.fit-width') {
  246. const fit = () => {
  247. if (el.open) {
  248. fitSelectBox(...$$(targetSel, el));
  249. }
  250. };
  251. el.on('change', ({target}) => {
  252. if (el.open && target.matches(targetSel)) {
  253. fitSelectBox(target);
  254. }
  255. });
  256. fit();
  257. new MutationObserver(fit)
  258. .observe(el, {attributeFilter: ['open'], attributes: true});
  259. }
  260. function highlightEditedStyle() {
  261. if (!sessionStore.justEditedStyleId) return;
  262. const entry = $entry(sessionStore.justEditedStyleId);
  263. delete sessionStore.justEditedStyleId;
  264. if (entry) {
  265. animateElement(entry);
  266. requestAnimationFrame(() => scrollElementIntoView(entry));
  267. }
  268. }
  269. function loadFavicons({all = false} = {}) {
  270. if (!installed.firstElementChild) return;
  271. let favicons = [];
  272. if (all) {
  273. favicons = $$('img[data-src]', installed);
  274. } else {
  275. const {left, top} = installed.firstElementChild.getBoundingClientRect();
  276. const x = Math.max(0, left);
  277. const y = Math.max(0, top);
  278. const first = document.elementFromPoint(x, y);
  279. if (!first) return requestAnimationFrame(loadFavicons.bind(null, ...arguments));
  280. const lastOffset = first.offsetTop + window.innerHeight;
  281. const numTargets = newUI.targets;
  282. let entry = first && first.closest('.entry') || installed.children[0];
  283. while (entry && entry.offsetTop <= lastOffset) {
  284. favicons.push(...$$('img', entry).slice(0, numTargets).filter(img => img.dataset.src));
  285. entry = entry.nextElementSibling;
  286. }
  287. }
  288. let i = 0;
  289. for (const img of favicons) {
  290. img.src = img.dataset.src;
  291. delete img.dataset.src;
  292. // loading too many icons at once will block the page while the new layout is recalculated
  293. if (++i > 100) break;
  294. }
  295. if ($('img[data-src]', installed)) {
  296. debounce(loadFavicons, 1, {all: true});
  297. }
  298. }
  299. /** Adding spaces so CSS can detect "bigness" of a value via amount of spaces at the beginning */
  300. function padLeft(val, width) {
  301. val = `${val}`;
  302. return ' '.repeat(Math.max(0, width - val.length)) + val;
  303. }
  304. function showStyles(styles = [], matchUrlIds) {
  305. const sorted = sorter.sort({
  306. styles: styles.map(style => {
  307. const name = style.customName || style.name || '';
  308. return {
  309. style,
  310. // sort case-insensitively the whole list then sort dupes like `Foo` and `foo` case-sensitively
  311. name: name.toLocaleLowerCase() + '\n' + name,
  312. };
  313. }),
  314. });
  315. let index = 0;
  316. let firstRun = true;
  317. installed.dataset.total = styles.length;
  318. const scrollY = (history.state || {}).scrollY;
  319. const shouldRenderAll = scrollY > window.innerHeight || sessionStore.justEditedStyleId;
  320. const renderBin = document.createDocumentFragment();
  321. if (scrollY) {
  322. renderStyles();
  323. } else {
  324. requestAnimationFrame(renderStyles);
  325. }
  326. function renderStyles() {
  327. const t0 = performance.now();
  328. while (index < sorted.length && (shouldRenderAll || performance.now() - t0 < 20)) {
  329. const info = sorted[index++];
  330. const entry = createStyleElement(info);
  331. if (matchUrlIds && !matchUrlIds.includes(info.style.id)) {
  332. entry.classList.add('not-matching');
  333. }
  334. renderBin.appendChild(entry);
  335. }
  336. filterAndAppend({container: renderBin}).then(sorter.updateStripes);
  337. if (index < sorted.length) {
  338. requestAnimationFrame(renderStyles);
  339. if (firstRun) setTimeout(getFaviconSrc);
  340. firstRun = false;
  341. return;
  342. }
  343. setTimeout(getFaviconSrc);
  344. if (sessionStore.justEditedStyleId) {
  345. setTimeout(highlightEditedStyle); // delaying to avoid forced layout
  346. } else if ('scrollY' in (history.state || {})) {
  347. setTimeout(window.scrollTo, 0, 0, history.state.scrollY);
  348. }
  349. }
  350. }
  351. /* exported switchUI */
  352. function switchUI({styleOnly} = {}) {
  353. const current = {};
  354. const changed = {};
  355. let someChanged = false;
  356. for (const id of newUI.ids) {
  357. const value = prefs.get(newUI.prefKeyForId(id));
  358. const valueChanged = value !== newUI[id] && (id === 'enabled' || current.enabled);
  359. current[id] = value;
  360. changed[id] = valueChanged;
  361. someChanged |= valueChanged;
  362. }
  363. if (!styleOnly && !someChanged) {
  364. return;
  365. }
  366. Object.assign(newUI, current);
  367. newUI.renderClass();
  368. installed.classList.toggle('has-favicons', newUI.enabled && newUI.favicons);
  369. installed.classList.toggle('favicons-grayed', newUI.enabled && newUI.faviconsGray);
  370. if (installed.style.getPropertyValue('--num-targets') !== `${newUI.targets}`) {
  371. installed.style.setProperty('--num-targets', newUI.targets);
  372. }
  373. if (styleOnly) {
  374. return;
  375. }
  376. const iconsEnabled = newUI.enabled && newUI.favicons;
  377. let iconsMissing = iconsEnabled && !$('.applies-to img');
  378. if (changed.enabled || (iconsMissing && !elementParts)) {
  379. installed.textContent = '';
  380. API.styles.getAll().then(showStyles);
  381. return;
  382. }
  383. if (changed.targets) {
  384. for (const entry of installed.children) {
  385. $('.applies-to', entry).classList.toggle('has-more', entry._numTargets > newUI.targets);
  386. if (!entry._allTargetsRendered && newUI.targets > $('.targets', entry).childElementCount) {
  387. createTargetsElement({entry, expanded: true});
  388. iconsMissing |= iconsEnabled;
  389. }
  390. }
  391. }
  392. if (iconsMissing) {
  393. debounce(getFaviconSrc);
  394. return;
  395. }
  396. }