Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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