Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2024-06-25 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Mouseover Popup Image Viewer
  3. // @namespace https://github.com/tophf
  4. // @description Shows images and videos behind links and thumbnails.
  5. //
  6. // @include *
  7. // @run-at document-start
  8. //
  9. // @grant GM_addElement
  10. // @grant GM_download
  11. // @grant GM_getValue
  12. // @grant GM_getValues
  13. // @grant GM_openInTab
  14. // @grant GM_registerMenuCommand
  15. // @grant GM_unregisterMenuCommand
  16. // @grant GM_setClipboard
  17. // @grant GM_setValue
  18. // @grant GM_xmlhttpRequest
  19. //
  20. // @grant GM.getValue
  21. // @grant GM.openInTab
  22. // @grant GM.registerMenuCommand
  23. // @grant GM.unregisterMenuCommand
  24. // @grant GM.setClipboard
  25. // @grant GM.setValue
  26. // @grant GM.xmlHttpRequest
  27. //
  28. // @version 1.4.1
  29. // @author tophf
  30. //
  31. // @original-version 2017.9.29
  32. // @original-author kuehlschrank
  33. //
  34. // @connect *
  35. // CSP check:
  36. // @connect self
  37. // rule installer in config dialog:
  38. // @connect github.com
  39. // big/trusted hostings for the built-in rules with "q":
  40. // @connect deviantart.com
  41. // @connect facebook.com
  42. // @connect fbcdn.com
  43. // @connect flickr.com
  44. // @connect gfycat.com
  45. // @connect googleusercontent.com
  46. // @connect gyazo.com
  47. // @connect imgur.com
  48. // @connect instagr.am
  49. // @connect instagram.com
  50. // @connect prnt.sc
  51. // @connect prntscr.com
  52. // @connect user-images.githubusercontent.com
  53. //
  54. // @supportURL https://github.com/tophf/mpiv/issues
  55. // @icon https://raw.githubusercontent.com/tophf/mpiv/master/icon.png
  56. // ==/UserScript==
  57.  
  58. 'use strict';
  59.  
  60. //#region Globals
  61.  
  62. /** @type mpiv.Config */
  63. let cfg;
  64. /** @type mpiv.AppInfo */
  65. let ai = {rule: {}};
  66. /** @type Element */
  67. let elSetup;
  68. let nonce;
  69.  
  70. const doc = document;
  71. const hostname = location.hostname;
  72. const dotDomain = '.' + hostname;
  73. const isFF = CSS.supports('-moz-appearance', 'none');
  74. const AudioContext = window.AudioContext || function () {};
  75. const {from: arrayFrom, isArray} = Array;
  76.  
  77. const PREFIX = 'mpiv-';
  78. const NOAA_ATTR = 'data-no-aa';
  79. const STATUS_ATTR = `${PREFIX}status`;
  80. const MSG = Object.assign({}, ...[
  81. 'getViewSize',
  82. 'viewSize',
  83. ].map(k => ({[k]: `${PREFIX}${k}`})));
  84. const WHEEL_EVENT = 'onwheel' in doc ? 'wheel' : 'mousewheel';
  85. // time for volatile things to settle down meanwhile we postpone action
  86. // examples: loading image from cache, quickly moving mouse over one element to another
  87. const SETTLE_TIME = 50;
  88. // used to detect JS code in host rules
  89. const RX_HAS_CODE = /(^|[^-\w])return[\W\s]/;
  90. const RX_EVAL_BLOCKED = /'Trusted(Script| Type)'|unsafe-eval/;
  91. const RX_MEDIA_URL = /^(?!data:)[^?#]+?\.(avif|bmp|jpe?g?|gif|mp4|png|svgz?|web[mp])($|[?#])/i;
  92. const BLANK_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
  93. const ZOOM_MAX = 16;
  94. const SYM_U = Symbol('u');
  95. const FN_ARGS = {
  96. s: ['m', 'node', 'rule'],
  97. c: ['text', 'doc', 'node', 'rule'],
  98. q: ['text', 'doc', 'node', 'rule'],
  99. g: ['text', 'doc', 'url', 'm', 'rule', 'node', 'cb'],
  100. };
  101. let trustedHTML, trustedScript;
  102. //#endregion
  103. //#region GM4 polyfill
  104.  
  105. if (typeof GM === 'undefined' || !GM.xmlHttpRequest)
  106. this.GM = {__proto__: null, info: GM_info};
  107. if (!GM.getValue)
  108. GM.getValue = GM_getValue; // we use it only with `await` so no need to return a Promise
  109. if (!GM.setValue)
  110. GM.setValue = GM_setValue; // we use it only with `await` so no need to return a Promise
  111. if (!GM.openInTab)
  112. GM.openInTab = GM_openInTab;
  113. if (!GM.registerMenuCommand && typeof GM_registerMenuCommand === 'function')
  114. GM.registerMenuCommand = GM_registerMenuCommand;
  115. if (!GM.unregisterMenuCommand && typeof GM_unregisterMenuCommand === 'function')
  116. GM.unregisterMenuCommand = GM_unregisterMenuCommand;
  117. if (!GM.setClipboard)
  118. GM.setClipboard = GM_setClipboard;
  119. if (!GM.xmlHttpRequest)
  120. GM.xmlHttpRequest = GM_xmlhttpRequest;
  121.  
  122. //#endregion
  123.  
  124. const App = {
  125.  
  126. isEnabled: true,
  127. isImageTab: false,
  128. globalStyle: '',
  129. popupStyleBase: '',
  130. tabfix: /\.(dumpoir|greatfon|picuki)\.com$/.test(dotDomain),
  131. NOP: /\.(facebook|instagram|chrome|google)\.com$/.test(dotDomain) &&
  132. (() => {}),
  133.  
  134. activate(info, event) {
  135. const {match, node, rule, url} = info;
  136. const auto = cfg.start === 'auto';
  137. const vidCtrl = cfg.videoCtrl && isVideo(node);
  138. if (elSetup) console.info({node, rule, url, match});
  139. if (auto && vidCtrl && !Events.ctrl)
  140. return;
  141. if (ai.node) App.deactivate();
  142. ai = info;
  143. ai.force = Events.ctrl;
  144. ai.gNum = 0;
  145. ai.zooming = cfg.css.includes(`${PREFIX}zooming`);
  146. Util.suppressTooltip();
  147. Calc.updateViewSize();
  148. Events.ctrl = false;
  149. Events.toggle(true);
  150. Events.trackMouse(event);
  151. if (ai.force && (auto || cfg.start === 'ctrl' || cfg.start === 'context')) {
  152. App.start();
  153. } else if ((auto || cfg.preload) && !vidCtrl && !rule.manual) {
  154. App.belate(auto);
  155. } else {
  156. Status.set('ready');
  157. }
  158. },
  159.  
  160. belate(auto) {
  161. if (cfg.preload) {
  162. ai.preloadStart = auto ? now() : -1;
  163. App.start();
  164. Status.set('+preloading');
  165. } else {
  166. ai.timer = setTimeout(App.start, cfg.delay);
  167. }
  168. },
  169.  
  170. checkProgress({start} = {}) {
  171. const p = ai.popup;
  172. if (!p)
  173. return;
  174. const w = ai.nwidth = p.naturalWidth || p.videoWidth || ai.popupLoaded && innerWidth / 2;
  175. const h = ai.nheight = p.naturalHeight || p.videoHeight || ai.popupLoaded && innerHeight / 2;
  176. if (h)
  177. return App.canCommit(w, h);
  178. if (start) {
  179. clearInterval(ai.timerProgress);
  180. ai.timerProgress = setInterval(App.checkProgress, 150);
  181. }
  182. },
  183.  
  184. canClose: (p = ai.popup) => !p || (
  185. isVideo(p)
  186. ? !cfg.keepVids
  187. : document.fullscreenElement !== p
  188. ),
  189.  
  190. canCommit(w, h) {
  191. if (!ai.force && ai.rect && !ai.gItems &&
  192. Math.max(w / (ai.rect.width || 1), h / (ai.rect.height || 1)) < cfg.scale) {
  193. App.deactivate();
  194. return false;
  195. }
  196. App.stopTimers();
  197. let wait = ai.preloadStart;
  198. if (wait < 0 && !ai.force || !ai.popup)
  199. return;
  200. if (wait > 0 && (wait += cfg.delay - now()) > 0) {
  201. ai.timer = setTimeout(App.checkProgress, wait);
  202. } else if ((!w || !h) && (ai.urls || []).length) {
  203. App.handleError({type: 'error'});
  204. } else {
  205. App.commit();
  206. }
  207. return true;
  208. },
  209.  
  210. async commit() {
  211. const p = ai.popupShown = ai.popup;
  212. const isDecoded = cfg.waitLoad && isFunction(p.decode);
  213. if (isDecoded) {
  214. await p.decode();
  215. if (p !== ai.popup)
  216. return;
  217. }
  218. Status.set('-preloading');
  219. App.updateStyles();
  220. Calc.measurePopup();
  221. const willZoom = cfg.zoom === 'auto' || App.isImageTab && cfg.imgtab;
  222. const willMove = !willZoom || App.toggleZoom({keepScale: true}) === undefined;
  223. if (willMove)
  224. Popup.move();
  225. Bar.updateName();
  226. Bar.updateDetails();
  227. Status.set(!ai.popupLoaded && 'loading');
  228. ai.large = ai.nwidth > p.clientWidth + ai.extras.w ||
  229. ai.nheight > p.clientHeight + ai.extras.h;
  230. if (ai.large) {
  231. Status.set('+large');
  232. // prevent a blank bg+border in FF
  233. if (isFF && p.complete && !isDecoded)
  234. p.style.backgroundImage = `url('${p.src}')`;
  235. }
  236. if (ai.preloadStart < 0 && isFunction(p.play))
  237. p.play().catch(now);
  238. },
  239.  
  240. deactivate({wait} = {}) {
  241. App.stopTimers(true);
  242. if (ai.req)
  243. tryCatch(ai.req.abort);
  244. if (ai.tooltip)
  245. ai.tooltip.node.title = ai.tooltip.text;
  246. Status.set(false);
  247. Bar.set(false);
  248. Events.toggle(false);
  249. Popup.destroy();
  250. if (wait) {
  251. App.isEnabled = false;
  252. setTimeout(App.enable, 200);
  253. }
  254. ai = {rule: {}};
  255. },
  256.  
  257. enable() {
  258. App.isEnabled = true;
  259. },
  260.  
  261. handleError(e, rule = ai.rule) {
  262. if (rule && rule.onerror === 'skip')
  263. return;
  264. if (ai.imageUrl &&
  265. !ai.xhr &&
  266. !ai.imageUrl.startsWith(location.origin + '/') &&
  267. location.protocol === 'https:' &&
  268. CspSniffer.init) {
  269. Popup.create(ai.imageUrl, ai.pageUrl, e);
  270. return;
  271. }
  272. const fe = Util.formatError(e, rule);
  273. if (!rule || !ai.urls || !ai.urls.length)
  274. console.warn(...fe);
  275. if (ai.urls && ai.urls.length) {
  276. ai.url = ai.urls.shift();
  277. if (ai.url) {
  278. App.stopTimers();
  279. App.startSingle();
  280. } else {
  281. App.deactivate();
  282. }
  283. } else if (ai.node) {
  284. Status.set('error');
  285. Bar.set(fe.message, 'error');
  286. }
  287. },
  288.  
  289. /** @param {MessageEvent} e */
  290. onMessage(e) {
  291. if (typeof e.data === 'string' && e.data === MSG.getViewSize) {
  292. e.stopImmediatePropagation();
  293. for (const el of doc.getElementsByTagName('iframe')) {
  294. if (el.contentWindow === e.source) {
  295. const s = Calc.frameSize(el, window).join(':');
  296. e.source.postMessage(`${MSG.viewSize}:${s}`, '*');
  297. return;
  298. }
  299. }
  300. }
  301. },
  302.  
  303. /** @param {MessageEvent} e */
  304. onMessageChild(e) {
  305. if (e.source === parent && typeof e.data === 'string' && e.data.startsWith(MSG.viewSize)) {
  306. e.stopImmediatePropagation();
  307. removeEventListener('message', App.onMessageChild, true);
  308. const [w, h, x, y] = e.data.split(':').slice(1).map(parseFloat);
  309. if (w && h) ai.view = {w, h, x, y};
  310. }
  311. },
  312.  
  313. start() {
  314. App.updateStyles();
  315. if (ai.gallery)
  316. App.startGallery();
  317. else
  318. App.startSingle();
  319. },
  320.  
  321. startSingle() {
  322. Status.loading();
  323. if (ai.force && ai.preloadStart < 0) {
  324. App.commit();
  325. return;
  326. }
  327. ai.imageUrl = null;
  328. if (ai.rule.follow && !ai.rule.q && !ai.rule.s) {
  329. Req.findRedirect();
  330. } else if (ai.rule.q && !isArray(ai.urls)) {
  331. App.startFromQ();
  332. } else {
  333. Popup.create(ai.url);
  334. Ruler.runC();
  335. }
  336. },
  337.  
  338. async startFromQ() {
  339. try {
  340. const {responseText, doc, finalUrl} = await Req.getDoc(ai.url);
  341. const url = Ruler.runQ(responseText, doc, finalUrl);
  342. if (!url)
  343. throw 'The "q" rule did not produce any URL.';
  344. if (RuleMatcher.isFollowableUrl(url, ai.rule)) {
  345. const info = RuleMatcher.find(url, ai.node, {noHtml: true});
  346. if (!info || !info.url)
  347. throw `Couldn't follow URL: ${url}`;
  348. Object.assign(ai, info);
  349. App.startSingle();
  350. } else {
  351. Popup.create(url, finalUrl);
  352. Ruler.runC(responseText, doc);
  353. }
  354. } catch (e) {
  355. App.handleError(e);
  356. }
  357. },
  358.  
  359. async startGallery() {
  360. Status.loading();
  361. try {
  362. const startUrl = ai.url;
  363. const p = await Req.getDoc(ai.rule.s !== 'gallery' && startUrl);
  364. const items = await new Promise(cb => {
  365. const res = ai.gallery(p.responseText, p.doc, p.finalUrl, ai.match, ai.rule, ai.node, cb);
  366. if (res !== undefined) cb(res);
  367. });
  368. // bail out if the gallery's async callback took too long
  369. if (ai.url !== startUrl) return;
  370. ai.gNum = items.length;
  371. ai.gItems = items.length && items;
  372. if (ai.gItems) {
  373. const i = items.index;
  374. ai.gIndex = i >= 0 && items[i] ? +i :
  375. Gallery.findIndex(typeof i === 'string' ? i : ai.url);
  376. setTimeout(Gallery.next);
  377. } else {
  378. throw 'Empty gallery';
  379. }
  380. } catch (e) {
  381. App.handleError(e);
  382. }
  383. },
  384.  
  385. stopTimers(bar) {
  386. for (const timer of ['timer', 'timerStatus', bar && 'timerBar'])
  387. clearTimeout(ai[timer]);
  388. clearInterval(ai.timerProgress);
  389. },
  390.  
  391. toggleZoom({keepScale} = {}) {
  392. const p = ai.popup;
  393. if (!p || !ai.scales || ai.scales.length < 2)
  394. return;
  395. ai.zoomed = !ai.zoomed;
  396. ai.scale = ai.zoomed && Calc.scaleForFirstZoom(keepScale) || ai.scales[0];
  397. if (ai.zooming)
  398. p.classList.add(`${PREFIX}zooming`);
  399. Popup.move();
  400. Bar.updateDetails();
  401. Status.set(ai.zoomed ? 'zoom' : false);
  402. return ai.zoomed;
  403. },
  404.  
  405. updateStyles() {
  406. Util.addStyle('global', (App.globalStyle || createGlobalStyle()) + cfg._getCss());
  407. Util.addStyle('rule', ai.rule.css || '');
  408. },
  409. };
  410.  
  411. const Bar = {
  412.  
  413. set(label, cls, prefix) {
  414. let b = ai.bar;
  415. if (typeof label !== 'string') {
  416. $remove(b);
  417. ai.bar = null;
  418. return;
  419. }
  420. const force = !b && 0;
  421. if (!b) b = ai.bar = $new('div', {id: `${PREFIX}bar`, className: `${PREFIX}${cls}`});
  422. ai.barText = label;
  423. App.updateStyles();
  424. Bar.updateDetails();
  425. Bar.setText(cfg.uiInfoCaption || cls === 'error' || cls === 'xhr' ? label : '');
  426. $dataset(b, 'prefix', prefix);
  427. setTimeout(Bar.show, 0, force);
  428. if (!b.parentNode) {
  429. doc.body.appendChild(b);
  430. Util.forceLayout(b);
  431. }
  432. },
  433.  
  434. setText(text) {
  435. if (/<([a-z][-a-z]*)[^<>]*>[^<>]*<\/\1\s*>/i.test(text)) { // checking for <tag...>...</tag>
  436. ai.bar.innerHTML = trustedHTML ? trustedHTML(text) : text;
  437. } else {
  438. ai.bar.textContent = text;
  439. }
  440. },
  441.  
  442. show(force) {
  443. const b = ai.bar;
  444. if (!force && (!cfg.uiInfo || force !== 0 && cfg.uiInfoOnce) || ai.barShown)
  445. return;
  446. clearTimeout(ai.timerBar);
  447. b.classList.add(PREFIX + 'show');
  448. $dataset(b, 'force', force === 2 ? '' : null);
  449. ai.timerBar = !force && setTimeout(Bar.hide, cfg.uiInfoHide * 1000);
  450. ai.barShown = true;
  451. },
  452.  
  453. hide(force) {
  454. const b = ai.bar;
  455. if (!b || !force && (!cfg.uiInfo || b.dataset.force) || !ai.barShown)
  456. return;
  457. $dataset(b, 'force', force === 2 ? '' : null);
  458. b.classList.remove(PREFIX + 'show');
  459. ai.barShown = false;
  460. },
  461.  
  462. updateName() {
  463. const {gItems: gi, gIndex: i, gNum: n} = ai;
  464. if (gi) {
  465. const item = gi[i];
  466. const noDesc = !gi.some(_ => _.desc);
  467. const c = [
  468. gi.title && (!i || noDesc) && !`${item.desc || ''}`.includes(gi.title) && gi.title || '',
  469. item.desc,
  470. ].filter(Boolean).join(' - ');
  471. Bar.set(c.trim() || ' ', 'gallery', n > 1 ? `${i + 1}/${n}` : null);
  472. } else if ('caption' in ai) {
  473. Bar.set(ai.caption, 'caption');
  474. } else if (ai.tooltip) {
  475. Bar.set(ai.tooltip.text, 'tooltip');
  476. } else {
  477. Bar.set(' ', 'info');
  478. }
  479. },
  480.  
  481. updateDetails() {
  482. if (!ai.bar) return;
  483. const r = ai.rotate;
  484. const zoom = ai.nwidth && `${
  485. Math.round(ai.scale * 100)
  486. }%${
  487. ai.flipX || ai.flipY ? `, ${ai.flipX ? '⇆' : ''}${ai.flipY ? '⇅' : ''}` : ''
  488. }${
  489. r ? ', ' + (r > 180 ? r - 360 : r) + '°' : ''
  490. }, ${
  491. ai.nwidth
  492. } x ${
  493. ai.nheight
  494. } px, ${
  495. Math.round(100 * (ai.nwidth * ai.nheight / 1e6)) / 100
  496. } MP, ${
  497. Calc.aspectRatio(ai.nwidth, ai.nheight)
  498. }`.replace(/\x20/g, '\xA0');
  499. if (ai.bar.dataset.zoom !== zoom || !ai.nwidth) {
  500. $dataset(ai.bar, 'zoom', zoom || null);
  501. Bar.show();
  502. }
  503. },
  504. };
  505.  
  506. const Calc = {
  507.  
  508. aspectRatio(w, h) {
  509. for (let rat = w / h, a, b = 0; ;) {
  510. b++;
  511. a = Math.round(w * b / h);
  512. if (a > 10 && b > 10 || a > 100 || b > 100)
  513. return rat.toFixed(2);
  514. if (Math.abs(a / b - rat) < .01)
  515. return `${a}:${b}`;
  516. }
  517. },
  518.  
  519. frameSize(elFrame, wnd) {
  520. if (!elFrame) return;
  521. const r = elFrame.getBoundingClientRect();
  522. const w = Math.min(r.right, wnd.innerWidth) - Math.max(r.left, 0);
  523. const h = Math.min(r.bottom, wnd.innerHeight) - Math.max(r.top, 0);
  524. const x = r.left < 0 ? -r.left : 0;
  525. const y = r.top < 0 ? -r.top : 0;
  526. return [w, h, x, y];
  527. },
  528.  
  529. generateScales(fit) {
  530. let [scale, goal] = fit < 1 ? [fit, 1] : [1, fit];
  531. const zoomStep = cfg.zoomStep / 100;
  532. const arr = [scale];
  533. if (fit !== 1) {
  534. const diff = goal / scale;
  535. const steps = Math.log(diff) / Math.log(zoomStep) | 0;
  536. const step = steps && Math.pow(diff, 1 / steps);
  537. for (let i = steps; --i > 0;)
  538. arr.push((scale *= step));
  539. arr.push(scale = goal);
  540. }
  541. while ((scale *= zoomStep) <= ZOOM_MAX)
  542. arr.push(scale);
  543. return arr;
  544. },
  545.  
  546. measurePopup() {
  547. let {popup: p, nwidth: nw, nheight: nh} = ai;
  548. // overriding custom CSS to detect an unrestricted SVG that scales to the entire page
  549. p.setAttribute('style', 'display:inline !important;' + App.popupStyleBase);
  550. if (p.clientWidth > nw) {
  551. const w = clamp(p.clientWidth, nw, innerWidth / 2) | 0;
  552. nh = ai.nheight = w / nw * nh | 0;
  553. nw = ai.nwidth = w;
  554. p.style.cssText = `width: ${nw}px !important; height: ${nh}px !important;`;
  555. }
  556. p.classList.add(`${PREFIX}show`);
  557. p.removeAttribute('style');
  558. const s = getComputedStyle(p);
  559. const o2 = sumProps(s.outlineOffset, s.outlineWidth) * 2;
  560. const inw = sumProps(s.paddingLeft, s.paddingRight, s.borderLeftWidth, s.borderRightWidth);
  561. const inh = sumProps(s.paddingTop, s.paddingBottom, s.borderTopWidth, s.borderBottomWidth);
  562. const outw = o2 + sumProps(s.marginLeft, s.marginRight);
  563. const outh = o2 + sumProps(s.marginTop, s.marginBottom);
  564. ai.extras = {
  565. inw, inh,
  566. outw, outh,
  567. o: o2 / 2,
  568. w: inw + outw,
  569. h: inh + outh,
  570. };
  571. const fit = Math.min(
  572. (ai.view.w - ai.extras.w) / ai.nwidth,
  573. (ai.view.h - ai.extras.h) / ai.nheight) || 1;
  574. const isCustom = !cfg.fit && cfg.scales.length;
  575. let cutoff = Math.min(1, fit);
  576. let scaleZoom = cfg.fit === 'all' && fit || cfg.fit === 'no' && 1 || cutoff;
  577. if (isCustom) {
  578. const dst = [];
  579. for (const scale of cfg.scales) {
  580. const val = parseFloat(scale) || fit;
  581. dst.push(val);
  582. if (isCustom && typeof scale === 'string') {
  583. if (scale.includes('!')) cutoff = val;
  584. if (scale.includes('*')) scaleZoom = val;
  585. }
  586. }
  587. ai.scales = dst.sort(compareNumbers).filter(Calc.scaleBiggerThan, cutoff);
  588. } else {
  589. ai.scales = Calc.generateScales(fit);
  590. }
  591. ai.scale = cfg.zoom === 'auto' ? scaleZoom : Math.min(1, fit);
  592. ai.scaleFit = fit;
  593. ai.scaleZoom = scaleZoom;
  594. },
  595.  
  596. rect() {
  597. const {node, rule} = ai;
  598. let n = rule.rect && node.closest(rule.rect);
  599. if (n) return n.getBoundingClientRect();
  600. const nested = (n = node).firstElementChild ? document.elementsFromPoint(ai.cx, ai.cy) : [];
  601. let maxArea = 0;
  602. let maxBounds;
  603. let i = 0;
  604. do {
  605. const bounds = n.getBoundingClientRect();
  606. const area = bounds.width * bounds.height;
  607. if (area > maxArea) {
  608. maxArea = area;
  609. maxBounds = bounds;
  610. }
  611. } while ((n = nested[i++]) && node.contains(n));
  612. return maxBounds;
  613. },
  614.  
  615. scaleBiggerThan(scale, i, arr) {
  616. return scale >= this && (!i || Math.abs(scale - arr[i - 1]) > .01);
  617. },
  618.  
  619. scaleIndex(dir) {
  620. const i = ai.scales.indexOf(ai.scale);
  621. if (i >= 0) return i + dir;
  622. for (
  623. let len = ai.scales.length,
  624. i = dir > 0 ? 0 : len - 1;
  625. i >= 0 && i < len;
  626. i += dir
  627. ) {
  628. if (Math.sign(ai.scales[i] - ai.scale) === dir)
  629. return i;
  630. }
  631. return -1;
  632. },
  633.  
  634. scaleForFirstZoom(keepScale) {
  635. const z = ai.scaleZoom;
  636. return keepScale || z !== ai.scale ? z : ai.scales.find(x => x > z);
  637. },
  638.  
  639. updateViewSize() {
  640. const view = doc.compatMode === 'BackCompat' ? doc.body : doc.documentElement;
  641. ai.view = {w: view.clientWidth, h: view.clientHeight, x: 0, y: 0};
  642. if (window === top) return;
  643. const [w, h] = Calc.frameSize(frameElement, parent) || [];
  644. if (w && h) {
  645. ai.view = {w, h, x: 0, y: 0};
  646. } else {
  647. addEventListener('message', App.onMessageChild, true);
  648. parent.postMessage(MSG.getViewSize, '*');
  649. }
  650. },
  651. };
  652.  
  653. class Config {
  654.  
  655. constructor({data: c, save}) {
  656. if (typeof c === 'string')
  657. c = tryJSON(c);
  658. if (typeof c !== 'object' || !c)
  659. c = {};
  660. const {DEFAULTS} = Config;
  661. c.fit = ['all', 'large', 'no', ''].includes(c.fit) ? c.fit :
  662. !(c.scales || 0).length || `${c.scales}` === `${DEFAULTS.scales}` ? 'large' :
  663. '';
  664. if (c.version !== DEFAULTS.version) {
  665. if (typeof c.hosts === 'string')
  666. c.hosts = c.hosts.split('\n')
  667. .map(s => tryJSON(s) || s)
  668. .filter(Boolean);
  669. if (c.close === true || c.close === false)
  670. c.zoomOut = c.close ? 'auto' : 'stay';
  671. for (const key in DEFAULTS)
  672. if (typeof c[key] !== typeof DEFAULTS[key])
  673. c[key] = DEFAULTS[key];
  674. if (c.version === 3 && c.scales[0] === 0)
  675. c.scales[0] = '0!';
  676. for (const key in c)
  677. if (!(key in DEFAULTS))
  678. delete c[key];
  679. c.version = DEFAULTS.version;
  680. if (save)
  681. GM.setValue('cfg', c);
  682. }
  683. if (Object.keys(cfg || {}).some(k => /^ui|^(css|globalStatus)$/.test(k) && cfg[k] !== c[k]))
  684. App.globalStyle = '';
  685. if (!isArray(c.scales))
  686. c.scales = [];
  687. c.scales = [...new Set(c.scales)].sort((a, b) => parseFloat(a) - parseFloat(b));
  688. Object.assign(this, DEFAULTS, c);
  689. }
  690.  
  691. static async load(opts) {
  692. opts.data = await GM.getValue('cfg');
  693. return new Config(opts);
  694. }
  695.  
  696. _getCss() {
  697. const {css} = this;
  698. return css.includes('{') ? css : `#${PREFIX}-popup {${css}}`;
  699. }
  700. }
  701.  
  702. Config.DEFAULTS = /** @type mpiv.Config */ {
  703. __proto__: null,
  704. center: false,
  705. css: '',
  706. delay: 500,
  707. fit: '',
  708. globalStatus: false,
  709. // prefer ' inside rules because " will be displayed as \"
  710. // example: "img[src*='icon']"
  711. hosts: [{
  712. name: 'No popup for YouTube thumbnails',
  713. d: 'www.youtube.com',
  714. e: 'ytd-rich-item-renderer *, ytd-thumbnail *',
  715. s: '',
  716. }, {
  717. name: 'No popup for SVG/PNG icons',
  718. d: '',
  719. e: "img[src*='icon']",
  720. r: '//[^/]+/.*\\bicons?\\b.*\\.(?:png|svg)',
  721. s: '',
  722. }],
  723. imgtab: false,
  724. keepOnBlur: false,
  725. keepVids: false,
  726. mute: false,
  727. night: false,
  728. preload: false,
  729. scale: 1.05,
  730. scales: ['0!', 0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 4, 5, 8, 16],
  731. start: 'auto',
  732. startAlt: 'context',
  733. startAltShown: false,
  734. uiBackgroundColor: '#ffffff',
  735. uiBackgroundOpacity: 100,
  736. uiBorderColor: '#000000',
  737. uiBorderOpacity: 100,
  738. uiBorder: 0,
  739. uiFadein: true,
  740. uiFadeinGallery: true, // some computers show white background while loading so fading hides it
  741. uiInfo: true,
  742. uiInfoCaption: true,
  743. uiInfoHide: 3,
  744. uiInfoOnce: true,
  745. uiShadowColor: '#000000',
  746. uiShadowOpacity: 80,
  747. uiShadow: 20,
  748. uiPadding: 0,
  749. uiMargin: 0,
  750. version: 6,
  751. videoCtrl: true,
  752. waitLoad: false,
  753. xhr: true,
  754. zoom: 'context',
  755. zoomOut: 'auto',
  756. zoomStep: 133,
  757. };
  758.  
  759. const CspSniffer = {
  760.  
  761. /** @type {?Object<string,string[]>} */
  762. csp: null,
  763. selfUrl: location.origin + '/',
  764.  
  765. // will be null when done
  766. init() {
  767. this.busy = new Promise(resolve => {
  768. const xhr = new XMLHttpRequest();
  769. xhr.open('get', location);
  770. xhr.timeout = Math.max(2000, (performance.timing.responseEnd - performance.timeOrigin) * 2);
  771. xhr.onreadystatechange = () => {
  772. if (xhr.readyState >= xhr.HEADERS_RECEIVED) {
  773. this.csp = this._parse([
  774. xhr.getResponseHeader('content-security-policy'),
  775. $prop('meta[http-equiv="Content-Security-Policy"]', 'content'),
  776. ].filter(Boolean).join(','));
  777. this.init = this.busy = xhr.onreadystatechange = null;
  778. xhr.abort();
  779. resolve();
  780. }
  781. };
  782. xhr.send();
  783. });
  784. },
  785.  
  786. async check(url, allowInit) {
  787. if (allowInit && this.init) this.init();
  788. if (this.busy) await this.busy;
  789. const isVideo = Util.isVideoUrl(url);
  790. let mode;
  791. if (this.csp) {
  792. const src = this.csp[isVideo ? 'media' : 'img'];
  793. if (!src.some(this._srcMatches, url))
  794. mode = [mode, 'blob', 'data'].find(m => src.includes(`${m}:`));
  795. }
  796. return [mode || ai.xhr, isVideo];
  797. },
  798.  
  799. _parse(csp) {
  800. if (!csp) return;
  801. const src = {};
  802. const rx = /(?:^|[;,])\s*(?:(default|img|media|script)-src|require-(trusted)-types-for) ([^;,]+)/g;
  803. for (let m; (m = rx.exec(csp));)
  804. src[m[1] || m[2]] = m[3].trim().split(/\s+/);
  805. if ((src.script || []).find(s => /^'nonce-(.+)'$/.test(s)))
  806. nonce = RegExp.$1;
  807. if ((src.trusted || []).includes("'script'"))
  808. App.NOP = () => {};
  809. if (!src.img) src.img = src.default || [];
  810. if (!src.media) src.media = src.default || [];
  811. for (const set of [src.img, src.media]) {
  812. set.forEach((item, i) => {
  813. if (item !== '*' && item.includes('*')) {
  814. set[i] = new RegExp(
  815. (/^\w+:/.test(item) ? '^' : '^\\w+://') +
  816. item
  817. .replace(/[.+?^$|()[\]{}]/g, '\\$&')
  818. .replace(/(\\\.)?(\*)(\\\.)?/g, (_, a, b, c) =>
  819. `${a ? '\\.?' : ''}[^:/]*${c ? '\\.?' : ''}`)
  820. .replace(/[^/]$/, '$&/'));
  821. }
  822. });
  823. }
  824. return src;
  825. },
  826.  
  827. /** @this string */
  828. _srcMatches(src) {
  829. return src instanceof RegExp ? src.test(this) :
  830. src === '*' ||
  831. src && this.startsWith(src) && (src.endsWith('/') || this[src.length] === '/') ||
  832. src === "'self'" && this.startsWith(CspSniffer.selfUrl);
  833. },
  834. };
  835.  
  836. const Events = {
  837.  
  838. ctrl: false,
  839. hoverData: null,
  840. hoverTimer: 0,
  841. ignoreKeyHeld: false,
  842.  
  843. onMouseOver(e) {
  844. let node = e.target;
  845. Events.ignoreKeyHeld = e.shiftKey;
  846. if (!App.isEnabled ||
  847. e.shiftKey ||
  848. ai.zoomed ||
  849. node === ai.popup ||
  850. node === doc.body ||
  851. node === doc.documentElement ||
  852. node === elSetup ||
  853. ai.gallery && ai.rectHovered ||
  854. !App.canClose())
  855. return;
  856. if (node.shadowRoot)
  857. node = Events.pierceShadow(node, e.clientX, e.clientY);
  858. // we don't want to process everything in the path of a quickly moving mouse cursor
  859. Events.hoverData = {e, node, start: now()};
  860. Events.hoverTimer = Events.hoverTimer || setTimeout(Events.onMouseOverThrottled, SETTLE_TIME);
  861. node.addEventListener('mouseout', Events.onMouseOutThrottled);
  862. },
  863.  
  864. onMouseOverThrottled(force) {
  865. const {start, e, node, nodeOut} = Events.hoverData || {};
  866. if (!node || node === nodeOut && (Events.hoverData = null, 1))
  867. return;
  868. // clearTimeout + setTimeout is expensive so we'll use the cheaper perf.now() for rescheduling
  869. const wait = force ? 0 : start + SETTLE_TIME - now();
  870. const t = Events.hoverTimer = wait > 10 && setTimeout(Events.onMouseOverThrottled, wait);
  871. if (t)
  872. return;
  873. Events.hoverData = null;
  874. if (!Ruler.rules)
  875. Ruler.init();
  876. const info = RuleMatcher.adaptiveFind(node);
  877. if (info && info.url && info.node !== ai.node)
  878. App.activate(info, e);
  879. },
  880.  
  881. onMouseOut(e) {
  882. if (!e.relatedTarget && !cfg.keepOnBlur && !e.shiftKey && App.canClose())
  883. App.deactivate();
  884. },
  885.  
  886. onMouseOutThrottled(e) {
  887. const d = Events.hoverData;
  888. if (d) d.nodeOut = this;
  889. this.removeEventListener('mouseout', Events.onMouseOutThrottled);
  890. Events.hoverTimer = 0;
  891. },
  892.  
  893. onMouseOutShadow(e) {
  894. const root = e.target.shadowRoot;
  895. if (root) {
  896. root.removeEventListener('mouseover', Events.onMouseOver);
  897. root.removeEventListener('mouseout', Events.onMouseOutShadow);
  898. }
  899. },
  900.  
  901. onMouseMove(e) {
  902. Events.trackMouse(e);
  903. if (e.shiftKey)
  904. return;
  905. if (!ai.zoomed && !ai.rectHovered && App.canClose()) {
  906. App.deactivate();
  907. } else if (ai.zoomed) {
  908. Popup.move();
  909. const {cx, cy, view: {w, h}} = ai;
  910. const bx = w / 6;
  911. const by = h / 6;
  912. const onEdge = cx < bx || cx > w - bx || cy < by || cy > h - by;
  913. Status.set(`${onEdge ? '+' : '-'}edge`);
  914. }
  915. },
  916.  
  917. onMouseDown({shiftKey, button, target}) {
  918. if (!button && target === ai.popup && ai.popup.controls && (shiftKey || !App.canClose())) {
  919. ai.controlled = ai.zoomed = true;
  920. } else if (button === 2 || shiftKey) {
  921. // Shift = ignore; RMB will be processed in onContext
  922. } else {
  923. App.deactivate({wait: true});
  924. doc.addEventListener('mouseup', App.enable, {once: true});
  925. }
  926. },
  927.  
  928. onMouseScroll(e) {
  929. const dir = (e.deltaY || -e.wheelDelta) < 0 ? 1 : -1;
  930. if (ai.zoomed) {
  931. Events.zoomInOut(dir);
  932. } else if (ai.gNum > 1 && ai.popup) {
  933. Gallery.next(-dir);
  934. } else if (cfg.zoom === 'wheel' && dir > 0 && ai.popup) {
  935. App.toggleZoom();
  936. } else if (App.canClose()) {
  937. App.deactivate();
  938. return;
  939. }
  940. dropEvent(e);
  941. },
  942.  
  943. onKeyDown(e) {
  944. // Synthesized events may be of the wrong type and not have a `key`
  945. const key = describeKey(e);
  946. const p = ai.popupShown;
  947. if (!p && key === '^Control') {
  948. addEventListener('keyup', Events.onKeyUp, true);
  949. Events.ctrl = true;
  950. }
  951. if (!p && key === '^ContextMenu')
  952. return Events.onContext.call(this, e);
  953. if (!p || e.repeat)
  954. return;
  955. switch (key) {
  956. case '+Shift':
  957. if (ai.shiftKeyTime)
  958. return;
  959. ai.shiftKeyTime = now();
  960. Status.set('+shift');
  961. if (cfg.uiInfo)
  962. Bar.show(1);
  963. if (isVideo(p))
  964. p.controls = true;
  965. return;
  966. case 'KeyA':
  967. p.toggleAttribute(NOAA_ATTR);
  968. break;
  969. case 'ArrowRight':
  970. case 'KeyJ':
  971. Gallery.next(1);
  972. break;
  973. case 'ArrowLeft':
  974. case 'KeyK':
  975. Gallery.next(-1);
  976. break;
  977. case 'KeyC':
  978. if (ai.bar.firstChild) {
  979. Bar.setText('');
  980. Bar.hide(0);
  981. } else {
  982. Bar.setText(ai.barText);
  983. Bar.show(2);
  984. }
  985. break;
  986. case 'KeyD':
  987. Req.saveFile();
  988. break;
  989. case 'KeyF':
  990. if (p !== document.fullscreenElement) p.requestFullscreen();
  991. else document.exitFullscreen();
  992. break;
  993. case 'KeyH': // flip horizontally
  994. case 'KeyV': // flip vertically
  995. case 'KeyL': // rotate left
  996. case 'KeyR': // rotate right
  997. if (!p)
  998. return;
  999. if (key === 'KeyH' || key === 'KeyV') {
  1000. const side = !!(ai.rotate % 180) ^ (key === 'KeyH') ? 'flipX' : 'flipY';
  1001. ai[side] = !ai[side];
  1002. } else {
  1003. ai.rotate = ((ai.rotate || 0) + 90 * (key === 'KeyL' ? -1 : 1) + 360) % 360;
  1004. }
  1005. Bar.updateDetails();
  1006. Popup.move();
  1007. break;
  1008. case 'KeyI':
  1009. (ai.barShown ? Bar.hide : Bar.show)(2);
  1010. break;
  1011. case 'KeyM':
  1012. if (isVideo(p))
  1013. p.muted = !p.muted;
  1014. break;
  1015. case 'KeyN':
  1016. ai.night = p.classList.toggle(`${PREFIX}night`);
  1017. break;
  1018. case 'KeyT':
  1019. GM.openInTab(Util.tabFixUrl() || p.src);
  1020. App.deactivate();
  1021. break;
  1022. case 'Minus':
  1023. case 'NumpadSubtract':
  1024. if (ai.zoomed) {
  1025. Events.zoomInOut(-1);
  1026. } else {
  1027. App.toggleZoom();
  1028. }
  1029. break;
  1030. case 'Equal':
  1031. case 'NumpadAdd':
  1032. if (ai.zoomed) {
  1033. Events.zoomInOut(1);
  1034. } else {
  1035. App.toggleZoom();
  1036. }
  1037. break;
  1038. case 'Escape':
  1039. App.deactivate({wait: true});
  1040. break;
  1041. case '!Alt':
  1042. return;
  1043. default:
  1044. App.deactivate({wait: true});
  1045. return;
  1046. }
  1047. dropEvent(e);
  1048. },
  1049.  
  1050. onKeyUp(e) {
  1051. const p = ai.popupShown || false;
  1052. if (e.key === 'Control') {
  1053. if (!p) removeEventListener('keyup', Events.onKeyUp, true);
  1054. setTimeout(() => (Events.ctrl = false));
  1055. }
  1056. if (p && e.key === 'Shift' && ai.shiftKeyTime) {
  1057. Status.set('-shift');
  1058. if (cfg.uiInfo)
  1059. Bar.hide(1);
  1060. if (p.controls)
  1061. p.controls = false;
  1062. // Chrome doesn't expose events for clicks on video controls so we'll guess
  1063. if (ai.controlled || !isFF && now() - ai.shiftKeyTime > 500)
  1064. ai.controlled = false;
  1065. else if (p && (ai.zoomed || ai.rectHovered !== false))
  1066. App.toggleZoom();
  1067. else
  1068. App.deactivate({wait: true});
  1069. ai.shiftKeyTime = 0;
  1070. } else if (
  1071. describeKey(e) === 'Control' && !p && !Events.ignoreKeyHeld &&
  1072. (cfg.start === 'ctrl' || cfg.start === 'context' || ai.rule.manual)
  1073. ) {
  1074. dropEvent(e);
  1075. if (Events.hoverData) {
  1076. Events.hoverData.e = e;
  1077. Events.onMouseOverThrottled(true);
  1078. }
  1079. if (ai.node) {
  1080. ai.force = true;
  1081. App.start();
  1082. }
  1083. }
  1084. },
  1085.  
  1086. onContext(e) {
  1087. if (Events.ignoreKeyHeld)
  1088. return;
  1089. const p = ai.popupShown;
  1090. if (cfg.zoom === 'context' && p && App.toggleZoom()) {
  1091. dropEvent(e);
  1092. } else if (!p && (!cfg.videoCtrl || !isVideo(ai.node) || Events.ctrl) && (
  1093. cfg.start === 'context' ||
  1094. cfg.start === 'contextMK' ||
  1095. cfg.start === 'contextM' && (e.button === 2) ||
  1096. cfg.start === 'contextK' && (e.button !== 2) ||
  1097. (cfg.start === 'auto' && ai.rule.manual)
  1098. )) {
  1099. // right-clicked on an image while the context menu is shown for something else
  1100. if (!ai.node && !Events.hoverData)
  1101. Events.onMouseOver(e);
  1102. Events.onMouseOverThrottled(true);
  1103. if (ai.node) {
  1104. ai.force = true;
  1105. App.start();
  1106. dropEvent(e);
  1107. }
  1108. } else if (p) {
  1109. setTimeout(App.deactivate, SETTLE_TIME, {wait: true});
  1110. }
  1111. },
  1112.  
  1113. onVisibility(e) {
  1114. Events.ctrl = false;
  1115. },
  1116.  
  1117. pierceShadow(node, x, y) {
  1118. for (let root; (root = node.shadowRoot);) {
  1119. root.addEventListener('mouseover', Events.onMouseOver, {passive: true});
  1120. root.addEventListener('mouseout', Events.onMouseOutShadow);
  1121. const inner = root.elementFromPoint(x, y);
  1122. if (!inner || inner === node)
  1123. break;
  1124. node = inner;
  1125. }
  1126. return node;
  1127. },
  1128.  
  1129. toggle(enable) {
  1130. const onOff = enable ? 'addEventListener' : 'removeEventListener';
  1131. const passive = {passive: true, capture: true};
  1132. window[onOff]('mousemove', Events.onMouseMove, passive);
  1133. window[onOff]('mouseout', Events.onMouseOut, passive);
  1134. window[onOff]('mousedown', Events.onMouseDown, passive);
  1135. window[onOff]('keyup', Events.onKeyUp, true);
  1136. window[onOff](WHEEL_EVENT, Events.onMouseScroll, {passive: false, capture: true});
  1137. ai.node.removeEventListener('mouseout', Events.onMouseOutThrottled);
  1138. },
  1139.  
  1140. trackMouse(e) {
  1141. const cx = ai.cx = e.clientX;
  1142. const cy = ai.cy = e.clientY;
  1143. const r = ai.rect || (ai.rect = Calc.rect());
  1144. ai.rectHovered =
  1145. cx > r.left - 2 && cx < r.right + 2 &&
  1146. cy > r.top - 2 && cy < r.bottom + 2;
  1147. },
  1148.  
  1149. zoomInOut(dir) {
  1150. const i = Calc.scaleIndex(dir);
  1151. const n = ai.scales.length;
  1152. if (i >= 0 && i < n)
  1153. ai.scale = ai.scales[i];
  1154. const zo = cfg.zoomOut;
  1155. if (i <= 0 && zo !== 'stay') {
  1156. if (ai.scaleFit < ai.scale * .99) {
  1157. ai.scales.unshift(ai.scale = ai.scaleFit);
  1158. } else if ((i <= 0 && zo === 'close' || i < 0 && !ai.rectHovered) && ai.gNum < 2) {
  1159. App.deactivate({wait: true});
  1160. return;
  1161. }
  1162. ai.zoomed = zo !== 'unzoom';
  1163. } else {
  1164. ai.popup.classList.toggle(`${PREFIX}zoom-max`, ai.scale >= 4 && i >= n - 1);
  1165. }
  1166. if (ai.zooming)
  1167. ai.popup.classList.add(`${PREFIX}zooming`);
  1168. Popup.move();
  1169. Bar.updateDetails();
  1170. },
  1171. };
  1172.  
  1173. const Gallery = {
  1174.  
  1175. makeParser(g) {
  1176. return isFunction(g) ? g : Gallery.defaultParser;
  1177. },
  1178.  
  1179. findIndex(gUrl) {
  1180. const sel = gUrl.split('#')[1];
  1181. if (!sel)
  1182. return 0;
  1183. let i = +sel;
  1184. if (i >= 0 && i === (i | 0))
  1185. return i;
  1186. for (i = 0; i < ai.gNum; i++) {
  1187. const {url} = ai.gItems[i];
  1188. if (isArray(url)
  1189. ? url.indexOf(sel) || url.some(u => u.indexOf(sel, u.lastIndexOf('/')) > 0)
  1190. : url === sel || url.indexOf(sel, url.lastIndexOf('/')) > 0
  1191. ) return i;
  1192. }
  1193. return 0;
  1194. },
  1195.  
  1196. next(dir) {
  1197. if (dir) ai.gIndex = Gallery.nextIndex(dir);
  1198. const item = ai.gItem = ai.gItems[ai.gIndex];
  1199. if (isArray(item.url)) {
  1200. ai.urls = item.url.slice(1);
  1201. ai.url = item.url[0];
  1202. } else {
  1203. ai.urls = null;
  1204. ai.url = item.url;
  1205. }
  1206. ai.gItemNext = ai.gItems[Gallery.nextIndex(dir || 1)];
  1207. App.startSingle();
  1208. Bar.updateName();
  1209. if (dir) Bar.show(0);
  1210. },
  1211.  
  1212. nextIndex(dir) {
  1213. return (ai.gIndex + dir + ai.gNum) % ai.gNum;
  1214. },
  1215.  
  1216. defaultParser(text, doc, docUrl, m, rule) {
  1217. const {g} = rule;
  1218. const gi = g.index;
  1219. const qEntry = g.entry;
  1220. const qCaption = ensureArray(g.caption);
  1221. const qImage = g.image || 'img';
  1222. const qTitle = g.title;
  1223. const fix =
  1224. (typeof g.fix === 'string' ? Util.newFunction('s', 'isURL', g.fix) : g.fix) ||
  1225. (s => s.trim());
  1226. const elems = [...$$(qEntry || qImage, doc)];
  1227. const items = elems.map(processEntry).filter(Boolean);
  1228. items.title = processTitle();
  1229. items.index =
  1230. RX_HAS_CODE.test(gi) ? Util.newFunction('items', 'node', gi)(items, ai.node) :
  1231. typeof gi === 'string' ? Req.findImageUrl(tryCatch($, gi, doc), docUrl) :
  1232. gi == null ? Math.max(0, elems.indexOf(ai.node)) :
  1233. gi;
  1234. return items;
  1235.  
  1236. function processEntry(entry) {
  1237. const item = {};
  1238. try {
  1239. const img = qEntry ? $(qImage, entry) : entry;
  1240. item.url = fix(Req.findImageUrl(img, docUrl), true);
  1241. item.desc = qCaption.map(processCaption, entry).filter(Boolean).join(' - ');
  1242. } catch (e) {}
  1243. return item.url && item;
  1244. }
  1245. function processCaption(sel) {
  1246. const el = !sel ? this
  1247. : $(sel, this) ||
  1248. $orSelf(sel, this.previousElementSibling) ||
  1249. $orSelf(sel, this.nextElementSibling);
  1250. return el && fix(Ruler.runCHandler.default(el) || el.textContent);
  1251. }
  1252. function processTitle() {
  1253. const el = $(qTitle, doc);
  1254. return el && fix(el.getAttribute('content') || el.textContent) || '';
  1255. }
  1256. function $orSelf(selector, el) {
  1257. if (el && !el.matches(qEntry))
  1258. return el.matches(selector) ? el : $(selector, el);
  1259. }
  1260. },
  1261. };
  1262.  
  1263. const Menu = window === top && GM.registerMenuCommand && {
  1264. curAltName: '',
  1265. unreg: GM.unregisterMenuCommand,
  1266. makeAltName: () => Menu.unreg
  1267. ? `MPIV: auto-start is ${cfg.start === 'auto' ? 'ON' : 'OFF'}`
  1268. : 'MPIV: toggle auto-start',
  1269. register() {
  1270. GM.registerMenuCommand('MPIV: configure', setup);
  1271. Menu.registerAlt();
  1272. },
  1273. registerAlt() {
  1274. if (cfg.startAltShown) {
  1275. Menu.curAltName = Menu.makeAltName();
  1276. GM.registerMenuCommand(Menu.curAltName, Menu.onAltToggled);
  1277. }
  1278. },
  1279. reRegisterAlt() {
  1280. const old = Menu.curAltName;
  1281. if (old && Menu.unreg) Menu.unreg(old);
  1282. if (!old || Menu.unreg) Menu.registerAlt();
  1283. },
  1284. onAltToggled() {
  1285. const wasAuto = cfg.start === 'auto';
  1286. if (wasAuto) {
  1287. cfg.start = cfg.startAlt || (cfg.startAlt = 'context');
  1288. } else {
  1289. cfg.startAlt = cfg.start;
  1290. cfg.start = 'auto';
  1291. }
  1292. Menu.reRegisterAlt();
  1293. },
  1294. };
  1295.  
  1296. const Popup = {
  1297.  
  1298. async create(src, pageUrl, error) {
  1299. const inGallery = !cfg.uiFadeinGallery && ai.gItems && ai.popup && !ai.zooming &&
  1300. (ai.popup.dataset.galleryFlip = '') === '';
  1301. if (!ai.gItems)
  1302. Popup.destroy();
  1303. else if (ai.blobUrl)
  1304. URL.revokeObjectURL(ai.blobUrl);
  1305. ai.imageUrl = src;
  1306. if (!src)
  1307. return;
  1308. const myAi = ai;
  1309. let [xhr, isVideo] = await CspSniffer.check(src, error);
  1310. if (ai !== myAi)
  1311. return;
  1312. if (!xhr && error) {
  1313. App.handleError(error);
  1314. return;
  1315. }
  1316. Object.assign(ai, {pageUrl, xhr});
  1317. if (xhr)
  1318. [src, isVideo] = await Req.getImage(src, pageUrl, xhr).catch(App.handleError) || [];
  1319. let vol;
  1320. if (ai !== myAi || !src || isVideo && (vol = await GM.getValue('volume'), ai !== myAi))
  1321. return;
  1322. let p = ai.popup, blank;
  1323. if (p) {
  1324. p.src = blank = BLANK_PIXEL;
  1325. ai.popupShown = null;
  1326. ai.popupLoaded = false;
  1327. } else p = ai.popup = isVideo ? PopupVideo.create(vol) : $new('img');
  1328. p.id = `${PREFIX}popup`;
  1329. p.src = src;
  1330. p.addEventListener('error', App.handleError);
  1331. if ((ai.night = (ai.night != null ? ai.night : cfg.night)))
  1332. p.classList.add(`${PREFIX}night`);
  1333. if (ai.zooming)
  1334. p.addEventListener('transitionend', Popup.onZoom);
  1335. $dataset(p, 'galleryFlip', inGallery);
  1336. p.toggleAttribute('loaded', inGallery);
  1337. const poo = ai.popover || typeof p.showPopover === 'function' && $('[popover]:popover-open');
  1338. ai.popover = poo && poo.getBoundingClientRect().width && ($css(poo, {opacity: 0}), poo) || null;
  1339. if (p.parentElement !== doc.body)
  1340. doc.body.insertBefore(p, ai.bar && ai.bar.parentElement === doc.body && ai.bar || null);
  1341. await 0;
  1342. if (ai.popup !== p || App.checkProgress({start: true}) === false)
  1343. return;
  1344. if (!blank && p.complete)
  1345. Popup.onLoad.call(p);
  1346. else if (!isVideo)
  1347. p.addEventListener('load', Popup.onLoad, {once: true});
  1348. },
  1349.  
  1350. destroy() {
  1351. const p = ai.popup;
  1352. if (!p) return;
  1353. p.removeEventListener('load', Popup.onLoad);
  1354. p.removeEventListener('error', App.handleError);
  1355. if (ai.popover) {
  1356. ai.popover.style.removeProperty('opacity');
  1357. ai.popover = null;
  1358. }
  1359. if (isFunction(p.pause))
  1360. p.pause();
  1361. if (ai.blobUrl)
  1362. setTimeout(URL.revokeObjectURL, SETTLE_TIME, ai.blobUrl);
  1363. p.remove();
  1364. ai.zoomed = ai.popup = ai.popupLoaded = ai.blobUrl = null;
  1365. },
  1366.  
  1367. move() {
  1368. let x, y;
  1369. const {cx, cy, extras, view} = ai;
  1370. const vw = view.w - extras.outw;
  1371. const vh = view.h - extras.outh;
  1372. const w0 = ai.scale * ai.nwidth + extras.inw;
  1373. const h0 = ai.scale * ai.nheight + extras.inh;
  1374. const isSwapped = ai.rotate % 180;
  1375. const w = isSwapped ? h0 : w0;
  1376. const h = isSwapped ? w0 : h0;
  1377. if (!ai.zoomed && ai.gNum < 2 && !cfg.center) {
  1378. const r = ai.rect;
  1379. const rx = (r.left + r.right) / 2;
  1380. const ry = (r.top + r.bottom) / 2;
  1381. if (vw - r.right - 40 > w || w < r.left - 40) {
  1382. if (h < vh - 60)
  1383. y = clamp(ry - h / 2, 30, vh - h - 30);
  1384. x = rx > vw / 2 ? r.left - 40 - w : r.right + 40;
  1385. } else if (vh - r.bottom - 40 > h || h < r.top - 40) {
  1386. if (w < vw - 60)
  1387. x = clamp(rx - w / 2, 30, vw - w - 30);
  1388. y = ry > vh / 2 ? r.top - 40 - h : r.bottom + 40;
  1389. }
  1390. }
  1391. if (x == null) {
  1392. x = vw > w
  1393. ? (vw - w) / 2 + view.x
  1394. : (vw - w) * clamp(5 / 3 * ((cx - view.x) / vw - .2), 0, 1);
  1395. }
  1396. if (y == null) {
  1397. y = vh > h
  1398. ? (vh - h) / 2 + view.y
  1399. : (vh - h) * clamp(5 / 3 * ((cy - view.y) / vh - .2), 0, 1);
  1400. }
  1401. const diff = isSwapped ? (w0 - h0) / 2 : 0;
  1402. x += extras.o - diff;
  1403. y += extras.o + diff;
  1404. $css(ai.popup, {
  1405. transform: `translate(${Math.round(x)}px, ${Math.round(y)}px) ` +
  1406. `rotate(${ai.rotate || 0}deg) ` +
  1407. `scale(${ai.flipX ? -1 : 1},${ai.flipY ? -1 : 1})`,
  1408. width: `${Math.round(w0)}px`,
  1409. height: `${Math.round(h0)}px`,
  1410. });
  1411. },
  1412.  
  1413. onLoad() {
  1414. if (this === ai.popup) {
  1415. this.setAttribute('loaded', '');
  1416. ai.popupLoaded = true;
  1417. Status.set('-loading');
  1418. let i = ai.gItem;
  1419. if (i) i.url = this.src;
  1420. if ((i = ai.gItemNext))
  1421. Popup.preload(this, i);
  1422. }
  1423. },
  1424.  
  1425. onZoom() {
  1426. this.classList.remove(`${PREFIX}zooming`);
  1427. },
  1428.  
  1429. async preload(p, item, u = item.url, el = $new('img')) {
  1430. ai.gItemNext = null;
  1431. if (!isArray(u)) {
  1432. el.src = u;
  1433. return;
  1434. }
  1435. for (const arr = u; p === ai.popup && item.url === arr && (u = arr[0]);) {
  1436. const {type} = await new Promise(cb => {
  1437. el.src = u;
  1438. el.onload = el.onerror = cb;
  1439. });
  1440. if (arr[0] === u)
  1441. arr.shift();
  1442. if (type === 'load') {
  1443. item.url = u;
  1444. break;
  1445. }
  1446. }
  1447. },
  1448. };
  1449.  
  1450. const PopupVideo = {
  1451. create(volume) {
  1452. ai.bufBar = false;
  1453. ai.bufStart = now();
  1454. return $new('video', {
  1455. autoplay: ai.preloadStart !== -1,
  1456. controls: true,
  1457. muted: cfg.mute || new AudioContext().state === 'suspended',
  1458. loop: true,
  1459. volume: clamp(+volume || .5, 0, 1),
  1460. onprogress: PopupVideo.progress,
  1461. oncanplaythrough: PopupVideo.progressDone,
  1462. onvolumechange: PopupVideo.rememberVolume,
  1463. });
  1464. },
  1465.  
  1466. progress() {
  1467. const {duration} = this;
  1468. if (duration && this.buffered.length && now() - ai.bufStart > 2000) {
  1469. const pct = Math.round(this.buffered.end(0) / duration * 100);
  1470. if (ai.bar && (ai.bufBar |= pct > 0 && pct < 50))
  1471. Bar.set(`${pct}% of ${Math.round(duration)}s`, 'xhr');
  1472. }
  1473. },
  1474.  
  1475. progressDone() {
  1476. this.onprogress = this.oncanplaythrough = null;
  1477. if (ai.bar && ai.bar.classList.contains(`${PREFIX}xhr`))
  1478. Bar.set(false);
  1479. Popup.onLoad.call(this);
  1480. },
  1481.  
  1482. rememberVolume() {
  1483. GM.setValue('volume', this.volume);
  1484. },
  1485. };
  1486.  
  1487. const Ruler = {
  1488. /*
  1489. 'u' works only with URLs so it's ignored if 'html' is true
  1490. ||some.domain = matches some.domain, anything.some.domain, etc.
  1491. |foo = url or text must start with foo
  1492. ^ = separator like / or ? or : but not a letter/number, not %._-
  1493. when used at the end like "foo^" it additionally matches when the source ends with "foo"
  1494. 'r' is checked only if 'u' matches first
  1495. */
  1496. init() {
  1497. const errors = new Map();
  1498. /** @type mpiv.HostRule[] */
  1499. const rules = Ruler.rules = (cfg.hosts || []).map(Ruler.parse, errors).filter(Boolean);
  1500. const hasGMAE = typeof GM_addElement === 'function';
  1501. const canEval = nonce || (nonce = ($('script[nonce]') || {}).nonce || '') || hasGMAE;
  1502. const evalId = canEval && `${GM_info.script.name}${Math.random()}`;
  1503. const evalRules = [];
  1504. const evalCode = [`window[${JSON.stringify(evalId)}]=[`];
  1505. for (const [rule, err] of errors.entries()) {
  1506. if (!RX_EVAL_BLOCKED.test(err)) {
  1507. App.handleError('Invalid custom host rule:', rule);
  1508. continue;
  1509. }
  1510. if (canEval) {
  1511. evalCode.push(evalRules.length ? ',' : '',
  1512. '[', rules.indexOf(rule), ',{',
  1513. ...Object.keys(FN_ARGS)
  1514. .map(k => RX_HAS_CODE.test(rule[k]) && `${k}(${FN_ARGS[k]}){${rule[k]}},`)
  1515. .filter(Boolean),
  1516. '}]');
  1517. }
  1518. evalRules.push(rule);
  1519. }
  1520. if (evalRules.length) {
  1521. let result, wnd;
  1522. if (canEval) {
  1523. const GMAE = hasGMAE
  1524. ? GM_addElement // eslint-disable-line no-undef
  1525. : (tag, {textContent: txt}) => document.head.appendChild(
  1526. Object.assign(document.createElement(tag), {
  1527. textContent: trustedScript ? trustedScript(txt) : txt,
  1528. nonce,
  1529. }));
  1530. evalCode.push(']; document.currentScript.remove();');
  1531. GMAE('script', {textContent: evalCode.join('')});
  1532. result = (wnd = unsafeWindow)[evalId] ||
  1533. isFF && (wnd = wnd.wrappedJSObject)[evalId];
  1534. }
  1535. if (result) {
  1536. for (const [index, fns] of result)
  1537. Object.assign(rules[index], fns);
  1538. delete wnd[evalId];
  1539. } else {
  1540. console.warn('Site forbids compiling JS code in these custom rules', evalRules);
  1541. }
  1542. }
  1543.  
  1544. // optimization: a rule is created only when on domain
  1545. switch (dotDomain.match(/[^.]+(?=\.com?(?:\.[^.]+)?$)|[^.]+\.[^.]+$|$/)[0]) {
  1546.  
  1547. case '4chan.org': rules.push({
  1548. e: '.is_catalog .thread a[href*="/thread/"], .catalog-thread a[href*="/thread/"]',
  1549. q: '.op .fileText a',
  1550. css: '#post-preview{display:none}',
  1551. }); break;
  1552.  
  1553. case 'amazon': rules.push({
  1554. r: /.+?images\/I\/.+?\./,
  1555. s: m => {
  1556. const uh = doc.getElementById('universal-hover');
  1557. return uh ? '' : m[0] + 'jpg';
  1558. },
  1559. css: '#zoomWindow{display:none!important;}',
  1560. }); break;
  1561.  
  1562. case 'bing': rules.push({
  1563. e: 'a[m*="murl"]',
  1564. r: /murl&quot;:&quot;(.+?)&quot;/,
  1565. s: '$1',
  1566. html: true,
  1567. }); break;
  1568.  
  1569. case 'deviantart': rules.push({
  1570. e: 'a[href*="/art/"] img[src*="/v1/"]',
  1571. r: /^(.+)\/v1\/\w+\/[^/]+\/(.+)-\d+.(\.\w+)(\?.+)/,
  1572. s: ([, base, name, ext, tok], node) => {
  1573. let v = Util.getReactChildren(node.closest('a'), 'props.deviation.media.types');
  1574. return v && (v = v.find(t => t.t === 'fullview')) && `${base}${
  1575. v.c ? v.c.replace('<prettyName>', name)
  1576. : `/v1/fill/w_${v.w},h_${v.h}/${name}-fullview${ext}`}${tok}`;
  1577. },
  1578. }, {
  1579. e: '.dev-view-deviation img',
  1580. s: () => [
  1581. $('.dev-page-download').href,
  1582. $('.dev-content-full').src,
  1583. ].filter(Boolean),
  1584. }, {
  1585. e: 'a[data-hook=deviation_link]',
  1586. q: 'link[as=image]',
  1587. }); break;
  1588.  
  1589. case 'discord': rules.push({
  1590. u: '||discordapp.net/external/',
  1591. r: /\/https?\/(.+)/,
  1592. s: '//$1',
  1593. follow: true,
  1594. }); break;
  1595.  
  1596. case 'dropbox': rules.push({
  1597. r: /(.+?&size_mode)=\d+(.*)/,
  1598. s: '$1=5$2',
  1599. }); break;
  1600.  
  1601. case 'facebook': rules.push({
  1602. e: 'a[href^="/photo/?"], a[href^="https://www.facebook.com/photo"]',
  1603. s: (m, el) => (m = Util.getReactChildren(el.parentNode)) &&
  1604. pick(m, (m[0] ? '0.props.linkProps' : 'props') + '.passthroughProps.origSrc'),
  1605. }); break;
  1606.  
  1607. case 'flickr': if (pick(unsafeWindow, 'YUI_config.flickr.api.site_key')) rules.push({
  1608. r: /flickr\.com\/photos\/[^/]+\/(\d+)/,
  1609. s: m => `https://www.flickr.com/services/rest/?${
  1610. new URLSearchParams({
  1611. photo_id: m[1],
  1612. api_key: unsafeWindow.YUI_config.flickr.api.site_key,
  1613. method: 'flickr.photos.getSizes',
  1614. format: 'json',
  1615. nojsoncallback: 1,
  1616. }).toString()}`,
  1617. q: text => JSON.parse(text).sizes.size.pop().source,
  1618. anonymous: true,
  1619. }); break;
  1620.  
  1621. case 'github': rules.push({
  1622. r: new RegExp([
  1623. /(avatars.+?&s=)\d+/,
  1624. /(raw\.github)(\.com\/.+?\/img\/.+)$/,
  1625. /\/(github)(\.com\/.+?\/)blob\/([^/]+\/.+?\.(?:avif|webp|png|jpe?g|bmp|gif|cur|ico|svg))$/,
  1626. ].map(rx => rx.source).join('|')),
  1627. s: m => `https://${
  1628. m[1] ? `${m[1]}460` :
  1629. m[2] ? `${m[2]}usercontent${m[3]}` :
  1630. $('.AppHeader-context-item > .octicon-lock')
  1631. ? `${m[4]}${m[5]}raw/${m[6]}`
  1632. : `raw.${m[4]}usercontent${m[5]}${m[6]}`
  1633. }`,
  1634. }); break;
  1635.  
  1636. case 'google': if (/[&?]tbm=isch(&|$)/.test(location.search)) rules.push({
  1637. e: 'a[href*="imgres?imgurl="] img',
  1638. s: (m, node) => new URLSearchParams(node.closest('a').search).get('imgurl'),
  1639. follow: true,
  1640. }, {
  1641. e: '[data-tbnid] a:not([href])',
  1642. s: (m, a) => {
  1643. const a2 = $('a[jsaction*="mousedown"]', a.closest('[data-tbnid]')) || a;
  1644. new MutationObserver((_, mo) => {
  1645. mo.disconnect();
  1646. App.isEnabled = true;
  1647. a.alt = a2.innerText;
  1648. const {left, top} = a.getBoundingClientRect();
  1649. Events.onMouseOver({target: $('img', a), clientX: left, clientY: top});
  1650. }).observe(a, {attributes: true, attributeFilter: ['href']});
  1651. a2.dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
  1652. a2.dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
  1653. },
  1654. }); break;
  1655.  
  1656. case 'instagram': rules.push({
  1657. e: 'a[href*="/p/"],' +
  1658. 'article [role="button"][tabindex="0"],' +
  1659. 'article [role="button"][tabindex="0"] div',
  1660. s: (m, node, rule) => {
  1661. let data, a, n, img, src;
  1662. if (location.pathname.startsWith('/p/') || location.pathname.startsWith('/tv/')) {
  1663. img = $('img[srcset], video', node.parentNode);
  1664. if (img && (isVideo(img) || parseFloat(img.sizes) > 900))
  1665. src = (img.srcset || img.currentSrc).split(',').pop().split(' ')[0];
  1666. }
  1667. if (!src && (n = node.closest('a[href*="/p/"], article'))) {
  1668. a = n.tagName === 'A' ? n : $('a[href*="/p/"]', n);
  1669. }
  1670. const numPics = a && pick(data, 'edge_sidecar_to_children.edges.length') ||
  1671. a && pick(data, 'carousel_media_count');
  1672. Ruler.toggle(rule, 'q', data && data.is_video && !data.video_url);
  1673. Ruler.toggle(rule, 'g', a && (numPics > 1 || /<\w+[^>]+carousel/i.test(a.innerHTML)));
  1674. rule.follow = !data && !rule.g;
  1675. rule._data = data;
  1676. rule._img = img;
  1677. return (
  1678. !a && !src ? false :
  1679. !data || rule.q || rule.g ? `${src || a.href}${rule.g ? '?__a=1&__d=dis' : ''}` :
  1680. data.video_url || data.display_url);
  1681. },
  1682. c: (html, doc, node, rule) =>
  1683. rule._getCaption(rule._data) || (rule._img || 0).alt || '',
  1684. follow: true,
  1685. _q: 'meta[property="og:video"]',
  1686. _g(text, doc, url, m, rule) {
  1687. const json = tryJSON(text);
  1688. const media =
  1689. pick(json, 'graphql.shortcode_media') ||
  1690. pick(json, 'items.0');
  1691. const items =
  1692. pick(media, 'edge_sidecar_to_children.edges', res => res.map(e => ({
  1693. url: e.node.video_url || e.node.display_url,
  1694. }))) ||
  1695. pick(media, 'carousel_media', res => res.map(e => ({
  1696. url: pick(e, 'video_versions.0.url') || pick(e, 'image_versions2.candidates.0.url'),
  1697. })));
  1698. items.title = rule._getCaption(media) || '';
  1699. return items;
  1700. },
  1701. _getCaption: data => pick(data, 'caption.text') ||
  1702. pick(data, 'edge_media_to_caption.edges.0.node.text'),
  1703. }); break;
  1704.  
  1705. case 'reddit': rules.push({
  1706. u: '||i.reddituploads.com/',
  1707. }, {
  1708. e: '[data-url*="i.redd.it"] img[src*="thumb"]',
  1709. s: (m, node) => $propUp(node, 'data-url'),
  1710. }, {
  1711. r: /preview(\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  1712. s: 'https://i$1',
  1713. }); break;
  1714.  
  1715. case 'stackoverflow': rules.push({
  1716. e: '.post-tag, .post-tag img',
  1717. s: '',
  1718. }); break;
  1719.  
  1720. case 'startpage': rules.push({
  1721. r: /[&?]piurl=([^&]+)/,
  1722. s: '$1',
  1723. follow: true,
  1724. }); break;
  1725.  
  1726. case 'tumblr': rules.push({
  1727. e: 'div.photo_stage_img, div.photo_stage > canvas',
  1728. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  1729. follow: true,
  1730. }); break;
  1731.  
  1732. case 'twitter': rules.push({
  1733. e: '.grid-tweet > .media-overlay',
  1734. s: (m, node) => node.previousElementSibling.src,
  1735. follow: true,
  1736. }); break;
  1737. }
  1738.  
  1739. rules.push(
  1740. {
  1741. r: /[/?=](https?%3A%2F%2F[^&]+)/i,
  1742. s: '$1',
  1743. follow: true,
  1744. onerror: 'skip',
  1745. },
  1746. {
  1747. u: [
  1748. '||500px.com/photo/',
  1749. '||cl.ly/',
  1750. '||cweb-pix.com/',
  1751. '//ibb.co/',
  1752. '||imgcredit.xyz/image/',
  1753. ],
  1754. r: /\.\w+\/.+/,
  1755. q: 'meta[property="og:image"]',
  1756. },
  1757. {
  1758. u: 'attachment.php',
  1759. r: /attachment\.php.+attachmentid/,
  1760. },
  1761. {
  1762. u: '||abload.de/image',
  1763. q: '#image',
  1764. },
  1765. {
  1766. u: '||deviantart.com/art/',
  1767. s: (m, node) =>
  1768. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  1769. '' :
  1770. m.input,
  1771. q: [
  1772. '#download-button[href*=".jpg"]',
  1773. '#download-button[href*=".jpeg"]',
  1774. '#download-button[href*=".gif"]',
  1775. '#download-button[href*=".png"]',
  1776. '#gmi-ResViewSizer_fullimg',
  1777. 'img.dev-content-full',
  1778. ],
  1779. },
  1780. {
  1781. u: '||dropbox.com/s',
  1782. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  1783. q: (text, doc) =>
  1784. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  1785. },
  1786. {
  1787. r: /[./]ebay\.[^/]+\/itm\//,
  1788. q: text =>
  1789. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  1790. .replace(/~~60_\d+/, '~~60_57'),
  1791. },
  1792. {
  1793. u: '||i.ebayimg.com/',
  1794. s: (m, node) =>
  1795. $('.zoom_trigger_mask', node.parentNode) ? '' :
  1796. m.input.replace(/~~60_\d+/, '~~60_57'),
  1797. },
  1798. {
  1799. u: '||fastpic.',
  1800. s: (m, node) => {
  1801. const a = node.closest('a');
  1802. const url = decodeURIComponent(Req.findImageUrl(a || node))
  1803. .replace(/\/i(\d+)\.(\w+\.\w+\/)\w+/, '/$2$1')
  1804. .replace(/^\w+:\/\/fastpic[^/]+((?:\/\d+){3})\/\w+(\/\w+\.\w+).*/,
  1805. 'https://fastpic.org/view$1$2.html');
  1806. return a || url.includes('.png') ? url : [url, url.replace(/\.jpe?g/, '.png')];
  1807. },
  1808. q: 'img[src*="/big/"]',
  1809. },
  1810. {
  1811. u: '||flickr.com/photos/',
  1812. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  1813. s: m =>
  1814. m.input.indexOf('/sizes/') < 0 ?
  1815. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  1816. false,
  1817. q: (text, doc) => {
  1818. const links = $$('.sizes-list a', doc);
  1819. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  1820. },
  1821. follow: true,
  1822. },
  1823. {
  1824. u: '||flickr.com/photos/',
  1825. r: /\/sizes\//,
  1826. q: '#allsizes-photo > img',
  1827. },
  1828. {
  1829. u: '||gfycat.com/',
  1830. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  1831. s: 'https://$1$3',
  1832. q: 'meta[content$=".webm"], #webmsource, source[src$=".webm"], .actual-gif-image',
  1833. },
  1834. {
  1835. u: [
  1836. '||googleusercontent.com/proxy',
  1837. '||googleusercontent.com/gadgets/proxy',
  1838. ],
  1839. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  1840. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  1841. },
  1842. {
  1843. u: [
  1844. '||googleusercontent.com/',
  1845. '||ggpht.com/',
  1846. ],
  1847. s: m => m.input.includes('webcache.') ? '' :
  1848. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  1849. .replace(/([&?]sz)?=[-\w]+([&#].*)?/, ''),
  1850. },
  1851. {
  1852. u: '||gravatar.com/',
  1853. r: /([a-z0-9]{32})/,
  1854. s: 'https://gravatar.com/avatar/$1?s=200',
  1855. },
  1856. {
  1857. u: '//gyazo.com/',
  1858. r: /\bgyazo\.com\/\w{32,}(\.\w+)?/,
  1859. s: (m, _, rule) => Ruler.toggle(rule, 'q', !m[1]) ? m.input : `https://i.${m[0]}`,
  1860. _q: 'link[rel="image_src"]',
  1861. },
  1862. {
  1863. u: '||hostingkartinok.com/show-image.php',
  1864. q: '.image img',
  1865. },
  1866. {
  1867. u: [
  1868. '||imagecurl.com/images/',
  1869. '||imagecurl.com/viewer.php',
  1870. ],
  1871. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1872. s: 'https://imagecurl.com/images/$1$2$3',
  1873. },
  1874. {
  1875. u: '||imagebam.com/',
  1876. r: /^(https:\/\/)thumbs\d+(\.imagebam\.com\/).*?([^/]+)_t\./,
  1877. s: '$1www$2view/$3',
  1878. q: 'img.main-image',
  1879. },
  1880. {
  1881. u: '||www.imagebam.com/view/',
  1882. q: 'img.main-image',
  1883. },
  1884. {
  1885. u: '||imageban.ru/thumbs',
  1886. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1887. s: '$1out$2/$3/$4',
  1888. },
  1889. {
  1890. u: [
  1891. '||imageban.ru/show',
  1892. '||imageban.net/show',
  1893. '||ibn.im/',
  1894. ],
  1895. q: '#img_main',
  1896. },
  1897. {
  1898. u: '||imageshack.us/img',
  1899. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1900. s: 'https://$2/download/$1/$3$4',
  1901. },
  1902. {
  1903. u: '||imageshack.us/i/',
  1904. q: '#share-dl',
  1905. },
  1906. {
  1907. u: '||imageteam.org/img',
  1908. q: 'img[alt="image"]',
  1909. },
  1910. {
  1911. u: [
  1912. '||imagetwist.com/',
  1913. '||imageshimage.com/',
  1914. ],
  1915. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1916. q: 'img.pic',
  1917. xhr: true,
  1918. },
  1919. {
  1920. u: '||imageupper.com/i/',
  1921. q: '#img',
  1922. xhr: true,
  1923. },
  1924. {
  1925. u: '||imagevenue.com/',
  1926. q: 'a[data-toggle="full"] img',
  1927. },
  1928. {
  1929. u: '||imagezilla.net/show/',
  1930. q: '#photo',
  1931. xhr: true,
  1932. },
  1933. {
  1934. u: [
  1935. '||images-na.ssl-images-amazon.com/images/',
  1936. '||media-imdb.com/images/',
  1937. ],
  1938. r: /images\/.+?\.jpg/,
  1939. s: '/V1\\.?_.+?\\.//g',
  1940. },
  1941. {
  1942. u: '||imgbox.com/',
  1943. r: /\.com\/([a-z0-9]+)$/i,
  1944. q: '#img',
  1945. xhr: hostname !== 'imgbox.com',
  1946. },
  1947. {
  1948. u: '||imgclick.net/',
  1949. r: /\.net\/(\w+)/,
  1950. q: 'img.pic',
  1951. xhr: true,
  1952. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1953. },
  1954. {
  1955. u: '.imgcredit.xyz/',
  1956. r: /^https?(:.*\.xyz\/\d[\w/]+)\.md(.+)/,
  1957. s: ['https$1$2', 'https$1.png'],
  1958. },
  1959. {
  1960. u: [
  1961. '||imgflip.com/i/',
  1962. '||imgflip.com/gif/',
  1963. ],
  1964. r: /\/(i|gif)\/([^/?#]+)/,
  1965. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1966. },
  1967. {
  1968. u: [
  1969. '||imgur.com/a/',
  1970. '||imgur.com/gallery/',
  1971. ],
  1972. s: 'gallery', // suppressing an unused network request for remote `document`
  1973. async g() {
  1974. let u = `https://imgur.com/ajaxalbums/getimages/${ai.url.split(/[/?#]/)[4]}/hit.json?all=true`;
  1975. let info = tryJSON((await Req.gmXhr(u)).responseText) || 0;
  1976. let images = (info.data || 0).images || [];
  1977. if (!images[0]) {
  1978. info = (await Req.gmXhr(ai.url)).responseText.match(/postDataJSON=(".*?")<|$/)[1];
  1979. info = tryJSON(tryJSON(info)) || 0;
  1980. images = info.media;
  1981. }
  1982. const items = [];
  1983. for (const img of images) {
  1984. const meta = img.metadata || img;
  1985. items.push({
  1986. url: img.url ||
  1987. (u = `https://i.imgur.com/${img.hash}`) && (
  1988. img.ext === '.gif' && img.animated !== false ?
  1989. [`${u}.webm`, `${u}.mp4`, u] :
  1990. u + img.ext
  1991. ),
  1992. desc: [meta.title, meta.description].filter(Boolean).join(' - '),
  1993. });
  1994. }
  1995. if (items[0] && info.title && !`${items[0].desc || ''}`.includes(info.title))
  1996. items.title = info.title;
  1997. return items;
  1998. },
  1999. },
  2000. {
  2001. u: '||imgur.com/',
  2002. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  2003. s: 'gallery',
  2004. g: (text, doc, url, m) =>
  2005. m[2].split(',').map(id => ({
  2006. url: `https://i.${m[1]}${id}.jpg`,
  2007. })),
  2008. },
  2009. {
  2010. u: '||imgur.com/',
  2011. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.(mp4|[a-z]+))/i,
  2012. s: (m, node) => {
  2013. if (/memegen|random|register|search|signin/.test(m.input))
  2014. return '';
  2015. const a = node.closest('a');
  2016. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  2017. return false;
  2018. // postfixes: huge, large, medium, thumbnail, big square, small square
  2019. const id = m[3].replace(/(.{7})[hlmtbs]$/, '$1');
  2020. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  2021. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  2022. return ext === 'webm' ?
  2023. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  2024. u + ext;
  2025. },
  2026. },
  2027. {
  2028. u: [
  2029. '||instagr.am/p/',
  2030. '||instagram.com/p/',
  2031. '||instagram.com/tv/',
  2032. ],
  2033. s: m => m.input.substr(0, m.input.lastIndexOf('/')).replace('/liked_by', '') +
  2034. '/?__a=1&__d=dis',
  2035. q: m => (m = tryJSON(m)) && (
  2036. m = pick(m, 'graphql.shortcode_media') || pick(m, 'items.0') || 0
  2037. ) && (
  2038. m.video_url ||
  2039. m.display_url ||
  2040. pick(m, 'video_versions.0.url') ||
  2041. pick(m, 'carousel_media.0.image_versions2.candidates.0.url') ||
  2042. pick(m, 'image_versions2.candidates.0.url')
  2043. ),
  2044. rect: 'div.PhotoGridMediaItem',
  2045. c: m => (m = tryJSON(m)) && (
  2046. pick(m, 'items.0.caption.text') ||
  2047. pick(m, 'graphql.shortcode_media.edge_media_to_caption.edges.0.node.text') ||
  2048. ''
  2049. ),
  2050. },
  2051. {
  2052. u: [
  2053. '||livememe.com/',
  2054. '||lvme.me/',
  2055. ],
  2056. r: /\.\w+\/([^.]+)$/,
  2057. s: 'http://i.lvme.me/$1.jpg',
  2058. },
  2059. {
  2060. u: '||lostpic.net/image',
  2061. q: '.image-viewer-image img',
  2062. },
  2063. {
  2064. u: '||makeameme.org/meme/',
  2065. r: /\/meme\/([^/?#]+)/,
  2066. s: 'https://media.makeameme.org/created/$1.jpg',
  2067. },
  2068. {
  2069. u: '||photobucket.com/',
  2070. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  2071. s: 'https://i$1$3',
  2072. xhr: !dotDomain.endsWith('.photobucket.com'),
  2073. },
  2074. {
  2075. u: '||piccy.info/view3/',
  2076. r: /(.+?\/view3)\/(.*)\//,
  2077. s: '$1/$2/orig/',
  2078. q: '#mainim',
  2079. },
  2080. {
  2081. u: '||pimpandhost.com/image/',
  2082. r: /(.+?\/image\/[0-9]+)/,
  2083. s: '$1?size=original',
  2084. q: 'img.original',
  2085. },
  2086. {
  2087. u: [
  2088. '||pixroute.com/',
  2089. '||imgspice.com/',
  2090. ],
  2091. r: /\.html$/,
  2092. q: 'img[id]',
  2093. xhr: true,
  2094. },
  2095. {
  2096. u: '||postima',
  2097. r: /postima?ge?\.org\/image\/\w+/,
  2098. q: [
  2099. 'a[href*="dl="]',
  2100. '#main-image',
  2101. ],
  2102. },
  2103. {
  2104. u: [
  2105. '||prntscr.com/',
  2106. '||prnt.sc/',
  2107. ],
  2108. r: /\.\w+\/.+/,
  2109. q: 'meta[property="og:image"]',
  2110. xhr: true,
  2111. },
  2112. {
  2113. u: '||radikal.ru/',
  2114. r: /\.ru\/(fp|.+?\.html)|^(.+?)t\.jpg/,
  2115. s: (m, node, rule) =>
  2116. m[2] && /radikal\.ru[\w%/]+?(\.\w+)/.test($propUp(node, 'href')) ? m[2] + RegExp.$1 :
  2117. Ruler.toggle(rule, 'q', m[1]) ? m.input : [m[2] + '.jpg', m[2] + '.png'],
  2118. _q: text => text.match(/https?:\/\/\w+\.radikal\.ru[\w/]+\.(jpg|gif|png)/i)[0],
  2119. },
  2120. {
  2121. u: '||tumblr.com',
  2122. r: /_500\.jpg/,
  2123. s: ['/_500/_1280/', ''],
  2124. },
  2125. {
  2126. u: '||twimg.com/media/',
  2127. r: /.+?format=(jpe?g|png|gif)/i,
  2128. s: '$0&name=orig',
  2129. },
  2130. {
  2131. u: '||twimg.com/media/',
  2132. r: /.+?\.(jpe?g|png|gif)/i,
  2133. s: '$0:orig',
  2134. },
  2135. {
  2136. u: '||twimg.com/1/proxy',
  2137. r: /t=([^&_]+)/i,
  2138. s: m => atob(m[1]).match(/http.+/),
  2139. },
  2140. {
  2141. u: '||twimg.com/',
  2142. r: /\/profile_images/i,
  2143. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  2144. },
  2145. {
  2146. u: '||pic.twitter.com/',
  2147. r: /\.com\/[a-z0-9]+/i,
  2148. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  2149. follow: true,
  2150. },
  2151. {
  2152. u: '||twitpic.com/',
  2153. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  2154. s: 'https://twitpic.com/show/large/$2',
  2155. },
  2156. {
  2157. u: '||wiki',
  2158. r: /\/(?:thumb|images)\/.+\.(?:jpe?g|gif|png|svg)/i,
  2159. s: m => m.input.replace(/\/(thumb(?=\/)|\d+px[^/]+(?=$|\?))/g, '')
  2160. .replace(/\/(scale-to-width(-[a-z]+)?\/\d+|(zoom-crop|smart)(\/(width|height)\/\d+)+)/g, '/'),
  2161. xhr: !hostname.includes('wiki'),
  2162. },
  2163. {
  2164. u: '||ytimg.com/vi/',
  2165. r: /(.+?\/vi\/[^/]+)/,
  2166. s: '$1/0.jpg',
  2167. rect: '.video-list-item',
  2168. },
  2169. {
  2170. u: '/viewer.php?file=',
  2171. r: /(.+?)\/viewer\.php\?file=(.+)/,
  2172. s: '$1/images/$2',
  2173. xhr: true,
  2174. },
  2175. {
  2176. u: '/thumb_',
  2177. r: /\/albums.+\/thumb_[^/]/,
  2178. s: '/thumb_//',
  2179. },
  2180. {
  2181. u: [
  2182. '.th.jp',
  2183. '.th.gif',
  2184. '.th.png',
  2185. ],
  2186. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  2187. s: '$1$2',
  2188. follow: true,
  2189. },
  2190. {
  2191. r: RX_MEDIA_URL,
  2192. }
  2193. );
  2194. },
  2195.  
  2196. format(rule, {expand} = {}) {
  2197. const s = Util.stringify(rule, null, ' ');
  2198. return expand ?
  2199. /* {"a": ...,
  2200. "b": ...,
  2201. "c": ...
  2202. } */
  2203. s.replace(/^{\s+/g, '{') :
  2204. /* {"a": ..., "b": ..., "c": ...} */
  2205. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  2206. },
  2207.  
  2208. fromElement(el) {
  2209. const text = el.textContent.trim();
  2210. if (text.startsWith('{') &&
  2211. text.endsWith('}') &&
  2212. /[{,]\s*"[degqrsu]"\s*:\s*"/.test(text)) {
  2213. const rule = tryJSON(text);
  2214. return rule && Object.keys(rule).some(k => /^[degqrsu]$/.test(k)) && rule;
  2215. }
  2216. },
  2217.  
  2218. isValidE2: ([k, v]) => k.trim() && typeof v === 'string' && v.trim(),
  2219.  
  2220. /** @returns mpiv.HostRule | Error | false | undefined */
  2221. parse(rule) {
  2222. const isBatchOp = this instanceof Map;
  2223. try {
  2224. if (typeof rule === 'string')
  2225. rule = JSON.parse(rule);
  2226. if ('d' in rule && typeof rule.d !== 'string')
  2227. rule.d = undefined;
  2228. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  2229. return false;
  2230. let {e} = rule;
  2231. if (e != null) {
  2232. e = typeof e === 'string' ? e.trim()
  2233. : isArray(e) ? e.join(',').trim()
  2234. : Object.entries(e).every(Ruler.isValidE2) && e;
  2235. if (!e)
  2236. throw new Error('Invalid syntax for "e". Examples: ' +
  2237. '"e": ".image" or ' +
  2238. '"e": [".image1", ".image2"] or ' +
  2239. '"e": {".parent": ".image"} or ' +
  2240. '"e": {".parent1": ".image1", ".parent2": ".image2"}');
  2241. if (isBatchOp) rule.e = e || undefined;
  2242. }
  2243. let compileTo = isBatchOp ? rule : {};
  2244. if (rule.r)
  2245. compileTo.r = new RegExp(rule.r, 'i');
  2246. if (App.NOP)
  2247. compileTo = {};
  2248. for (const key of Object.keys(FN_ARGS)) {
  2249. if (RX_HAS_CODE.test(rule[key])) {
  2250. const fn = Util.newFunction(...FN_ARGS[key], rule[key]);
  2251. if (fn !== App.NOP || !isBatchOp) {
  2252. compileTo[key] = fn;
  2253. } else if (isBatchOp) {
  2254. this.set(rule, 'unsafe-eval');
  2255. }
  2256. }
  2257. }
  2258. return rule;
  2259. } catch (err) {
  2260. if (isBatchOp) {
  2261. this.set(rule, err);
  2262. return rule;
  2263. } else {
  2264. return err;
  2265. }
  2266. }
  2267. },
  2268.  
  2269. runC(text, doc = document) {
  2270. const fn = Ruler.runCHandler[typeof ai.rule.c] || Ruler.runCHandler.default;
  2271. ai.caption = fn(text, doc);
  2272. },
  2273.  
  2274. runCHandler: {
  2275. function: (text, doc) =>
  2276. ai.rule.c(text || doc.documentElement.outerHTML, doc, ai.node, ai.rule),
  2277. string: (text, doc) => {
  2278. const el = $many(ai.rule.c, doc);
  2279. return !el ? '' :
  2280. el.getAttribute('content') ||
  2281. el.getAttribute('title') ||
  2282. el.textContent;
  2283. },
  2284. default: (text, doc, el = ai.node) =>
  2285. (ai.tooltip || 0).text ||
  2286. el.alt ||
  2287. $propUp(el, 'title') ||
  2288. Req.getFileName(
  2289. el.tagName === (ai.popup || 0).tagName
  2290. ? ai.url
  2291. : el.src || $propUp(el, 'href')),
  2292. },
  2293.  
  2294. runQ(text, doc, docUrl) {
  2295. let url;
  2296. if (isFunction(ai.rule.q)) {
  2297. url = ai.rule.q(text, doc, ai.node, ai.rule);
  2298. if (isArray(url)) {
  2299. ai.urls = url.slice(1);
  2300. url = url[0];
  2301. }
  2302. } else {
  2303. const el = $many(ai.rule.q, doc);
  2304. url = Req.findImageUrl(el, docUrl);
  2305. }
  2306. return url;
  2307. },
  2308.  
  2309. /** @returns {?boolean|mpiv.RuleMatchInfo} */
  2310. runE(rule, e, node) {
  2311. let p, img, res, info;
  2312. for (const selParent in e) {
  2313. if ((p = node.closest(selParent)) && (img = $(e[selParent], p))) {
  2314. if (img === node)
  2315. res = true;
  2316. else if ((info = RuleMatcher.adaptiveFind(img, {rules: [rule]})))
  2317. return info;
  2318. }
  2319. }
  2320. return res;
  2321. },
  2322.  
  2323. /** @returns {?Array} if falsy then the rule should be skipped */
  2324. runS(node, rule, m) {
  2325. let urls = [], u;
  2326. for (const s of ensureArray(rule.s))
  2327. urls.push(
  2328. typeof s === 'string' ? Util.decodeUrl(Ruler.substituteSingle(s, m)) :
  2329. isFunction(s) ? s(m, node, rule) :
  2330. s);
  2331. if (rule.q && urls.length > 1) {
  2332. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  2333. return;
  2334. }
  2335. if (isArray(u = urls[0]))
  2336. u = [urls = u][0];
  2337. return u === '' /* "stop all rules" */ ? urls
  2338. : u && arrayFrom(new Set(urls), Util.decodeUrl);
  2339. },
  2340.  
  2341. /** @returns {boolean} */
  2342. runU(rule, url) {
  2343. const u = rule[SYM_U] || (rule[SYM_U] = UrlMatcher(rule.u));
  2344. return u.fn.call(u.data, url);
  2345. },
  2346.  
  2347. substituteSingle(s, m) {
  2348. if (!m || m.input == null) return s;
  2349. if (s.startsWith('/') && !s.startsWith('//')) {
  2350. const mid = s.search(/[^\\]\//) + 1;
  2351. const end = s.lastIndexOf('/');
  2352. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  2353. return m.input.replace(re, s.slice(mid + 1, end));
  2354. }
  2355. if (m.length && s.includes('$')) {
  2356. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  2357. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  2358. for (let i = maxLength; i >= 0; i--) {
  2359. const part = num.slice(0, i) | 0;
  2360. if (part < m.length)
  2361. return (m[part] || '') + num.slice(i);
  2362. }
  2363. return text;
  2364. });
  2365. }
  2366. return s;
  2367. },
  2368.  
  2369. toggle(rule, prop, condition) {
  2370. rule[prop] = condition ? rule[`_${prop}`] : null;
  2371. return condition;
  2372. },
  2373. };
  2374.  
  2375. const RuleMatcher = {
  2376.  
  2377. /** @returns {Object} */
  2378. adaptiveFind(node, opts) {
  2379. const tn = node.tagName;
  2380. const src = node.currentSrc || node.src || '';
  2381. const isPic = tn === 'IMG' || tn === 'VIDEO' && Util.isVideoUrlExt(src);
  2382. let a, info, url;
  2383. // note that data URLs aren't passed to rules as those may have fatally ineffective regexps
  2384. if (tn !== 'A') {
  2385. url = isPic && !src.startsWith('data:') && Util.rel2abs(src);
  2386. info = RuleMatcher.find(url, node, opts);
  2387. }
  2388. if (!info && (a = node.closest('A'))) {
  2389. const ds = a.dataset;
  2390. url = ds.expandedUrl || ds.fullUrl || ds.url || a.href || '';
  2391. url = url.includes('//t.co/') ? 'https://' + a.textContent : url;
  2392. url = !url.startsWith('data:') && url;
  2393. info = RuleMatcher.find(url, a, opts);
  2394. }
  2395. if (!info && isPic)
  2396. info = {node, rule: {}, url: src};
  2397. return info;
  2398. },
  2399.  
  2400. /** @returns ?mpiv.RuleMatchInfo */
  2401. find(url, node, {noHtml, rules, skipRules} = {}) {
  2402. let tn, isPic, html, h;
  2403. for (const rule of rules || Ruler.rules) {
  2404. let e, m;
  2405. if (skipRules && skipRules.includes(rule) ||
  2406. rule.u && (!url || !Ruler.runU(rule, url)) ||
  2407. !rules && (e = rule.e) &&
  2408. !(m = typeof e === 'string' ? node.matches(e) : Ruler.runE(rule, e, node)))
  2409. continue;
  2410. if (m && m.url)
  2411. return m;
  2412. const {r, s} = rule;
  2413. let hasS = s != null;
  2414. h = !noHtml && (r || hasS) && rule.html && (html || (html = node.outerHTML));
  2415. if (r) {
  2416. m = h ? r.exec(h) : url && r.exec(url);
  2417. } else {
  2418. m = ['']; m[0] = m.input = h || url || ''; m.index = 0;
  2419. }
  2420. if (!m)
  2421. continue;
  2422. if (s === '')
  2423. return {};
  2424. // a rule with follow:true for the currently hovered IMG produced a URL,
  2425. // but we'll only allow it to match rules without 's' in the nested find call
  2426. if (!hasS && !skipRules && (tn ? isPic : isPic = (tn = node.tagName) === 'IMG' || tn === 'VIDEO'))
  2427. continue;
  2428. hasS &= s !== 'gallery';
  2429. const urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  2430. if (urls)
  2431. return RuleMatcher.makeInfo(hasS, rule, m, node, skipRules, urls);
  2432. }
  2433. },
  2434.  
  2435. /** @returns ?mpiv.RuleMatchInfo */
  2436. makeInfo(hasS, rule, match, node, skipRules, urls) {
  2437. let info;
  2438. let url = `${urls[0]}`;
  2439. const follow = url && hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule);
  2440. if (url)
  2441. url = Util.rel2abs(url);
  2442. else
  2443. info = {};
  2444. if (follow)
  2445. info = RuleMatcher.find(url, node, {skipRules: [...skipRules || [], rule]});
  2446. if (!info && (!follow || RX_MEDIA_URL.test(url))) {
  2447. const xhr = cfg.xhr && rule.xhr;
  2448. info = {
  2449. match,
  2450. node,
  2451. rule,
  2452. url,
  2453. urls: urls.length > 1 ? urls.slice(1) : null,
  2454. gallery: rule.g && Gallery.makeParser(rule.g),
  2455. post: isFunction(rule.post) ? rule.post(match) : rule.post,
  2456. xhr: xhr != null ? xhr : isSecureContext && !url.startsWith(location.protocol),
  2457. };
  2458. }
  2459. return info;
  2460. },
  2461.  
  2462. isFollowableUrl(url, rule) {
  2463. const f = rule.follow;
  2464. return isFunction(f) ? f(url) : f;
  2465. },
  2466. };
  2467.  
  2468. const Req = {
  2469.  
  2470. gmXhr(url, opts = {}) {
  2471. if (ai.req)
  2472. tryCatch(ai.req.abort);
  2473. return new Promise((resolve, reject) => {
  2474. const {anonymous} = ai.rule || {};
  2475. ai.req = GM.xmlHttpRequest(Object.assign({
  2476. url,
  2477. anonymous,
  2478. withCredentials: !anonymous,
  2479. method: 'GET',
  2480. timeout: 30e3,
  2481. }, opts, {
  2482. onload: done,
  2483. onerror: done,
  2484. ontimeout() {
  2485. ai.req = null;
  2486. reject(`Timeout fetching ${url}`);
  2487. },
  2488. }));
  2489. function done(r) {
  2490. ai.req = null;
  2491. if (r.status < 400 && !r.error)
  2492. resolve(r);
  2493. else
  2494. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2495. }
  2496. });
  2497. },
  2498.  
  2499. async getDoc(url) {
  2500. if (!url) {
  2501. // current document
  2502. return {
  2503. doc,
  2504. finalUrl: location.href,
  2505. responseText: doc.documentElement.outerHTML,
  2506. };
  2507. }
  2508. const r = await (!ai.post ?
  2509. Req.gmXhr(url) :
  2510. Req.gmXhr(url, {
  2511. method: 'POST',
  2512. data: ai.post,
  2513. headers: {
  2514. 'Content-Type': 'application/x-www-form-urlencoded',
  2515. 'Referer': url,
  2516. },
  2517. }));
  2518. r.doc = $parseHtml(r.responseText);
  2519. return r;
  2520. },
  2521.  
  2522. async getImage(url, pageUrl, xhr = ai.xhr) {
  2523. ai.bufBar = false;
  2524. ai.bufStart = now();
  2525. const response = await Req.gmXhr(url, {
  2526. responseType: 'blob',
  2527. headers: {
  2528. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2529. Referer: pageUrl || (isFunction(xhr) ? xhr() : url),
  2530. },
  2531. onprogress: Req.getImageProgress,
  2532. });
  2533. Bar.set(false);
  2534. const type = Req.guessMimeType(response);
  2535. let b = response.response;
  2536. if (!b) throw 'Empty response';
  2537. if (b.type !== type)
  2538. b = b.slice(0, b.size, type);
  2539. const res = xhr === 'blob'
  2540. ? (ai.blobUrl = URL.createObjectURL(b))
  2541. : await Req.blobToDataUrl(b);
  2542. return [res, type.startsWith('video')];
  2543. },
  2544.  
  2545. getImageProgress(e) {
  2546. if (!ai.bufBar && now() - ai.bufStart > 3000 && e.loaded / e.total < 0.5)
  2547. ai.bufBar = true;
  2548. if (ai.bufBar) {
  2549. const pct = e.loaded / e.total * 100 | 0;
  2550. const size = e.total / 1024 | 0;
  2551. Bar.set(`${pct}% of ${size} kiB`, 'xhr');
  2552. }
  2553. },
  2554.  
  2555. async findRedirect() {
  2556. try {
  2557. const {finalUrl} = await Req.gmXhr(ai.url, {
  2558. method: 'HEAD',
  2559. headers: {
  2560. 'Referer': location.href.split('#', 1)[0],
  2561. },
  2562. });
  2563. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2564. if (!info || !info.url)
  2565. throw `Couldn't follow redirection target: ${finalUrl}`;
  2566. Object.assign(ai, info);
  2567. App.startSingle();
  2568. } catch (e) {
  2569. App.handleError(e);
  2570. }
  2571. },
  2572.  
  2573. async saveFile() {
  2574. const url = ai.popup.src || ai.popup.currentSrc;
  2575. let name = Req.getFileName(ai.imageUrl || url);
  2576. if (!name.includes('.'))
  2577. name += '.jpg';
  2578. if (url.startsWith('blob:') || url.startsWith('data:')) {
  2579. $new('a', {href: url, download: name})
  2580. .dispatchEvent(new MouseEvent('click'));
  2581. } else {
  2582. Status.set('+loading');
  2583. const onload = () => Status.set('-loading');
  2584. const gmDL = typeof GM_download === 'function';
  2585. (gmDL ? GM_download : GM.xmlHttpRequest)({
  2586. url,
  2587. name,
  2588. headers: {Referer: url},
  2589. method: 'get', // polyfilling GM_download
  2590. responseType: 'blob', // polyfilling GM_download
  2591. overrideMimeType: 'application/octet-stream', // polyfilling GM_download
  2592. onerror: e => {
  2593. Bar.set(`Could not download ${name}: ${e.error || e.message || e}.`, 'error');
  2594. onload();
  2595. },
  2596. onprogress: Req.getImageProgress,
  2597. onload({response}) {
  2598. onload();
  2599. if (!gmDL) { // polyfilling GM_download
  2600. const a = Object.assign(document.createElement('a'), {
  2601. href: URL.createObjectURL(response),
  2602. download: name,
  2603. });
  2604. a.dispatchEvent(new MouseEvent('click'));
  2605. setTimeout(URL.revokeObjectURL, 10e3, a.href);
  2606. }
  2607. },
  2608. });
  2609. }
  2610. },
  2611.  
  2612. getFileName(url) {
  2613. return decodeURIComponent(url).split(/[#?&]/, 1)[0].split('/').pop();
  2614. },
  2615.  
  2616. blobToDataUrl(blob) {
  2617. return new Promise((resolve, reject) => {
  2618. const fr = new FileReader();
  2619. fr.onload = () => resolve(fr.result);
  2620. fr.onerror = reject;
  2621. fr.readAsDataURL(blob);
  2622. });
  2623. },
  2624.  
  2625. guessMimeType({responseHeaders, finalUrl}) {
  2626. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2627. !RegExp.$1.includes('text/plain'))
  2628. return RegExp.$1;
  2629. const ext = Util.extractFileExt(finalUrl) || 'jpg';
  2630. switch (ext.toLowerCase()) {
  2631. case 'bmp': return 'image/bmp';
  2632. case 'gif': return 'image/gif';
  2633. case 'jpe': return 'image/jpeg';
  2634. case 'jpeg': return 'image/jpeg';
  2635. case 'jpg': return 'image/jpeg';
  2636. case 'mp4': return 'video/mp4';
  2637. case 'png': return 'image/png';
  2638. case 'svg': return 'image/svg+xml';
  2639. case 'tif': return 'image/tiff';
  2640. case 'tiff': return 'image/tiff';
  2641. case 'webm': return 'video/webm';
  2642. default: return 'application/octet-stream';
  2643. }
  2644. },
  2645.  
  2646. findImageUrl(n, url) {
  2647. if (!n) return;
  2648. let html;
  2649. const path =
  2650. n.getAttribute('data-src') || // lazy loaded src, whereas current `src` is an empty 1x1 pixel
  2651. n.getAttribute('src') ||
  2652. n.getAttribute('data-m4v') ||
  2653. n.getAttribute('href') ||
  2654. n.getAttribute('content') ||
  2655. (html = n.outerHTML).includes('http') &&
  2656. html.match(/https?:\/\/[^\s"<>]+?\.(jpe?g|gif|png|svg|web[mp]|mp4)[^\s"<>]*|$/i)[0];
  2657. return !!path && Util.rel2abs(Util.decodeHtmlEntities(path),
  2658. $prop('base[href]', 'href', n.ownerDocument) || url);
  2659. },
  2660. };
  2661.  
  2662. const Status = {
  2663.  
  2664. set(status) {
  2665. if (!status && !cfg.globalStatus) {
  2666. if (ai.node) ai.node.removeAttribute(STATUS_ATTR);
  2667. return;
  2668. }
  2669. const prefix = cfg.globalStatus ? PREFIX : '';
  2670. const action = status && /^[+-]/.test(status) && status[0];
  2671. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  2672. const el = cfg.globalStatus ? doc.documentElement :
  2673. name === 'edge' ? ai.popup :
  2674. ai.node;
  2675. if (!el) return;
  2676. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  2677. const oldValue = (el.getAttribute(attr) || '').trim();
  2678. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  2679. switch (action) {
  2680. case '-':
  2681. cls.delete(name);
  2682. break;
  2683. case false:
  2684. for (const c of cls)
  2685. if (c.startsWith(prefix) && c !== name)
  2686. cls.delete(c);
  2687. // fallthrough to +
  2688. case '+':
  2689. if (name)
  2690. cls.add(name);
  2691. break;
  2692. }
  2693. const newValue = [...cls].join(' ');
  2694. if (newValue !== oldValue)
  2695. el.setAttribute(attr, newValue);
  2696. },
  2697.  
  2698. loading(force) {
  2699. if (!force) {
  2700. clearTimeout(ai.timerStatus);
  2701. ai.timerStatus = setTimeout(Status.loading, SETTLE_TIME, true);
  2702. } else if (!ai.popupLoaded) {
  2703. Status.set('+loading');
  2704. }
  2705. },
  2706. };
  2707.  
  2708. const UrlMatcher = (() => {
  2709. // string-to-regexp escaped chars
  2710. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  2711. // rx for '^' symbol in simple url match
  2712. const RX_SEP = /[^\w%._-]/y;
  2713. const RXS_SEP = RX_SEP.source;
  2714. return match => {
  2715. const results = [];
  2716. for (const s of ensureArray(match)) {
  2717. const pinDomain = s.startsWith('||');
  2718. const pinStart = !pinDomain && s.startsWith('|');
  2719. const endSep = s.endsWith('^');
  2720. let fn;
  2721. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  2722. if (needle.includes('^')) {
  2723. let plain = '';
  2724. for (const part of needle.split('^'))
  2725. if (part.length > plain.length)
  2726. plain = part;
  2727. const rx = new RegExp(
  2728. (pinStart ? '^' : '') +
  2729. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  2730. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  2731. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  2732. needle = [plain, rx];
  2733. fn = regexp;
  2734. } else if (pinStart) {
  2735. fn = endSep ? equals : starts;
  2736. } else if (pinDomain) {
  2737. const slashPos = needle.indexOf('/');
  2738. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  2739. needle = [needle, domain, slashPos > 0, endSep];
  2740. fn = startsDomainPrescreen;
  2741. } else if (endSep) {
  2742. fn = ends;
  2743. } else {
  2744. fn = has;
  2745. }
  2746. results.push({fn, data: needle});
  2747. }
  2748. return results.length > 1 ?
  2749. {fn: checkArray, data: results} :
  2750. results[0];
  2751. };
  2752. function checkArray(s) {
  2753. return this.some(checkArrayItem, s);
  2754. }
  2755. function checkArrayItem(item) {
  2756. return item.fn.call(item.data, this);
  2757. }
  2758. function ends(s) {
  2759. return s.endsWith(this) || (
  2760. s.length > this.length &&
  2761. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  2762. endsWithSep(s));
  2763. }
  2764. function endsWithSep(s, pos = s.length - 1) {
  2765. RX_SEP.lastIndex = pos;
  2766. return RX_SEP.test(s);
  2767. }
  2768. function equals(s) {
  2769. return s.startsWith(this) && (
  2770. s.length === this.length ||
  2771. s.length === this.length + 1 && endsWithSep(s));
  2772. }
  2773. function has(s) {
  2774. return s.includes(this);
  2775. }
  2776. function regexp(s) {
  2777. return s.includes(this[0]) && this[1].test(s);
  2778. }
  2779. function starts(s) {
  2780. return s.startsWith(this);
  2781. }
  2782. function startsDomainPrescreen(url) {
  2783. return url.includes(this[0]) && startsDomain.call(this, url);
  2784. }
  2785. function startsDomain(url) {
  2786. let hostStart = url.indexOf('//');
  2787. if (hostStart && url[hostStart - 1] !== ':')
  2788. return;
  2789. hostStart = hostStart < 0 ? 0 : hostStart + 2;
  2790. const host = url.slice(hostStart, (url.indexOf('/', hostStart) + 1 || url.length + 1) - 1);
  2791. const [needle, domain, pinDomainEnd, endSep] = this;
  2792. let start = pinDomainEnd ? host.length - domain.length : 0;
  2793. for (; ; start++) {
  2794. start = host.indexOf(domain, start);
  2795. if (start < 0)
  2796. return;
  2797. if (!start || host[start - 1] === '.')
  2798. break;
  2799. }
  2800. start += hostStart;
  2801. if (url.lastIndexOf(needle, start) !== start)
  2802. return;
  2803. const end = start + needle.length;
  2804. return !endSep || end === host.length || end === url.length || endsWithSep(url, end);
  2805. }
  2806. })();
  2807.  
  2808. const Util = {
  2809.  
  2810. addStyle(name, css) {
  2811. const id = `${PREFIX}style:${name}`;
  2812. const el = doc.getElementById(id) ||
  2813. css && $new('style', {id});
  2814. if (!el) return;
  2815. if (el.textContent !== css)
  2816. el.textContent = css;
  2817. if (el.parentElement !== doc.head)
  2818. doc.head.appendChild(el);
  2819. return el;
  2820. },
  2821.  
  2822. color(color, opacity = cfg[`ui${color}Opacity`]) {
  2823. return (color.startsWith('#') ? color : cfg[`ui${color}Color`]) +
  2824. (0x100 + Math.round(opacity / 100 * 255)).toString(16).slice(1);
  2825. },
  2826.  
  2827. decodeHtmlEntities(s) {
  2828. return s
  2829. .replace(/&quot;/g, '"')
  2830. .replace(/&apos;/g, '\'')
  2831. .replace(/&lt;/g, '<')
  2832. .replace(/&gt;/g, '>')
  2833. .replace(/&amp;/g, '&');
  2834. },
  2835.  
  2836. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2837. decodeUrl(url) {
  2838. if (!url || typeof url !== 'string') return url;
  2839. const iPct = url.indexOf('%');
  2840. const iColon = url.indexOf(':');
  2841. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2842. decodeURIComponent(url) :
  2843. url;
  2844. },
  2845.  
  2846. deepEqual(a, b) {
  2847. if (!a || !b || typeof a !== 'object' || typeof a !== typeof b)
  2848. return a === b;
  2849. if (isArray(a)) {
  2850. return isArray(b) &&
  2851. a.length === b.length &&
  2852. a.every((v, i) => Util.deepEqual(v, b[i]));
  2853. }
  2854. const keys = Object.keys(a);
  2855. return keys.length === Object.keys(b).length &&
  2856. keys.every(k => Util.deepEqual(a[k], b[k]));
  2857. },
  2858.  
  2859. extractFileExt: url => (url = RX_MEDIA_URL.exec(url)) && url[1],
  2860.  
  2861. forceLayout(node) {
  2862. // eslint-disable-next-line no-unused-expressions
  2863. node.clientHeight;
  2864. },
  2865.  
  2866. formatError(e, rule) {
  2867. const msg = e.message;
  2868. const {url: u, imageUrl: iu} = ai;
  2869. e = msg ? e :
  2870. e.readyState && 'Request failed.' ||
  2871. e.type === 'error' && `File can't be displayed.${
  2872. $('div[bgactive*="flashblock"]', doc) ? ' Check Flashblock settings.' : ''
  2873. }` ||
  2874. e;
  2875. let fmt;
  2876. const res = [
  2877. fmt = '%c%s%c', 'font-weight:bold', e, 'font-weight:normal',
  2878. (fmt += '\nNode: %o', ai.node),
  2879. (fmt += '\nRule: %o', rule),
  2880. u && (fmt += '\nURL: %s', u),
  2881. iu && iu !== u && (fmt += '\nFile: %s', iu),
  2882. e.stack,
  2883. ].filter(Boolean);
  2884. res[0] = fmt;
  2885. res.message = msg || e;
  2886. return res;
  2887. },
  2888.  
  2889. getReactChildren(el, path) {
  2890. if (isFF) el = el.wrappedJSObject || el;
  2891. for (const k of Object.keys(el))
  2892. if (typeof k === 'string' && k.startsWith('__reactProps'))
  2893. return (el = el[k].children) && (path ? pick(el, path) : el);
  2894. },
  2895.  
  2896. isVideoUrl: url => url.startsWith('data:video') || Util.isVideoUrlExt(url),
  2897.  
  2898. isVideoUrlExt: url => (url = Util.extractFileExt(url)) && /^(webm|mp4)$/i.test(url),
  2899.  
  2900. newFunction(...args) {
  2901. try {
  2902. return App.NOP || (trustedScript
  2903. // eslint-disable-next-line no-eval
  2904. ? window.eval(trustedScript(`(function anonymous(${args.slice(0, -1).join(',')}){${args.slice(-1)[0]}})`))
  2905. : new Function(...args)
  2906. );
  2907. } catch (e) {
  2908. if (!RX_EVAL_BLOCKED.test(e.message))
  2909. throw e;
  2910. App.NOP = () => {};
  2911. return App.NOP;
  2912. }
  2913. },
  2914.  
  2915. rel2abs(rel, abs = location.href) {
  2916. try {
  2917. return /^(data:|blob:|[-\w]+:\/\/)/.test(rel) ? rel :
  2918. new URL(rel, abs).href;
  2919. } catch (e) {
  2920. return rel;
  2921. }
  2922. },
  2923.  
  2924. stringify(...args) {
  2925. const p = Array.prototype;
  2926. const {toJSON} = p;
  2927. if (toJSON) p.toJSON = null;
  2928. const res = JSON.stringify(...args);
  2929. if (toJSON) p.toJSON = toJSON;
  2930. return res;
  2931. },
  2932.  
  2933. suppressTooltip() {
  2934. for (const node of [
  2935. ai.node.parentNode,
  2936. ai.node,
  2937. ai.node.firstElementChild,
  2938. ]) {
  2939. const t = (node || 0).title;
  2940. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2941. ai.tooltip = {node, text: t};
  2942. node.title = '';
  2943. break;
  2944. }
  2945. }
  2946. },
  2947.  
  2948. tabFixUrl() {
  2949. const {tabfix = App.tabfix} = ai.rule;
  2950. return tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  2951. flattenHtml(`data:text/html;charset=utf8,
  2952. <style>
  2953. body {
  2954. margin: 0;
  2955. padding: 0;
  2956. background: #222;
  2957. }
  2958. .fit {
  2959. overflow: hidden
  2960. }
  2961. .fit > img {
  2962. max-width: 100vw;
  2963. max-height: 100vh;
  2964. }
  2965. body > img {
  2966. margin: auto;
  2967. position: absolute;
  2968. left: 0;
  2969. right: 0;
  2970. top: 0;
  2971. bottom: 0;
  2972. }
  2973. </style>
  2974. <body class=fit>
  2975. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2976. </body>
  2977. `).replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2978. },
  2979. };
  2980.  
  2981. async function setup({rule} = {}) {
  2982. if (!isFunction(doc.body.attachShadow)) {
  2983. alert('Cannot show MPIV config dialog: the browser is probably too old.\n' +
  2984. 'You can edit the script\'s storage directly in your userscript manager.');
  2985. return;
  2986. }
  2987. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2988. let uiCfg;
  2989. let root = (elSetup || 0).shadowRoot;
  2990. let {blankRuleElement} = setup;
  2991. let mover, moveX = 0, moveY = 0, moveBaseX = 0, moveBaseY = 0;
  2992. /** @type {{[id:string]: HTMLElement}} */
  2993. const UI = setup.UI = new Proxy({}, {
  2994. get(_, id) {
  2995. return root.getElementById(id);
  2996. },
  2997. });
  2998. if (!elSetup)
  2999. build();
  3000. init(await Config.load({save: true}));
  3001. if (elSetup.parentElement !== doc.body)
  3002. doc.body.append(elSetup);
  3003. if (rule)
  3004. installRule(rule);
  3005.  
  3006. function build() {
  3007. elSetup = $new('div', {contentEditable: true});
  3008. root = elSetup.attachShadow({mode: 'open'});
  3009. root.append(...createSetupElement());
  3010. initEvents();
  3011. }
  3012.  
  3013. function init(data) {
  3014. uiCfg = data;
  3015. renderAll();
  3016. renderVolatiles();
  3017. renderRules();
  3018. requestAnimationFrame(() => {
  3019. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, elSetup.clientHeight / 4) + 'px';
  3020. });
  3021. }
  3022.  
  3023. function initEvents() {
  3024. UI._mover.onmousedown = e => {
  3025. if (e.button || eventModifiers(e))
  3026. return;
  3027. if (!mover) {
  3028. mover = UI._cssSetup.sheet;
  3029. mover.insertRule(':host {}');
  3030. mover = mover.cssRules[1];
  3031. }
  3032. addEventListener('mousemove', onMove, true);
  3033. addEventListener('mouseup', onMoveDone, true);
  3034. addEventListener('keydown', onMoveKey, true);
  3035. moveX = e.x - moveBaseX;
  3036. moveY = e.y - moveBaseY;
  3037. $css(mover, {opacity: .75});
  3038. };
  3039. UI._apply.onclick = UI._cancel.onclick = UI._ok.onclick = UI._x.onclick = closeSetup;
  3040. UI._export.onclick = e => {
  3041. dropEvent(e);
  3042. GM.setClipboard(Util.stringify(collectConfig(), null, ' '));
  3043. UI._exportNotification.hidden = false;
  3044. setTimeout(() => (UI._exportNotification.hidden = true), 1000);
  3045. };
  3046. UI._import.onclick = e => {
  3047. dropEvent(e);
  3048. const s = prompt('Paste settings:');
  3049. if (s)
  3050. init(new Config({data: s}));
  3051. };
  3052. UI._install.onclick = setupRuleInstaller;
  3053. const /** @type {HTMLTextAreaElement} */ cssApp = UI._cssApp;
  3054. UI._reveal.onclick = e => {
  3055. e.preventDefault();
  3056. cssApp.hidden = !cssApp.hidden;
  3057. if (!cssApp.hidden) {
  3058. if (!cssApp.value) {
  3059. App.updateStyles();
  3060. cssApp.value = App.globalStyle.trim();
  3061. cssApp.setSelectionRange(0, 0);
  3062. }
  3063. cssApp.focus();
  3064. }
  3065. };
  3066. UI.start.onchange = function () {
  3067. UI[PREFIX + 'setup'].dataset.start = this.value;
  3068. };
  3069. UI.xhr.onclick = ({target: el}) => el.checked || confirm($propUp(el, 'title'));
  3070. // color
  3071. for (const el of $$('[type="color"]', root)) {
  3072. el.oninput = colorOnInput;
  3073. el.elSwatch = el.nextElementSibling;
  3074. el.elOpacity = UI[el.id.replace('Color', 'Opacity')];
  3075. el.elOpacity.elColor = el;
  3076. }
  3077. function onMove({x, y}) {
  3078. x = moveBaseX = clamp(x - moveX, -innerWidth + CSS_SETUP_X * 4, elSetup.clientWidth - CSS_SETUP_X);
  3079. y = moveBaseY = clamp(y - moveY, 0, innerHeight - CSS_SETUP_X * 3);
  3080. $css(mover, {transform: `translate(${x}px, ${y}px)`});
  3081. UI._ul.style.maxHeight = `calc(100vh - ${CSS_SETUP_MAX_Y + y - CSS_SETUP_X}px)`;
  3082. }
  3083. function onMoveDone() {
  3084. removeEventListener('mousemove', onMove, true);
  3085. removeEventListener('mouseup', onMoveDone, true);
  3086. removeEventListener('keydown', onMoveKey, true);
  3087. $css(mover, {opacity: ''});
  3088. }
  3089. function onMoveKey(e) {
  3090. if (e.key === 'Escape' && !eventModifiers(e)) {
  3091. e.stopPropagation();
  3092. onMove({x: moveX, y: moveY});
  3093. onMoveDone();
  3094. }
  3095. }
  3096. function colorOnInput() {
  3097. this.elSwatch.style.setProperty('--color',
  3098. Util.color(this.value, this.elOpacity.valueAsNumber));
  3099. }
  3100. // range
  3101. for (const el of $$('[type="range"]', root)) {
  3102. el.oninput = rangeOnInput;
  3103. el.onblur = rangeOnBlur;
  3104. el.addEventListener('focusin', rangeOnFocus);
  3105. }
  3106. function rangeOnBlur(e) {
  3107. if (this.elEdit && e.relatedTarget !== this.elEdit)
  3108. this.elEdit.onblur(e);
  3109. }
  3110. function rangeOnFocus() {
  3111. if (this.elEdit) return;
  3112. const {min, max, step, value} = this;
  3113. this.elEdit = $new('input', {
  3114. value, min, max, step,
  3115. className: 'range-edit',
  3116. style: `left: ${this.offsetLeft}px; margin-top: ${this.offsetHeight + 1}px`,
  3117. type: 'number',
  3118. elRange: this,
  3119. onblur: rangeEditOnBlur,
  3120. oninput: rangeEditOnInput,
  3121. });
  3122. this.insertAdjacentElement('afterend', this.elEdit);
  3123. }
  3124. function rangeOnInput() {
  3125. this.title = (this.dataset.title || '').replace('$', this.value);
  3126. if (this.elColor) this.elColor.oninput();
  3127. if (this.elEdit) this.elEdit.valueAsNumber = this.valueAsNumber;
  3128. }
  3129. // range-edit
  3130. function rangeEditOnBlur(e) {
  3131. if (e.relatedTarget !== this.elRange) {
  3132. this.remove();
  3133. this.elRange.elEdit = null;
  3134. }
  3135. }
  3136. function rangeEditOnInput() {
  3137. this.elRange.valueAsNumber = this.valueAsNumber;
  3138. this.elRange.oninput();
  3139. }
  3140. // prevent the main page from interpreting key presses in inputs as hotkeys
  3141. // which may happen since it sees only the outer <div> in the event |target|
  3142. root.addEventListener('keydown', e => !e.altKey && !e.metaKey && e.stopPropagation(), true);
  3143. }
  3144.  
  3145. function closeSetup(event) {
  3146. const isApply = this.id === '_apply';
  3147. if (event && (this.id === '_ok' || isApply)) {
  3148. cfg = uiCfg = collectConfig({save: true, clone: isApply});
  3149. Ruler.init();
  3150. Menu.reRegisterAlt();
  3151. if (isApply)
  3152. return renderVolatiles();
  3153. }
  3154. $remove(elSetup);
  3155. elSetup = null;
  3156. }
  3157.  
  3158. function collectConfig({save, clone} = {}) {
  3159. let data = {};
  3160. for (const el of $$('input[id], select[id]', root))
  3161. data[el.id] = el.type === 'checkbox' ? el.checked :
  3162. (el.type === 'number' || el.type === 'range') ? el.valueAsNumber :
  3163. el.value || '';
  3164. Object.assign(data, {
  3165. css: UI.css.value.trim(),
  3166. delay: UI.delay.valueAsNumber * 1000,
  3167. hosts: collectRules(),
  3168. scale: clamp(UI.scale.valueAsNumber / 100, 0, 1) + 1,
  3169. scales: UI.scales.value
  3170. .trim()
  3171. .split(/[,;]*\s+/)
  3172. .map(x => x.replace(',', '.'))
  3173. .filter(x => !isNaN(parseFloat(x))),
  3174. });
  3175. if (clone)
  3176. data = JSON.parse(Util.stringify(data));
  3177. return new Config({data, save});
  3178. }
  3179.  
  3180. function collectRules() {
  3181. return [...UI._rules.children]
  3182. .map(el => [el.value.trim(), el[RULE]])
  3183. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  3184. .map(([s, json]) => json || s)
  3185. .filter(Boolean);
  3186. }
  3187.  
  3188. function checkRule({target: el}) {
  3189. let json, error, title;
  3190. const prev = el.previousElementSibling;
  3191. if (el.value) {
  3192. json = Ruler.parse(el.value);
  3193. error = json instanceof Error && (json.message || String(json));
  3194. const invalidDomain = !error && json && typeof json.d === 'string' &&
  3195. !/^[-.a-z0-9]*$/i.test(json.d);
  3196. title = [invalidDomain && 'Disabled due to invalid characters in "d"', error]
  3197. .filter(Boolean).join('\n');
  3198. el.classList.toggle('invalid-domain', invalidDomain);
  3199. el.classList.toggle('matching-domain', !!json.d && hostname.includes(json.d));
  3200. if (!prev)
  3201. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  3202. } else if (prev) {
  3203. prev.focus();
  3204. el.remove();
  3205. }
  3206. el[RULE] = !error && json;
  3207. el.title = title;
  3208. el.setCustomValidity(error || '');
  3209. }
  3210.  
  3211. async function focusRule({target: el, relatedTarget: from}) {
  3212. if (el === this)
  3213. return;
  3214. await new Promise(setTimeout);
  3215. if (el[RULE] && el.rows < 2) {
  3216. let i = el.selectionStart;
  3217. const txt = el.value = Ruler.format(el[RULE], {expand: true});
  3218. i += txt.slice(0, i).match(/^\s*/gm).reduce((len, s) => len + s.length, 0);
  3219. el.setSelectionRange(i, i);
  3220. el.rows = txt.match(/^/gm).length;
  3221. }
  3222. if (!this.contains(from))
  3223. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  3224. }
  3225.  
  3226. function installRule(rule) {
  3227. const inputs = UI._rules.children;
  3228. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  3229. if (!el) {
  3230. el = inputs[0];
  3231. el[RULE] = rule;
  3232. el.value = Ruler.format(rule);
  3233. el.hidden = false;
  3234. const i = Math.max(0, collectRules().indexOf(rule));
  3235. inputs[i].insertAdjacentElement('afterend', el);
  3236. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  3237. }
  3238. const rect = el.getBoundingClientRect();
  3239. if (rect.bottom < 0 ||
  3240. rect.bottom > el.parentNode.offsetHeight)
  3241. el.scrollIntoView();
  3242. el.classList.add('highlight');
  3243. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  3244. el.focus();
  3245. }
  3246.  
  3247. function renderRules() {
  3248. const rules = UI._rules;
  3249. rules.addEventListener('input', checkRule);
  3250. rules.addEventListener('focusin', focusRule);
  3251. rules.addEventListener('paste', focusRule);
  3252. blankRuleElement =
  3253. setup.blankRuleElement =
  3254. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  3255. for (const rule of uiCfg.hosts || []) {
  3256. const el = blankRuleElement.cloneNode();
  3257. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  3258. rules.appendChild(el);
  3259. checkRule({target: el});
  3260. }
  3261. const search = UI._search;
  3262. search.oninput = () => {
  3263. setup.search = search.value;
  3264. const s = search.value.toLowerCase();
  3265. for (const el of rules.children)
  3266. el.hidden = s && !el.value.toLowerCase().includes(s);
  3267. };
  3268. search.value = setup.search || '';
  3269. if (search.value)
  3270. search.oninput();
  3271. }
  3272.  
  3273. function renderVolatiles() {
  3274. UI.scales.value = uiCfg.scales.join(' ').trim() || Config.DEFAULTS.scales.join(' ');
  3275. UI._css.textContent = cfg._getCss();
  3276. }
  3277.  
  3278. function renderAll() {
  3279. for (const el of $$('input[id], select[id], textarea[id]', root))
  3280. if (el.id in uiCfg)
  3281. el[el.type === 'checkbox' ? 'checked' : 'value'] = uiCfg[el.id];
  3282. for (const el of $$('input[type="range"]', root))
  3283. el.oninput();
  3284. for (const el of $$('a[href^="http"]', root))
  3285. Object.assign(el, {target: '_blank', rel: 'noreferrer noopener external'});
  3286. UI.delay.valueAsNumber = uiCfg.delay / 1000;
  3287. UI.scale.valueAsNumber = Math.round(clamp(uiCfg.scale - 1, 0, 1) * 100);
  3288. UI.start.onchange();
  3289. }
  3290. }
  3291.  
  3292. function setupClickedRule(event) {
  3293. let rule;
  3294. const el = event.target.closest('blockquote, code, pre');
  3295. if (el && !event.button && !eventModifiers(event) && (rule = Ruler.fromElement(el))) {
  3296. dropEvent(event);
  3297. setup({rule});
  3298. }
  3299. }
  3300.  
  3301. /** @this {HTMLButtonElement} */
  3302. async function setupRuleInstaller(e) {
  3303. dropEvent(e);
  3304. const parent = setup.UI._rules2;
  3305. this.disabled = true;
  3306. this.textContent = 'Loading...';
  3307. let rules;
  3308.  
  3309. try {
  3310. rules = extractRules(await Req.getDoc(this.parentElement.href));
  3311. this.textContent = 'Rules loaded.';
  3312. const el = $new('select', {
  3313. size: 8,
  3314. style: 'width: 100%',
  3315. ondblclick: e => e.target !== el && maybeSetup(e),
  3316. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  3317. }, rules.map(renderRule));
  3318. const i = el.selectedIndex = findMatchingRuleIndex();
  3319. parent.append(
  3320. $new('div#_installHint', [
  3321. 'Double-click the rule (or select and press Enter) to add it. ',
  3322. 'Click ', $new('code', 'Apply'), ' or ', $new('code', 'OK'), ' to confirm.',
  3323. ]),
  3324. el
  3325. );
  3326. if (i) requestAnimationFrame(() => {
  3327. const optY = el.selectedOptions[0].offsetTop - el.offsetTop;
  3328. el.scrollTo(0, optY - el.offsetHeight / 2);
  3329. });
  3330. el.focus();
  3331. } catch (e) {
  3332. parent.textContent = 'Error loading rules: ' + (e.message || e);
  3333. }
  3334.  
  3335. function extractRules({doc}) {
  3336. // sort by name
  3337. return [...$$('#wiki-body tr', doc)]
  3338. .map(tr => [
  3339. tr.cells[0].textContent.trim(),
  3340. Ruler.fromElement(tr.cells[1]),
  3341. ])
  3342. .filter(([name, r]) =>
  3343. name && r && (!r.d || hostname.includes(r.d)))
  3344. .sort(([a], [b]) =>
  3345. (a = a.toLowerCase()) < (b = b.toLowerCase()) ? -1 :
  3346. a > b ? 1 :
  3347. 0);
  3348. }
  3349.  
  3350. function findMatchingRuleIndex() {
  3351. const dottedHost = `.${hostname}.`;
  3352. let maxCount = 0, maxIndex = 0, index = 0;
  3353. for (const [name, {d}] of rules) {
  3354. let count = !!(d && hostname.includes(d)) * 10;
  3355. for (const part of name.toLowerCase().split(/[^a-z\d.-]+/i))
  3356. count += dottedHost.includes(`.${part}.`) && part.length;
  3357. if (count > maxCount) {
  3358. maxCount = count;
  3359. maxIndex = index;
  3360. }
  3361. index++;
  3362. }
  3363. return maxIndex;
  3364. }
  3365.  
  3366. function renderRule([name, rule]) {
  3367. return $new('option', {
  3368. textContent: name,
  3369. title: Ruler.format(rule, {expand: true})
  3370. .replace(/^{|\s*}$/g, '')
  3371. .split('\n')
  3372. .slice(0, 12)
  3373. .map(renderTitleLine)
  3374. .filter(Boolean)
  3375. .join('\n'),
  3376. });
  3377. }
  3378.  
  3379. function renderTitleLine(line, i, arr) {
  3380. return (
  3381. // show ... on 10th line if there are more lines
  3382. i === 9 && arr.length > 10 ? '...' :
  3383. i > 10 ? '' :
  3384. // truncate to 100 chars
  3385. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  3386. // strip the leading space
  3387. .replace(/^\s/, ''));
  3388. }
  3389.  
  3390. function maybeSetup(e) {
  3391. if (!eventModifiers(e))
  3392. setup({rule: rules[e.currentTarget.selectedIndex][1]});
  3393. }
  3394. }
  3395.  
  3396. const CSS_SETUP_X = 20;
  3397. const CSS_SETUP_MAX_Y = 200;
  3398. const CSS_SETUP = /*language=css*/ `
  3399. :host {
  3400. all: initial !important;
  3401. position: fixed !important;
  3402. z-index: 2147483647 !important;
  3403. top: ${CSS_SETUP_X}px !important;
  3404. right: 20px !important;
  3405. padding: 1.5em !important;
  3406. color: #000 !important;
  3407. --bg: #eee;
  3408. background: var(--bg) !important;
  3409. box-shadow: 5px 5px 25px 2px #000 !important;
  3410. width: 33em !important;
  3411. border: 1px solid black !important;
  3412. display: flex !important;
  3413. flex-direction: column !important;
  3414. }
  3415. main {
  3416. font: 12px/15px sans-serif;
  3417. }
  3418. main:not([data-start=auto]) [data-start-auto] {
  3419. opacity: .5;
  3420. }
  3421. table {
  3422. text-align:left;
  3423. }
  3424. ul {
  3425. min-height: 430px;
  3426. max-height: calc(100vh - ${CSS_SETUP_MAX_Y}px);
  3427. margin: 0 0 15px 0;
  3428. padding: 0;
  3429. list-style: none;
  3430. }
  3431. li {
  3432. margin: 0;
  3433. padding: .25em 0;
  3434. }
  3435. li.options {
  3436. display: flex;
  3437. align-items: center;
  3438. justify-content: space-between;
  3439. }
  3440. li.row {
  3441. align-items: start;
  3442. flex-wrap: wrap;
  3443. }
  3444. li.row label {
  3445. display: flex;
  3446. flex-direction: row;
  3447. align-items: center;
  3448. }
  3449. li.row input {
  3450. margin-right: .25em;
  3451. }
  3452. li.stretch label {
  3453. flex: 1;
  3454. white-space: nowrap;
  3455. }
  3456. li.stretch label > span {
  3457. display: flex;
  3458. flex-direction: row;
  3459. flex: 1;
  3460. }
  3461. label {
  3462. display: inline-flex;
  3463. flex-direction: column;
  3464. }
  3465. label:not(:last-child) {
  3466. margin-right: 1em;
  3467. }
  3468. input, select {
  3469. min-height: 1.3em;
  3470. box-sizing: border-box;
  3471. }
  3472. input[type=checkbox] {
  3473. margin-left: 0;
  3474. }
  3475. input[type=number] {
  3476. width: 4em;
  3477. }
  3478. input:not([type=checkbox]) {
  3479. padding: 0 .25em;
  3480. }
  3481. input[type=range] {
  3482. flex: 1;
  3483. width: 100%;
  3484. margin: 0 .25em;
  3485. padding: 0;
  3486. filter: saturate(0);
  3487. opacity: .5;
  3488. }
  3489. u + input[type=range] {
  3490. max-width: 3em;
  3491. }
  3492. input[type=range]:hover {
  3493. filter: none;
  3494. opacity: 1;
  3495. }
  3496. input[type=color] {
  3497. position: absolute;
  3498. width: calc(1.5em + 2px);
  3499. opacity: 0;
  3500. cursor: pointer;
  3501. }
  3502. u {
  3503. position: relative;
  3504. flex: 0 0 1.5em;
  3505. height: 1.5em;
  3506. border: 1px solid #888;
  3507. pointer-events: none;
  3508. color: #888;
  3509. background-image:
  3510. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%),
  3511. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%);
  3512. background-size: .5em .5em;
  3513. background-position: 0 0, .25em .25em;
  3514. }
  3515. u::after {
  3516. position: absolute;
  3517. top: 0;
  3518. left: 0;
  3519. right: 0;
  3520. bottom: 0;
  3521. content: "";
  3522. background-color: var(--color);
  3523. }
  3524. .range-edit {
  3525. position: absolute;
  3526. box-shadow: 0 0.25em 1em #000;
  3527. z-index: 99;
  3528. }
  3529. textarea {
  3530. resize: vertical;
  3531. margin: 1px 0;
  3532. font: 11px/1.25 Consolas, monospace;
  3533. }
  3534. :invalid {
  3535. background-color: #f002;
  3536. border-color: #800;
  3537. }
  3538. code {
  3539. font-weight: bold;
  3540. }
  3541. a {
  3542. text-decoration: none;
  3543. color: LinkText;
  3544. cursor: pointer;
  3545. }
  3546. a:hover {
  3547. text-decoration: underline;
  3548. }
  3549. button {
  3550. padding: .2em .5em;
  3551. margin-right: 1em;
  3552. }
  3553. kbd {
  3554. padding: 1px 6px;
  3555. font-weight: bold;
  3556. font-family: Consolas, monospace;
  3557. border: 1px solid #888;
  3558. border-radius: 3px;
  3559. box-shadow: inset 1px 1px 5px #8888, .25px .5px 2px #0008;
  3560. }
  3561. .column {
  3562. display: flex;
  3563. flex-direction: column;
  3564. }
  3565. .flex {
  3566. display: flex;
  3567. }
  3568. .highlight {
  3569. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  3570. animation-fill-mode: both;
  3571. }
  3572. #_rules > * {
  3573. word-break: break-all;
  3574. }
  3575. #_rules > :not(:focus) {
  3576. overflow: hidden; /* prevents wrapping in FF */
  3577. }
  3578. .invalid-domain {
  3579. opacity: .5;
  3580. }
  3581. .matching-domain {
  3582. border-color: #56b8ff;
  3583. background: #d7eaff;
  3584. }
  3585. #_mover {
  3586. cursor: move;
  3587. user-select: none;
  3588. position: absolute;
  3589. top: 0;
  3590. left: 8px;
  3591. right: 24px;
  3592. height: 24px;
  3593. text-align: center;
  3594. background: linear-gradient(transparent 10px, currentColor 10px, currentColor 11px, transparent 11px,
  3595. transparent 13px, currentColor 13px, currentColor 14px, transparent 14px);
  3596. }
  3597. #_mover::after {
  3598. content: 'MPIV ${GM.info.script.version}';
  3599. font: bold 150% sans;
  3600. background: var(--bg);
  3601. padding: 0 1ex;
  3602. }
  3603. #_x {
  3604. position: absolute;
  3605. top: 0;
  3606. right: 0;
  3607. padding: 4px 8px;
  3608. cursor: pointer;
  3609. user-select: none;
  3610. }
  3611. #_x:hover {
  3612. background-color: #8884;
  3613. }
  3614. #_cssApp {
  3615. color: seagreen;
  3616. }
  3617. #_exportNotification {
  3618. color: green;
  3619. font-weight: bold;
  3620. position: absolute;
  3621. bottom: 4px;
  3622. right: 26px;
  3623. }
  3624. #_installHint {
  3625. color: green;
  3626. }
  3627. #_usage {
  3628. display: flex;
  3629. flex-wrap: wrap;
  3630. align-items: flex-start;
  3631. gap: 1em;
  3632. }
  3633. #_usage th {
  3634. font-weight: normal;
  3635. padding-right: .5em;
  3636. }
  3637. #_usage tr:nth-last-child(n + 2) > :not(br) {
  3638. white-space: pre-line;
  3639. border-bottom: 1px dotted #8888;
  3640. }
  3641. #_usage kbd {
  3642. font-family: monospace;
  3643. font-weight: bold;
  3644. }
  3645. @keyframes fade-in {
  3646. from { background-color: deepskyblue }
  3647. to {}
  3648. }
  3649. @media (prefers-color-scheme: dark) {
  3650. :host {
  3651. color: #aaa !important;
  3652. --bg: #333 !important;
  3653. }
  3654. a {
  3655. color: deepskyblue;
  3656. }
  3657. button {
  3658. background: linear-gradient(-5deg, #333, #555);
  3659. border: 1px solid #000;
  3660. box-shadow: 0 2px 6px #181818;
  3661. border-radius: 3px;
  3662. cursor: pointer;
  3663. }
  3664. button:hover {
  3665. background: linear-gradient(-5deg, #333, #666);
  3666. }
  3667. textarea, input, select {
  3668. background: #111;
  3669. color: #BBB;
  3670. border: 1px solid #555;
  3671. }
  3672. input[type=checkbox] {
  3673. filter: invert(1);
  3674. }
  3675. input[type=range] {
  3676. filter: invert(1) saturate(0);
  3677. }
  3678. input[type=range]:hover {
  3679. filter: invert(1);
  3680. }
  3681. kbd {
  3682. border-color: #666;
  3683. }
  3684. @supports (-moz-appearance: none) {
  3685. input[type=checkbox],
  3686. input[type=range],
  3687. input[type=range]:hover {
  3688. filter: none;
  3689. }
  3690. }
  3691. .range-edit {
  3692. box-shadow: 0 .5em 1em .5em #000;
  3693. }
  3694. .matching-domain {
  3695. border-color: #0065af;
  3696. background: #032b58;
  3697. color: #ddd;
  3698. }
  3699. #_cssApp {
  3700. color: darkseagreen;
  3701. }
  3702. #_installHint {
  3703. color: greenyellow;
  3704. }
  3705. ::-webkit-scrollbar {
  3706. width: 14px;
  3707. height: 14px;
  3708. background: #333;
  3709. }
  3710. ::-webkit-scrollbar-button:single-button {
  3711. background: radial-gradient(circle at center, #555 40%, #333 40%)
  3712. }
  3713. ::-webkit-scrollbar-track-piece {
  3714. background: #444;
  3715. border: 4px solid #333;
  3716. border-radius: 8px;
  3717. }
  3718. ::-webkit-scrollbar-thumb {
  3719. border: 3px solid #333;
  3720. border-radius: 8px;
  3721. background: #666;
  3722. }
  3723. ::-webkit-resizer {
  3724. background: #111 linear-gradient(-45deg, transparent 3px, #888 3px, #888 4px, transparent 4px, transparent 6px, #888 6px, #888 7px, transparent 7px) no-repeat;
  3725. border: 2px solid transparent;
  3726. }
  3727. }
  3728. `;
  3729.  
  3730. function createSetupElement() {
  3731. const MPIV_BASE_URL = 'https://github.com/tophf/mpiv/wiki/';
  3732. const scalesHint = 'Leave it empty and click Apply or OK to restore the default values.';
  3733. const $newLink = (text, href, props) =>
  3734. $new('a', Object.assign({target: '_blank'}, href && {href}, props), text);
  3735. const $newCheck = (label, id, title = '', props) =>
  3736. $new('label', Object.assign({title}, props), [
  3737. $new('input', {id, type: 'checkbox'}),
  3738. label,
  3739. ]);
  3740. const $newKbd = s => s[0] === '{' ? $new('kbd', s.slice(1, -1)) : s;
  3741. const $newRange = (id, title = '', min = 0, max = 100, step = 1, type = 'range') =>
  3742. $new('input', {id, min, max, step, type, 'data-title': title});
  3743. const $newSelect = (label, id, values) =>
  3744. $new('label', [
  3745. label,
  3746. $new('select', {id}, Object.entries(values).map(([k, v]) =>
  3747. $new('option', Object.assign({value: k}, typeof v === 'object' ? v : {textContent: v})))),
  3748. ]);
  3749. const $newTR = ([name, val]) =>
  3750. $new('tr', !name ? $new('br') : [
  3751. $new('th', ((name = name.split(/(\n)/))[0] = $new('b', name[0])) && name),
  3752. $new('td', val.split(/({.+?})/).map($newKbd)),
  3753. ]);
  3754. const kAutoTooltip = '...when activation is "automatically"';
  3755. const kAutoProps = {'data-start-auto': ''};
  3756. return [
  3757. $new('style#_cssSetup', CSS_SETUP),
  3758. $new('style#_css'),
  3759. $new(`main#${PREFIX}setup`, [
  3760. $new('#_mover'),
  3761. $new('#_x', 'x'),
  3762. $new('ul#_ul.column', [
  3763. $new('details', {style: 'order:1; padding-top: .5em;'}, [
  3764. $new('summary', {style: 'cursor: pointer'},
  3765. $new('b', 'Help & hotkeys...')),
  3766. $new('#_usage', [
  3767. $new('table', [
  3768. ['Activate', 'hover the target'],
  3769. ['Deactivate', 'move cursor off target, or click, or zoom out fully'],
  3770. ['Ignore target', 'hold {Shift} ⏵ hover the target ⏵ release the key'],
  3771. ['Freeze popup', 'hold {Shift} ⏵ leave the target ⏵ release the key'],
  3772. ['Force-activate\n(videos or small pics)', 'hold {Ctrl} ⏵ hover the target ⏵ release the key'],
  3773. ].map($newTR)),
  3774. $new('table', [
  3775. ['Start zooming', 'configurable (automatic or via right-click)\nor tap {Shift} while popup is visible'],
  3776. ['Zoom', 'mouse wheel'],
  3777. [],
  3778. ['Rotate', '{L} {r} for "left" or "right"'],
  3779. ['Flip/mirror', '{h} {v} for "horizontal" or "vertical"'],
  3780. ['Previous/next\n(in album)', 'mouse wheel, {j} {k} or {←} {→} keys'],
  3781. ].map($newTR)),
  3782. $new('table', [
  3783. ['Antialiasing', '{a}'],
  3784. ['Caption in info', '{c}'],
  3785. ['Download', '{d}'],
  3786. ['Fullscreen', '{f}'],
  3787. ['Info', '{i}'],
  3788. ['Mute', '{m}'],
  3789. ['Night mode', '{n}'],
  3790. ['Open in tab', '{t}'],
  3791. ].map($newTR)),
  3792. ]),
  3793. ]),
  3794. $new('li.options.stretch', [
  3795. $newSelect('Popup shows on', 'start', {
  3796. context: 'Right-click / \u2261 / Ctrl',
  3797. contextMK: 'Right-click / \u2261',
  3798. contextM: 'Right-click',
  3799. contextK: {
  3800. textContent: '\u2261 key',
  3801. title: '\u2261 is the Menu key (near the right Ctrl)',
  3802. },
  3803. ctrl: 'Ctrl',
  3804. auto: 'automatically',
  3805. }),
  3806. $new('label', {title: kAutoTooltip, ...kAutoProps},
  3807. ['after, sec', $newRange('delay', 'seconds', .05, 10, .05, 'number')]),
  3808. $new('label', {title: '(if the full version of the hovered image is ...% larger)'},
  3809. ['if larger, %', $newRange('scale', null, 0, 100, 1, 'number')]),
  3810. $newSelect('Zoom activates on', 'zoom', {
  3811. context: 'Right click / Shift',
  3812. wheel: 'Wheel up / Shift',
  3813. shift: 'Shift',
  3814. auto: 'automatically',
  3815. }),
  3816. $newSelect('...and zooms to', 'fit', {
  3817. 'all': 'fit to window',
  3818. 'large': 'fit if larger',
  3819. 'no': '100%',
  3820. '': {textContent: 'custom', title: 'Use custom scale factors'},
  3821. }),
  3822. ]),
  3823. $new('li.options', [
  3824. $new('label', ['Zoom step, %', $newRange('zoomStep', null, 100, 400, 1, 'number')]),
  3825. $newSelect('When fully zoomed out:', 'zoomOut', {
  3826. stay: 'stay in zoom mode',
  3827. auto: 'stay if still hovered',
  3828. unzoom: 'undo zoom mode',
  3829. close: 'close popup',
  3830. }),
  3831. $new('label', {
  3832. style: 'flex: 1',
  3833. title: `
  3834. Scale factors to use when zooms to selector is set to custom”.
  3835. 0 = fit to window,
  3836. 0! = same as 0 but also removes smaller values,
  3837. * after a value marks the default zoom factor, for example: 1*
  3838. The popup won't shrink below the image's natural size or window size for bigger mages.
  3839. ${scalesHint}
  3840. `.trim().replace(/\n\s+/g, '\r'),
  3841. }, ['Custom scale factors:', $new('input#scales', {placeholder: scalesHint})]),
  3842. ]),
  3843. $new('li.options.row', [
  3844. $new([
  3845. $newCheck('Centered*', 'center',
  3846. '...or try to keep the original link/thumbnail unobscured by the popup'),
  3847. $newCheck('Preload on hover*', 'preload',
  3848. 'Provides smoother experience but increases network traffic'),
  3849. $newCheck('Require Ctrl key for video*', 'videoCtrl', kAutoTooltip, kAutoProps),
  3850. $newCheck('Mute videos*', 'mute', 'Hotkey: "m" in the popup'),
  3851. $newCheck('Keep playing video*', 'keepVids',
  3852. '...until you press Esc key or click elsewhere'),
  3853. $newCheck('Keep preview on blur*', 'keepOnBlur',
  3854. 'i.e. when mouse pointer moves outside the page'),
  3855. ]),
  3856. $new([
  3857. $newCheck('Wait for complete image*', 'waitLoad',
  3858. '...or immediately show a partial image while still loading'),
  3859. $new('div.flex', {style: 'align-items:center'}, [
  3860. $newCheck('Info: show for', 'uiInfo', 'Hotkey: "i" (or hold "Shift") in the popup'),
  3861. $new('input#uiInfoHide', {min: 1, step: 'any', type: 'number'}),
  3862. 'sec',
  3863. ]),
  3864. $newCheck('Info: only once*', 'uiInfoOnce', '...or every time the info changes'),
  3865. $newCheck('Info: caption*', 'uiInfoCaption', 'Hotkey: "c" in the popup'),
  3866. $newCheck('Fade-in transition', 'uiFadein'),
  3867. $newCheck('Fade-in transition in gallery', 'uiFadeinGallery'),
  3868. ]),
  3869. $new([
  3870. $newCheck('Night mode*', 'night', 'Hotkey: "n" in the popup'),
  3871. $newCheck('Run in image tabs', 'imgtab'),
  3872. $newCheck('Spoof hotlinking*', 'xhr',
  3873. 'Disable only if you spoof the HTTP headers yourself'),
  3874. $newCheck('Set status on <html>*', 'globalStatus',
  3875. "Causes slowdowns so don't enable unless you explicitly use it in your custom CSS"),
  3876. $newCheck('Auto-start switch in menu*', 'startAltShown',
  3877. "Show a switch for 'auto-start' mode in userscript manager menu"),
  3878. ]),
  3879. ]),
  3880. $new('li.options.stretch', [
  3881. $new('label', [
  3882. 'Background',
  3883. $new('span', [
  3884. $new('input#uiBackgroundColor', {type: 'color'}), $new('u'),
  3885. $newRange('uiBackgroundOpacity', 'Opacity: $%'),
  3886. ]),
  3887. ]),
  3888. $new('label', [
  3889. 'Border color, opacity, size',
  3890. $new('span', [
  3891. $new('input#uiBorderColor', {type: 'color'}), $new('u'),
  3892. $newRange('uiBorderOpacity', 'Opacity: $%'),
  3893. $newRange('uiBorder', 'Border size: $px', 0, 20),
  3894. ]),
  3895. ]),
  3896. $new('label', [
  3897. 'Shadow color, opacity, size',
  3898. $new('span', [
  3899. $new('input#uiShadowColor', {type: 'color'}), $new('u'),
  3900. $newRange('uiShadowOpacity', 'Opacity: $%'),
  3901. $newRange('uiShadow', 'Shadow blur radius: $px\n"0" disables the shadow.', 0, 20),
  3902. ]),
  3903. ]),
  3904. $new('label', ['Padding', $new('span', $newRange('uiPadding', 'Padding: $px'))]),
  3905. $new('label', ['Margin', $new('span', $newRange('uiMargin', 'Margin: $px'))]),
  3906. ]),
  3907. $new('li', [
  3908. $newLink('Custom CSS:', `${MPIV_BASE_URL}Custom-CSS`),
  3909. ' e.g. ', $new('b', '#mpiv-popup { animation: none !important }'),
  3910. $newLink('View the built-in CSS', '', {
  3911. id: '_reveal',
  3912. tabIndex: 0,
  3913. style: 'float: right',
  3914. title: 'You can copy parts of it to override them in your custom CSS',
  3915. }),
  3916. $new('.column', [
  3917. $new('textarea#css', {spellcheck: false}),
  3918. $new('textarea#_cssApp', {spellcheck: false, hidden: true, readOnly: true, rows: 30}),
  3919. ]),
  3920. ]),
  3921. $new('li.flex', {style: 'justify-content: space-between;'}, [
  3922. $new('div',
  3923. $newLink('Custom host rules:', `${MPIV_BASE_URL}Custom-host-rules`)),
  3924. $new('div', {style: 'white-space: pre-line'}, [
  3925. 'To disable, put any symbol except ', $new('code', 'a..z 0..9 - .'),
  3926. '\nin "d" value, for example ', $new('code', '"d": "!foo.com"'),
  3927. ]),
  3928. $new('div',
  3929. $new('input#_search',
  3930. {type: 'search', placeholder: 'Search', style: 'width: 10em; margin-left: 1em'})),
  3931. ]),
  3932. $new('li', {
  3933. style: 'margin-left: -3px; margin-right: -3px; overflow-y: auto; ' +
  3934. 'padding-left: 3px; padding-right: 3px;',
  3935. }, [
  3936. $new('div#_rules.column',
  3937. $new('textarea', {spellcheck: false, rows: 1})),
  3938. ]),
  3939. $new('li#_rules2'),
  3940. ]),
  3941. $new('div.flex', [
  3942. $new('button#_ok', {accessKey: 'o'}, 'OK'),
  3943. $new('button#_apply', {accessKey: 'a'}, 'Apply'),
  3944. $new('button#_cancel', 'Cancel'),
  3945. $new('a', {href: `${MPIV_BASE_URL}Rules`, style: 'margin: 0 auto'},
  3946. $new('button#_install', {style: 'color: inherit'}, 'Find rule...')),
  3947. $new('button#_import', 'Import'),
  3948. $new('button#_export', {style: 'margin: 0'}, 'Export'),
  3949. $new('div#_exportNotification', {hidden: true}, 'Copied to clipboard'),
  3950. ]),
  3951. ]),
  3952. ];
  3953. }
  3954.  
  3955. function createGlobalStyle() {
  3956. App.globalStyle = /*language=CSS*/ (String.raw`
  3957. #\mpiv-bar {
  3958. position: fixed;
  3959. z-index: 2147483647;
  3960. top: 0;
  3961. left: 0;
  3962. right: 0;
  3963. text-align: center;
  3964. font-family: sans-serif;
  3965. font-size: 15px;
  3966. font-weight: bold;
  3967. background: #0005;
  3968. color: white;
  3969. padding: 4px 10px;
  3970. text-shadow: .5px .5px 2px #000;
  3971. transition: opacity 1s ease .25s;
  3972. opacity: 0;
  3973. }
  3974. #\mpiv-bar[data-force] {
  3975. transition: none;
  3976. }
  3977. #\mpiv-bar.\mpiv-show {
  3978. opacity: 1;
  3979. }
  3980. #\mpiv-bar[data-zoom][data-prefix]::before {
  3981. content: "[" attr(data-prefix) "] ";
  3982. color: gold;
  3983. }
  3984. #\mpiv-bar[data-zoom]:not(:empty)::after {
  3985. content: " (" attr(data-zoom) ")";
  3986. opacity: .8;
  3987. }
  3988. #\mpiv-bar[data-zoom]:empty::after {
  3989. content: attr(data-zoom);
  3990. }
  3991. #\mpiv-popup.\mpiv-show {
  3992. display: inline;
  3993. }
  3994. #\mpiv-popup {
  3995. display: none;
  3996. cursor: none;
  3997. ${cfg.uiFadein ? String.raw`
  3998. animation: .2s \mpiv-fadein both;
  3999. transition: box-shadow .25s, background-color .25s;
  4000. ` : ''}
  4001. ${App.popupStyleBase = `
  4002. border: none;
  4003. box-sizing: border-box;
  4004. background-size: cover;
  4005. position: fixed;
  4006. z-index: 2147483647;
  4007. padding: 0;
  4008. margin: 0;
  4009. top: 0;
  4010. left: 0;
  4011. width: auto;
  4012. height: auto;
  4013. transform-origin: center;
  4014. max-width: none;
  4015. max-height: none;
  4016. `}
  4017. }
  4018. #\mpiv-popup.\mpiv-show {
  4019. ${cfg.uiBorder ? `border: ${cfg.uiBorder}px solid ${Util.color('Border')};` : ''}
  4020. ${cfg.uiPadding ? `padding: ${cfg.uiPadding}px;` : ''}
  4021. ${cfg.uiMargin ? `margin: ${cfg.uiMargin}px;` : ''}
  4022. box-shadow: ${cfg.uiShadow ? `2px 4px ${cfg.uiShadow}px 4px transparent` : 'none'};
  4023. }
  4024. #\mpiv-popup.\mpiv-show[loaded] {
  4025. background-color: ${Util.color('Background')};
  4026. ${cfg.uiShadow ? `box-shadow: 2px 4px ${cfg.uiShadow}px 4px ${Util.color('Shadow')};` : ''}
  4027. }
  4028. #\mpiv-popup[data-gallery-flip] {
  4029. animation: none;
  4030. transition: none;
  4031. }
  4032. #\mpiv-popup[${NOAA_ATTR}],
  4033. #\mpiv-popup.\mpiv-zoom-max {
  4034. image-rendering: pixelated;
  4035. }
  4036. #\mpiv-popup.\mpiv-night:not(#\\0) {
  4037. box-shadow: 0 0 0 ${Math.max(screen.width, screen.height)}px #000;
  4038. }
  4039. body:has(#\mpiv-popup.\mpiv-night)::-webkit-scrollbar {
  4040. background: #000;
  4041. }
  4042. #\mpiv-setup {
  4043. }
  4044. @keyframes \mpiv-fadein {
  4045. from {
  4046. opacity: 0;
  4047. border-color: transparent;
  4048. }
  4049. to {
  4050. opacity: 1;
  4051. }
  4052. }
  4053. ` + (cfg.globalStatus ? String.raw`
  4054. :root.\mpiv-loading:not(.\mpiv-preloading) *:hover {
  4055. cursor: progress !important;
  4056. }
  4057. :root.\mpiv-edge #\mpiv-popup {
  4058. cursor: default;
  4059. }
  4060. :root.\mpiv-error *:hover {
  4061. cursor: not-allowed !important;
  4062. }
  4063. :root.\mpiv-ready *:hover,
  4064. :root.\mpiv-large *:hover {
  4065. cursor: zoom-in !important;
  4066. }
  4067. :root.\mpiv-shift *:hover {
  4068. cursor: default !important;
  4069. }
  4070. ` : String.raw`
  4071. [\mpiv-status~="loading"]:not([\mpiv-status~="preloading"]):hover {
  4072. cursor: progress;
  4073. }
  4074. [\mpiv-status~="edge"]:hover {
  4075. cursor: default;
  4076. }
  4077. [\mpiv-status~="error"]:hover {
  4078. cursor: not-allowed;
  4079. }
  4080. [\mpiv-status~="ready"]:hover,
  4081. [\mpiv-status~="large"]:hover {
  4082. cursor: zoom-in;
  4083. }
  4084. [\mpiv-status~="shift"]:hover {
  4085. cursor: default;
  4086. }
  4087. `)).replace(/\\mpiv-status/g, STATUS_ATTR).replace(/\\mpiv-/g, PREFIX);
  4088. App.popupStyleBase = App.popupStyleBase.replace(/;/g, '!important;');
  4089. return App.globalStyle;
  4090. }
  4091.  
  4092. //#region Global utilities
  4093.  
  4094. const clamp = (v, min, max) =>
  4095. v < min ? min : v > max ? max : v;
  4096.  
  4097. const compareNumbers = (a, b) =>
  4098. a - b;
  4099.  
  4100. const flattenHtml = str =>
  4101. str.trim().replace(/\n\s*/g, '');
  4102.  
  4103. const dropEvent = e =>
  4104. (e.preventDefault(), e.stopPropagation());
  4105.  
  4106. const ensureArray = v =>
  4107. isArray(v) ? v : [v];
  4108.  
  4109. /** @param {KeyboardEvent} e */
  4110. const eventModifiers = e =>
  4111. (e.altKey ? '!' : '') +
  4112. (e.ctrlKey ? '^' : '') +
  4113. (e.metaKey ? '#' : '') +
  4114. (e.shiftKey ? '+' : '');
  4115.  
  4116. /** @param {KeyboardEvent} e */
  4117. const describeKey = e => eventModifiers(e) + (e.key && e.key.length > 1 ? e.key : e.code);
  4118.  
  4119. const isFunction = val => typeof val === 'function';
  4120.  
  4121. const isVideo = el => el && el.tagName === 'VIDEO';
  4122.  
  4123. const now = performance.now.bind(performance);
  4124.  
  4125. const sumProps = (...props) => {
  4126. let sum = 0;
  4127. for (const p of props)
  4128. sum += parseFloat(p) || 0;
  4129. return sum;
  4130. };
  4131.  
  4132. const tryCatch = (fn, ...args) => {
  4133. try {
  4134. return fn(...args);
  4135. } catch (e) {}
  4136. };
  4137.  
  4138. const tryJSON = str =>
  4139. tryCatch(JSON.parse, str);
  4140.  
  4141. const pick = (obj, path, fn) => {
  4142. if (obj && path)
  4143. for (const p of path.split('.'))
  4144. if (obj) obj = obj[p]; else break;
  4145. return fn && obj !== undefined ? fn(obj) : obj;
  4146. };
  4147.  
  4148. const $ = (sel, node = doc) =>
  4149. node.querySelector(sel) || false;
  4150.  
  4151. const $$ = (sel, node = doc) =>
  4152. node.querySelectorAll(sel);
  4153.  
  4154. const $new = (sel, props, children) => {
  4155. if (typeof sel !== 'string') {
  4156. children = props;
  4157. props = sel;
  4158. sel = '';
  4159. }
  4160. if (!children && props != null && ({}).toString.call(props) !== '[object Object]') {
  4161. children = props;
  4162. props = null;
  4163. }
  4164. const isFrag = sel === 'fragment';
  4165. const [, tag, id, cls] = sel.match(/^(\w*)(?:#([^.]+))?(?:\.(.+))?$/);
  4166. const el = isFrag ? doc.createDocumentFragment() : doc.createElement(tag || 'div');
  4167. if (id) el.id = id;
  4168. if (cls) el.className = cls.replace(/\./g, ' ');
  4169. if (props) {
  4170. for (const [k, v] of Object.entries(props)) {
  4171. if (!k.startsWith('data-')) {
  4172. el[k] = v;
  4173. } else if (v != null) {
  4174. el.setAttribute(k, v);
  4175. }
  4176. }
  4177. }
  4178. if (children != null) {
  4179. if (isArray(children))
  4180. el.append(...children.filter(Boolean));
  4181. else if (children instanceof Node)
  4182. el.appendChild(children);
  4183. else
  4184. el.textContent = children;
  4185. }
  4186. return el;
  4187. };
  4188.  
  4189. const $css = (el, props) =>
  4190. Object.entries(props).forEach(([k, v]) =>
  4191. el.style.setProperty(k, v, 'important'));
  4192.  
  4193. const $parseHtml = str =>
  4194. new DOMParser().parseFromString(str, 'text/html');
  4195.  
  4196. const $many = (q, doc) => {
  4197. for (const selector of ensureArray(q)) {
  4198. const el = selector && $(selector, doc);
  4199. if (el)
  4200. return el;
  4201. }
  4202. };
  4203.  
  4204. const $prop = (sel, prop, node = doc) =>
  4205. (node = $(sel, node)) && node[prop] || '';
  4206.  
  4207. const $propUp = (node, prop) =>
  4208. (node = node.closest(`[${prop}]`)) &&
  4209. (prop.startsWith('data-') ? node.getAttribute(prop) : node[prop]) ||
  4210. '';
  4211.  
  4212. const $remove = node =>
  4213. node && node.remove();
  4214.  
  4215. const $dataset = ({dataset: d}, key, val) =>
  4216. val == null ? delete d[key] : (d[key] = val);
  4217.  
  4218. //#endregion
  4219. //#region Init
  4220.  
  4221. (async () => {
  4222. cfg = await Config.load({save: true});
  4223. if (!doc.body) {
  4224. await new Promise(resolve =>
  4225. new MutationObserver((_, mo) => doc.body && (mo.disconnect(), resolve()))
  4226. .observe(document, {subtree: true, childList: true}));
  4227. }
  4228. const el = doc.body.firstElementChild;
  4229. if (el) {
  4230. App.isImageTab = el === doc.body.lastElementChild && el.matches('img, video');
  4231. App.isEnabled = cfg.imgtab || !App.isImageTab;
  4232. }
  4233. if (Menu) Menu.register();
  4234. addEventListener('mouseover', Events.onMouseOver, true);
  4235. addEventListener('contextmenu', Events.onContext, true);
  4236. addEventListener('keydown', Events.onKeyDown, true);
  4237. addEventListener('visibilitychange', Events.onVisibility, true);
  4238. addEventListener('blur', Events.onVisibility, true);
  4239. if (['greasyfork.org', 'github.com'].includes(hostname))
  4240. addEventListener('click', setupClickedRule, true);
  4241. addEventListener('message', App.onMessage, true);
  4242. })();
  4243.  
  4244. if (window.trustedTypes) {
  4245. const TT = window.trustedTypes;
  4246. const CP = 'createPolicy';
  4247. const createPolicy = TT[CP];
  4248. TT[CP] = function ovr(name, opts) {
  4249. let fn;
  4250. const p = createPolicy.call(TT, name, opts);
  4251. if ((trustedHTML || opts[fn = 'createHTML'] && (trustedHTML = p[fn].bind(p))) &&
  4252. (trustedScript || opts[fn = 'createScript'] && (trustedScript = p[fn].bind(p))) &&
  4253. TT[CP] === ovr)
  4254. delete TT[CP];
  4255. return p;
  4256. };
  4257. }
  4258.  
  4259. //#endregion