Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-01-08 提交的版本,查看 最新版本

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