Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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