Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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