Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2023-08-31 提交的版本,查看 最新版本

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