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