Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-03-07 提交的版本,查看 最新版本

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