Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2024-03-26 提交的版本,檢視 最新版本

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

QingJ © 2025

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