Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址