Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-02-26 提交的版本。查看 最新版本

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