Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-10-30 提交的版本,查看 最新版本

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