Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2020-05-14 提交的版本,檢視 最新版本

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