Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-03-01 提交的版本。查看 最新版本

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