Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

As of 01.01.2022. See ბოლო ვერსია.

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