Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

As of 2020-03-02. See the latest version.

  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 http*
  7. // @connect *
  8.  
  9. // allow rule installer in config dialog https://w9p.co/userscripts/mpiv/more_host_rules.html
  10. // @connect w9p.co
  11.  
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_xmlhttpRequest
  15. // @grant GM_openInTab
  16. // @grant GM_registerMenuCommand
  17.  
  18. // @version 1.1.1
  19. // @author tophf
  20.  
  21. // @original-version 2017.9.29
  22. // @original-author kuehlschrank
  23.  
  24. // @supportURL https://github.com/tophf/mpiv/issues
  25. // @homepage https://w9p.co/userscripts/mpiv/
  26. // @icon https://w9p.co/userscripts/mpiv/icon.png
  27. // ==/UserScript==
  28.  
  29. 'use strict';
  30.  
  31. const doc = document;
  32. const hostname = location.hostname;
  33. const dotDomain = '.' + hostname;
  34. const installableSites = ['greatest.deepsurf.us', 'w9p.co', 'github.com'];
  35. const isGoogleDomain = /(^|\.)google(\.com?)?(\.\w+)?$/.test(hostname);
  36. const isGoogleImages = isGoogleDomain && /[&?]tbm=isch(&|$)/.test(location.search);
  37.  
  38. const PREFIX = 'mpiv-';
  39. const STATUS_ATTR = `${PREFIX}status`;
  40. const MSG = Object.assign({}, ...[
  41. 'getViewSize',
  42. 'viewSize',
  43. ].map(k => ({[k]: `${PREFIX}${k}`})));
  44. const WHEEL_EVENT = 'onwheel' in doc ? 'wheel' : 'mousewheel';
  45. const PASSIVE = {passive: true};
  46. // time for volatile things to settle down meanwhile we postpone action
  47. // examples: loading image from cache, quickly moving mouse over one element to another
  48. const SETTLE_TIME = 50;
  49. // used to detect JS code in host rules
  50. const RX_HAS_CODE = /(^|[^-\w])return[\W\s]/;
  51.  
  52. /** @type mpiv.Config */
  53. let cfg;
  54. /** @type mpiv.AppInfo */
  55. let ai = {rule: {}};
  56. /** @type Element */
  57. let elConfig;
  58.  
  59. const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
  60. const compareNumbers = (a, b) => a - b;
  61. const dropEvent = e => (e.preventDefault(), e.stopPropagation());
  62. const ensureArray = v => Array.isArray(v) ? v : [v];
  63. const now = () => performance.now();
  64. const safeIncludes = (a, b) => typeof a === 'string' && a.includes(b);
  65. const sumProps = (...props) => props.reduce((sum, v) => sum + (parseFloat(v) || 0), 0);
  66. const tryCatch = function (fn, ...args) {
  67. try {
  68. return fn.apply(this, args);
  69. } catch (e) {}
  70. };
  71.  
  72. const $ = (s, n = doc) => n.querySelector(s) || 0;
  73. const $$ = (s, n = doc) => n.querySelectorAll(s);
  74. const $create = (tag, props) => Object.assign(document.createElement(tag), props);
  75. const $many = (q, doc) => q && ensureArray(q).reduce((el, sel) => el || $(sel, doc), null);
  76. const $prop = (s, prop, n = doc) => (n.querySelector(s) || 0)[prop] || '';
  77. const $propUp = (n, prop) =>
  78. (n = n.closest(`[${prop}]`)) && (prop.startsWith('data-') ? n.getAttribute(prop) : n[prop]) || '';
  79. const $remove = el => el && el.remove();
  80.  
  81. class App {
  82.  
  83. static init() {
  84. cfg = new Config({save: true});
  85. App.isImageTab = doc.images.length === 1 &&
  86. doc.images[0].parentNode === doc.body &&
  87. !doc.links.length;
  88. App.enabled = cfg.imgtab || !App.isImageTab;
  89.  
  90. GM_registerMenuCommand('MPIV: configure', setup);
  91. doc.addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  92.  
  93. if (isGoogleDomain && doc.getElementById('main'))
  94. doc.getElementById('main').addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  95.  
  96. if (installableSites.includes(hostname)) {
  97. doc.addEventListener('click', e => {
  98. if (hostname === 'github.com' && !location.pathname.startsWith('/tophf/mpiv/')) return;
  99. const el = e.target.closest('blockquote, code, pre');
  100. const text = el && el.textContent.trim();
  101. let rule;
  102. if (text && e.button === 0 &&
  103. /^\s*{\s*"\w+"\s*:[\s\S]+}\s*$/.test(text) &&
  104. (rule = tryCatch(JSON.parse, text))) {
  105. setup({rule});
  106. dropEvent(e);
  107. }
  108. });
  109. }
  110.  
  111. window.addEventListener('message', App.onMessageParent);
  112. }
  113.  
  114. /** @param {MessageEvent} e */
  115. static onMessageParent(e) {
  116. if (typeof e.data === 'string' && e.data === MSG.getViewSize) {
  117. const [w, h] = Util.getFrameSize(e.source, window);
  118. e.source.postMessage(`${MSG.viewSize}:${w}:${h}`, '*');
  119. }
  120. }
  121.  
  122. /** @param {MessageEvent} e */
  123. static onMessageChild(e) {
  124. if (e.source === parent && typeof e.data === 'string' && e.data.startsWith(MSG.viewSize)) {
  125. window.removeEventListener('message', App.onMessageChild);
  126. const [w, h] = e.data.split(':').slice(1).map(parseFloat);
  127. if (w && h) ai.view = {w, h};
  128. }
  129. }
  130.  
  131. static activate(info, event) {
  132. const {match, node, rule, url} = info;
  133. const force = event.ctrlKey;
  134. const scale = !force && Util.findScale(url, node.parentNode);
  135. if (elConfig) console.info(Object.assign({node, rule, url, match}, scale && {scale}));
  136. if (scale && scale < cfg.scale)
  137. return;
  138. if (ai.node)
  139. App.deactivate();
  140. ai = info;
  141. ai.zooming = cfg.css.includes(`${PREFIX}zooming`);
  142. Util.suppressHoverTooltip();
  143. App.updateViewSize();
  144. App.setListeners();
  145. App.updateMouse(event);
  146. if (force) {
  147. Popup.start();
  148. } else if (cfg.start === 'auto' && !rule.manual) {
  149. Popup.schedule();
  150. } else {
  151. App.setStatus('ready');
  152. }
  153. }
  154.  
  155. static checkProgress({start} = {}) {
  156. const p = ai.popup;
  157. if (p) {
  158. ai.nheight = p.naturalHeight || p.videoHeight || ai.popupLoaded && 800;
  159. ai.nwidth = p.naturalWidth || p.videoWidth || ai.popupLoaded && 1200;
  160. if (ai.nheight) {
  161. App.updateProgress();
  162. return;
  163. }
  164. }
  165. if (start)
  166. ai.timerProgress = setInterval(App.checkProgress, 150);
  167. }
  168.  
  169. static deactivate({wait} = {}) {
  170. App.stopTimers();
  171. if (ai.req)
  172. tryCatch.call(ai.req, ai.req.abort);
  173. if (ai.tooltip)
  174. ai.tooltip.node.title = ai.tooltip.text;
  175. App.setStatus(false);
  176. App.setBar(false);
  177. App.setListeners(false);
  178. Popup.destroy();
  179. if (wait) {
  180. App.enabled = false;
  181. setTimeout(App.enable, 200);
  182. }
  183. ai = {rule: {}};
  184. }
  185.  
  186. static enable() {
  187. App.enabled = true;
  188. }
  189.  
  190. static handleError(e, rule = ai.rule) {
  191. const fe = Util.formatError(e, rule);
  192. if (!rule || !ai.urls || !ai.urls.length)
  193. console.warn(fe.consoleFormat, ...fe.consoleArgs);
  194. if (cfg.xhr && !ai.xhr && isGoogleImages) {
  195. ai.xhr = true;
  196. Popup.startSingle();
  197. } else if (ai.urls && ai.urls.length) {
  198. ai.url = ai.urls.shift();
  199. if (ai.url) {
  200. App.stopTimers();
  201. Popup.startSingle();
  202. } else {
  203. App.deactivate();
  204. }
  205. } else if (ai.node) {
  206. App.setStatus('error');
  207. App.setBar(fe.message, 'error');
  208. }
  209. }
  210.  
  211. static setBar(label, className) {
  212. let b = ai.bar;
  213. if (typeof label !== 'string') {
  214. $remove(b);
  215. ai.bar = null;
  216. return;
  217. }
  218. if (!b)
  219. b = ai.bar = $create('div', {id: `${PREFIX}bar`});
  220. App.updateStyles();
  221. App.updateTitle();
  222. App.updateBar();
  223. b.innerHTML = label;
  224. if (!b.parentNode) {
  225. doc.body.appendChild(b);
  226. Util.forceLayout(b);
  227. }
  228. b.className = `${PREFIX}show ${PREFIX}${className}`;
  229. }
  230.  
  231. static setListeners(enable = true) {
  232. const onOff = enable ? doc.addEventListener : doc.removeEventListener;
  233. const passive = enable ? PASSIVE : undefined;
  234. onOff.call(doc, 'mousemove', Events.onMouseMove, passive);
  235. onOff.call(doc, 'mouseout', Events.onMouseOut, passive);
  236. onOff.call(doc, 'mousedown', Events.onMouseDown, passive);
  237. onOff.call(doc, 'contextmenu', Events.onContext);
  238. onOff.call(doc, 'keydown', Events.onKeyDown);
  239. onOff.call(doc, 'keyup', Events.onKeyUp);
  240. onOff.call(doc, WHEEL_EVENT, Events.onMouseScroll, enable ? {passive: false} : undefined);
  241. }
  242.  
  243. static setStatus(status) {
  244. if (!status && !cfg.globalStatus) {
  245. ai.node && ai.node.removeAttribute(STATUS_ATTR);
  246. return;
  247. }
  248. const prefix = cfg.globalStatus ? PREFIX : '';
  249. const action = status && /^[+-]/.test(status) && status[0];
  250. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  251. const el = cfg.globalStatus ? doc.documentElement :
  252. name === 'edge' ? ai.popup :
  253. ai.node;
  254. if (!el) return;
  255. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  256. const oldValue = (el.getAttribute(attr) || '').trim();
  257. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  258. switch (action) {
  259. case '-':
  260. cls.delete(name);
  261. break;
  262. case false:
  263. for (const c of cls)
  264. if (c.startsWith(prefix) && c !== name)
  265. cls.delete(c);
  266. // fallthrough to +
  267. case '+':
  268. if (name)
  269. cls.add(name);
  270. break;
  271. }
  272. const newValue = [...cls].join(' ');
  273. if (newValue !== oldValue)
  274. el.setAttribute(attr, newValue);
  275. }
  276.  
  277. static setStatusLoading(force) {
  278. if (!force) {
  279. clearTimeout(ai.timerStatus);
  280. ai.timerStatus = setTimeout(App.setStatusLoading, SETTLE_TIME, true);
  281. } else if (!ai.popupLoaded) {
  282. App.setStatus('+loading');
  283. }
  284. }
  285.  
  286. static stopTimers() {
  287. clearTimeout(ai.timer);
  288. clearTimeout(ai.timerBar);
  289. clearTimeout(ai.timerStatus);
  290. clearInterval(ai.timerProgress);
  291. }
  292.  
  293. static updateBar() {
  294. clearTimeout(ai.timerBar);
  295. ai.bar.style.removeProperty('opacity');
  296. ai.timerBar = setTimeout(() => ai.bar && ai.bar.style.setProperty('opacity', 0), 3000);
  297. }
  298.  
  299. static updateCaption(text, doc = document) {
  300. switch (typeof ai.rule.c) {
  301. case 'function':
  302. // not specifying as a parameter's default value to get the html only when needed
  303. if (text === undefined)
  304. text = doc.documentElement.outerHTML;
  305. ai.caption = ai.rule.c(text, doc, ai.node, ai.rule);
  306. break;
  307. case 'string': {
  308. const el = $many(ai.rule.c, doc);
  309. ai.caption = !el ? '' :
  310. el.getAttribute('content') ||
  311. el.getAttribute('title') ||
  312. el.textContent;
  313. break;
  314. }
  315. default:
  316. ai.caption = (ai.tooltip || 0).text || ai.node.alt || $propUp(ai.node, 'title') ||
  317. Remoting.getFileName(ai.node.src || $propUp(ai.node, 'href'));
  318. }
  319. }
  320.  
  321. static updateFileInfo() {
  322. const gi = ai.gItems;
  323. if (gi) {
  324. const item = gi[ai.gIndex];
  325. let c = gi.length > 1 ? '[' + (ai.gIndex + 1) + '/' + gi.length + '] ' : '';
  326. if (ai.gIndex === 0 && gi.title && (!item.desc || !safeIncludes(item.desc, gi.title)))
  327. c += gi.title + (item.desc ? ' - ' : '');
  328. if (item.desc)
  329. c += item.desc;
  330. App.setBar(c.trim() || ' ', 'gallery', true);
  331. } else if ('caption' in ai) {
  332. App.setBar(ai.caption, 'caption');
  333. } else if (ai.tooltip) {
  334. App.setBar(ai.tooltip.text, 'tooltip');
  335. } else {
  336. App.setBar(' ', 'info');
  337. }
  338. }
  339.  
  340. static updateMouse(e) {
  341. const cx = ai.clientX = e.clientX;
  342. const cy = ai.clientY = e.clientY;
  343. const r = ai.rect;
  344. if (r)
  345. ai.isOverRect =
  346. cx > r.left - 2 && cx < r.right + 2 &&
  347. cy > r.top - 2 && cy < r.bottom + 2;
  348. }
  349.  
  350. static updateProgress() {
  351. App.stopTimers();
  352. let wait;
  353. if (ai.preloadStart && (wait = ai.preloadStart + cfg.delay - now()) > 0) {
  354. ai.timer = setTimeout(App.checkProgress, wait);
  355. return;
  356. }
  357. if ((ai.urls || 0).length && Math.max(ai.nheight, ai.nwidth) < 130) {
  358. App.handleError({type: 'error'});
  359. return;
  360. }
  361. App.setStatus(false);
  362. Util.forceLayout(ai.popup);
  363. ai.popup.className = `${PREFIX}show`;
  364. App.updateSpacing();
  365. App.updateScales();
  366. if (!(cfg.imgtab && App.isImageTab || cfg.zoom === 'auto') ||
  367. App.zoomToggle({keepScale: true}) === undefined)
  368. Popup.move();
  369. App.updateTitle();
  370. if (!ai.bar)
  371. App.updateFileInfo();
  372. ai.large = ai.nwidth > ai.popup.clientWidth + ai.mbw ||
  373. ai.nheight > ai.popup.clientHeight + ai.mbh;
  374. if (ai.large)
  375. App.setStatus('large');
  376. }
  377.  
  378. static updateScales() {
  379. const fit = Math.min(
  380. (ai.view.w - ai.mbw - ai.outline * 2) / ai.nwidth,
  381. (ai.view.h - ai.mbh - ai.outline * 2) / ai.nheight);
  382. const isCustom = !cfg.fit;
  383. const src = (isCustom && cfg.scales.length ? cfg : Config.DEFAULTS).scales;
  384. const dst = isCustom ? [] : [fit];
  385. let cutoff = Math.min(1, fit);
  386. ai.scaleZoom = cfg.fit === 'all' && fit || cfg.fit === 'no' && 1 || cutoff;
  387. ai.scale = cfg.zoom === 'auto' ? ai.scaleZoom : cutoff;
  388. for (const scale of src) {
  389. const val = parseFloat(scale) || fit;
  390. dst.push(val);
  391. if (isCustom && typeof scale === 'string') {
  392. if (scale.includes('!')) cutoff = val;
  393. if (scale.includes('*')) ai.scaleZoom = val;
  394. }
  395. }
  396. ai.scales = dst.sort(compareNumbers).filter(Util.scaleCut, cutoff);
  397. }
  398.  
  399. static updateSpacing() {
  400. const s = getComputedStyle(ai.popup);
  401. ai.outline = sumProps(s.outlineOffset, s.outlineWidth);
  402. ai.pw = sumProps(s.paddingLeft, s.paddingRight);
  403. ai.ph = sumProps(s.paddingTop, s.paddingBottom);
  404. ai.mbw = sumProps(s.marginLeft, s.marginRight, s.borderLeftWidth, s.borderRightWidth);
  405. ai.mbh = sumProps(s.marginTop, s.marginBottom, s.borderTopWidth, s.borderBottomWidth);
  406. }
  407.  
  408. static updateStyles() {
  409. let cssApp = App.globalStyle;
  410. if (!cssApp) {
  411. cssApp = App.globalStyle = /*language=CSS*/ (String.raw`
  412. #\mpiv-bar {
  413. position: fixed;
  414. z-index: 2147483647;
  415. top: 0;
  416. left: 0;
  417. right: 0;
  418. opacity: 0;
  419. transition: opacity 1s ease .25s;
  420. text-align: center;
  421. font-family: sans-serif;
  422. font-size: 15px;
  423. font-weight: bold;
  424. background: #0005;
  425. color: white;
  426. padding: 4px 10px;
  427. text-shadow: .5px .5px 2px #000;
  428. }
  429. #\mpiv-bar.\mpiv-show {
  430. opacity: 1;
  431. }
  432. #\mpiv-bar[data-zoom]::after {
  433. content: " (" attr(data-zoom) ")";
  434. opacity: .8;
  435. }
  436. #\mpiv-popup.\mpiv-show {
  437. display: inline;
  438. }
  439. #\mpiv-popup {
  440. display: none;
  441. border: none !important;
  442. box-sizing: content-box !important;
  443. position: fixed !important;
  444. z-index: 2147483647 !important;
  445. margin: 0 !important;
  446. top: 0 !important;
  447. left: 0 !important;
  448. width: auto !important;
  449. height: auto !important;
  450. transform-origin: top left !important;
  451. max-width: none !important;
  452. max-height: none !important;
  453. cursor: none;
  454. animation: .2s \mpiv-fadein both;
  455. }
  456. #\mpiv-popup.\mpiv-show {
  457. box-shadow: 6px 6px 30px transparent;
  458. transition: box-shadow .25s, background-color .25s;
  459. }
  460. #\mpiv-popup.\mpiv-show[loaded] {
  461. box-shadow: 6px 6px 30px black;
  462. background-color: white;
  463. }
  464. #\mpiv-popup.\mpiv-zoom-max {
  465. image-rendering: pixelated;
  466. }
  467. @keyframes \mpiv-fadein {
  468. from { opacity: 0; }
  469. to { opacity: 1; }
  470. }
  471. ` + (cfg.globalStatus ? String.raw`
  472. .\mpiv-loading:not(.\mpiv-preloading) * {
  473. cursor: wait !important;
  474. }
  475. .\mpiv-edge #\mpiv-popup {
  476. cursor: default;
  477. }
  478. .\mpiv-error * {
  479. cursor: not-allowed !important;
  480. }
  481. .\mpiv-ready *, .\mpiv-large * {
  482. cursor: zoom-in !important;
  483. }
  484. .\mpiv-shift * {
  485. cursor: default !important;
  486. }
  487. ` : String.raw`
  488. [\mpiv-status~="loading"]:not([\mpiv-status~="preloading"]) {
  489. cursor: wait !important;
  490. }
  491. #\mpiv-popup[\mpiv-status~="edge"] {
  492. cursor: default !important;
  493. }
  494. [\mpiv-status~="error"] {
  495. cursor: not-allowed !important;
  496. }
  497. [\mpiv-status~="ready"],
  498. [\mpiv-status~="large"] {
  499. cursor: zoom-in !important;
  500. }
  501. [\mpiv-status~="shift"] {
  502. cursor: default !important;
  503. }
  504. `)).replace(/\\mpiv-status/g, STATUS_ATTR).replace(/\\mpiv-/g, PREFIX);
  505. }
  506. const {css} = cfg;
  507. Util.addStyle('global', cssApp + (css.includes('{') ? css : `#${PREFIX}-popup {${css}}`));
  508. Util.addStyle('rule', ai.rule.css || '');
  509. }
  510.  
  511. static updateTitle() {
  512. if (!ai.bar) return;
  513. const zoom = ai.nwidth && `${
  514. Math.round(ai.scale * 100)
  515. }%, ${
  516. ai.nwidth
  517. } x ${
  518. ai.nheight
  519. } px, ${
  520. Math.round(100 * (ai.nwidth * ai.nheight / 1e6)) / 100
  521. } MP`.replace(/\x20/g, '\xA0');
  522. if (ai.bar.dataset.zoom !== zoom || !ai.nwidth) {
  523. if (zoom) ai.bar.dataset.zoom = zoom;
  524. else delete ai.bar.dataset.zoom;
  525. App.updateBar();
  526. }
  527. }
  528.  
  529. static updateViewSize() {
  530. const view = doc.compatMode === 'BackCompat' ? doc.body : doc.documentElement;
  531. ai.view = {
  532. w: view.clientWidth,
  533. h: view.clientHeight,
  534. };
  535. if (window === top) return;
  536. const [w, h] = tryCatch(Util.getFrameSize, window, parent) || 0;
  537. if (w && h) {
  538. ai.view = {w, h};
  539. } else {
  540. window.addEventListener('message', App.onMessageChild);
  541. parent.postMessage(MSG.getViewSize, '*');
  542. }
  543. }
  544.  
  545. static zoomToggle({keepScale} = {}) {
  546. const p = ai.popup;
  547. if (!p || !ai.scales || ai.scales.length < 2)
  548. return;
  549. ai.zoom = !ai.zoom;
  550. ai.zoomed = true;
  551. ai.scale = ai.zoom && Util.scaleNextToZoom(keepScale) || ai.scales[0];
  552. if (ai.zooming)
  553. p.classList.add(`${PREFIX}zooming`);
  554. Popup.move();
  555. App.updateTitle();
  556. App.setStatus(ai.zoom ? 'zoom' : false);
  557. if (!ai.zoom)
  558. App.updateFileInfo();
  559. return ai.zoom;
  560. }
  561.  
  562. static zoomInOut(dir) {
  563. const i = Util.findScaleIndex(dir);
  564. const n = ai.scales.length;
  565. if (i >= 0 && i < n)
  566. ai.scale = ai.scales[i];
  567. if (i <= 0 && cfg.zoomOut !== 'stay') {
  568. if ((cfg.zoomOut === 'close' || !ai.isOverRect) && (!ai.gItems || ai.gItems.length < 2)) {
  569. App.deactivate({wait: true});
  570. return;
  571. }
  572. ai.zoom = cfg.zoomOut === 'auto';
  573. ai.zoomed = false;
  574. App.updateFileInfo();
  575. } else {
  576. ai.popup.classList.toggle(`${PREFIX}zoom-max`, ai.scale >= 4 && i >= n - 1);
  577. }
  578. if (ai.zooming)
  579. ai.popup.classList.add(`${PREFIX}zooming`);
  580. Popup.move();
  581. App.updateTitle();
  582. }
  583. }
  584.  
  585. class Config {
  586. constructor({data: c = GM_getValue('cfg'), save}) {
  587. if (typeof c === 'string')
  588. c = tryCatch(JSON.parse, c);
  589. if (typeof c !== 'object' || !c)
  590. c = {};
  591. const {DEFAULTS} = Config;
  592. if (c.version !== DEFAULTS.version) {
  593. if (typeof c.hosts === 'string')
  594. c.hosts = c.hosts.split('\n')
  595. .map(s => tryCatch(JSON.parse, s) || s)
  596. .filter(Boolean);
  597. if (c.close === true || c.close === false)
  598. c.zoomOut = c.close ? 'auto' : 'stay';
  599. for (const key in DEFAULTS)
  600. if (typeof c[key] !== typeof DEFAULTS[key])
  601. c[key] = DEFAULTS[key];
  602. if (c.version === 3 && c.scales[0] === 0)
  603. c.scales[0] = '0!';
  604. for (const key in c)
  605. if (!(key in DEFAULTS))
  606. delete c[key];
  607. c.version = DEFAULTS.version;
  608. if (save)
  609. GM_setValue('cfg', JSON.stringify(c));
  610. }
  611. if (cfg && (
  612. cfg.css !== c.css ||
  613. cfg.globalStatus !== c.globalStatus
  614. )) {
  615. App.globalStyle = '';
  616. }
  617. if (!Array.isArray(c.scales)) c.scales = [];
  618. c.scales = [...new Set(c.scales)].sort((a, b) => parseFloat(a) - parseFloat(b));
  619. c.fit = ['all', 'large', 'no'].includes(c.fit) ? c.fit :
  620. !c.scales.length || `${c.scales}` === `${Config.DEFAULTS.scales}` ? 'large' :
  621. '';
  622. Object.assign(this, c);
  623. }
  624. }
  625.  
  626. /** @type mpiv.Config */
  627. Config.DEFAULTS = Object.assign(Object.create(null), {
  628. center: false,
  629. css: '',
  630. delay: 500,
  631. fit: '',
  632. globalStatus: false,
  633. // prefer ' inside rules because " will be displayed as \"
  634. // example: "img[src*='icon']"
  635. hosts: [{
  636. name: 'No popup for YouTube thumbnails',
  637. d: 'www.youtube.com',
  638. e: 'ytd-rich-item-renderer *, ytd-thumbnail *',
  639. s: '',
  640. }, {
  641. name: 'No popup for SVG/PNG icons',
  642. d: '',
  643. e: "img[src*='icon']",
  644. r: '//[^/]+/.*\\bicons?\\b.*\\.(?:png|svg)',
  645. s: '',
  646. }],
  647. imgtab: false,
  648. preload: false,
  649. scale: 1.25,
  650. scales: ['0!', 0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 4, 5, 8, 16],
  651. start: 'auto',
  652. version: 6,
  653. xhr: true,
  654. zoom: 'context',
  655. zoomOut: 'auto',
  656. });
  657.  
  658. class Ruler {
  659. /*
  660. 'u' works only with URLs so it's ignored if 'html' is true
  661. ||some.domain = matches some.domain, anything.some.domain, etc.
  662. |foo = url or text must start with foo
  663. ^ = separator like / or ? or : but not a letter/number, not %._-
  664. when used at the end like "foo^" it additionally matches when the source ends with "foo"
  665. 'r' is checked only if 'u' matches first
  666. */
  667. static init() {
  668. const errors = new Map();
  669. const customRules = (cfg.hosts || []).map(Ruler.parse, errors);
  670. for (const rule of errors.keys())
  671. App.handleError('Invalid custom host rule:', rule);
  672.  
  673. // rules that disable previewing
  674. const disablers = [
  675. dotDomain.endsWith('.stackoverflow.com') && {
  676. e: '.post-tag, .post-tag img',
  677. s: '',
  678. },
  679. {
  680. u: '||disqus.com/',
  681. s: '',
  682. },
  683. ];
  684.  
  685. // optimization: a rule is created only when on domain
  686. const perDomain = [
  687. hostname.includes('startpage') && {
  688. r: /\boiu=(.+)/,
  689. s: '$1',
  690. follow: true,
  691. },
  692. dotDomain.endsWith('.4chan.org') && {
  693. e: '.is_catalog .thread a[href*="/thread/"], .catalog-thread a[href*="/thread/"]',
  694. q: '.op .fileText a',
  695. css: '#post-preview{display:none}',
  696. },
  697. hostname.includes('amazon.') && {
  698. r: /.+?images\/I\/.+?\./,
  699. s: m => {
  700. const uh = doc.getElementById('universal-hover');
  701. return uh ? '' : m[0] + 'jpg';
  702. },
  703. css: '#zoomWindow{display:none!important;}',
  704. },
  705. dotDomain.endsWith('.bing.com') && {
  706. e: 'a[m*="murl"]',
  707. r: /murl&quot;:&quot;(.+?)&quot;/,
  708. s: '$1',
  709. html: true,
  710. },
  711. dotDomain.endsWith('.deviantart.com') && {
  712. e: '[data-super-full-img] *, img[src*="/th/"]',
  713. s: (m, node) =>
  714. $propUp(node, 'data-super-full-img') ||
  715. (node = node.dataset.embedId && node.nextElementSibling) &&
  716. node.dataset.embedId && node.src,
  717. },
  718. dotDomain.endsWith('.deviantart.com') && {
  719. e: '.dev-view-deviation img',
  720. s: () => [
  721. $('.dev-page-download').href,
  722. $('.dev-content-full').src,
  723. ].filter(Boolean),
  724. },
  725. dotDomain.endsWith('.deviantart.com') && {
  726. u: ',strp/',
  727. s: '/\\/v1\\/.*//',
  728. },
  729. dotDomain.endsWith('.dropbox.com') && {
  730. r: /(.+?&size_mode)=\d+(.*)/,
  731. s: '$1=5$2',
  732. },
  733. dotDomain.endsWith('.facebook.com') && {
  734. e: 'a[href*="ref=hovercard"]',
  735. s: (m, node) =>
  736. 'https://www.facebook.com/photo.php?fbid=' +
  737. /\/[0-9]+_([0-9]+)_/.exec($('img', node).src)[1],
  738. follow: true,
  739. },
  740. dotDomain.endsWith('.facebook.com') && {
  741. r: /(fbcdn|external).*?(app_full_proxy|safe_image).+?(src|url)=(http.+?)[&"']/,
  742. s: (m, node) =>
  743. node.parentNode.className.includes('video') && m[4].includes('fbcdn') ? '' :
  744. decodeURIComponent(m[4]),
  745. html: true,
  746. follow: true,
  747. },
  748. dotDomain.endsWith('.flickr.com') &&
  749. tryCatch(() => unsafeWindow.YUI_config.flickr.api.site_key) && {
  750. r: /flickr\.com\/photos\/[^/]+\/(\d+)/,
  751. s: m => `https://www.flickr.com/services/rest/?${
  752. new URLSearchParams({
  753. photo_id: m[1],
  754. api_key: unsafeWindow.YUI_config.flickr.api.site_key,
  755. method: 'flickr.photos.getSizes',
  756. format: 'json',
  757. nojsoncallback: 1,
  758. }).toString()}`,
  759. q: text => JSON.parse(text).sizes.size.pop().source,
  760. },
  761. dotDomain.endsWith('.github.com') && {
  762. r: new RegExp([
  763. /(avatars.+?&s=)\d+/,
  764. /(raw\.github)(\.com\/.+?\/img\/.+)$/,
  765. /\/(github)(\.com\/.+?\/)blob\/([^/]+\/.+?\.(?:png|jpe?g|bmp|gif|cur|ico))$/,
  766. ].map(rx => rx.source).join('|')),
  767. s: m => `https://${
  768. m[1] ? `${m[1]}460` :
  769. m[2] ? `${m[2]}usercontent${m[3]}` :
  770. `raw.${m[4]}usercontent${m[5]}${m[6]}`
  771. }`,
  772. },
  773. isGoogleImages && {
  774. e: 'a',
  775. r: /imgres\?imgurl=([^&]+)/,
  776. s: '$1',
  777. },
  778. isGoogleImages && {
  779. e: '[data-tbnid] a',
  780. s: (m, node, rule) => {
  781. const id = $propUp(node, 'data-tbnid');
  782. for (const {text} of $$('script', doc)) {
  783. let i = text.indexOf(id);
  784. if (i < 0) continue;
  785. i = text.indexOf('[', i + id.length + 9) + 2;
  786. const url = text.slice(i, text.indexOf('"', i + 1));
  787. if (!url.startsWith('http')) continue;
  788. rule.xhr = !url.startsWith(location.protocol);
  789. return url;
  790. }
  791. },
  792. },
  793. dotDomain.endsWith('.instagram.com') && {
  794. e: [
  795. 'a[href*="/p/"]',
  796. 'a[role="button"][data-reactid*="scontent-"]',
  797. 'article div',
  798. 'article div div img',
  799. ],
  800. s: (m, node, rule) => {
  801. const {a = false, data = false, src} = rule._getData(node);
  802. rule.q = data.is_video && !data.video_url && 'meta[property="og:video"]';
  803. rule.g = a && $('[class*="Carousel"]', a) && rule._g;
  804. rule.follow = !data && !rule.g;
  805. return (
  806. !a && !src ? false :
  807. !data || rule.q || rule.g ? `${src || a.href}${rule.g ? '?__a=1' : ''}` :
  808. data.video_url || data.display_url);
  809. },
  810. c: (html, doc, node, rule) => {
  811. const {data, img} = rule._getData(node);
  812. return tryCatch(rule._getCaption, data) || img && img.alt || '';
  813. },
  814. anonymous: true,
  815. follow: true,
  816. _g(text, doc, url, m, rule) {
  817. const media = JSON.parse(text).graphql.shortcode_media;
  818. const items = media.edge_sidecar_to_children.edges.map(e => ({
  819. url: e.node.video_url || e.node.display_url,
  820. desc: e.node.accessibility_caption || '',
  821. }));
  822. items.title = tryCatch(rule._getCaption, media) || '';
  823. return items;
  824. },
  825. _getCaption: data => data && data.edge_media_to_caption.edges[0].node.text,
  826. _getEdge: shortcode => unsafeWindow._sharedData.entry_data.ProfilePage[0].graphql.user
  827. .edge_owner_to_timeline_media.edges.find(e => e.node.shortcode === shortcode).node,
  828. _getData(node) {
  829. if (location.pathname.startsWith('/p/')) {
  830. const img = $('img[srcset], video', node.parentNode);
  831. if (img && (img.currentSrc || parseFloat(img.sizes) > 900))
  832. return {img, src: (img.srcset || img.currentSrc).split(',').pop().split(' ')[0]};
  833. }
  834. const n = node.closest('a[href*="/p/"], article');
  835. const a = n && (n.tagName === 'A' ? n : $('a[href*="/p/"]', n));
  836. const data = a && tryCatch(this._getEdge, a.pathname.split('/')[2]);
  837. return {a, data};
  838. },
  839. },
  840. ...dotDomain.endsWith('.reddit.com') && [{
  841. u: '||i.reddituploads.com/',
  842. }, {
  843. e: '[data-url*="i.redd.it"] img[src*="thumb"]',
  844. s: (m, node) => $propUp(node, 'data-url'),
  845. }, {
  846. r: /preview(\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  847. s: 'https://i$1',
  848. }] || [],
  849. dotDomain.endsWith('.tumblr.com') && {
  850. e: 'div.photo_stage_img, div.photo_stage > canvas',
  851. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  852. follow: true,
  853. },
  854. dotDomain.endsWith('.tweetdeck.twitter.com') && {
  855. e: 'a.media-item, a.js-media-image-link',
  856. s: (m, node) => /http[^)]+/.exec(node.style.backgroundImage)[0],
  857. follow: true,
  858. },
  859. dotDomain.endsWith('.twitter.com') && {
  860. e: '.grid-tweet > .media-overlay',
  861. s: (m, node) => node.previousElementSibling.src,
  862. follow: true,
  863. },
  864. ];
  865.  
  866. const main = [
  867. {
  868. r: /[/?=](https?[^&]+)/,
  869. s: '$1',
  870. follow: true,
  871. },
  872. {
  873. u: [
  874. '||500px.com/photo/',
  875. '||cl.ly/',
  876. '||cweb-pix.com/',
  877. '||ibb.co/',
  878. '||imgcredit.xyz/image/',
  879. ],
  880. r: /\.\w+\/.+/,
  881. q: 'meta[property="og:image"]',
  882. },
  883. {
  884. u: 'attachment.php',
  885. r: /attachment\.php.+attachmentid/,
  886. },
  887. {
  888. u: '||abload.de/image',
  889. q: '#image',
  890. },
  891. {
  892. u: '||deviantart.com/art/',
  893. s: (m, node) =>
  894. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  895. '' :
  896. m.input,
  897. q: [
  898. '#download-button[href*=".jpg"]',
  899. '#download-button[href*=".jpeg"]',
  900. '#download-button[href*=".gif"]',
  901. '#download-button[href*=".png"]',
  902. '#gmi-ResViewSizer_fullimg',
  903. 'img.dev-content-full',
  904. ],
  905. },
  906. {
  907. u: '||dropbox.com/s',
  908. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  909. q: (text, doc) =>
  910. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  911. },
  912. {
  913. r: /[./]ebay\.[^/]+\/itm\//,
  914. q: text =>
  915. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  916. .replace(/~~60_\d+/, '~~60_57'),
  917. },
  918. {
  919. u: '||i.ebayimg.com/',
  920. s: (m, node) =>
  921. $('.zoom_trigger_mask', node.parentNode) ? '' :
  922. m.input.replace(/~~60_\d+/, '~~60_57'),
  923. },
  924. {
  925. u: [
  926. '||fastpic.ru/big',
  927. '||fastpic.ru/thumb',
  928. ],
  929. r: /\/\/(?:i(\d+)\.)?([^/]+\/)(big|thumb|view)\/([^.]+?)\.(\w+)/,
  930. s: (m, node, rule) => {
  931. const a = node.closest('[href*="fastpic.ru"]');
  932. const am = a && rule.r.exec(decodeURIComponent(a.href)) || [];
  933. const p = a && am[4].split('/');
  934. return `https://i${am[1] || m[1] || am[3] === 'view' && p[0]}.${m[2]}big/${
  935. am[3] === 'big' ? am[4] : m[4]}.${am[5] || m[5]}?noht=1`;
  936. },
  937. xhr: () => 'https://fastpic.ru',
  938. },
  939. {
  940. u: '||fastpic.ru/view/',
  941. q: 'img[src*="/big/"]',
  942. xhr: true,
  943. },
  944. {
  945. u: '||facebook.com/',
  946. r: /photo\.php|[^/]+\/photos\//,
  947. s: (m, node) =>
  948. node.id === 'fbPhotoImage' ? false :
  949. /gradient\.png$/.test(m.input) ? '' :
  950. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  951. q: [
  952. 'div + span > a:first-child:not([href*="tag_faces"])',
  953. 'div + span > a[href*="tag_faces"] ~ a',
  954. ],
  955. rect: '#fbProfileCover',
  956. },
  957. {
  958. u: '||fbcdn.',
  959. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  960. s: m =>
  961. dotDomain.endsWith('.facebook.com') &&
  962. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  963. false,
  964. manual: true,
  965. },
  966. {
  967. u: ['||fbcdn-', 'fbcdn.net/'],
  968. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  969. s: (m, node) => {
  970. if (node.id === 'fbPhotoImage') {
  971. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  972. if (a) return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  973. }
  974. if (m[4])
  975. return false;
  976. const pn = node.parentNode;
  977. if (pn.outerHTML.includes('/hovercard/'))
  978. return '';
  979. if (node.outerHTML.includes('profile') && pn.parentNode.href.includes('/photo'))
  980. return false;
  981. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  982. },
  983. rect: '.photoWrap',
  984. },
  985. {
  986. u: '||flickr.com/photos/',
  987. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  988. s: m =>
  989. m.input.indexOf('/sizes/') < 0 ?
  990. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  991. false,
  992. q: (text, doc) => {
  993. const links = $$('.sizes-list a', doc);
  994. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  995. },
  996. follow: true,
  997. },
  998. {
  999. u: '||flickr.com/photos/',
  1000. r: /\/sizes\//,
  1001. q: '#allsizes-photo > img',
  1002. },
  1003. {
  1004. u: '||gfycat.com/',
  1005. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  1006. s: 'https://$1$3',
  1007. q: [
  1008. 'meta[content$=".webm"]',
  1009. '#webmsource',
  1010. 'source[src$=".webm"]',
  1011. ],
  1012. },
  1013. {
  1014. u: [
  1015. '||googleusercontent.com/proxy',
  1016. '||googleusercontent.com/gadgets/proxy',
  1017. ],
  1018. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  1019. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  1020. },
  1021. {
  1022. u: [
  1023. '||googleusercontent.com/',
  1024. '||ggpht.com/',
  1025. ],
  1026. s: (m, node) =>
  1027. m.input.includes('webcache.') ||
  1028. node.outerHTML.match(/favicons\?|\b(Ol Rf Ep|Ol Zb ag|Zb HPb|Zb Gtb|Rf Pg|ho PQc|Uk wi hE|go wi Wh|we D0b|Bea)\b/) ||
  1029. node.matches('.g-hovercard *, a[href*="profile_redirector"] > img') ?
  1030. '' :
  1031. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  1032. .replace(/=[-\w]+([&#].*|$)/, ''),
  1033. },
  1034. {
  1035. u: '||gravatar.com/',
  1036. r: /([a-z0-9]{32})/,
  1037. s: 'https://gravatar.com/avatar/$1?s=200',
  1038. },
  1039. {
  1040. u: '//gyazo.com/',
  1041. r: /\.com\/\w{32,}/,
  1042. q: 'meta[name="twitter:image"]',
  1043. xhr: true,
  1044. },
  1045. {
  1046. u: '||hostingkartinok.com/show-image.php',
  1047. q: '.image img',
  1048. },
  1049. {
  1050. u: [
  1051. '||imagecurl.com/images/',
  1052. '||imagecurl.com/viewer.php',
  1053. ],
  1054. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1055. s: 'https://imagecurl.com/images/$1$2$3',
  1056. },
  1057. {
  1058. u: '||imagebam.com/image/',
  1059. q: 'meta[property="og:image"]',
  1060. tabfix: true,
  1061. xhr: hostname.includes('planetsuzy'),
  1062. },
  1063. {
  1064. u: '||imageban.ru/thumbs',
  1065. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1066. s: '$1out$2/$3/$4',
  1067. },
  1068. {
  1069. u: [
  1070. '||imageban.ru/show',
  1071. '||imageban.net/show',
  1072. '||ibn.im/',
  1073. ],
  1074. q: '#img_main',
  1075. },
  1076. {
  1077. u: '||imageshack.us/img',
  1078. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1079. s: 'https://$2/download/$1/$3$4',
  1080. },
  1081. {
  1082. u: '||imageshack.us/i/',
  1083. q: '#share-dl',
  1084. },
  1085. {
  1086. u: '||imageteam.org/img',
  1087. q: 'img[alt="image"]',
  1088. },
  1089. {
  1090. u: [
  1091. '||imagetwist.com/',
  1092. '||imageshimage.com/',
  1093. ],
  1094. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1095. q: 'img.pic',
  1096. xhr: true,
  1097. },
  1098. {
  1099. u: '||imageupper.com/i/',
  1100. q: '#img',
  1101. xhr: true,
  1102. },
  1103. {
  1104. u: '||imagevenue.com/img.php',
  1105. q: '#thepic',
  1106. },
  1107. {
  1108. u: '||imagezilla.net/show/',
  1109. q: '#photo',
  1110. xhr: true,
  1111. },
  1112. {
  1113. u: [
  1114. '||images-na.ssl-images-amazon.com/images/',
  1115. '||media-imdb.com/images/',
  1116. ],
  1117. r: /images\/.+?\.jpg/,
  1118. s: '/V1\\.?_.+?\\.//g',
  1119. },
  1120. {
  1121. u: '||imgbox.com/',
  1122. r: /\.com\/([a-z0-9]+)$/i,
  1123. q: '#img',
  1124. xhr: hostname !== 'imgbox.com',
  1125. },
  1126. {
  1127. u: '||imgclick.net/',
  1128. r: /\.net\/(\w+)/,
  1129. q: 'img.pic',
  1130. xhr: true,
  1131. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1132. },
  1133. {
  1134. u: [
  1135. '||imgflip.com/i/',
  1136. '||imgflip.com/gif/',
  1137. ],
  1138. r: /\/(i|gif)\/([^/?#]+)/,
  1139. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1140. },
  1141. {
  1142. u: [
  1143. '||imgur.com/a/',
  1144. '||imgur.com/gallery/',
  1145. '||imgur.com/t/',
  1146. ],
  1147. g: async (text, doc, url, m, rule, cb) => {
  1148. // simplified extraction of JSON as it occupies only one line
  1149. if (!/(?:mergeConfig\('gallery',\s*|Imgur\.Album\.getInstance\()[\s\S]*?[,\s{"'](?:image|album)\s*:\s*({[^\r\n]+?}),?[\r\n]/.test(text))
  1150. return;
  1151. const info = JSON.parse(RegExp.$1);
  1152. let images = info.is_album ? info.album_images.images : [info];
  1153. if (info.num_images > images.length) {
  1154. const url = `https://imgur.com/ajaxalbums/getimages/${info.hash}/hit.json?all=true`;
  1155. images = JSON.parse((await Remoting.gmXhr(url)).responseText).data.images;
  1156. }
  1157. const items = [];
  1158. for (const img of images || []) {
  1159. const u = `https://i.imgur.com/${img.hash}`;
  1160. items.push({
  1161. url: img.ext === '.gif' && img.animated !== false ?
  1162. [`${u}.webm`, `${u}.mp4`, u] :
  1163. u + img.ext,
  1164. desc: [img.title, img.description].filter(Boolean).join(' - '),
  1165. });
  1166. }
  1167. if (images && info.is_album && !safeIncludes(items[0].desc, info.title))
  1168. items.title = info.title;
  1169. cb(items);
  1170. },
  1171. css: '.post > .hover { display:none!important; }',
  1172. },
  1173. {
  1174. u: '||imgur.com/',
  1175. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1176. s: 'gallery',
  1177. g: (text, doc, url, m) =>
  1178. m[2].split(',').map(id => ({
  1179. url: `https://i.${m[1]}${id}.jpg`,
  1180. })),
  1181. },
  1182. {
  1183. u: '||imgur.com/',
  1184. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.([a-z]+))/i,
  1185. s: (m, node) => {
  1186. if (/memegen|random|register|search|signin/.test(m.input))
  1187. return '';
  1188. const a = node.closest('a');
  1189. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1190. return false;
  1191. const id = m[3].replace(/(.{7})[bhm]$/, '$1');
  1192. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1193. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1194. return ext === 'webm' ?
  1195. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1196. u + ext;
  1197. },
  1198. },
  1199. {
  1200. u: [
  1201. '||instagr.am/p/',
  1202. '||instagram.com/p/',
  1203. ],
  1204. s: m => m.input.substr(0, m.input.lastIndexOf('/')) + '/?__a=1',
  1205. q: text => {
  1206. const m = JSON.parse(text).graphql.shortcode_media;
  1207. return m.video_url || m.display_url;
  1208. },
  1209. rect: 'div.PhotoGridMediaItem',
  1210. c: text => {
  1211. const m = JSON.parse(text).graphql.shortcode_media.edge_media_to_caption.edges[0];
  1212. return m === undefined ? '(no caption)' : m.node.text;
  1213. },
  1214. },
  1215. {
  1216. u: [
  1217. '||livememe.com/',
  1218. '||lvme.me/',
  1219. ],
  1220. r: /\.\w+\/([^.]+)$/,
  1221. s: 'http://i.lvme.me/$1.jpg',
  1222. },
  1223. {
  1224. u: '||lostpic.net/image',
  1225. q: '.image-viewer-image img',
  1226. },
  1227. {
  1228. u: '||makeameme.org/meme/',
  1229. r: /\/meme\/([^/?#]+)/,
  1230. s: 'https://media.makeameme.org/created/$1.jpg',
  1231. },
  1232. {
  1233. u: '||photobucket.com/',
  1234. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  1235. s: 'https://i$1$3',
  1236. xhr: !dotDomain.endsWith('.photobucket.com'),
  1237. },
  1238. {
  1239. u: '||piccy.info/view3/',
  1240. r: /(.+?\/view3)\/(.*)\//,
  1241. s: '$1/$2/orig/',
  1242. q: '#mainim',
  1243. },
  1244. {
  1245. u: '||pimpandhost.com/image/',
  1246. r: /(.+?\/image\/[0-9]+)/,
  1247. s: '$1?size=original',
  1248. q: 'img.original',
  1249. },
  1250. {
  1251. u: [
  1252. '||pixroute.com/',
  1253. '||imgspice.com/',
  1254. ],
  1255. r: /\.html$/,
  1256. q: 'img[id]',
  1257. xhr: true,
  1258. },
  1259. {
  1260. u: '||postima',
  1261. r: /postima?ge?\.org\/image\/\w+/,
  1262. q: [
  1263. 'a[href*="dl="]',
  1264. '#main-image',
  1265. ],
  1266. },
  1267. {
  1268. u: [
  1269. '||prntscr.com/',
  1270. '||prnt.sc/',
  1271. ],
  1272. r: /\.\w+\/.+/,
  1273. q: 'meta[property="og:image"]',
  1274. xhr: true,
  1275. },
  1276. {
  1277. u: '||radikal.ru/',
  1278. r: /\.ru\/(fp|.+\.html)/,
  1279. q: text => text.match(/http:\/\/[a-z0-9]+\.radikal\.ru[a-z0-9/]+\.(jpg|gif|png)/i)[0],
  1280. },
  1281. {
  1282. u: '||tumblr.com',
  1283. r: /_500\.jpg/,
  1284. s: ['/_500/_1280/', ''],
  1285. },
  1286. {
  1287. u: '||twimg.com/',
  1288. r: /\/profile_images/i,
  1289. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  1290. },
  1291. {
  1292. u: '||twimg.com/media/',
  1293. r: /.+?format=(jpe?g|png|gif)/i,
  1294. s: '$0&name=large',
  1295. },
  1296. {
  1297. u: '||twimg.com/1/proxy',
  1298. r: /t=([^&_]+)/i,
  1299. s: m => atob(m[1]).match(/http.+/),
  1300. },
  1301. {
  1302. u: '||pic.twitter.com/',
  1303. r: /\.com\/[a-z0-9]+/i,
  1304. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  1305. follow: true,
  1306. },
  1307. {
  1308. u: '||twitpic.com/',
  1309. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  1310. s: 'https://twitpic.com/show/large/$2',
  1311. },
  1312. {
  1313. u: '||upix.me/files',
  1314. s: '/#//',
  1315. },
  1316. {
  1317. u: '||wiki',
  1318. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  1319. s: '/\\/thumb(?=\\/)|' +
  1320. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  1321. '\\/revision\\/latest|\\/[^\\/]+$//g',
  1322. xhr: !hostname.includes('wiki'),
  1323. },
  1324. {
  1325. u: '||ytimg.com/vi/',
  1326. r: /(.+?\/vi\/[^/]+)/,
  1327. s: '$1/0.jpg',
  1328. rect: '.video-list-item',
  1329. },
  1330. {
  1331. u: '/viewer.php?file=',
  1332. r: /(.+?)\/viewer\.php\?file=(.+)/,
  1333. s: '$1/images/$2',
  1334. xhr: true,
  1335. },
  1336. {
  1337. u: '/thumb_',
  1338. r: /\/albums.+\/thumb_[^/]/,
  1339. s: '/thumb_//',
  1340. },
  1341. {
  1342. u: [
  1343. '.th.jp',
  1344. '.th.gif',
  1345. '.th.png',
  1346. ],
  1347. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  1348. s: '$1$2',
  1349. follow: true,
  1350. },
  1351. {
  1352. r: /^[^?]+?\.(bmp|jpe?g?|gif|mp4|png|svg|webm)($|\?)/i,
  1353. },
  1354. ];
  1355.  
  1356. /** @type mpiv.HostRule[] */
  1357. Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean);
  1358. }
  1359.  
  1360. static format(rule, {expand} = {}) {
  1361. const s = JSON.stringify(rule, null, ' ');
  1362. return expand ?
  1363. /* {"a": ...,
  1364. "b": ...,
  1365. "c": ...
  1366. } */
  1367. s.replace(/^{\s+/g, '{') :
  1368. /* {"a": ..., "b": ..., "c": ...} */
  1369. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  1370. }
  1371.  
  1372. /** @returns mpiv.HostRule | Error | false | undefined */
  1373. static parse(rule) {
  1374. const isBatchOp = this instanceof Map;
  1375. try {
  1376. if (typeof rule === 'string')
  1377. rule = JSON.parse(rule);
  1378. if ('d' in rule && typeof rule.d !== 'string')
  1379. rule.d = undefined;
  1380. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  1381. return false;
  1382. const compileTo = isBatchOp ? rule : {};
  1383. if (rule.r)
  1384. compileTo.r = new RegExp(rule.r, 'i');
  1385. if (RX_HAS_CODE.test(rule.s))
  1386. compileTo.s = Util.newFunction('m', 'node', 'rule', rule.s);
  1387. if (RX_HAS_CODE.test(rule.q))
  1388. compileTo.q = Util.newFunction('text', 'doc', 'node', 'rule', rule.q);
  1389. if (RX_HAS_CODE.test(rule.c))
  1390. compileTo.c = Util.newFunction('text', 'doc', 'node', 'rule', rule.c);
  1391. return rule;
  1392. } catch (e) {
  1393. if (!e.message.includes('unsafe-eval'))
  1394. if (isBatchOp) {
  1395. this.set(rule, e);
  1396. } else {
  1397. return e;
  1398. }
  1399. }
  1400. }
  1401.  
  1402. static runQ(text, doc, docUrl) {
  1403. let url;
  1404. if (typeof ai.rule.q === 'function') {
  1405. url = ai.rule.q(text, doc, ai.node, ai.rule);
  1406. if (Array.isArray(url)) {
  1407. ai.urls = url.slice(1);
  1408. url = url[0];
  1409. }
  1410. } else {
  1411. const el = $many(ai.rule.q, doc);
  1412. url = el && Remoting.findImageUrl(el, docUrl);
  1413. }
  1414. return url;
  1415. }
  1416.  
  1417. static runS(node, rule, m) {
  1418. let urls = [];
  1419. for (const s of ensureArray(rule.s))
  1420. urls.push(
  1421. typeof s === 'string' ? Util.maybeDecodeUrl(Ruler.substituteSingle(s, m)) :
  1422. typeof s === 'function' ? s(m, node, rule) :
  1423. s);
  1424. if (rule.q && urls.length > 1) {
  1425. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  1426. return {skipRule: true};
  1427. }
  1428. if (Array.isArray(urls[0]))
  1429. urls = urls[0];
  1430. // `false` returned by "s" property means "skip this rule"
  1431. // any other falsy value (like say "") means "stop all rules"
  1432. return urls[0] === false ? {skipRule: true} : urls.map(Util.maybeDecodeUrl);
  1433. }
  1434.  
  1435. static substituteSingle(s, m) {
  1436. if (!m) return s;
  1437. if (s.startsWith('/') && !s.startsWith('//')) {
  1438. const mid = s.search(/[^\\]\//) + 1;
  1439. const end = s.lastIndexOf('/');
  1440. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  1441. return m.input.replace(re, s.slice(mid + 1, end));
  1442. }
  1443. if (m.length && s.includes('$')) {
  1444. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  1445. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  1446. for (let i = maxLength; i >= 0; i--) {
  1447. const part = num.slice(0, i) | 0;
  1448. if (part < m.length)
  1449. return (m[part] || '') + num.slice(i);
  1450. }
  1451. return text;
  1452. });
  1453. }
  1454. return s;
  1455. }
  1456. }
  1457.  
  1458. const SimpleUrlMatcher = (() => {
  1459. // string-to-regexp escaped chars
  1460. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  1461. // rx for '^' symbol in simple url match
  1462. const RX_SEP = /[^\w%._-]/g;
  1463. const RXS_SEP = RX_SEP.source;
  1464. return match => {
  1465. const results = [];
  1466. for (const s of ensureArray(match)) {
  1467. const pinDomain = s.startsWith('||');
  1468. const pinStart = !pinDomain && s.startsWith('|');
  1469. const endSep = s.endsWith('^');
  1470. let fn;
  1471. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  1472. if (needle.includes('^')) {
  1473. const plain = findLongestPart(needle);
  1474. const rx = new RegExp(
  1475. (pinStart ? '^' : '') +
  1476. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  1477. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  1478. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  1479. needle = [plain, rx];
  1480. fn = regexp;
  1481. } else if (pinStart) {
  1482. fn = endSep ? equals : starts;
  1483. } else if (pinDomain) {
  1484. const slashPos = needle.indexOf('/');
  1485. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  1486. needle = [needle, domain, slashPos > 0, endSep];
  1487. fn = startsDomainPrescreen;
  1488. } else if (endSep) {
  1489. fn = ends;
  1490. } else {
  1491. fn = has;
  1492. }
  1493. results.push({fn, this: needle});
  1494. }
  1495. return results.length > 1 ?
  1496. {fn: checkArray, this: results} :
  1497. results[0];
  1498. };
  1499. function checkArray(s) {
  1500. return this.some(checkArrayItem, s);
  1501. }
  1502. function checkArrayItem(item) {
  1503. return item.fn.call(item.this, this);
  1504. }
  1505. function equals(s) {
  1506. return s.startsWith(this) && (
  1507. s.length === this.length ||
  1508. s.length === this.length + 1 && endsWithSep(s));
  1509. }
  1510. function starts(s) {
  1511. return s.startsWith(this);
  1512. }
  1513. function ends(s) {
  1514. return s.endsWith(this) || (
  1515. s.length > this.length &&
  1516. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  1517. endsWithSep(s));
  1518. }
  1519. function has(s) {
  1520. return s.includes(this);
  1521. }
  1522. function regexp(s) {
  1523. return s.includes(this[0]) && this[1].test(s);
  1524. }
  1525. function endsWithSep(s) {
  1526. RX_SEP.lastIndex = s.length - 1;
  1527. return RX_SEP.test(s);
  1528. }
  1529. function startsDomainPrescreen(url) {
  1530. return url.includes(this[0]) && startsDomain.call(this, url);
  1531. }
  1532. function startsDomain(url) {
  1533. const [p, gap, host] = url.split('/', 3);
  1534. if (gap || p && !p.endsWith(':'))
  1535. return;
  1536. const [needle, domain, pinDomainEnd, endSep] = this;
  1537. let start = pinDomainEnd ? host.length - domain.length : 0;
  1538. for (; ; start++) {
  1539. start = host.indexOf(domain, start);
  1540. if (start < 0)
  1541. return;
  1542. if (!start || host[start - 1] === '.')
  1543. break;
  1544. }
  1545. start += p.length + 2;
  1546. return url.lastIndexOf(needle, start) === start &&
  1547. (!endSep || start + needle.length === url.length);
  1548. }
  1549. function findLongestPart(s) {
  1550. const len = s.length;
  1551. let maxLen = 0;
  1552. let start;
  1553. for (let i = 0, j; i < len; i = j + 1) {
  1554. j = s.indexOf('^', i);
  1555. if (j < 0)
  1556. j = len;
  1557. if (j - i > maxLen) {
  1558. maxLen = j - i;
  1559. start = i;
  1560. }
  1561. }
  1562. return maxLen < len ? s.substr(start, maxLen) : s;
  1563. }
  1564. })();
  1565.  
  1566. class RuleMatcher {
  1567.  
  1568. /** @returns ?mpiv.RuleMatchInfo */
  1569. static findForLink(a) {
  1570. let url =
  1571. a.getAttribute('data-expanded-url') ||
  1572. a.getAttribute('data-full-url') ||
  1573. a.getAttribute('data-url') ||
  1574. a.href;
  1575. if (url.startsWith('data:'))
  1576. url = false;
  1577. else if (url.includes('//t.co/'))
  1578. url = 'http://' + a.textContent;
  1579. return RuleMatcher.find(url, a);
  1580. }
  1581.  
  1582. /** @returns ?mpiv.RuleMatchInfo */
  1583. static find(url, node, {noHtml, skipRule} = {}) {
  1584. const tn = node.tagName;
  1585. let m, html, urls;
  1586. for (const rule of Ruler.rules) {
  1587. const {e} = rule;
  1588. if (e && !node.matches(e) || rule === skipRule)
  1589. continue;
  1590. const {r, u} = rule;
  1591. if (r && !noHtml && rule.html && ('A,IMG,VIDEO'.includes(tn) || e))
  1592. m = r.exec(html || (html = node.outerHTML));
  1593. else if (r || u)
  1594. m = url && RuleMatcher.makeUrlMatch(url, node, rule, r, u);
  1595. else
  1596. m = url ? RuleMatcher.makeDummyMatch(url) : [];
  1597. if (!m ||
  1598. // a rule with follow:true for the currently hovered IMG produced a URL,
  1599. // but we'll only allow it to match rules without 's' in the nested find call
  1600. 'IMG,VIDEO'.includes(tn) && !('s' in rule) && !skipRule)
  1601. continue;
  1602. if (rule.s === '')
  1603. return {};
  1604. const hasS = 's' in rule && rule.s !== 'gallery';
  1605. urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  1606. if (!urls.skipRule) {
  1607. const url = urls[0];
  1608. return !url ? {} :
  1609. hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule) ?
  1610. RuleMatcher.find(url, node, {skipRule: rule}) :
  1611. RuleMatcher.makeInfo(urls, node, rule, m);
  1612. }
  1613. }
  1614. }
  1615.  
  1616. static makeUrlMatch(url, node, rule, r, u) {
  1617. let m;
  1618. if (u) {
  1619. u = rule._u || (rule._u = SimpleUrlMatcher(u));
  1620. m = u.fn.call(u.this, url) && (r || RuleMatcher.makeDummyMatch(url));
  1621. }
  1622. return (m || !u) && r ? r.exec(url) : m;
  1623. }
  1624.  
  1625. static makeDummyMatch(url) {
  1626. const m = [url];
  1627. m.index = 0;
  1628. m.input = url;
  1629. return m;
  1630. }
  1631.  
  1632. /** @returns mpiv.RuleMatchInfo */
  1633. static makeInfo(urls, node, rule, m) {
  1634. const url = urls[0];
  1635. const info = {
  1636. node,
  1637. rule,
  1638. url,
  1639. urls: urls.length > 1 ? urls.slice(1) : null,
  1640. match: m,
  1641. gallery: rule.g && Gallery.makeParser(rule.g),
  1642. post: typeof rule.post === 'function' ? rule.post(m) : rule.post,
  1643. xhr: cfg.xhr && rule.xhr,
  1644. };
  1645. Util.lazyGetRect(info, node, rule.rect);
  1646. if (
  1647. dotDomain.endsWith('.twitter.com') && !/(facebook|google|twimg|twitter)\.com\//.test(url) ||
  1648. dotDomain.endsWith('.github.com') && !/github/.test(url) ||
  1649. dotDomain.endsWith('.facebook.com') && /\bimgur\.com/.test(url)
  1650. ) {
  1651. info.xhr = 'data';
  1652. }
  1653. return info;
  1654. }
  1655.  
  1656. static isFollowableUrl(url, rule) {
  1657. const f = rule.follow;
  1658. return typeof f === 'function' ? f(url) : f;
  1659. }
  1660. }
  1661.  
  1662. class Events {
  1663.  
  1664. static onMouseOver(e) {
  1665. if (!App.enabled || e.shiftKey || ai.zoom)
  1666. return;
  1667. let node = e.target;
  1668. if (node === ai.popup ||
  1669. node === doc.body ||
  1670. node === doc.documentElement)
  1671. return;
  1672. if (node.shadowRoot)
  1673. node = Events.pierceShadow(node, e.clientX, e.clientY);
  1674. if (!Ruler.rules)
  1675. Ruler.init();
  1676. let a;
  1677. const tag = node.tagName;
  1678. const src = node.currentSrc || node.src;
  1679. const isPic = tag === 'IMG' || tag === 'VIDEO' && /\.(webm|mp4)(\?|$)/.test(src);
  1680. const info =
  1681. tag !== 'A' &&
  1682. RuleMatcher.find(isPic && Util.rel2abs(src), node) ||
  1683. (a = node.closest('A')) &&
  1684. RuleMatcher.findForLink(a) ||
  1685. isPic &&
  1686. Util.lazyGetRect({node, rule: {}, url: src}, node);
  1687. if (info && info.url && info.node !== ai.node)
  1688. App.activate(info, e);
  1689. }
  1690.  
  1691. static pierceShadow(node, x, y) {
  1692. for (let root; (root = node.shadowRoot);) {
  1693. root.addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  1694. root.addEventListener('mouseout', Events.onMouseOutShadow);
  1695. const inner = root.elementFromPoint(x, y);
  1696. if (!inner || inner === node)
  1697. break;
  1698. node = inner;
  1699. }
  1700. return node;
  1701. }
  1702.  
  1703. static onMouseOut(e) {
  1704. if (!e.relatedTarget && !e.shiftKey)
  1705. App.deactivate();
  1706. }
  1707.  
  1708. static onMouseOutShadow(e) {
  1709. const root = e.target.shadowRoot;
  1710. if (root) {
  1711. root.removeEventListener('mouseover', Events.onMouseOver);
  1712. root.removeEventListener('mouseout', Events.onMouseOutShadow);
  1713. }
  1714. }
  1715.  
  1716. static onMouseMove(e) {
  1717. App.updateMouse(e);
  1718. if (e.shiftKey) {
  1719. ai.lazyUnload = true;
  1720. } else if (!ai.zoomed && !ai.isOverRect) {
  1721. App.deactivate();
  1722. } else if (ai.zoom) {
  1723. Popup.move();
  1724. const {w, h} = ai.view;
  1725. const {clientX: cx, clientY: cy} = ai;
  1726. const bx = w / 6;
  1727. const by = h / 6;
  1728. const onEdge = cx < bx || cx > w - bx || cy < by || cy > h - by;
  1729. App.setStatus(`${onEdge ? '+' : '-'}edge`);
  1730. }
  1731. }
  1732.  
  1733. static onMouseDown({shiftKey, button}) {
  1734. if (button === 0 && shiftKey && ai.popup && ai.popup.controls) {
  1735. ai.controlled = ai.zoomed = true;
  1736. } else if (button === 2 || shiftKey) {
  1737. // we ignore RMB and Shift
  1738. } else {
  1739. App.deactivate({wait: true});
  1740. }
  1741. }
  1742.  
  1743. static onMouseScroll(e) {
  1744. const dir = (e.deltaY || -e.wheelDelta) < 0 ? 1 : -1;
  1745. if (ai.zoom) {
  1746. App.zoomInOut(dir);
  1747. } else if (ai.gItems && ai.gItems.length > 1 && ai.popup) {
  1748. Gallery.next(dir);
  1749. } else if (cfg.zoom === 'wheel' && dir > 0 && ai.popup) {
  1750. App.zoomToggle();
  1751. } else {
  1752. App.deactivate();
  1753. return;
  1754. }
  1755. dropEvent(e);
  1756. }
  1757.  
  1758. static onKeyDown(e) {
  1759. switch (e.key) {
  1760. case 'Shift':
  1761. App.setStatus('+shift');
  1762. if (ai.popup && 'controls' in ai.popup)
  1763. ai.popup.controls = true;
  1764. break;
  1765. case 'Control':
  1766. if (!ai.popup && (cfg.start !== 'auto' || ai.rule.manual))
  1767. Popup.start();
  1768. break;
  1769. }
  1770. }
  1771.  
  1772. static onKeyUp(e) {
  1773. switch (e.key.length > 1 ? e.key : e.code) {
  1774. case 'Shift':
  1775. App.setStatus('-shift');
  1776. if ((ai.popup || {}).controls)
  1777. ai.popup.controls = false;
  1778. if (ai.controlled) {
  1779. ai.controlled = false;
  1780. return;
  1781. }
  1782. ai.popup && (ai.zoomed || ai.isOverRect !== false) ?
  1783. App.zoomToggle() :
  1784. App.deactivate({wait: true});
  1785. break;
  1786. case 'Control':
  1787. break;
  1788. case 'Escape':
  1789. App.deactivate({wait: true});
  1790. break;
  1791. case 'ArrowRight':
  1792. case 'KeyJ':
  1793. dropEvent(e);
  1794. Gallery.next(1);
  1795. break;
  1796. case 'ArrowLeft':
  1797. case 'KeyK':
  1798. dropEvent(e);
  1799. Gallery.next(-1);
  1800. break;
  1801. case 'KeyD': {
  1802. dropEvent(e);
  1803. Remoting.saveFile();
  1804. break;
  1805. }
  1806. case 'KeyT':
  1807. ai.lazyUnload = true;
  1808. GM_openInTab(
  1809. ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  1810. navigator.userAgent.includes('Gecko/') ?
  1811. Util.tabFixUrl() :
  1812. ai.popup.src);
  1813. App.deactivate();
  1814. break;
  1815. default:
  1816. App.deactivate({wait: true});
  1817. }
  1818. }
  1819.  
  1820. static onContext(e) {
  1821. if (e.shiftKey) return;
  1822. if (cfg.zoom === 'context' && ai.popup && App.zoomToggle()) {
  1823. dropEvent(e);
  1824. } else if (!ai.popup && (cfg.start === 'context' || (cfg.start === 'auto' && ai.rule.manual))) {
  1825. Popup.start();
  1826. dropEvent(e);
  1827. } else {
  1828. setTimeout(App.deactivate, SETTLE_TIME, {wait: true});
  1829. }
  1830. }
  1831. }
  1832.  
  1833. class Popup {
  1834.  
  1835. static schedule(force) {
  1836. if (!cfg.preload) {
  1837. ai.timer = setTimeout(Popup.start, cfg.delay);
  1838. } else if (!force) {
  1839. // we don't want to preload everything in the path of a quickly moving mouse cursor
  1840. ai.timer = setTimeout(Popup.schedule, SETTLE_TIME, true);
  1841. ai.preloadStart = now();
  1842. } else {
  1843. Popup.start();
  1844. App.setStatus('+preloading');
  1845. setTimeout(App.setStatus, cfg.delay, '-preloading');
  1846. }
  1847. }
  1848.  
  1849. static start() {
  1850. App.updateStyles();
  1851. ai.gallery ?
  1852. Popup.startGallery() :
  1853. Popup.startSingle();
  1854. }
  1855.  
  1856. static startSingle() {
  1857. App.setStatusLoading();
  1858. ai.imageUrl = null;
  1859. if (ai.rule.follow && !ai.rule.q && !ai.rule.s) {
  1860. Remoting.findRedirect();
  1861. } else if (ai.rule.q && !Array.isArray(ai.urls)) {
  1862. Popup.startFromQ();
  1863. } else {
  1864. App.updateCaption();
  1865. Popup.render(ai.url);
  1866. }
  1867. }
  1868.  
  1869. static async startFromQ() {
  1870. try {
  1871. const {responseText, doc, finalUrl} = await Remoting.getDoc(ai.url);
  1872. const url = Ruler.runQ(responseText, doc, finalUrl);
  1873. if (!url)
  1874. throw 'File not found.';
  1875. App.updateCaption(responseText, doc);
  1876. if (RuleMatcher.isFollowableUrl(url, ai.rule)) {
  1877. const info = RuleMatcher.find(url, ai.node, {noHtml: true});
  1878. if (!info || !info.url)
  1879. throw `Couldn't follow URL: ${url}`;
  1880. Object.assign(ai, info);
  1881. Popup.startSingle();
  1882. } else {
  1883. Popup.render(url, finalUrl);
  1884. }
  1885. } catch (e) {
  1886. App.handleError(e);
  1887. }
  1888. }
  1889.  
  1890. static async startGallery() {
  1891. App.setStatusLoading();
  1892. try {
  1893. const startUrl = ai.url;
  1894. const p = ai.rule.s === 'gallery' ? {} : await Remoting.getDoc(startUrl);
  1895. const items = await new Promise(resolve => {
  1896. const it = ai.gallery(p.responseText, p.doc, p.finalUrl, ai.match, ai.rule, resolve);
  1897. if (Array.isArray(it))
  1898. resolve(it);
  1899. });
  1900. // bail out if the gallery's async callback took too long
  1901. if (ai.url !== startUrl) return;
  1902. ai.gItems = items.length && items;
  1903. if (ai.gItems) {
  1904. ai.gIndex = Gallery.findIndex(ai.url);
  1905. setTimeout(Gallery.next);
  1906. } else {
  1907. throw 'Empty gallery';
  1908. }
  1909. } catch (e) {
  1910. App.handleError(e);
  1911. }
  1912. }
  1913.  
  1914. static async render(src, pageUrl) {
  1915. Popup.destroy();
  1916. ai.imageUrl = src;
  1917. if (ai.xhr && src)
  1918. src = await Remoting.getImage(src, pageUrl).catch(App.handleError);
  1919. if (!src) return;
  1920. const p = ai.popup =
  1921. src.startsWith('data:video') ||
  1922. !src.startsWith('data:') && /\.(webm|mp4)($|\?)/.test(src) ?
  1923. PopupVideo.create() :
  1924. $create('img');
  1925. p.id = `${PREFIX}popup`;
  1926. p.src = src;
  1927. p.addEventListener('error', App.handleError);
  1928. p.addEventListener('load', Popup.onLoad, {once: true});
  1929. if (ai.zooming)
  1930. p.addEventListener('transitionend', Popup.onZoom);
  1931. doc.body.insertBefore(p, ai.bar || undefined);
  1932. await 0;
  1933. App.checkProgress({start: true});
  1934. }
  1935.  
  1936. static onLoad() {
  1937. this.setAttribute('loaded', '');
  1938. ai.popupLoaded = true;
  1939. if (!ai.bar)
  1940. App.updateFileInfo();
  1941. }
  1942.  
  1943. static onZoom() {
  1944. this.classList.remove(`${PREFIX}zooming`);
  1945. }
  1946.  
  1947. static move() {
  1948. const p = ai.popup;
  1949. if (!p) return;
  1950. let x, y;
  1951. const w = Math.round(ai.scale * ai.nwidth);
  1952. const h = Math.round(ai.scale * ai.nheight);
  1953. const cx = ai.clientX;
  1954. const cy = ai.clientY;
  1955. const vw = ai.view.w - ai.outline * 2;
  1956. const vh = ai.view.h - ai.outline * 2;
  1957. if (!ai.zoom && (!ai.gItems || ai.gItems.length < 2) && !cfg.center) {
  1958. const r = ai.rect;
  1959. const rx = (r.left + r.right) / 2;
  1960. const ry = (r.top + r.bottom) / 2;
  1961. if (vw - r.right - 40 > w + ai.mbw || w + ai.mbw < r.left - 40) {
  1962. if (h + ai.mbh < vh - 60)
  1963. y = clamp(ry - h / 2, 30, vh - h - 30);
  1964. x = rx > vw / 2 ? r.left - 40 - w : r.right + 40;
  1965. } else if (vh - r.bottom - 40 > h + ai.mbh || h + ai.mbh < r.top - 40) {
  1966. if (w + ai.mbw < vw - 60)
  1967. x = clamp(rx - w / 2, 30, vw - w - 30);
  1968. y = ry > vh / 2 ? r.top - 40 - h : r.bottom + 40;
  1969. }
  1970. }
  1971. if (x === undefined) {
  1972. const mid = vw > w ?
  1973. vw / 2 - w / 2 :
  1974. -1 * clamp(5 / 3 * (cx / vw - 0.2), 0, 1) * (w - vw);
  1975. x = Math.round(mid - (ai.pw + ai.mbw) / 2);
  1976. }
  1977. if (y === undefined) {
  1978. const mid = vh > h ?
  1979. vh / 2 - h / 2 :
  1980. -1 * clamp(5 / 3 * (cy / vh - 0.2), 0, 1) * (h - vh);
  1981. y = Math.round(mid - (ai.ph + ai.mbh) / 2);
  1982. }
  1983. p.style.setProperty('transform',
  1984. `translate(${x + ai.outline}px, ${y + ai.outline}px) scale(${ai.scale})`, 'important');
  1985. }
  1986.  
  1987. static destroy() {
  1988. const p = ai.popup;
  1989. if (!p) return;
  1990. p.removeEventListener('error', App.handleError);
  1991. if (typeof p.pause === 'function')
  1992. p.pause();
  1993. if (!ai.lazyUnload) {
  1994. if (p.src.startsWith('blob:'))
  1995. URL.revokeObjectURL(p.src);
  1996. p.src = '';
  1997. }
  1998. p.remove();
  1999. ai.zoom = ai.popup = ai.popupLoaded = null;
  2000. }
  2001. }
  2002.  
  2003. class PopupVideo {
  2004. static create() {
  2005. const p = $create('video');
  2006. p.autoplay = true;
  2007. p.loop = true;
  2008. p.volume = 0.5;
  2009. p.controls = false;
  2010. p.addEventListener('progress', PopupVideo.progress);
  2011. p.addEventListener('canplaythrough', PopupVideo.progressDone, {once: true});
  2012. ai.bufBar = false;
  2013. ai.bufStart = now();
  2014. return p;
  2015. }
  2016.  
  2017. static progress() {
  2018. const {duration} = this;
  2019. if (duration && this.buffered.length && now() - ai.bufStart > 2000) {
  2020. const pct = Math.round(this.buffered.end(0) / duration * 100);
  2021. if ((ai.bufBar |= pct > 0 && pct < 50))
  2022. App.setBar(`${pct}% of ${Math.round(duration)}s`, 'xhr');
  2023. }
  2024. }
  2025.  
  2026. static async progressDone() {
  2027. this.removeEventListener('progress', PopupVideo.progress);
  2028. if (ai.bar && ai.bar.classList.contains(`${PREFIX}xhr`)) {
  2029. App.setBar(false);
  2030. App.updateFileInfo();
  2031. }
  2032. try {
  2033. await this.play();
  2034. } catch (e) {
  2035. if (this.paused) this.controls = true;
  2036. }
  2037. }
  2038. }
  2039.  
  2040. class Gallery {
  2041.  
  2042. static makeParser(g) {
  2043. return (
  2044. typeof g === 'function' ? g :
  2045. typeof g === 'string' ? Util.newFunction('text', 'doc', 'url', 'm', 'rule', 'cb', g) :
  2046. Gallery.defaultParser
  2047. );
  2048. }
  2049.  
  2050. static findIndex(gUrl) {
  2051. const sel = gUrl.split('#')[1];
  2052. if (!sel)
  2053. return 0;
  2054. if (/^\d+$/.test(sel))
  2055. return parseInt(sel);
  2056. for (let i = ai.gItems.length; i--;) {
  2057. let {url} = ai.gItems[i];
  2058. if (Array.isArray(url))
  2059. url = url[0];
  2060. if (url.indexOf(sel, url.lastIndexOf('/')) > 0)
  2061. return i;
  2062. }
  2063. return 0;
  2064. }
  2065.  
  2066. static next(dir) {
  2067. if (dir < 0 && (ai.gIndex -= dir) >= ai.gItems.length) {
  2068. ai.gIndex = 0;
  2069. } else if (dir > 0 && (ai.gIndex -= dir) < 0) {
  2070. ai.gIndex = ai.gItems.length - 1;
  2071. }
  2072. const item = ai.gItems[ai.gIndex];
  2073. if (Array.isArray(item.url)) {
  2074. ai.urls = item.url.slice(1);
  2075. ai.url = item.url[0];
  2076. } else {
  2077. ai.urls = null;
  2078. ai.url = item.url;
  2079. }
  2080. Popup.destroy();
  2081. Popup.startSingle();
  2082. App.updateFileInfo();
  2083. Gallery.preload(dir);
  2084. }
  2085.  
  2086. static preload(dir) {
  2087. const i = ai.gIndex - dir;
  2088. if (ai.popup && i >= 0 && i < ai.gItems.length) {
  2089. ai.preloadUrl = ensureArray(ai.gItems[i].url)[0];
  2090. ai.popup.addEventListener('load', Gallery.preloadOnLoad, {once: true});
  2091. }
  2092. }
  2093.  
  2094. static preloadOnLoad() {
  2095. $create('img', {src: ai.preloadUrl});
  2096. }
  2097.  
  2098. static defaultParser(text, doc, docUrl, m, rule) {
  2099. const {g} = rule;
  2100. const qEntry = g.entry;
  2101. const qCaption = ensureArray(g.caption);
  2102. const qImage = g.image;
  2103. const qTitle = g.title;
  2104. const fix =
  2105. (typeof g.fix === 'string' ? Util.newFunction('s', 'isURL', g.fix) : g.fix) ||
  2106. (s => s.trim());
  2107. const items = [...$$(qEntry || qImage, doc)]
  2108. .map(processEntry)
  2109. .filter(Boolean);
  2110. items.title = processTitle();
  2111. return items;
  2112.  
  2113. function processEntry(entry) {
  2114. const item = {};
  2115. try {
  2116. const img = qEntry ? $(qImage, entry) : entry;
  2117. item.url = fix(Remoting.findImageUrl(img, docUrl), true);
  2118. item.desc = qCaption.map(processCaption, entry).filter(Boolean).join(' - ');
  2119. } catch (e) {}
  2120. return item.url && item;
  2121. }
  2122.  
  2123. function processCaption(selector) {
  2124. const el = $(selector, this) ||
  2125. $orSelf(selector, this.previousElementSibling) ||
  2126. $orSelf(selector, this.nextElementSibling);
  2127. return el && fix(el.textContent);
  2128. }
  2129.  
  2130. function processTitle() {
  2131. const el = $(qTitle, doc);
  2132. return el && fix(el.getAttribute('content') || el.textContent) || '';
  2133. }
  2134.  
  2135. function $orSelf(selector, el) {
  2136. if (el && !el.matches(qEntry))
  2137. return el.matches(selector) ? el : $(selector, el);
  2138. }
  2139. }
  2140. }
  2141.  
  2142. class Remoting {
  2143.  
  2144. static gmXhr(url, opts = {}) {
  2145. if (ai.req)
  2146. tryCatch.call(ai.req, ai.req.abort);
  2147. return new Promise((resolve, reject) => {
  2148. ai.req = GM_xmlhttpRequest({
  2149. url,
  2150. method: 'GET',
  2151. anonymous: (ai.rule || {}).anonymous,
  2152. timeout: 10e3,
  2153. ...opts,
  2154. onload: done,
  2155. onerror: done,
  2156. ontimeout() {
  2157. ai.req = null;
  2158. reject(`Timeout fetching ${url}`);
  2159. },
  2160. });
  2161. function done(r) {
  2162. ai.req = null;
  2163. r.status < 400 && !r.error ?
  2164. resolve(r) :
  2165. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2166. }
  2167. });
  2168. }
  2169.  
  2170. static async getDoc(url) {
  2171. const r = await (!ai.post ?
  2172. Remoting.gmXhr(url) :
  2173. Remoting.gmXhr(url, {
  2174. method: 'POST',
  2175. data: ai.post,
  2176. headers: {
  2177. 'Content-Type': 'application/x-www-form-urlencoded',
  2178. 'Referer': url,
  2179. },
  2180. }));
  2181. r.doc = new DOMParser().parseFromString(r.responseText, 'text/html');
  2182. return r;
  2183. }
  2184.  
  2185. static async getImage(url, pageUrl) {
  2186. ai.bufBar = false;
  2187. ai.bufStart = now();
  2188. const response = await Remoting.gmXhr(url, {
  2189. responseType: 'blob',
  2190. headers: {
  2191. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2192. Referer: pageUrl || (typeof ai.xhr === 'function' ? ai.xhr() : url),
  2193. },
  2194. onprogress: Remoting.getImageProgress,
  2195. });
  2196. App.setBar(false);
  2197. const type = Remoting.guessMimeType(response);
  2198. let b = response.response;
  2199. if (b.type !== type)
  2200. b = b.slice(0, b.size, type);
  2201. return ai.xhr === 'data' ?
  2202. Remoting.blobToDataUrl(b) :
  2203. URL.createObjectURL(b);
  2204. }
  2205.  
  2206. static getImageProgress(e) {
  2207. if (!ai.bufBar && now() - ai.bufStart > 3000 && e.loaded / e.total < 0.5)
  2208. ai.bufBar = true;
  2209. if (ai.bufBar) {
  2210. const pct = e.loaded / e.total * 100 | 0;
  2211. const size = e.total / 1024 | 0;
  2212. App.setBar(`${pct}% of ${size} kiB`, 'xhr');
  2213. }
  2214. }
  2215.  
  2216. static async findRedirect() {
  2217. try {
  2218. const {finalUrl} = await Remoting.gmXhr(ai.url, {
  2219. method: 'HEAD',
  2220. headers: {
  2221. 'Referer': location.href.split('#', 1)[0],
  2222. },
  2223. });
  2224. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2225. if (!info || !info.url)
  2226. throw `Couldn't follow redirection target: ${finalUrl}`;
  2227. Object.assign(ai, info);
  2228. Popup.startSingle();
  2229. } catch (e) {
  2230. App.handleError(e);
  2231. }
  2232. }
  2233.  
  2234. static async saveFile() {
  2235. let url = ai.popup.src || ai.popup.currentSrc;
  2236. let name = Remoting.getFileName(ai.imageUrl || url);
  2237. if (!name.includes('.'))
  2238. name += '.jpg';
  2239. try {
  2240. if (!url.startsWith('blob:') && !url.startsWith('data:')) {
  2241. const {response} = await Remoting.gmXhr(url, {
  2242. responseType: 'blob',
  2243. headers: {'Referer': url},
  2244. });
  2245. url = URL.createObjectURL(response);
  2246. setTimeout(() => URL.revokeObjectURL(url), 1000);
  2247. }
  2248. $create('a', {href: url, download: name})
  2249. .dispatchEvent(new MouseEvent('click'));
  2250. } catch (e) {
  2251. App.setBar(`Could not download ${name}.`, 'error');
  2252. }
  2253. }
  2254.  
  2255. static getFileName(url) {
  2256. return decodeURIComponent(url).split('/').pop().replace(/[:#?].*/, '');
  2257. }
  2258.  
  2259. static blobToDataUrl(blob) {
  2260. return new Promise((resolve, reject) => {
  2261. const fr = new FileReader();
  2262. fr.onload = () => resolve(fr.result);
  2263. fr.onerror = reject;
  2264. fr.readAsDataURL(blob);
  2265. });
  2266. }
  2267.  
  2268. static guessMimeType({responseHeaders, finalUrl}) {
  2269. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2270. !RegExp.$1.includes('text/plain'))
  2271. return RegExp.$1;
  2272. const ext = /\.([a-z0-9]+?)($|\?|#)/i.exec(finalUrl) ? RegExp.$1 : 'jpg';
  2273. switch (ext.toLowerCase()) {
  2274. case 'bmp': return 'image/bmp';
  2275. case 'gif': return 'image/gif';
  2276. case 'jpe': return 'image/jpeg';
  2277. case 'jpeg': return 'image/jpeg';
  2278. case 'jpg': return 'image/jpeg';
  2279. case 'mp4': return 'video/mp4';
  2280. case 'png': return 'image/png';
  2281. case 'svg': return 'image/svg+xml';
  2282. case 'tif': return 'image/tiff';
  2283. case 'tiff': return 'image/tiff';
  2284. case 'webm': return 'video/webm';
  2285. default: return 'application/octet-stream';
  2286. }
  2287. }
  2288.  
  2289. static findImageUrl(n, url) {
  2290. let html;
  2291. const path =
  2292. n.getAttribute('src') ||
  2293. n.getAttribute('data-m4v') ||
  2294. n.getAttribute('href') ||
  2295. n.getAttribute('content') ||
  2296. (html = n.outerHTML).includes('http') &&
  2297. html.match(/https?:\/\/[^\s"<>]+?\.(jpe?g|gif|png|svg|web[mp]|mp4)[^\s"<>]*|$/i)[0];
  2298. return !!path && Util.rel2abs(Util.decodeHtmlEntities(path),
  2299. $prop('base[href]', 'href', n.ownerDocument) || url);
  2300. }
  2301. }
  2302.  
  2303. class Util {
  2304.  
  2305. static addStyle(name, css) {
  2306. const id = `${PREFIX}style:${name}`;
  2307. const el = doc.getElementById(id) ||
  2308. css && $create('style', {id});
  2309. if (!el) return;
  2310. if (el.textContent !== css)
  2311. el.textContent = css;
  2312. if (el.parentElement !== doc.head)
  2313. doc.head.appendChild(el);
  2314. return el;
  2315. }
  2316.  
  2317. static decodeHtmlEntities(s) {
  2318. return s
  2319. .replace(/&quot;/g, '"')
  2320. .replace(/&apos;/g, '\'')
  2321. .replace(/&lt;/g, '<')
  2322. .replace(/&gt;/g, '>')
  2323. .replace(/&amp;/g, '&');
  2324. }
  2325. static deepEqual(a, b) {
  2326. if (!a || !b || typeof a !== 'object' || typeof a !== typeof b)
  2327. return a === b;
  2328. if (Array.isArray(a)) {
  2329. return Array.isArray(b) &&
  2330. a.length === b.length &&
  2331. a.every((v, i) => Util.deepEqual(v, b[i]));
  2332. }
  2333. const keys = Object.keys(a);
  2334. return keys.length === Object.keys(b).length &&
  2335. keys.every(k => Util.deepEqual(a[k], b[k]));
  2336. }
  2337.  
  2338. static findScale(url, parent) {
  2339. const imgs = $$('img, video', parent);
  2340. for (let i = imgs.length, img; (img = imgs[--i]);) {
  2341. if ((img.currentSrc || img.src) !== url || img.sizes)
  2342. continue;
  2343. const scaleX = (img.naturalWidth || img.videoWidth) / img.offsetWidth;
  2344. const scaleY = (img.naturalHeight || img.videoHeight) / img.offsetHeight;
  2345. const s = Math.max(scaleX, scaleY);
  2346. if (isFinite(s))
  2347. return s;
  2348. }
  2349. }
  2350.  
  2351. static findScaleIndex(dir) {
  2352. const i = ai.scales.indexOf(ai.scale);
  2353. if (i >= 0) return i + dir;
  2354. for (let len = ai.scales.length, i = dir > 0 ? 0 : len - 1; i >= 0 && i < len; i += dir)
  2355. if (Math.sign(ai.scales[i] - ai.scale) === dir)
  2356. return i;
  2357. return -1;
  2358. }
  2359.  
  2360. static forceLayout(node) {
  2361. // eslint-disable-next-line no-unused-expressions
  2362. node.clientHeight;
  2363. }
  2364.  
  2365. static formatError(e, rule) {
  2366. const message =
  2367. e.message ||
  2368. e.readyState && 'Request failed.' ||
  2369. e.type === 'error' && `File can't be displayed.${
  2370. $('div[bgactive*="flashblock"]', doc) ? ' Check Flashblock settings.' : ''
  2371. }` ||
  2372. e;
  2373. const m = [
  2374. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold;color:yellow'],
  2375. ['', 'font-weight:normal;color:unset'],
  2376. ];
  2377. m.push(...[
  2378. rule.u && ['Url simple match: %o', rule.u],
  2379. rule.e && ['Element match: %o', rule.e],
  2380. rule.r && ['RegExp match: %o', rule.r],
  2381. ai.url && ['URL: %s', ai.url],
  2382. ai.imageUrl && ai.imageUrl !== ai.url && ['File: %s', ai.imageUrl],
  2383. ['Node: %o', ai.node],
  2384. ].filter(Boolean));
  2385. return {
  2386. message,
  2387. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2388. consoleArgs: m.map(([, v]) => v),
  2389. };
  2390. }
  2391.  
  2392. static getFrameSize(frameWindow, parentWindow) {
  2393. const r = frameWindow.frameElement.getBoundingClientRect();
  2394. const w = clamp(r.width, 0, parentWindow.innerWidth - r.left);
  2395. const h = clamp(r.height, 0, parentWindow.innerHeight - r.top);
  2396. return [w, h];
  2397. }
  2398.  
  2399. static lazyGetRect(obj, node, selector) {
  2400. return Object.defineProperty(obj, 'rect', {
  2401. configurable: true,
  2402. get() {
  2403. const value = Util.rect(node, selector);
  2404. Object.defineProperty(obj, 'rect', {value, configurable: true});
  2405. return value;
  2406. },
  2407. });
  2408. }
  2409.  
  2410. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2411. static maybeDecodeUrl(url) {
  2412. if (!url) return url;
  2413. const iPct = url.indexOf('%');
  2414. const iColon = url.indexOf(':');
  2415. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2416. decodeURIComponent(url) :
  2417. url;
  2418. }
  2419.  
  2420. static newFunction(...args) {
  2421. try {
  2422. return App.NOP || new Function(...args);
  2423. } catch (e) {
  2424. if (!e.message.includes('unsafe-eval'))
  2425. throw e;
  2426. App.NOP = () => {};
  2427. return App.NOP;
  2428. }
  2429. }
  2430.  
  2431. static rect(node, selector) {
  2432. let n = selector && node.closest(selector);
  2433. if (n) return n.getBoundingClientRect();
  2434. const nested = node.getElementsByTagName('*');
  2435. let maxArea = 0;
  2436. let maxBounds;
  2437. n = node;
  2438. for (let i = 0; n; n = nested[i++]) {
  2439. const bounds = n.getBoundingClientRect();
  2440. const area = bounds.width * bounds.height;
  2441. if (area > maxArea) {
  2442. maxArea = area;
  2443. maxBounds = bounds;
  2444. node = n;
  2445. }
  2446. }
  2447. return maxBounds;
  2448. }
  2449.  
  2450. static rel2abs(rel, abs = location.href) {
  2451. try {
  2452. return rel.startsWith('data:') ? rel :
  2453. rel.startsWith('blob:') ? '' : // blobs don't work because they're usually revoked
  2454. new URL(rel, abs).href;
  2455. } catch (e) {
  2456. return rel;
  2457. }
  2458. }
  2459.  
  2460. static scaleCut(scale, i, arr) {
  2461. return scale >= this && (!i || Math.abs(scale - arr[i - 1]) > .01);
  2462. }
  2463.  
  2464. static scaleNextToZoom(keepScale) {
  2465. const z = ai.scaleZoom;
  2466. return keepScale || z !== ai.scale ? z :
  2467. z >= 1 ? ai.scales.find(x => x > z) :
  2468. 1;
  2469. }
  2470.  
  2471. static suppressHoverTooltip() {
  2472. for (const node of [
  2473. ai.node.parentNode,
  2474. ai.node,
  2475. ai.node.firstElementChild,
  2476. ]) {
  2477. const t = (node || 0).title;
  2478. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2479. ai.tooltip = {node, text: t};
  2480. node.title = '';
  2481. break;
  2482. }
  2483. }
  2484. }
  2485.  
  2486. static tabFixUrl() {
  2487. return `data:text/html;charset=utf8,
  2488. <style>
  2489. body {
  2490. margin: 0;
  2491. padding: 0;
  2492. background: #222;
  2493. }
  2494. .fit {
  2495. overflow: hidden
  2496. }
  2497. .fit > img {
  2498. max-width: 100vw;
  2499. max-height: 100vh;
  2500. }
  2501. body > img {
  2502. margin: auto;
  2503. position: absolute;
  2504. left: 0;
  2505. right: 0;
  2506. top: 0;
  2507. bottom: 0;
  2508. }
  2509. </style>
  2510. <body class=fit>
  2511. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2512. </body>
  2513. `.replace(/\n\s*/g, '').replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2514. }
  2515. }
  2516.  
  2517. function setup({rule} = {}) {
  2518. const MPIV_BASE_URL = 'https://w9p.co/userscripts/mpiv/';
  2519. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2520. let root = (elConfig || 0).shadowRoot;
  2521. let {blankRuleElement} = setup;
  2522. /** @type NodeList */
  2523. const UI = new Proxy({}, {
  2524. get(_, id) {
  2525. return root.getElementById(id);
  2526. },
  2527. });
  2528. if (!rule || !elConfig)
  2529. init(new Config({save: true}));
  2530. if (rule)
  2531. installRule(rule);
  2532.  
  2533. function closeSetup(event) {
  2534. if (event && this.id !== 'x') {
  2535. cfg = collectConfig({save: true, clone: this.id === 'apply'});
  2536. Ruler.init();
  2537. if (this.id === 'apply') {
  2538. renderCustomScales(cfg);
  2539. return;
  2540. }
  2541. }
  2542. $remove(elConfig);
  2543. }
  2544.  
  2545. function collectConfig({save, clone} = {}) {
  2546. const delay = parseInt(UI.delay.value);
  2547. const scale = parseFloat(UI.scale.value.replace(',', '.'));
  2548. let data = {
  2549. css: UI.css.value.trim(),
  2550. delay: !isNaN(delay) && delay >= 0 ? delay : undefined,
  2551. fit: UI.fit.value || '',
  2552. hosts: collectRules(),
  2553. scale: !isNaN(scale) ? Math.max(1, scale) : undefined,
  2554. scales: UI.scales.value
  2555. .trim()
  2556. .split(/[,;]*\s+/)
  2557. .map(x => x.replace(',', '.'))
  2558. .filter(x => !isNaN(parseFloat(x))),
  2559. start: UI.start.value,
  2560. zoom: UI.zoom.value,
  2561. zoomOut: UI.zoomOut.value,
  2562. };
  2563. for (const el of $$('[type="checkbox"]', root))
  2564. data[el.id] = el.checked;
  2565. if (clone)
  2566. data = JSON.parse(JSON.stringify(data));
  2567. return new Config({data, save});
  2568. }
  2569.  
  2570. function collectRules() {
  2571. return [...UI.rules.children]
  2572. .map(el => [el.value.trim(), el[RULE]])
  2573. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  2574. .map(([s, json]) => json || s)
  2575. .filter(Boolean);
  2576. }
  2577.  
  2578. function exportSettings(e) {
  2579. dropEvent(e);
  2580. const txt = $create('textarea', {
  2581. style: 'opacity:0; position:absolute',
  2582. value: JSON.stringify(collectConfig(), null, ' '),
  2583. });
  2584. root.appendChild(txt);
  2585. txt.select();
  2586. txt.focus();
  2587. document.execCommand('copy');
  2588. e.target.focus();
  2589. txt.remove();
  2590. UI.exportNotification.hidden = false;
  2591. setTimeout(() => (UI.exportNotification.hidden = true), 1000);
  2592. }
  2593.  
  2594. function importSettings(e) {
  2595. dropEvent(e);
  2596. const s = prompt('Paste settings:');
  2597. if (s)
  2598. init(new Config({data: s}));
  2599. }
  2600.  
  2601. function checkRule({target: el}) {
  2602. let json, error;
  2603. const prev = el.previousElementSibling;
  2604. if (el.value) {
  2605. json = Ruler.parse(el.value);
  2606. error = json instanceof Error && (json.message || String(json));
  2607. if (!prev)
  2608. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2609. } else if (prev) {
  2610. prev.focus();
  2611. el.remove();
  2612. }
  2613. el[RULE] = !error && json;
  2614. el.title = error || '';
  2615. el.setCustomValidity(error || '');
  2616. }
  2617.  
  2618. function focusRule({type, target: el, relatedTarget: from}) {
  2619. if (el === this)
  2620. return;
  2621. if (type === 'paste') {
  2622. setTimeout(() => focusRule.call(this, {target: el}));
  2623. return;
  2624. }
  2625. if (el[RULE])
  2626. el.value = Ruler.format(el[RULE], {expand: true});
  2627. const h = clamp(el.scrollHeight, 15, elConfig.clientHeight / 4);
  2628. if (h > el.offsetHeight)
  2629. el.style.minHeight = h + 'px';
  2630. if (!this.contains(from))
  2631. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  2632. if (from) {
  2633. from.style.minHeight = '';
  2634. if (from[RULE])
  2635. from.value = Ruler.format(from[RULE]);
  2636. }
  2637. }
  2638.  
  2639. function installRule(rule) {
  2640. const inputs = UI.rules.children;
  2641. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  2642. if (!el) {
  2643. el = inputs[0];
  2644. el[RULE] = rule;
  2645. el.value = Ruler.format(rule);
  2646. el.hidden = false;
  2647. const i = Math.max(0, collectRules().indexOf(rule));
  2648. inputs[i].insertAdjacentElement('afterend', el);
  2649. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2650. }
  2651. const rect = el.getBoundingClientRect();
  2652. if (rect.bottom < 0 ||
  2653. rect.bottom > el.parentNode.offsetHeight)
  2654. el.scrollIntoView();
  2655. el.classList.add('highlight');
  2656. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  2657. el.focus();
  2658. }
  2659.  
  2660. function renderCustomScales(config) {
  2661. UI.scales.value = config.scales.join(' ').trim() || Config.DEFAULTS.scales.join(' ');
  2662. }
  2663.  
  2664. function init(config) {
  2665. closeSetup();
  2666. // preventing the main page from interpreting key presses in inputs as hotkeys
  2667. // which may happen since it sees only the outer <div> in the event |target|
  2668. elConfig = $create('div', {contentEditable: true});
  2669. const scalesHint = 'Leave it empty and click Apply or Save to restore the default values.';
  2670. const trimLeft = s => s.trim().replace(/\n\s+/g, '\n');
  2671. root = elConfig.attachShadow({mode: 'open'});
  2672. root.innerHTML = `
  2673. <style>
  2674. :host {
  2675. all: initial !important;
  2676. position: fixed !important;
  2677. z-index: 2147483647 !important;
  2678. top: 20px !important;
  2679. right: 20px !important;
  2680. padding: 20px 30px !important;
  2681. color: #000 !important;
  2682. background: #eee !important;
  2683. box-shadow: 5px 5px 25px 2px #000 !important;
  2684. width: 500px !important;
  2685. border: 1px solid black !important;
  2686. display: flex !important;
  2687. flex-direction: column !important;
  2688. }
  2689. main {
  2690. font: 12px/15px sans-serif;
  2691. }
  2692. ul {
  2693. max-height: calc(100vh - 200px);
  2694. margin: 10px 0 15px 0;
  2695. padding: 0;
  2696. list-style: none;
  2697. }
  2698. li {
  2699. margin: 0;
  2700. padding: .25em 0;
  2701. }
  2702. li.options {
  2703. display: flex;
  2704. align-items: center;
  2705. justify-content: space-between;
  2706. }
  2707. li.row {
  2708. flex-wrap: wrap;
  2709. justify-content: flex-start;
  2710. }
  2711. li.row label {
  2712. flex-direction: row;
  2713. align-items: center;
  2714. }
  2715. li.row input {
  2716. margin-right: .25em;
  2717. }
  2718. label {
  2719. display: inline-flex;
  2720. flex-direction: column;
  2721. }
  2722. label:not(:last-child) {
  2723. margin-right: 1em;
  2724. }
  2725. input, select {
  2726. min-height: 1.6em;
  2727. box-sizing: border-box;
  2728. }
  2729. input[type="checkbox"] {
  2730. margin-left: 0;
  2731. }
  2732. input[type="number"] {
  2733. width: 4em;
  2734. }
  2735. input:not([type="checkbox"]) {
  2736. padding: 0 .25em;
  2737. }
  2738. textarea {
  2739. flex: 1;
  2740. resize: vertical;
  2741. margin: 1px 0;
  2742. font: 11px/1.25 Consolas, monospace;
  2743. }
  2744. textarea:invalid {
  2745. background-color: #f002;
  2746. border-color: #800;
  2747. }
  2748. code {
  2749. font-weight: bold;
  2750. }
  2751. a {
  2752. text-decoration: none;
  2753. }
  2754. a:hover {
  2755. text-decoration: underline;
  2756. }
  2757. button {
  2758. padding: .2em 1em;
  2759. margin: 0 1em;
  2760. }
  2761. .column {
  2762. display: flex;
  2763. flex-direction: column;
  2764. }
  2765. .highlight {
  2766. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  2767. animation-fill-mode: both;
  2768. }
  2769. #rules textarea {
  2770. word-break: break-all;
  2771. }
  2772. #x {
  2773. position: absolute;
  2774. top: 0;
  2775. right: 0;
  2776. padding: 4px 8px;
  2777. cursor: pointer;
  2778. user-select: none;
  2779. }
  2780. #x:hover {
  2781. background-color: #8884;
  2782. }
  2783. #cssApp {
  2784. color: seagreen;
  2785. }
  2786. #exportNotification {
  2787. color: green;
  2788. font-weight: bold;
  2789. position: absolute;
  2790. left: 0;
  2791. right: 0;
  2792. bottom: 2px;
  2793. }
  2794. #installHint {
  2795. color: green;
  2796. }
  2797. @keyframes fade-in {
  2798. from { background-color: deepskyblue }
  2799. to {}
  2800. }
  2801. @media (prefers-color-scheme: dark) {
  2802. :host {
  2803. color: #aaa !important;
  2804. background: #333 !important;
  2805. }
  2806. a {
  2807. color: deepskyblue;
  2808. }
  2809. textarea, input, select {
  2810. background: #111;
  2811. color: #BBB;
  2812. border: 1px solid #555;
  2813. }
  2814. input[type="checkbox"] {
  2815. filter: invert(1);
  2816. }
  2817. #cssApp {
  2818. color: darkseagreen;
  2819. }
  2820. #installHint {
  2821. color: greenyellow;
  2822. }
  2823. }
  2824. </style>
  2825. <main>
  2826. <a href="${MPIV_BASE_URL}">${GM_info.script.name}</a>
  2827. <div id=x>x</div>
  2828. <ul class=column>
  2829. <li class=options>
  2830. <label>Popup shows on
  2831. <select id=start>
  2832. <option value=auto>automatically
  2833. <option value=context>Right click / Ctrl
  2834. <option value=ctrl>Ctrl
  2835. </select>
  2836. </label>
  2837. <label>after, ms <input id=delay type=number min=0 max=10000 step=50 title=milliseconds></label>
  2838. <label title="Activate only if the full version of the hovered image is that many times larger">
  2839. if larger <input id=scale type=number min=1 max=100 step=.05>
  2840. </label>
  2841. <label>Zoom activates on
  2842. <select id=zoom>
  2843. <option value=context>Right click / Shift
  2844. <option value=wheel>Wheel up / Shift
  2845. <option value=shift>Shift
  2846. <option value=auto>automatically
  2847. </select>
  2848. </label>
  2849. <label>...and zooms to
  2850. <select id=fit>
  2851. <option value=all>fit to window
  2852. <option value=large>fit if larger
  2853. <option value=no>100%
  2854. <option value="" title="Use custom scale factors">custom
  2855. </select>
  2856. </label>
  2857. </li>
  2858. <li class=options>
  2859. <label>When fully zoomed out:
  2860. <select id=zoomOut>
  2861. <option value=stay>stay in zoom mode
  2862. <option value=auto>stay if still hovered
  2863. <option value=close>close popup
  2864. </select>
  2865. </label>
  2866. <label style="flex: 1" title="${trimLeft(`
  2867. 0 = fit to window,
  2868. 0! = same as 0 but also removes smaller values,
  2869. * after a value marks the default zoom factor, for example: 1*
  2870. The popup won't shrink below the image's natural size or window size for bigger mages.
  2871. ${scalesHint}
  2872. `)}">Custom scale factors to use if zooms to is set to custom”:
  2873. <input id=scales placeholder="${scalesHint}">
  2874. </label>
  2875. </li>
  2876. <li class="options row">
  2877. <label><input type=checkbox id=center>Always centered</label>
  2878. <label title="Disable only if you spoof the HTTP headers yourself">
  2879. <input type=checkbox id=xhr>Anti-hotlinking workaround
  2880. </label>
  2881. <label><input type=checkbox id=preload>Start preloading immediately</label>
  2882. <label><input type=checkbox id=imgtab>Run in image tabs</label>
  2883. <label title="Don't enable unless you explicitly use it in your custom CSS">
  2884. <input type=checkbox id=globalStatus>Expose status on &lt;html&gt; node (may cause slowdowns)
  2885. </label>
  2886. </li>
  2887. <li>
  2888. <a href="${MPIV_BASE_URL}css.html">Custom CSS:</a>
  2889. e.g. <code>#mpiv-popup.mpiv-show { animation: none }</code>
  2890. <a href="#" id=reveal style="float: right"
  2891. title="You can copy parts of it to override them in your custom CSS">
  2892. View the built-in CSS</a>
  2893. <div class=column>
  2894. <textarea id=css spellcheck=false></textarea>
  2895. <textarea id=cssApp spellcheck=false hidden readonly rows=30></textarea>
  2896. </div>
  2897. </li>
  2898. <li style="display: flex; justify-content: space-between;">
  2899. <div><a href="${MPIV_BASE_URL}host_rules.html">Custom host rules:</a></div>
  2900. <div style="white-space: nowrap">
  2901. To disable, put any symbol except <code>a..z 0..9 - .</code><br>
  2902. in "d" value, for example <code>"d": "!foo.com"</code>
  2903. </div>
  2904. <div>
  2905. <input id=search type=search placeholder=Search style="width: 10em; margin-left: 1em">
  2906. </div>
  2907. </li>
  2908. <li style="margin-left: -3px; margin-right: -3px; overflow-y: auto; padding-left: 3px; padding-right: 3px;">
  2909. <div id=rules class=column>
  2910. <textarea rows=1 spellcheck=false></textarea>
  2911. </div>
  2912. </li>
  2913. <li>
  2914. <div hidden id=installLoading>Loading...</div>
  2915. <div hidden id=installHint>Double-click the rule (or select and press Enter) to add it.
  2916. Click <code>Apply</code> or <code>Save</code> to confirm.</div>
  2917. <a href="${MPIV_BASE_URL}more_host_rules.html" id=install>Install rule from repository...</a>
  2918. </li>
  2919. </ul>
  2920. <div style="text-align:center">
  2921. <button id=ok accesskey=s>Save</button>
  2922. <button id=apply accesskey=a>Apply</button>
  2923. <button id=import style="margin-right: 0">Import</button>
  2924. <button id=export style="margin-left: 0">Export</button>
  2925. <button id=cancel>Cancel</button>
  2926. <div id=exportNotification hidden>Copied to clipboard.</div>
  2927. </div>
  2928. </main>
  2929. `;
  2930. // rules
  2931. const rules = UI.rules;
  2932. rules.addEventListener('input', checkRule);
  2933. rules.addEventListener('focusin', focusRule);
  2934. rules.addEventListener('paste', focusRule);
  2935. blankRuleElement =
  2936. setup.blankRuleElement =
  2937. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  2938. for (const rule of config.hosts || []) {
  2939. const el = blankRuleElement.cloneNode();
  2940. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  2941. rules.appendChild(el);
  2942. checkRule({target: el});
  2943. }
  2944. // search rules
  2945. const search = UI.search;
  2946. search.oninput = () => {
  2947. setup.search = search.value;
  2948. const s = search.value.toLowerCase();
  2949. for (const el of rules.children)
  2950. el.hidden = s && !el.value.toLowerCase().includes(s);
  2951. };
  2952. search.value = setup.search || '';
  2953. if (search.value)
  2954. search.oninput();
  2955. // prevent the main page from interpreting key presses in inputs as hotkeys
  2956. // which may happen since it sees only the outer <div> in the event |target|
  2957. root.addEventListener('keydown', e =>
  2958. !e.altKey && !e.ctrlKey && !e.metaKey && e.stopPropagation(), true);
  2959. UI.apply.onclick = UI.cancel.onclick = UI.ok.onclick = UI.x.onclick = closeSetup;
  2960. UI.css.value = config.css;
  2961. UI.delay.value = config.delay;
  2962. UI.export.onclick = exportSettings;
  2963. UI.fit.value = config.fit;
  2964. UI.import.onclick = importSettings;
  2965. UI.install.onclick = setupRuleInstaller;
  2966. const {/** @type {HTMLTextAreaElement} */ cssApp} = UI;
  2967. UI.reveal.onclick = e => {
  2968. e.preventDefault();
  2969. cssApp.hidden = !cssApp.hidden;
  2970. if (!cssApp.hidden) {
  2971. if (!cssApp.value) {
  2972. App.updateStyles();
  2973. cssApp.value = App.globalStyle.trim();
  2974. cssApp.setSelectionRange(0, 0);
  2975. }
  2976. cssApp.focus();
  2977. }
  2978. };
  2979. UI.scale.value = config.scale;
  2980. UI.start.value = config.start;
  2981. UI.start.onchange = function () {
  2982. UI.delay.closest('label').hidden =
  2983. UI.preload.closest('label').hidden =
  2984. this.value !== 'auto';
  2985. };
  2986. UI.start.onchange();
  2987. UI.xhr.onclick = ({target: el}) => el.checked || confirm($propUp(el, 'title'));
  2988. UI.zoom.value = config.zoom;
  2989. UI.zoomOut.value = config.zoomOut;
  2990. for (const el of $$('[type="checkbox"]', root))
  2991. el.checked = config[el.id];
  2992. for (const el of $$('a[href^="http"]', root)) {
  2993. el.target = '_blank';
  2994. el.rel = 'noreferrer noopener external';
  2995. }
  2996. renderCustomScales(config);
  2997. doc.body.appendChild(elConfig);
  2998. requestAnimationFrame(() => {
  2999. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, elConfig.clientHeight / 4) + 'px';
  3000. });
  3001. }
  3002. }
  3003.  
  3004. async function setupRuleInstaller(e) {
  3005. dropEvent(e);
  3006. const parent = this.parentElement;
  3007. parent.children.installLoading.hidden = false;
  3008. this.remove();
  3009. let rules;
  3010.  
  3011. try {
  3012. rules = extractRules((await Remoting.getDoc(this.href)).doc);
  3013. const selector = $create('select', {
  3014. size: 8,
  3015. style: 'width: 100%',
  3016. ondblclick: e => e.target !== selector && maybeSetup(e),
  3017. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  3018. });
  3019. selector.append(...rules.map(renderRule));
  3020. selector.selectedIndex = findMatchingRuleIndex();
  3021. // remove "name" since the installed rules don't need it
  3022. for (const r of rules)
  3023. delete r.name;
  3024. parent.children.installLoading.remove();
  3025. parent.children.installHint.hidden = false;
  3026. parent.appendChild(selector);
  3027. } catch (e) {
  3028. parent.textContent = 'Error loading rules: ' + (e.message || e);
  3029. }
  3030.  
  3031. function extractRules(doc) {
  3032. const code = $('script', doc).textContent;
  3033. // sort by name
  3034. return JSON.parse(code.match(/var\s+rules\s*=\s*(\[.+]);?[\r\n]/)[1])
  3035. .filter(r => !r.d || hostname.includes(r.d))
  3036. .sort((a, b) =>
  3037. (a = a.name.toLowerCase()) < (b = b.name.toLowerCase()) ? -1 :
  3038. a > b ? 1 :
  3039. 0);
  3040. }
  3041.  
  3042. function findMatchingRuleIndex() {
  3043. // get the core part of the current domain that's not "www", "m", etc.
  3044. const h = hostname.split('.');
  3045. const core = h[0] === 'www' || h.length > 2 && h[0].length === 1 ? h[1] : h[0];
  3046. // find a rule matching the domain core
  3047. return rules.findIndex(r =>
  3048. r.name.toLowerCase().includes(core) ||
  3049. r.d && hostname.includes(r.d));
  3050. }
  3051.  
  3052. function renderRule(r) {
  3053. const {name, ...copy} = r;
  3054. return $create('option', {
  3055. textContent: name,
  3056. title: Ruler.format(copy, {expand: true})
  3057. .replace(/^{|\s*}$/g, '')
  3058. .split('\n')
  3059. .slice(0, 12)
  3060. .map(renderTitleLine)
  3061. .filter(Boolean)
  3062. .join('\n'),
  3063. });
  3064. }
  3065.  
  3066. function renderTitleLine(line, i, arr) {
  3067. return (
  3068. // show ... on 10th line if there are more lines
  3069. i === 9 && arr.length > 10 ? '...' :
  3070. i > 10 ? '' :
  3071. // truncate to 100 chars
  3072. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  3073. // strip the leading space
  3074. .replace(/^\s/, ''));
  3075. }
  3076.  
  3077. function maybeSetup(e) {
  3078. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey)
  3079. setup({rule: rules[e.currentTarget.selectedIndex]});
  3080. }
  3081. }
  3082.  
  3083. App.init();