Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2024-02-10 提交的版本,查看 最新版本

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

QingJ © 2025

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