Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2022-02-03 提交的版本,查看 最新版本

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