Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

  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.18
  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. },
  1317. },
  1318. dotDomain.endsWith('.instagram.com') && {
  1319. e: [
  1320. 'a[href*="/p/"]',
  1321. 'article [role="button"][tabindex="0"], article [role="button"][tabindex="0"] div',
  1322. ],
  1323. s: (m, node, rule) => {
  1324. let data, a, n, img, src;
  1325. if (location.pathname.startsWith('/p/')) {
  1326. img = $('img[srcset], video', node.parentNode);
  1327. if (img && (img.localName === 'video' || parseFloat(img.sizes) > 900))
  1328. src = (img.srcset || img.currentSrc).split(',').pop().split(' ')[0];
  1329. }
  1330. if (!src && (n = node.closest('a[href*="/p/"], article'))) {
  1331. a = n.tagName === 'A' ? n : $('a[href*="/p/"]', n);
  1332. data = a && tryCatch(this._getEdge, a.pathname.split('/')[2]);
  1333. }
  1334. Ruler.toggle(rule, 'q', data && data.is_video && !data.video_url);
  1335. Ruler.toggle(rule, 'g', a && $('[class*="Carousel"]', a));
  1336. rule.follow = !data && !rule.g;
  1337. rule._data = data;
  1338. rule._img = img;
  1339. return (
  1340. !a && !src ? false :
  1341. !data || rule.q || rule.g ? `${src || a.href}${rule.g ? '?__a=1' : ''}` :
  1342. data.video_url || data.display_url);
  1343. },
  1344. c: (html, doc, node, rule) =>
  1345. tryCatch(rule._getCaption, rule._data) || (rule._img || 0).alt || '',
  1346. follow: true,
  1347. _q: 'meta[property="og:video"]',
  1348. _g(text, doc, url, m, rule) {
  1349. const media = JSON.parse(text).graphql.shortcode_media;
  1350. const items = media.edge_sidecar_to_children.edges.map(e => ({
  1351. url: e.node.video_url || e.node.display_url,
  1352. }));
  1353. items.title = tryCatch(rule._getCaption, media) || '';
  1354. return items;
  1355. },
  1356. _getCaption: data => data && data.edge_media_to_caption.edges[0].node.text,
  1357. _getEdge: shortcode => unsafeWindow._sharedData.entry_data.ProfilePage[0].graphql.user
  1358. .edge_owner_to_timeline_media.edges.find(e => e.node.shortcode === shortcode).node,
  1359. },
  1360. ...dotDomain.endsWith('.reddit.com') && [{
  1361. u: '||i.reddituploads.com/',
  1362. }, {
  1363. e: '[data-url*="i.redd.it"] img[src*="thumb"]',
  1364. s: (m, node) => $propUp(node, 'data-url'),
  1365. }, {
  1366. r: /preview(\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  1367. s: 'https://i$1',
  1368. }] || [],
  1369. dotDomain.endsWith('.tumblr.com') && {
  1370. e: 'div.photo_stage_img, div.photo_stage > canvas',
  1371. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  1372. follow: true,
  1373. },
  1374. dotDomain.endsWith('.tweetdeck.twitter.com') && {
  1375. e: 'a.media-item, a.js-media-image-link',
  1376. s: (m, node) => /http[^)]+/.exec(node.style.backgroundImage)[0],
  1377. follow: true,
  1378. },
  1379. dotDomain.endsWith('.twitter.com') && {
  1380. e: '.grid-tweet > .media-overlay',
  1381. s: (m, node) => node.previousElementSibling.src,
  1382. follow: true,
  1383. },
  1384. ];
  1385.  
  1386. const main = [
  1387. {
  1388. r: /[/?=](https?%3A%2F%2F[^&]+)/i,
  1389. s: '$1',
  1390. follow: true,
  1391. onerror: 'skip',
  1392. },
  1393. {
  1394. u: [
  1395. '||500px.com/photo/',
  1396. '||cl.ly/',
  1397. '||cweb-pix.com/',
  1398. '||ibb.co/',
  1399. '||imgcredit.xyz/image/',
  1400. ],
  1401. r: /\.\w+\/.+/,
  1402. q: 'meta[property="og:image"]',
  1403. },
  1404. {
  1405. u: 'attachment.php',
  1406. r: /attachment\.php.+attachmentid/,
  1407. },
  1408. {
  1409. u: '||abload.de/image',
  1410. q: '#image',
  1411. },
  1412. {
  1413. u: '||deviantart.com/art/',
  1414. s: (m, node) =>
  1415. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  1416. '' :
  1417. m.input,
  1418. q: [
  1419. '#download-button[href*=".jpg"]',
  1420. '#download-button[href*=".jpeg"]',
  1421. '#download-button[href*=".gif"]',
  1422. '#download-button[href*=".png"]',
  1423. '#gmi-ResViewSizer_fullimg',
  1424. 'img.dev-content-full',
  1425. ],
  1426. },
  1427. {
  1428. u: '||dropbox.com/s',
  1429. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  1430. q: (text, doc) =>
  1431. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  1432. },
  1433. {
  1434. r: /[./]ebay\.[^/]+\/itm\//,
  1435. q: text =>
  1436. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  1437. .replace(/~~60_\d+/, '~~60_57'),
  1438. },
  1439. {
  1440. u: '||i.ebayimg.com/',
  1441. s: (m, node) =>
  1442. $('.zoom_trigger_mask', node.parentNode) ? '' :
  1443. m.input.replace(/~~60_\d+/, '~~60_57'),
  1444. },
  1445. {
  1446. u: '||fastpic.ru',
  1447. e: 'a',
  1448. q: 'img[src*="/big/"]',
  1449. xhr: true,
  1450. },
  1451. {
  1452. u: '||facebook.com/',
  1453. r: /photo\.php|[^/]+\/photos\//,
  1454. s: (m, node) =>
  1455. node.id === 'fbPhotoImage' ? false :
  1456. /gradient\.png$/.test(m.input) ? '' :
  1457. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  1458. q: [
  1459. 'div + span > a:first-child:not([href*="tag_faces"])',
  1460. 'div + span > a[href*="tag_faces"] ~ a',
  1461. ],
  1462. rect: '#fbProfileCover',
  1463. },
  1464. {
  1465. u: '||fbcdn.',
  1466. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  1467. s: m =>
  1468. dotDomain.endsWith('.facebook.com') &&
  1469. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  1470. false,
  1471. manual: true,
  1472. },
  1473. {
  1474. u: ['||fbcdn-', 'fbcdn.net/'],
  1475. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  1476. s: (m, node) => {
  1477. if (node.id === 'fbPhotoImage') {
  1478. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  1479. if (a) return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  1480. }
  1481. if (m[4])
  1482. return false;
  1483. const pn = node.parentNode;
  1484. if (pn.outerHTML.includes('/hovercard/'))
  1485. return '';
  1486. if (node.outerHTML.includes('profile') && pn.parentNode.href.includes('/photo'))
  1487. return false;
  1488. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  1489. },
  1490. rect: '.photoWrap',
  1491. },
  1492. {
  1493. u: '||flickr.com/photos/',
  1494. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  1495. s: m =>
  1496. m.input.indexOf('/sizes/') < 0 ?
  1497. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  1498. false,
  1499. q: (text, doc) => {
  1500. const links = $$('.sizes-list a', doc);
  1501. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  1502. },
  1503. follow: true,
  1504. },
  1505. {
  1506. u: '||flickr.com/photos/',
  1507. r: /\/sizes\//,
  1508. q: '#allsizes-photo > img',
  1509. },
  1510. {
  1511. u: '||gfycat.com/',
  1512. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  1513. s: 'https://$1$3',
  1514. q: [
  1515. 'meta[content$=".webm"]',
  1516. '#webmsource',
  1517. 'source[src$=".webm"]',
  1518. ],
  1519. },
  1520. {
  1521. u: [
  1522. '||googleusercontent.com/proxy',
  1523. '||googleusercontent.com/gadgets/proxy',
  1524. ],
  1525. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  1526. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  1527. },
  1528. {
  1529. u: [
  1530. '||googleusercontent.com/',
  1531. '||ggpht.com/',
  1532. ],
  1533. s: m => m.input.includes('webcache.') ? '' :
  1534. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  1535. .replace(/([&?]sz)?=[-\w]+([&#].*)?/, ''),
  1536. },
  1537. {
  1538. u: '||gravatar.com/',
  1539. r: /([a-z0-9]{32})/,
  1540. s: 'https://gravatar.com/avatar/$1?s=200',
  1541. },
  1542. {
  1543. u: '//gyazo.com/',
  1544. r: /\bgyazo\.com\/\w{32,}(\.\w+)?/,
  1545. s: (m, _, rule) => Ruler.toggle(rule, 'q', !m[1]) ? m.input : `https://i.${m[0]}`,
  1546. _q: 'meta[name="twitter:image"]',
  1547. },
  1548. {
  1549. u: '||hostingkartinok.com/show-image.php',
  1550. q: '.image img',
  1551. },
  1552. {
  1553. u: [
  1554. '||imagecurl.com/images/',
  1555. '||imagecurl.com/viewer.php',
  1556. ],
  1557. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1558. s: 'https://imagecurl.com/images/$1$2$3',
  1559. },
  1560. {
  1561. u: '||imagebam.com/image/',
  1562. q: 'meta[property="og:image"]',
  1563. tabfix: true,
  1564. xhr: hostname.includes('planetsuzy'),
  1565. },
  1566. {
  1567. u: '||imageban.ru/thumbs',
  1568. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1569. s: '$1out$2/$3/$4',
  1570. },
  1571. {
  1572. u: [
  1573. '||imageban.ru/show',
  1574. '||imageban.net/show',
  1575. '||ibn.im/',
  1576. ],
  1577. q: '#img_main',
  1578. },
  1579. {
  1580. u: '||imageshack.us/img',
  1581. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1582. s: 'https://$2/download/$1/$3$4',
  1583. },
  1584. {
  1585. u: '||imageshack.us/i/',
  1586. q: '#share-dl',
  1587. },
  1588. {
  1589. u: '||imageteam.org/img',
  1590. q: 'img[alt="image"]',
  1591. },
  1592. {
  1593. u: [
  1594. '||imagetwist.com/',
  1595. '||imageshimage.com/',
  1596. ],
  1597. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1598. q: 'img.pic',
  1599. xhr: true,
  1600. },
  1601. {
  1602. u: '||imageupper.com/i/',
  1603. q: '#img',
  1604. xhr: true,
  1605. },
  1606. {
  1607. u: '||imagevenue.com/',
  1608. q: 'a[data-toggle="full"] img',
  1609. },
  1610. {
  1611. u: '||imagezilla.net/show/',
  1612. q: '#photo',
  1613. xhr: true,
  1614. },
  1615. {
  1616. u: [
  1617. '||images-na.ssl-images-amazon.com/images/',
  1618. '||media-imdb.com/images/',
  1619. ],
  1620. r: /images\/.+?\.jpg/,
  1621. s: '/V1\\.?_.+?\\.//g',
  1622. },
  1623. {
  1624. u: '||imgbox.com/',
  1625. r: /\.com\/([a-z0-9]+)$/i,
  1626. q: '#img',
  1627. xhr: hostname !== 'imgbox.com',
  1628. },
  1629. {
  1630. u: '||imgclick.net/',
  1631. r: /\.net\/(\w+)/,
  1632. q: 'img.pic',
  1633. xhr: true,
  1634. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1635. },
  1636. {
  1637. u: [
  1638. '||imgflip.com/i/',
  1639. '||imgflip.com/gif/',
  1640. ],
  1641. r: /\/(i|gif)\/([^/?#]+)/,
  1642. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1643. },
  1644. {
  1645. u: [
  1646. '||imgur.com/a/',
  1647. '||imgur.com/gallery/',
  1648. ],
  1649. g: async (text, doc, url, m, rule, node, cb) => {
  1650. let u = `https://imgur.com/ajaxalbums/getimages/${url.split(/[/?#]/)[4]}/hit.json?all=true`;
  1651. const info = tryCatch(JSON.parse, (await Remoting.gmXhr(u)).responseText);
  1652. const images = ((info || 0).data || 0).images;
  1653. const items = [];
  1654. for (const img of images || []) {
  1655. u = `https://i.imgur.com/${img.hash}`;
  1656. items.push({
  1657. url: img.ext === '.gif' && img.animated !== false ?
  1658. [`${u}.webm`, `${u}.mp4`, u] :
  1659. u + img.ext,
  1660. desc: [img.title, img.description].filter(Boolean).join(' - '),
  1661. });
  1662. }
  1663. if (items[0] && info.title && !`${items[0].desc || ''}`.includes(info.title))
  1664. items.title = info.title;
  1665. cb(items);
  1666. },
  1667. css: '.post > .hover { display:none!important; }',
  1668. },
  1669. {
  1670. u: '||imgur.com/',
  1671. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1672. s: 'gallery',
  1673. g: (text, doc, url, m) =>
  1674. m[2].split(',').map(id => ({
  1675. url: `https://i.${m[1]}${id}.jpg`,
  1676. })),
  1677. },
  1678. {
  1679. u: '||imgur.com/',
  1680. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.(mp4|[a-z]+))/i,
  1681. s: (m, node) => {
  1682. if (/memegen|random|register|search|signin/.test(m.input))
  1683. return '';
  1684. const a = node.closest('a');
  1685. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1686. return false;
  1687. // postfixes: huge, large, medium, thumbnail, big square, small square
  1688. const id = m[3].replace(/(.{7})[hlmtbs]$/, '$1');
  1689. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1690. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1691. return ext === 'webm' ?
  1692. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1693. u + ext;
  1694. },
  1695. },
  1696. {
  1697. u: [
  1698. '||instagr.am/p/',
  1699. '||instagram.com/p/',
  1700. ],
  1701. s: m => m.input.substr(0, m.input.lastIndexOf('/')) + '/?__a=1',
  1702. q: text => {
  1703. const m = JSON.parse(text).graphql.shortcode_media;
  1704. return m.video_url || m.display_url;
  1705. },
  1706. rect: 'div.PhotoGridMediaItem',
  1707. c: text => {
  1708. const m = JSON.parse(text).graphql.shortcode_media.edge_media_to_caption.edges[0];
  1709. return m === undefined ? '(no caption)' : m.node.text;
  1710. },
  1711. },
  1712. {
  1713. u: [
  1714. '||livememe.com/',
  1715. '||lvme.me/',
  1716. ],
  1717. r: /\.\w+\/([^.]+)$/,
  1718. s: 'http://i.lvme.me/$1.jpg',
  1719. },
  1720. {
  1721. u: '||lostpic.net/image',
  1722. q: '.image-viewer-image img',
  1723. },
  1724. {
  1725. u: '||makeameme.org/meme/',
  1726. r: /\/meme\/([^/?#]+)/,
  1727. s: 'https://media.makeameme.org/created/$1.jpg',
  1728. },
  1729. {
  1730. u: '||photobucket.com/',
  1731. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  1732. s: 'https://i$1$3',
  1733. xhr: !dotDomain.endsWith('.photobucket.com'),
  1734. },
  1735. {
  1736. u: '||piccy.info/view3/',
  1737. r: /(.+?\/view3)\/(.*)\//,
  1738. s: '$1/$2/orig/',
  1739. q: '#mainim',
  1740. },
  1741. {
  1742. u: '||pimpandhost.com/image/',
  1743. r: /(.+?\/image\/[0-9]+)/,
  1744. s: '$1?size=original',
  1745. q: 'img.original',
  1746. },
  1747. {
  1748. u: [
  1749. '||pixroute.com/',
  1750. '||imgspice.com/',
  1751. ],
  1752. r: /\.html$/,
  1753. q: 'img[id]',
  1754. xhr: true,
  1755. },
  1756. {
  1757. u: '||postima',
  1758. r: /postima?ge?\.org\/image\/\w+/,
  1759. q: [
  1760. 'a[href*="dl="]',
  1761. '#main-image',
  1762. ],
  1763. },
  1764. {
  1765. u: [
  1766. '||prntscr.com/',
  1767. '||prnt.sc/',
  1768. ],
  1769. r: /\.\w+\/.+/,
  1770. q: 'meta[property="og:image"]',
  1771. xhr: true,
  1772. },
  1773. {
  1774. u: '||radikal.ru/',
  1775. r: /\.ru\/(fp|.+?\.html)|^(.+?)t\.jpg/,
  1776. s: (m, node, rule) =>
  1777. m[2] && /radikal\.ru[\w%/]+?(\.\w+)/.test($propUp(node, 'href')) ? m[2] + RegExp.$1 :
  1778. Ruler.toggle(rule, 'q', m[1]) ? m.input : [m[2] + '.jpg', m[2] + '.png'],
  1779. _q: text => text.match(/https?:\/\/\w+\.radikal\.ru[\w/]+\.(jpg|gif|png)/i)[0],
  1780. },
  1781. {
  1782. u: '||tumblr.com',
  1783. r: /_500\.jpg/,
  1784. s: ['/_500/_1280/', ''],
  1785. },
  1786. {
  1787. u: '||twimg.com/',
  1788. r: /\/profile_images/i,
  1789. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  1790. },
  1791. {
  1792. u: '||twimg.com/media/',
  1793. r: /.+?format=(jpe?g|png|gif)/i,
  1794. s: '$0&name=orig',
  1795. },
  1796. {
  1797. u: '||twimg.com/1/proxy',
  1798. r: /t=([^&_]+)/i,
  1799. s: m => atob(m[1]).match(/http.+/),
  1800. },
  1801. {
  1802. u: '||pic.twitter.com/',
  1803. r: /\.com\/[a-z0-9]+/i,
  1804. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  1805. follow: true,
  1806. },
  1807. {
  1808. u: '||twitpic.com/',
  1809. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  1810. s: 'https://twitpic.com/show/large/$2',
  1811. },
  1812. {
  1813. u: '||upix.me/files',
  1814. s: '/#//',
  1815. },
  1816. {
  1817. u: '||wiki',
  1818. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  1819. s: '/\\/thumb(?=\\/)|' +
  1820. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  1821. '\\/revision\\/latest|\\/[^\\/]+$//g',
  1822. xhr: !hostname.includes('wiki'),
  1823. },
  1824. {
  1825. u: '||ytimg.com/vi/',
  1826. r: /(.+?\/vi\/[^/]+)/,
  1827. s: '$1/0.jpg',
  1828. rect: '.video-list-item',
  1829. },
  1830. {
  1831. u: '/viewer.php?file=',
  1832. r: /(.+?)\/viewer\.php\?file=(.+)/,
  1833. s: '$1/images/$2',
  1834. xhr: true,
  1835. },
  1836. {
  1837. u: '/thumb_',
  1838. r: /\/albums.+\/thumb_[^/]/,
  1839. s: '/thumb_//',
  1840. },
  1841. {
  1842. u: [
  1843. '.th.jp',
  1844. '.th.gif',
  1845. '.th.png',
  1846. ],
  1847. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  1848. s: '$1$2',
  1849. follow: true,
  1850. },
  1851. {
  1852. r: RX_MEDIA_URL,
  1853. },
  1854. ];
  1855.  
  1856. /** @type mpiv.HostRule[] */
  1857. Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean);
  1858. },
  1859.  
  1860. format(rule, {expand} = {}) {
  1861. const s = Util.stringify(rule, null, ' ');
  1862. return expand ?
  1863. /* {"a": ...,
  1864. "b": ...,
  1865. "c": ...
  1866. } */
  1867. s.replace(/^{\s+/g, '{') :
  1868. /* {"a": ..., "b": ..., "c": ...} */
  1869. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  1870. },
  1871.  
  1872. /** @returns mpiv.HostRule | Error | false | undefined */
  1873. parse(rule) {
  1874. const isBatchOp = this instanceof Map;
  1875. try {
  1876. if (typeof rule === 'string')
  1877. rule = JSON.parse(rule);
  1878. if ('d' in rule && typeof rule.d !== 'string')
  1879. rule.d = undefined;
  1880. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  1881. return false;
  1882. const compileTo = isBatchOp ? rule : {};
  1883. if (rule.r)
  1884. compileTo.r = new RegExp(rule.r, 'i');
  1885. if (RX_HAS_CODE.test(rule.s))
  1886. compileTo.s = Util.newFunction('m', 'node', 'rule', rule.s);
  1887. if (RX_HAS_CODE.test(rule.q))
  1888. compileTo.q = Util.newFunction('text', 'doc', 'node', 'rule', rule.q);
  1889. if (RX_HAS_CODE.test(rule.c))
  1890. compileTo.c = Util.newFunction('text', 'doc', 'node', 'rule', rule.c);
  1891. return rule;
  1892. } catch (e) {
  1893. if (!e.message.includes('unsafe-eval'))
  1894. if (isBatchOp) {
  1895. this.set(rule, e);
  1896. } else {
  1897. return e;
  1898. }
  1899. }
  1900. },
  1901.  
  1902. runC(text, doc = document) {
  1903. const fn = Ruler.runCHandler[typeof ai.rule.c] || Ruler.runCHandler.default;
  1904. ai.caption = fn(text, doc);
  1905. },
  1906.  
  1907. runCHandler: {
  1908. function: (text, doc) =>
  1909. ai.rule.c(text || doc.documentElement.outerHTML, doc, ai.node, ai.rule),
  1910. string: (text, doc) => {
  1911. const el = $many(ai.rule.c, doc);
  1912. return !el ? '' :
  1913. el.getAttribute('content') ||
  1914. el.getAttribute('title') ||
  1915. el.textContent;
  1916. },
  1917. default: () =>
  1918. (ai.tooltip || 0).text ||
  1919. ai.node.alt ||
  1920. $propUp(ai.node, 'title') ||
  1921. Remoting.getFileName(
  1922. ai.node.tagName === (ai.popup || 0).tagName
  1923. ? ai.url
  1924. : ai.node.src || $propUp(ai.node, 'href')),
  1925. },
  1926.  
  1927. runQ(text, doc, docUrl) {
  1928. let url;
  1929. if (typeof ai.rule.q === 'function') {
  1930. url = ai.rule.q(text, doc, ai.node, ai.rule);
  1931. if (Array.isArray(url)) {
  1932. ai.urls = url.slice(1);
  1933. url = url[0];
  1934. }
  1935. } else {
  1936. const el = $many(ai.rule.q, doc);
  1937. url = Remoting.findImageUrl(el, docUrl);
  1938. }
  1939. return url;
  1940. },
  1941.  
  1942. /** @returns {?Array} if falsy then the rule should be skipped */
  1943. runS(node, rule, m) {
  1944. let urls = [];
  1945. for (const s of ensureArray(rule.s))
  1946. urls.push(
  1947. typeof s === 'string' ? Util.decodeUrl(Ruler.substituteSingle(s, m)) :
  1948. typeof s === 'function' ? s(m, node, rule) :
  1949. s);
  1950. if (rule.q && urls.length > 1) {
  1951. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  1952. return;
  1953. }
  1954. if (Array.isArray(urls[0]))
  1955. urls = urls[0];
  1956. // `false` returned by "s" property means "skip this rule", "" means "stop all rules"
  1957. return urls[0] !== false && urls.map(Util.decodeUrl);
  1958. },
  1959.  
  1960. substituteSingle(s, m) {
  1961. if (!m) return s;
  1962. if (s.startsWith('/') && !s.startsWith('//')) {
  1963. const mid = s.search(/[^\\]\//) + 1;
  1964. const end = s.lastIndexOf('/');
  1965. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  1966. return m.input.replace(re, s.slice(mid + 1, end));
  1967. }
  1968. if (m.length && s.includes('$')) {
  1969. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  1970. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  1971. for (let i = maxLength; i >= 0; i--) {
  1972. const part = num.slice(0, i) | 0;
  1973. if (part < m.length)
  1974. return (m[part] || '') + num.slice(i);
  1975. }
  1976. return text;
  1977. });
  1978. }
  1979. return s;
  1980. },
  1981.  
  1982. toggle(rule, prop, condition) {
  1983. rule[prop] = condition ? rule[`_${prop}`] : null;
  1984. return condition;
  1985. },
  1986. };
  1987.  
  1988. const RuleMatcher = {
  1989.  
  1990. /** @returns ?mpiv.RuleMatchInfo */
  1991. findForLink(a) {
  1992. let url =
  1993. a.getAttribute('data-expanded-url') ||
  1994. a.getAttribute('data-full-url') ||
  1995. a.getAttribute('data-url') ||
  1996. a.href;
  1997. if (url.startsWith('data:'))
  1998. url = false;
  1999. else if (url.includes('//t.co/'))
  2000. url = 'http://' + a.textContent;
  2001. return RuleMatcher.find(url, a);
  2002. },
  2003.  
  2004. /** @returns ?mpiv.RuleMatchInfo */
  2005. find(url, node, {noHtml, skipRules} = {}) {
  2006. const tn = node.tagName;
  2007. const isPic = tn === 'IMG' || tn === 'VIDEO';
  2008. const isPicOrLink = isPic || tn === 'A';
  2009. let m, html;
  2010. for (const rule of Ruler.rules) {
  2011. const u = rule[SYM_U] || rule.u && (rule[SYM_U] = UrlMatcher(rule.u));
  2012. if (u && (!url || !u.fn.call(u.data, url)) ||
  2013. rule.e && !node.matches(rule.e) ||
  2014. skipRules && skipRules.includes(rule))
  2015. continue;
  2016. if (rule.r)
  2017. m = !noHtml && rule.html && (isPicOrLink || rule.e)
  2018. ? rule.r.exec(html || (html = node.outerHTML))
  2019. : url && rule.r.exec(url);
  2020. else if (url)
  2021. m = Object.assign([url], {index: 0, input: url});
  2022. else
  2023. m = [];
  2024. if (!m)
  2025. continue;
  2026. if (rule.s === '')
  2027. return {};
  2028. let hasS = rule.s != null;
  2029. // a rule with follow:true for the currently hovered IMG produced a URL,
  2030. // but we'll only allow it to match rules without 's' in the nested find call
  2031. if (isPic && !hasS && !skipRules)
  2032. continue;
  2033. hasS &= rule.s !== 'gallery';
  2034. const urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  2035. if (urls)
  2036. return RuleMatcher.makeInfo(hasS, rule, m, node, skipRules, urls);
  2037. }
  2038. },
  2039.  
  2040. /** @returns ?mpiv.RuleMatchInfo */
  2041. makeInfo(hasS, rule, match, node, skipRules, urls) {
  2042. let info;
  2043. let url = `${urls[0]}`;
  2044. const follow = url && hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule);
  2045. if (!url)
  2046. info = {};
  2047. if (follow)
  2048. info = RuleMatcher.find(url, node, {skipRules: [...skipRules || [], rule]});
  2049. if (!info && (!follow || RX_MEDIA_URL.test(url))) {
  2050. const xhr = cfg.xhr && rule.xhr;
  2051. if (url.startsWith('//'))
  2052. url = location.protocol + url;
  2053. info = {
  2054. match,
  2055. node,
  2056. rule,
  2057. url,
  2058. urls: urls.length > 1 ? urls.slice(1) : null,
  2059. gallery: rule.g && Gallery.makeParser(rule.g),
  2060. post: typeof rule.post === 'function' ? rule.post(match) : rule.post,
  2061. xhr: xhr != null ? xhr : isSecureContext && !url.startsWith(location.protocol),
  2062. };
  2063. }
  2064. return info;
  2065. },
  2066.  
  2067. isFollowableUrl(url, rule) {
  2068. const f = rule.follow;
  2069. return typeof f === 'function' ? f(url) : f;
  2070. },
  2071. };
  2072.  
  2073. const Remoting = {
  2074.  
  2075. gmXhr(url, opts = {}) {
  2076. if (ai.req)
  2077. tryCatch.call(ai.req, ai.req.abort);
  2078. return new Promise((resolve, reject) => {
  2079. ai.req = GM_xmlhttpRequest({
  2080. url,
  2081. method: 'GET',
  2082. anonymous: (ai.rule || {}).anonymous,
  2083. timeout: 30e3,
  2084. ...opts,
  2085. onload: done,
  2086. onerror: done,
  2087. ontimeout() {
  2088. ai.req = null;
  2089. reject(`Timeout fetching ${url}`);
  2090. },
  2091. });
  2092. function done(r) {
  2093. ai.req = null;
  2094. if (r.status < 400 && !r.error)
  2095. resolve(r);
  2096. else
  2097. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2098. }
  2099. });
  2100. },
  2101.  
  2102. async getDoc(url) {
  2103. const r = await (!ai.post ?
  2104. Remoting.gmXhr(url) :
  2105. Remoting.gmXhr(url, {
  2106. method: 'POST',
  2107. data: ai.post,
  2108. headers: {
  2109. 'Content-Type': 'application/x-www-form-urlencoded',
  2110. 'Referer': url,
  2111. },
  2112. }));
  2113. r.doc = new DOMParser().parseFromString(r.responseText, 'text/html');
  2114. return r;
  2115. },
  2116.  
  2117. async getImage(url, pageUrl, xhr = ai.xhr) {
  2118. ai.bufBar = false;
  2119. ai.bufStart = now();
  2120. const response = await Remoting.gmXhr(url, {
  2121. responseType: 'blob',
  2122. headers: {
  2123. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2124. Referer: pageUrl || (typeof xhr === 'function' ? xhr() : url),
  2125. },
  2126. onprogress: Remoting.getImageProgress,
  2127. });
  2128. Bar.set(false);
  2129. const type = Remoting.guessMimeType(response);
  2130. let b = response.response;
  2131. if (!b) throw 'Empty response';
  2132. if (b.type !== type)
  2133. b = b.slice(0, b.size, type);
  2134. return [
  2135. xhr === 'blob' ? URL.createObjectURL(b) : await Remoting.blobToDataUrl(b),
  2136. type.startsWith('video'),
  2137. ];
  2138. },
  2139.  
  2140. getImageProgress(e) {
  2141. if (!ai.bufBar && now() - ai.bufStart > 3000 && e.loaded / e.total < 0.5)
  2142. ai.bufBar = true;
  2143. if (ai.bufBar) {
  2144. const pct = e.loaded / e.total * 100 | 0;
  2145. const size = e.total / 1024 | 0;
  2146. Bar.set(`${pct}% of ${size} kiB`, 'xhr');
  2147. }
  2148. },
  2149.  
  2150. async findRedirect() {
  2151. try {
  2152. const {finalUrl} = await Remoting.gmXhr(ai.url, {
  2153. method: 'HEAD',
  2154. headers: {
  2155. 'Referer': location.href.split('#', 1)[0],
  2156. },
  2157. });
  2158. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2159. if (!info || !info.url)
  2160. throw `Couldn't follow redirection target: ${finalUrl}`;
  2161. Object.assign(ai, info);
  2162. App.startSingle();
  2163. } catch (e) {
  2164. App.handleError(e);
  2165. }
  2166. },
  2167.  
  2168. async saveFile() {
  2169. const url = ai.popup.src || ai.popup.currentSrc;
  2170. let name = Remoting.getFileName(ai.imageUrl || url);
  2171. if (!name.includes('.'))
  2172. name += '.jpg';
  2173. if (url.startsWith('blob:') || url.startsWith('data:')) {
  2174. $create('a', {href: url, download: name})
  2175. .dispatchEvent(new MouseEvent('click'));
  2176. } else {
  2177. Status.set('+loading');
  2178. const onload = () => Status.set('-loading');
  2179. GM_download({
  2180. url,
  2181. name,
  2182. headers: {Referer: url},
  2183. onerror: e => {
  2184. Bar.set(`Could not download ${name}: ${e.error || e.message || e}.`, 'error');
  2185. onload();
  2186. },
  2187. onprogress: Remoting.getImageProgress,
  2188. onload,
  2189. });
  2190. }
  2191. },
  2192.  
  2193. getFileName(url) {
  2194. return decodeURIComponent(url).split('/').pop().replace(/[:#?].*/, '');
  2195. },
  2196.  
  2197. blobToDataUrl(blob) {
  2198. return new Promise((resolve, reject) => {
  2199. const fr = new FileReader();
  2200. fr.onload = () => resolve(fr.result);
  2201. fr.onerror = reject;
  2202. fr.readAsDataURL(blob);
  2203. });
  2204. },
  2205.  
  2206. guessMimeType({responseHeaders, finalUrl}) {
  2207. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2208. !RegExp.$1.includes('text/plain'))
  2209. return RegExp.$1;
  2210. const ext = /\.([a-z0-9]+?)($|\?|#)/i.exec(finalUrl) ? RegExp.$1 : 'jpg';
  2211. switch (ext.toLowerCase()) {
  2212. case 'bmp': return 'image/bmp';
  2213. case 'gif': return 'image/gif';
  2214. case 'jpe': return 'image/jpeg';
  2215. case 'jpeg': return 'image/jpeg';
  2216. case 'jpg': return 'image/jpeg';
  2217. case 'mp4': return 'video/mp4';
  2218. case 'png': return 'image/png';
  2219. case 'svg': return 'image/svg+xml';
  2220. case 'tif': return 'image/tiff';
  2221. case 'tiff': return 'image/tiff';
  2222. case 'webm': return 'video/webm';
  2223. default: return 'application/octet-stream';
  2224. }
  2225. },
  2226.  
  2227. findImageUrl(n, url) {
  2228. if (!n) return;
  2229. let html;
  2230. const path =
  2231. n.getAttribute('src') ||
  2232. n.getAttribute('data-m4v') ||
  2233. n.getAttribute('href') ||
  2234. n.getAttribute('content') ||
  2235. (html = n.outerHTML).includes('http') &&
  2236. html.match(/https?:\/\/[^\s"<>]+?\.(jpe?g|gif|png|svg|web[mp]|mp4)[^\s"<>]*|$/i)[0];
  2237. return !!path && Util.rel2abs(Util.decodeHtmlEntities(path),
  2238. $prop('base[href]', 'href', n.ownerDocument) || url);
  2239. },
  2240. };
  2241.  
  2242. const Status = {
  2243.  
  2244. set(status) {
  2245. if (!status && !cfg.globalStatus) {
  2246. ai.node && ai.node.removeAttribute(STATUS_ATTR);
  2247. return;
  2248. }
  2249. const prefix = cfg.globalStatus ? PREFIX : '';
  2250. const action = status && /^[+-]/.test(status) && status[0];
  2251. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  2252. const el = cfg.globalStatus ? doc.documentElement :
  2253. name === 'edge' ? ai.popup :
  2254. ai.node;
  2255. if (!el) return;
  2256. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  2257. const oldValue = (el.getAttribute(attr) || '').trim();
  2258. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  2259. switch (action) {
  2260. case '-':
  2261. cls.delete(name);
  2262. break;
  2263. case false:
  2264. for (const c of cls)
  2265. if (c.startsWith(prefix) && c !== name)
  2266. cls.delete(c);
  2267. // fallthrough to +
  2268. case '+':
  2269. if (name)
  2270. cls.add(name);
  2271. break;
  2272. }
  2273. const newValue = [...cls].join(' ');
  2274. if (newValue !== oldValue)
  2275. el.setAttribute(attr, newValue);
  2276. },
  2277.  
  2278. loading(force) {
  2279. if (!force) {
  2280. clearTimeout(ai.timerStatus);
  2281. ai.timerStatus = setTimeout(Status.loading, SETTLE_TIME, true);
  2282. } else if (!ai.popupLoaded) {
  2283. Status.set('+loading');
  2284. }
  2285. },
  2286. };
  2287.  
  2288. const UrlMatcher = (() => {
  2289. // string-to-regexp escaped chars
  2290. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  2291. // rx for '^' symbol in simple url match
  2292. const RX_SEP = /[^\w%._-]/y;
  2293. const RXS_SEP = RX_SEP.source;
  2294. return match => {
  2295. const results = [];
  2296. for (const s of ensureArray(match)) {
  2297. const pinDomain = s.startsWith('||');
  2298. const pinStart = !pinDomain && s.startsWith('|');
  2299. const endSep = s.endsWith('^');
  2300. let fn;
  2301. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  2302. if (needle.includes('^')) {
  2303. let plain = '';
  2304. for (const part of needle.split('^'))
  2305. if (part.length > plain.length)
  2306. plain = part;
  2307. const rx = new RegExp(
  2308. (pinStart ? '^' : '') +
  2309. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  2310. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  2311. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  2312. needle = [plain, rx];
  2313. fn = regexp;
  2314. } else if (pinStart) {
  2315. fn = endSep ? equals : starts;
  2316. } else if (pinDomain) {
  2317. const slashPos = needle.indexOf('/');
  2318. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  2319. needle = [needle, domain, slashPos > 0, endSep];
  2320. fn = startsDomainPrescreen;
  2321. } else if (endSep) {
  2322. fn = ends;
  2323. } else {
  2324. fn = has;
  2325. }
  2326. results.push({fn, data: needle});
  2327. }
  2328. return results.length > 1 ?
  2329. {fn: checkArray, data: results} :
  2330. results[0];
  2331. };
  2332. function checkArray(s) {
  2333. return this.some(checkArrayItem, s);
  2334. }
  2335. function checkArrayItem(item) {
  2336. return item.fn.call(item.data, this);
  2337. }
  2338. function ends(s) {
  2339. return s.endsWith(this) || (
  2340. s.length > this.length &&
  2341. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  2342. endsWithSep(s));
  2343. }
  2344. function endsWithSep(s, pos = s.length - 1) {
  2345. RX_SEP.lastIndex = pos;
  2346. return RX_SEP.test(s);
  2347. }
  2348. function equals(s) {
  2349. return s.startsWith(this) && (
  2350. s.length === this.length ||
  2351. s.length === this.length + 1 && endsWithSep(s));
  2352. }
  2353. function has(s) {
  2354. return s.includes(this);
  2355. }
  2356. function regexp(s) {
  2357. return s.includes(this[0]) && this[1].test(s);
  2358. }
  2359. function starts(s) {
  2360. return s.startsWith(this);
  2361. }
  2362. function startsDomainPrescreen(url) {
  2363. return url.includes(this[0]) && startsDomain.call(this, url);
  2364. }
  2365. function startsDomain(url) {
  2366. let hostStart = url.indexOf('//');
  2367. if (hostStart && url[hostStart - 1] !== ':')
  2368. return;
  2369. hostStart = hostStart < 0 ? 0 : hostStart + 2;
  2370. const host = url.slice(hostStart, (url.indexOf('/', hostStart) + 1 || url.length + 1) - 1);
  2371. const [needle, domain, pinDomainEnd, endSep] = this;
  2372. let start = pinDomainEnd ? host.length - domain.length : 0;
  2373. for (; ; start++) {
  2374. start = host.indexOf(domain, start);
  2375. if (start < 0)
  2376. return;
  2377. if (!start || host[start - 1] === '.')
  2378. break;
  2379. }
  2380. start += hostStart;
  2381. if (url.lastIndexOf(needle, start) !== start)
  2382. return;
  2383. const end = start + needle.length;
  2384. return !endSep || end === host.length || end === url.length || endsWithSep(url, end);
  2385. }
  2386. })();
  2387.  
  2388. const Util = {
  2389.  
  2390. addStyle(name, css) {
  2391. const id = `${PREFIX}style:${name}`;
  2392. const el = doc.getElementById(id) ||
  2393. css && $create('style', {id});
  2394. if (!el) return;
  2395. if (el.textContent !== css)
  2396. el.textContent = css;
  2397. if (el.parentElement !== doc.head)
  2398. doc.head.appendChild(el);
  2399. return el;
  2400. },
  2401.  
  2402. color(color, opacity = cfg[`ui${color}Opacity`]) {
  2403. return (color.startsWith('#') ? color : cfg[`ui${color}Color`]) +
  2404. (0x100 + Math.round(opacity / 100 * 255)).toString(16).slice(1);
  2405. },
  2406.  
  2407. decodeHtmlEntities(s) {
  2408. return s
  2409. .replace(/&quot;/g, '"')
  2410. .replace(/&apos;/g, '\'')
  2411. .replace(/&lt;/g, '<')
  2412. .replace(/&gt;/g, '>')
  2413. .replace(/&amp;/g, '&');
  2414. },
  2415.  
  2416. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2417. decodeUrl(url) {
  2418. if (!url) return url;
  2419. const iPct = url.indexOf('%');
  2420. const iColon = url.indexOf(':');
  2421. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2422. decodeURIComponent(url) :
  2423. url;
  2424. },
  2425.  
  2426. deepEqual(a, b) {
  2427. if (!a || !b || typeof a !== 'object' || typeof a !== typeof b)
  2428. return a === b;
  2429. if (Array.isArray(a)) {
  2430. return Array.isArray(b) &&
  2431. a.length === b.length &&
  2432. a.every((v, i) => Util.deepEqual(v, b[i]));
  2433. }
  2434. const keys = Object.keys(a);
  2435. return keys.length === Object.keys(b).length &&
  2436. keys.every(k => Util.deepEqual(a[k], b[k]));
  2437. },
  2438.  
  2439. forceLayout(node) {
  2440. // eslint-disable-next-line no-unused-expressions
  2441. node.clientHeight;
  2442. },
  2443.  
  2444. formatError(e, rule) {
  2445. const message =
  2446. e.message ||
  2447. e.readyState && 'Request failed.' ||
  2448. e.type === 'error' && `File can't be displayed.${
  2449. $('div[bgactive*="flashblock"]', doc) ? ' Check Flashblock settings.' : ''
  2450. }` ||
  2451. e;
  2452. const m = [
  2453. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold;color:yellow'],
  2454. ['', 'font-weight:normal;color:unset'],
  2455. ];
  2456. m.push(...[
  2457. ['Node: %o', ai.node],
  2458. ['Rule: %o', rule],
  2459. ai.url && ['URL: %s', ai.url],
  2460. ai.imageUrl && ai.imageUrl !== ai.url && ['File: %s', ai.imageUrl],
  2461. ].filter(Boolean));
  2462. return {
  2463. message,
  2464. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2465. consoleArgs: m.map(([, v]) => v),
  2466. };
  2467. },
  2468.  
  2469. isHovered(el) {
  2470. // doesn't work in image tabs, browser bug?
  2471. return App.isImageTab || el.closest(':hover');
  2472. },
  2473.  
  2474. isVideoUrl(url) {
  2475. return url.startsWith('data:video') ||
  2476. !url.startsWith('data:') && /\.(webm|mp4)($|\?)/.test(url);
  2477. },
  2478.  
  2479. newFunction(...args) {
  2480. try {
  2481. return App.NOP || new Function(...args);
  2482. } catch (e) {
  2483. if (!e.message.includes('unsafe-eval'))
  2484. throw e;
  2485. App.NOP = () => {};
  2486. return App.NOP;
  2487. }
  2488. },
  2489.  
  2490. rel2abs(rel, abs = location.href) {
  2491. try {
  2492. return rel.startsWith('data:') ? rel :
  2493. rel.startsWith('blob:') ? '' : // blobs don't work because they're usually revoked
  2494. new URL(rel, abs).href;
  2495. } catch (e) {
  2496. return rel;
  2497. }
  2498. },
  2499.  
  2500. stringify(...args) {
  2501. const p = Array.prototype;
  2502. const {toJSON} = p;
  2503. if (toJSON) p.toJSON = null;
  2504. const res = JSON.stringify(...args);
  2505. if (toJSON) p.toJSON = toJSON;
  2506. return res;
  2507. },
  2508.  
  2509. suppressTooltip() {
  2510. for (const node of [
  2511. ai.node.parentNode,
  2512. ai.node,
  2513. ai.node.firstElementChild,
  2514. ]) {
  2515. const t = (node || 0).title;
  2516. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2517. ai.tooltip = {node, text: t};
  2518. node.title = '';
  2519. break;
  2520. }
  2521. }
  2522. },
  2523.  
  2524. tabFixUrl() {
  2525. return ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  2526. navigator.userAgent.includes('Gecko/') &&
  2527. flattenHtml(`data:text/html;charset=utf8,
  2528. <style>
  2529. body {
  2530. margin: 0;
  2531. padding: 0;
  2532. background: #222;
  2533. }
  2534. .fit {
  2535. overflow: hidden
  2536. }
  2537. .fit > img {
  2538. max-width: 100vw;
  2539. max-height: 100vh;
  2540. }
  2541. body > img {
  2542. margin: auto;
  2543. position: absolute;
  2544. left: 0;
  2545. right: 0;
  2546. top: 0;
  2547. bottom: 0;
  2548. }
  2549. </style>
  2550. <body class=fit>
  2551. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2552. </body>
  2553. `).replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2554. },
  2555. };
  2556.  
  2557. function setup({rule} = {}) {
  2558. if (typeof doc.body.attachShadow !== 'function') {
  2559. alert('Cannot show MPIV config dialog: the browser is probably too old.\n' +
  2560. 'You can edit the script\'s storage directly in your userscript manager.');
  2561. return;
  2562. }
  2563. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2564. let uiCfg;
  2565. let root = (elConfig || 0).shadowRoot;
  2566. let {blankRuleElement} = setup;
  2567. /** @type NodeList */
  2568. const UI = new Proxy({}, {
  2569. get(_, id) {
  2570. return root.getElementById(id);
  2571. },
  2572. });
  2573. if (!rule || !elConfig)
  2574. init(new Config({save: true}));
  2575. if (rule)
  2576. installRule(rule);
  2577.  
  2578. function init(data) {
  2579. uiCfg = data;
  2580. $remove(elConfig);
  2581. elConfig = $create('div', {contentEditable: true});
  2582. root = elConfig.attachShadow({mode: 'open'});
  2583. root.innerHTML = createConfigHtml();
  2584. initEvents();
  2585. renderAll();
  2586. renderCustomScales();
  2587. renderRules();
  2588. doc.body.appendChild(elConfig);
  2589. requestAnimationFrame(() => {
  2590. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, elConfig.clientHeight / 4) + 'px';
  2591. });
  2592. }
  2593.  
  2594. function initEvents() {
  2595. UI._apply.onclick = UI._cancel.onclick = UI._ok.onclick = UI._x.onclick = closeSetup;
  2596. UI._export.onclick = e => {
  2597. dropEvent(e);
  2598. GM_setClipboard(Util.stringify(collectConfig(), null, ' '));
  2599. UI._exportNotification.hidden = false;
  2600. setTimeout(() => (UI._exportNotification.hidden = true), 1000);
  2601. };
  2602. UI._import.onclick = e => {
  2603. dropEvent(e);
  2604. const s = prompt('Paste settings:');
  2605. if (s)
  2606. init(new Config({data: s}));
  2607. };
  2608. UI._install.onclick = setupRuleInstaller;
  2609. const /** @type {HTMLTextAreaElement} */ cssApp = UI._cssApp;
  2610. UI._reveal.onclick = e => {
  2611. e.preventDefault();
  2612. cssApp.hidden = !cssApp.hidden;
  2613. if (!cssApp.hidden) {
  2614. if (!cssApp.value) {
  2615. App.updateStyles();
  2616. cssApp.value = App.globalStyle.trim();
  2617. cssApp.setSelectionRange(0, 0);
  2618. }
  2619. cssApp.focus();
  2620. }
  2621. };
  2622. UI.start.onchange = function () {
  2623. UI.delay.closest('label').hidden =
  2624. UI.preload.closest('label').hidden =
  2625. this.value !== 'auto';
  2626. };
  2627. UI.start.onchange();
  2628. UI.xhr.onclick = ({target: el}) => el.checked || confirm($propUp(el, 'title'));
  2629. // color
  2630. for (const el of $$('[type="color"]', root)) {
  2631. el.oninput = colorOnInput;
  2632. el.elSwatch = el.nextElementSibling;
  2633. el.elOpacity = UI[el.id.replace('Color', 'Opacity')];
  2634. el.elOpacity.elColor = el;
  2635. }
  2636. function colorOnInput() {
  2637. this.elSwatch.style.setProperty('--color',
  2638. Util.color(this.value, this.elOpacity.valueAsNumber));
  2639. }
  2640. // range
  2641. for (const el of $$('[type="range"]', root)) {
  2642. el.oninput = rangeOnInput;
  2643. el.onblur = rangeOnBlur;
  2644. el.addEventListener('focusin', rangeOnFocus);
  2645. }
  2646. function rangeOnBlur(e) {
  2647. if (this.elEdit && e.relatedTarget !== this.elEdit)
  2648. this.elEdit.onblur(e);
  2649. }
  2650. function rangeOnFocus() {
  2651. if (this.elEdit) return;
  2652. const {min, max, step, value} = this;
  2653. this.elEdit = $create('input', {
  2654. value, min, max, step,
  2655. className: 'range-edit',
  2656. style: `left: ${this.offsetLeft}px; margin-top: ${this.offsetHeight + 1}px`,
  2657. type: 'number',
  2658. elRange: this,
  2659. onblur: rangeEditOnBlur,
  2660. oninput: rangeEditOnInput,
  2661. });
  2662. this.insertAdjacentElement('afterend', this.elEdit);
  2663. }
  2664. function rangeOnInput() {
  2665. this.title = (this.dataset.title || '').replace('$', this.value);
  2666. if (this.elColor) this.elColor.oninput();
  2667. if (this.elEdit) this.elEdit.valueAsNumber = this.valueAsNumber;
  2668. }
  2669. // range-edit
  2670. function rangeEditOnBlur(e) {
  2671. if (e.relatedTarget !== this.elRange) {
  2672. this.remove();
  2673. this.elRange.elEdit = null;
  2674. }
  2675. }
  2676. function rangeEditOnInput() {
  2677. this.elRange.valueAsNumber = this.valueAsNumber;
  2678. this.elRange.oninput();
  2679. }
  2680. // prevent the main page from interpreting key presses in inputs as hotkeys
  2681. // which may happen since it sees only the outer <div> in the event |target|
  2682. root.addEventListener('keydown', e => !e.altKey && !e.metaKey && e.stopPropagation(), true);
  2683. }
  2684.  
  2685. function closeSetup(event) {
  2686. const isApply = this.id === '_apply';
  2687. if (event && (this.id === '_ok' || isApply)) {
  2688. cfg = uiCfg = collectConfig({save: true, clone: isApply});
  2689. Ruler.init();
  2690. if (isApply) {
  2691. renderCustomScales();
  2692. return;
  2693. }
  2694. }
  2695. $remove(elConfig);
  2696. elConfig = null;
  2697. }
  2698.  
  2699. function collectConfig({save, clone} = {}) {
  2700. let data = {};
  2701. for (const el of $$('input[id], select[id]', root))
  2702. data[el.id] = el.type === 'checkbox' ? el.checked :
  2703. (el.type === 'number' || el.type === 'range') ? el.valueAsNumber :
  2704. el.value || '';
  2705. Object.assign(data, {
  2706. css: UI.css.value.trim(),
  2707. delay: UI.delay.valueAsNumber * 1000,
  2708. hosts: collectRules(),
  2709. scale: clamp(UI.scale.valueAsNumber / 100, 0, 1) + 1,
  2710. scales: UI.scales.value
  2711. .trim()
  2712. .split(/[,;]*\s+/)
  2713. .map(x => x.replace(',', '.'))
  2714. .filter(x => !isNaN(parseFloat(x))),
  2715. });
  2716. if (clone)
  2717. data = JSON.parse(Util.stringify(data));
  2718. return new Config({data, save});
  2719. }
  2720.  
  2721. function collectRules() {
  2722. return [...UI._rules.children]
  2723. .map(el => [el.value.trim(), el[RULE]])
  2724. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  2725. .map(([s, json]) => json || s)
  2726. .filter(Boolean);
  2727. }
  2728.  
  2729. function checkRule({target: el}) {
  2730. let json, error, title;
  2731. const prev = el.previousElementSibling;
  2732. if (el.value) {
  2733. json = Ruler.parse(el.value);
  2734. error = json instanceof Error && (json.message || String(json));
  2735. const invalidDomain = !error && json && typeof json.d === 'string' &&
  2736. !/^[-.a-z0-9]*$/i.test(json.d);
  2737. title = [invalidDomain && 'Disabled due to invalid characters in "d"', error]
  2738. .filter(Boolean).join('\n');
  2739. el.classList.toggle('invalid-domain', invalidDomain);
  2740. el.classList.toggle('matching-domain', !!json.d && hostname.includes(json.d));
  2741. if (!prev)
  2742. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2743. } else if (prev) {
  2744. prev.focus();
  2745. el.remove();
  2746. }
  2747. el[RULE] = !error && json;
  2748. el.title = title;
  2749. el.setCustomValidity(error || '');
  2750. }
  2751.  
  2752. function focusRule({type, target: el, relatedTarget: from}) {
  2753. if (el === this)
  2754. return;
  2755. if (type === 'paste') {
  2756. setTimeout(() => focusRule.call(this, {target: el}));
  2757. return;
  2758. }
  2759. if (el[RULE])
  2760. el.value = Ruler.format(el[RULE], {expand: true});
  2761. const h = clamp(el.scrollHeight, 15, elConfig.clientHeight / 4);
  2762. if (h > el.offsetHeight)
  2763. el.style.minHeight = h + 'px';
  2764. if (!this.contains(from))
  2765. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  2766. if (from) {
  2767. from.style.minHeight = '';
  2768. if (from[RULE])
  2769. from.value = Ruler.format(from[RULE]);
  2770. }
  2771. }
  2772.  
  2773. function installRule(rule) {
  2774. const inputs = UI._rules.children;
  2775. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  2776. if (!el) {
  2777. el = inputs[0];
  2778. el[RULE] = rule;
  2779. el.value = Ruler.format(rule);
  2780. el.hidden = false;
  2781. const i = Math.max(0, collectRules().indexOf(rule));
  2782. inputs[i].insertAdjacentElement('afterend', el);
  2783. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2784. }
  2785. const rect = el.getBoundingClientRect();
  2786. if (rect.bottom < 0 ||
  2787. rect.bottom > el.parentNode.offsetHeight)
  2788. el.scrollIntoView();
  2789. el.classList.add('highlight');
  2790. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  2791. el.focus();
  2792. }
  2793.  
  2794. function renderRules() {
  2795. const rules = UI._rules;
  2796. rules.addEventListener('input', checkRule);
  2797. rules.addEventListener('focusin', focusRule);
  2798. rules.addEventListener('paste', focusRule);
  2799. blankRuleElement =
  2800. setup.blankRuleElement =
  2801. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  2802. for (const rule of uiCfg.hosts || []) {
  2803. const el = blankRuleElement.cloneNode();
  2804. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  2805. rules.appendChild(el);
  2806. checkRule({target: el});
  2807. }
  2808. const search = UI._search;
  2809. search.oninput = () => {
  2810. setup.search = search.value;
  2811. const s = search.value.toLowerCase();
  2812. for (const el of rules.children)
  2813. el.hidden = s && !el.value.toLowerCase().includes(s);
  2814. };
  2815. search.value = setup.search || '';
  2816. if (search.value)
  2817. search.oninput();
  2818. }
  2819.  
  2820. function renderCustomScales() {
  2821. UI.scales.value = uiCfg.scales.join(' ').trim() || Config.DEFAULTS.scales.join(' ');
  2822. }
  2823.  
  2824. function renderAll() {
  2825. for (const el of $$('input[id], select[id], textarea[id]', root))
  2826. if (el.id in uiCfg)
  2827. el[el.type === 'checkbox' ? 'checked' : 'value'] = uiCfg[el.id];
  2828. for (const el of $$('input[type="range"]', root))
  2829. el.oninput();
  2830. for (const el of $$('a[href^="http"]', root))
  2831. Object.assign(el, {target: '_blank', rel: 'noreferrer noopener external'});
  2832. UI.delay.valueAsNumber = uiCfg.delay / 1000;
  2833. UI.scale.valueAsNumber = Math.round(clamp(uiCfg.scale - 1, 0, 1) * 100);
  2834. }
  2835. }
  2836.  
  2837. function setupClickedRule(event) {
  2838. const el = event.target.closest('blockquote, code, pre');
  2839. const text = el && el.textContent.trim() || '';
  2840. if (!event.button &&
  2841. !eventModifiers(event) &&
  2842. text.startsWith('{') &&
  2843. text.endsWith('}') &&
  2844. /[{,]\s*"[degqrsu]"\s*:\s*"/.test(text)) {
  2845. const rule = tryCatch(JSON.parse, text);
  2846. if (Object.keys(rule).some(k => /^[degqrsu]$/.test(k))) {
  2847. dropEvent(event);
  2848. setup({rule});
  2849. }
  2850. }
  2851. }
  2852.  
  2853. async function setupRuleInstaller(e) {
  2854. dropEvent(e);
  2855. const parent = this.parentElement;
  2856. parent.children._installLoading.hidden = false;
  2857. this.remove();
  2858. let rules;
  2859.  
  2860. try {
  2861. rules = extractRules(await Remoting.getDoc(this.href));
  2862. const selector = $create('select', {
  2863. size: 8,
  2864. style: 'width: 100%',
  2865. ondblclick: e => e.target !== selector && maybeSetup(e),
  2866. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  2867. });
  2868. selector.append(...rules.map(renderRule));
  2869. selector.selectedIndex = findMatchingRuleIndex();
  2870. // remove "name" since the installed rules don't need it
  2871. for (const r of rules)
  2872. delete r.name;
  2873. parent.children._installLoading.remove();
  2874. parent.children._installHint.hidden = false;
  2875. parent.appendChild(selector);
  2876. requestAnimationFrame(() => {
  2877. const optY = selector.selectedOptions[0].offsetTop - selector.offsetTop;
  2878. selector.scrollTo(0, optY - selector.offsetHeight / 2);
  2879. selector.focus();
  2880. });
  2881. } catch (e) {
  2882. parent.textContent = 'Error loading rules: ' + (e.message || e);
  2883. }
  2884.  
  2885. function extractRules({doc}) {
  2886. const code = $('script', doc).textContent;
  2887. // sort by name
  2888. return JSON.parse(code.match(/var\s+rules\s*=\s*(\[.+]);?[\r\n]/)[1])
  2889. .filter(r => !r.d || hostname.includes(r.d))
  2890. .sort((a, b) =>
  2891. (a = a.name.toLowerCase()) < (b = b.name.toLowerCase()) ? -1 :
  2892. a > b ? 1 :
  2893. 0);
  2894. }
  2895.  
  2896. function findMatchingRuleIndex() {
  2897. const dottedHost = `.${hostname}.`;
  2898. let maxCount = 0, maxIndex = 0, index = 0;
  2899. for (const {d, name} of rules) {
  2900. let count = !!(d && hostname.includes(d)) * 10;
  2901. for (const part of name.toLowerCase().split(/[^a-z\d.-]+/i))
  2902. count += dottedHost.includes(`.${part}.`) && part.length;
  2903. if (count > maxCount) {
  2904. maxCount = count;
  2905. maxIndex = index;
  2906. }
  2907. index++;
  2908. }
  2909. return maxIndex;
  2910. }
  2911.  
  2912. function renderRule(r) {
  2913. const {name, ...copy} = r;
  2914. return $create('option', {
  2915. textContent: name,
  2916. title: Ruler.format(copy, {expand: true})
  2917. .replace(/^{|\s*}$/g, '')
  2918. .split('\n')
  2919. .slice(0, 12)
  2920. .map(renderTitleLine)
  2921. .filter(Boolean)
  2922. .join('\n'),
  2923. });
  2924. }
  2925.  
  2926. function renderTitleLine(line, i, arr) {
  2927. return (
  2928. // show ... on 10th line if there are more lines
  2929. i === 9 && arr.length > 10 ? '...' :
  2930. i > 10 ? '' :
  2931. // truncate to 100 chars
  2932. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  2933. // strip the leading space
  2934. .replace(/^\s/, ''));
  2935. }
  2936.  
  2937. function maybeSetup(e) {
  2938. if (!eventModifiers(e))
  2939. setup({rule: rules[e.currentTarget.selectedIndex]});
  2940. }
  2941. }
  2942.  
  2943. function createConfigHtml() {
  2944. const MPIV_BASE_URL = 'https://w9p.co/userscripts/mpiv/';
  2945. const scalesHint = 'Leave it empty and click Apply or OK to restore the default values.';
  2946. const trimLeft = s => s.trim().replace(/\n\s+/g, '\r');
  2947. return flattenHtml(`
  2948. <style>
  2949. :host {
  2950. all: initial !important;
  2951. position: fixed !important;
  2952. z-index: 2147483647 !important;
  2953. top: 20px !important;
  2954. right: 20px !important;
  2955. padding: 1.5em !important;
  2956. color: #000 !important;
  2957. background: #eee !important;
  2958. box-shadow: 5px 5px 25px 2px #000 !important;
  2959. width: 32em !important;
  2960. border: 1px solid black !important;
  2961. display: flex !important;
  2962. flex-direction: column !important;
  2963. }
  2964. main {
  2965. font: 12px/15px sans-serif;
  2966. }
  2967. ul {
  2968. max-height: calc(100vh - 200px);
  2969. margin: 10px 0 15px 0;
  2970. padding: 0;
  2971. list-style: none;
  2972. }
  2973. li {
  2974. margin: 0;
  2975. padding: .25em 0;
  2976. }
  2977. li.options {
  2978. display: flex;
  2979. align-items: center;
  2980. justify-content: space-between;
  2981. }
  2982. li.row {
  2983. flex-wrap: wrap;
  2984. justify-content: flex-start;
  2985. }
  2986. li.row label {
  2987. flex-direction: row;
  2988. align-items: center;
  2989. }
  2990. li.row input {
  2991. margin-right: .25em;
  2992. }
  2993. li.stretch label {
  2994. flex: 1;
  2995. white-space: nowrap;
  2996. }
  2997. li.stretch label > span {
  2998. display: flex;
  2999. flex-direction: row;
  3000. flex: 1;
  3001. }
  3002. label {
  3003. display: inline-flex;
  3004. flex-direction: column;
  3005. }
  3006. label:not(:last-child) {
  3007. margin-right: 1em;
  3008. }
  3009. input, select {
  3010. min-height: 1.6em;
  3011. box-sizing: border-box;
  3012. }
  3013. input[type=checkbox] {
  3014. margin-left: 0;
  3015. }
  3016. input[type=number] {
  3017. width: 4em;
  3018. }
  3019. input:not([type=checkbox]) {
  3020. padding: 0 .25em;
  3021. }
  3022. input[type=range] {
  3023. flex: 1;
  3024. width: 100%;
  3025. margin: 0 .25em;
  3026. padding: 0;
  3027. filter: saturate(0);
  3028. opacity: .5;
  3029. }
  3030. u + input[type=range] {
  3031. max-width: 3em;
  3032. }
  3033. input[type=range]:hover {
  3034. filter: none;
  3035. opacity: 1;
  3036. }
  3037. input[type=color] {
  3038. position: absolute;
  3039. width: calc(1.5em + 2px);
  3040. opacity: 0;
  3041. cursor: pointer;
  3042. }
  3043. u {
  3044. display: inline-block;
  3045. position: relative;
  3046. width: 1.5em;
  3047. height: 1.5em;
  3048. border: 1px solid #888;
  3049. pointer-events: none;
  3050. color: #888;
  3051. background-image:
  3052. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%),
  3053. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%);
  3054. background-size: .5em .5em;
  3055. background-position: 0 0, .25em .25em;
  3056. }
  3057. u::after {
  3058. position: absolute;
  3059. top: 0;
  3060. left: 0;
  3061. right: 0;
  3062. bottom: 0;
  3063. content: "";
  3064. background-color: var(--color);
  3065. }
  3066. .range-edit {
  3067. position: absolute;
  3068. box-shadow: 0 0.25em 1em #000;
  3069. z-index: 99;
  3070. }
  3071. #_rules input,
  3072. textarea {
  3073. flex: 1;
  3074. resize: vertical;
  3075. margin: 1px 0;
  3076. font: 11px/1.25 Consolas, monospace;
  3077. }
  3078. :invalid {
  3079. background-color: #f002;
  3080. border-color: #800;
  3081. }
  3082. code {
  3083. font-weight: bold;
  3084. }
  3085. a {
  3086. text-decoration: none;
  3087. }
  3088. a:hover {
  3089. text-decoration: underline;
  3090. }
  3091. button {
  3092. padding: .2em 1em;
  3093. margin: 0 1em;
  3094. }
  3095. kbd {
  3096. padding: 1px 6px;
  3097. font-weight: bold;
  3098. font-family: Consolas, monospace;
  3099. border: 1px solid #888;
  3100. border-radius: 3px;
  3101. box-shadow: inset 1px 1px 5px #8888, .25px .5px 2px #0008;
  3102. }
  3103. .column {
  3104. display: flex;
  3105. flex-direction: column;
  3106. }
  3107. .highlight {
  3108. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  3109. animation-fill-mode: both;
  3110. }
  3111. #_rules > * {
  3112. word-break: break-all;
  3113. }
  3114. #_rules > :not(:focus) {
  3115. overflow: hidden; /* prevents wrapping in FF */
  3116. }
  3117. .invalid-domain {
  3118. opacity: .5;
  3119. }
  3120. .matching-domain {
  3121. border-color: #56b8ff;
  3122. background: #d7eaff;
  3123. }
  3124. #_x {
  3125. position: absolute;
  3126. top: 0;
  3127. right: 0;
  3128. padding: 4px 8px;
  3129. cursor: pointer;
  3130. user-select: none;
  3131. }
  3132. #_x:hover {
  3133. background-color: #8884;
  3134. }
  3135. #_cssApp {
  3136. color: seagreen;
  3137. }
  3138. #_exportNotification {
  3139. color: green;
  3140. font-weight: bold;
  3141. position: absolute;
  3142. left: 0;
  3143. right: 0;
  3144. bottom: 2px;
  3145. }
  3146. #_installHint {
  3147. color: green;
  3148. }
  3149. @keyframes fade-in {
  3150. from { background-color: deepskyblue }
  3151. to {}
  3152. }
  3153. @media (prefers-color-scheme: dark) {
  3154. :host {
  3155. color: #aaa !important;
  3156. background: #333 !important;
  3157. }
  3158. a {
  3159. color: deepskyblue;
  3160. }
  3161. button {
  3162. background: linear-gradient(-5deg, #333, #555);
  3163. border: 1px solid #000;
  3164. box-shadow: 0 2px 6px #181818;
  3165. border-radius: 3px;
  3166. cursor: pointer;
  3167. }
  3168. button:hover {
  3169. background: linear-gradient(-5deg, #333, #666);
  3170. }
  3171. textarea, input, select {
  3172. background: #111;
  3173. color: #BBB;
  3174. border: 1px solid #555;
  3175. }
  3176. input[type=checkbox] {
  3177. filter: invert(1);
  3178. }
  3179. input[type=range] {
  3180. filter: invert(1) saturate(0);
  3181. }
  3182. input[type=range]:hover {
  3183. filter: invert(1);
  3184. }
  3185. kbd {
  3186. border-color: #666;
  3187. }
  3188. @supports (-moz-appearance: none) {
  3189. input[type=checkbox],
  3190. input[type=range],
  3191. input[type=range]:hover {
  3192. filter: none;
  3193. }
  3194. }
  3195. .range-edit {
  3196. box-shadow: 0 .5em 1em .5em #000;
  3197. }
  3198. .matching-domain {
  3199. border-color: #0065af;
  3200. background: #032b58;
  3201. color: #ddd;
  3202. }
  3203. #_cssApp {
  3204. color: darkseagreen;
  3205. }
  3206. #_installHint {
  3207. color: greenyellow;
  3208. }
  3209. ::-webkit-scrollbar {
  3210. width: 14px;
  3211. height: 14px;
  3212. background: #333;
  3213. }
  3214. ::-webkit-scrollbar-button:single-button {
  3215. background: radial-gradient(circle at center, #555 40%, #333 40%)
  3216. }
  3217. ::-webkit-scrollbar-track-piece {
  3218. background: #444;
  3219. border: 4px solid #333;
  3220. border-radius: 8px;
  3221. }
  3222. ::-webkit-scrollbar-thumb {
  3223. border: 3px solid #333;
  3224. border-radius: 8px;
  3225. background: #666;
  3226. }
  3227. ::-webkit-resizer {
  3228. background: #111 linear-gradient(-45deg, transparent 3px, #888 3px, #888 4px, transparent 4px, transparent 6px, #888 6px, #888 7px, transparent 7px) no-repeat;
  3229. border: 2px solid transparent;
  3230. }
  3231. }
  3232. </style>
  3233. <main>
  3234. <div id=_x>x</div>
  3235. <ul class=column>
  3236. <details style="margin: -2em 0 1em">
  3237. <summary style="cursor:pointer"><b>Click to view help & hotkeys</b></summary>
  3238. <table style="text-align:left">
  3239. <tr><th>Activate</th><td>move mouse cursor over thumbnail</td></tr>
  3240. <tr><th>Deactivate</th><td>move cursor off thumbnail, or click, or zoom out fully</td></tr>
  3241. <tr><th>Prevent/freeze</th><td>hold down <kbd>Shift</kbd> while entering/leaving thumbnail</td></tr>
  3242. <tr><th>Force-activate<br>(for small pics)</th>
  3243. <td>hold <kbd>Ctrl</kbd> while entering image element</td></tr>
  3244. <tr><td>&nbsp;</td></tr>
  3245. <tr><th>Start zooming</th>
  3246. <td>configurable: automatic or via right-click / <kbd>Shift</kbd> while popup is visible</td></tr>
  3247. <tr><th>Zoom</th><td>mouse wheel</td></tr>
  3248. <tr><th>Rotate</th><td><kbd>L</kbd> <kbd>r</kbd> keys (left or right)</td></tr>
  3249. <tr><th>Flip/mirror</th><td><kbd>h</kbd> <kbd>v</kbd> keys (horizontally or vertically)</td></tr>
  3250. <tr><th>Previous/next<br>in album</th>
  3251. <td>mouse wheel, <kbd>j</kbd> <kbd>k</kbd> or <kbd>←</kbd> <kbd>→</kbd> keys</td></tr>
  3252. <tr><td>&nbsp;</td></tr>
  3253. <tr><th>Download</th><td><kbd>d</kbd> key while popup is visible</td></tr>
  3254. <tr><th>Mute/unmute</th><td><kbd>m</kbd> key while popup is visible</td></tr>
  3255. <tr><th>Open in tab</th><td><kbd>t</kbd> key while popup is visible</td></tr>
  3256. </table>
  3257. </details>
  3258. <li class=options>
  3259. <label>Popup shows on
  3260. <select id=start>
  3261. <option value=auto>automatically
  3262. <option value=context>Right click / Ctrl
  3263. <option value=ctrl>Ctrl
  3264. </select>
  3265. </label>
  3266. <label>after, sec<input id=delay type=number min=0.05 max=10 step=0.05 title=seconds></label>
  3267. <label title="(if the full version of the hovered image is ...% larger)">
  3268. if larger, %<input id=scale type=number min=0 max=100 step=1>
  3269. </label>
  3270. <label>Zoom activates on
  3271. <select id=zoom>
  3272. <option value=context>Right click / Shift
  3273. <option value=wheel>Wheel up / Shift
  3274. <option value=shift>Shift
  3275. <option value=auto>automatically
  3276. </select>
  3277. </label>
  3278. <label>...and zooms to
  3279. <select id=fit>
  3280. <option value=all>fit to window
  3281. <option value=large>fit if larger
  3282. <option value=no>100%
  3283. <option value="" title="Use custom scale factors">custom
  3284. </select>
  3285. </label>
  3286. </li>
  3287. <li class=options>
  3288. <label>Zoom step, %<input id=zoomStep type=number min=100 max=400 step=1>
  3289. </label>
  3290. <label>When fully zoomed out:
  3291. <select id=zoomOut>
  3292. <option value=stay>stay in zoom mode
  3293. <option value=auto>stay if still hovered
  3294. <option value=unzoom>undo zoom mode
  3295. <option value=close>close popup
  3296. </select>
  3297. </label>
  3298. <label style="flex: 1" title="${trimLeft(`
  3299. Scale factors to use when zooms to selector is set to custom”.
  3300. 0 = fit to window,
  3301. 0! = same as 0 but also removes smaller values,
  3302. * after a value marks the default zoom factor, for example: 1*
  3303. The popup won't shrink below the image's natural size or window size for bigger mages.
  3304. ${scalesHint}
  3305. `)}">Custom scale factors:
  3306. <input id=scales placeholder="${scalesHint}">
  3307. </label>
  3308. </li>
  3309. <li class="options row">
  3310. <label title="...or try to keep the original link/thumbnail unobscured by the popup">
  3311. <input type=checkbox id=center>Centered*</label>
  3312. <label title="Provides smoother experience but increases network traffic">
  3313. <input type=checkbox id=preload>Preload on hover*</label>
  3314. <label title="...or show a partial image while still loading">
  3315. <input type=checkbox id=waitLoad>Show when fully loaded*</label>
  3316. <label><input type=checkbox id=uiFadein>Fade-in transition</label>
  3317. <label><input type=checkbox id=mute>Mute videos</label>
  3318. <label><input type=checkbox id=imgtab>Run in image tabs</label>
  3319. <label title="Causes slowdowns so don't enable unless you explicitly use it in your custom CSS">
  3320. <input type=checkbox id=globalStatus>Expose status on &lt;html&gt;*</label>
  3321. <label title="Disable only if you spoof the HTTP headers yourself">
  3322. <input type=checkbox id=xhr>Spoof hotlinking*</label>
  3323. </li>
  3324. <li class="options stretch">
  3325. <label>Background
  3326. <span>
  3327. <input id=uiBackgroundColor type=color><u></u>
  3328. <input id=uiBackgroundOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3329. </span>
  3330. </label>
  3331. <label>Border color, opacity, size
  3332. <span>
  3333. <input id=uiBorderColor type=color><u></u>
  3334. <input id=uiBorderOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3335. <input id=uiBorder type=range min=0 max=20 step=1 data-title="Border size: $px">
  3336. </span>
  3337. </label>
  3338. <label>Shadow color, opacity, size
  3339. <span>
  3340. <input id=uiShadowColor type=color><u></u>
  3341. <input id=uiShadowOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3342. <input id=uiShadow type=range min=0 max=100 step=1 data-title="
  3343. ${'Shadow blur radius: $px\n"0" disables the shadow.'}">
  3344. </span>
  3345. </label>
  3346. <label>Padding
  3347. <span><input id=uiPadding type=range min=0 max=100 step=1 data-title="Padding: $px"></span>
  3348. </label>
  3349. <label>Margin
  3350. <span><input id=uiMargin type=range min=0 max=100 step=1 data-title="Margin: $px"></span>
  3351. </label>
  3352. </li>
  3353. <li>
  3354. <a href="${MPIV_BASE_URL}css.html">Custom CSS:</a>&nbsp;
  3355. e.g. <b>#mpiv-popup { animation: none !important }</b>
  3356. <a href="#" id=_reveal style="float: right"
  3357. title="You can copy parts of it to override them in your custom CSS">
  3358. View the built-in CSS</a>
  3359. <div class=column>
  3360. <textarea id=css spellcheck=false></textarea>
  3361. <textarea id=_cssApp spellcheck=false hidden readonly rows=30></textarea>
  3362. </div>
  3363. </li>
  3364. <li style="display: flex; justify-content: space-between;">
  3365. <div><a href="${MPIV_BASE_URL}host_rules.html">Custom host rules:</a></div>
  3366. <div style="white-space: nowrap">
  3367. To disable, put any symbol except <code>a..z 0..9 - .</code><br>
  3368. in "d" value, for example <code>"d": "!foo.com"</code>
  3369. </div>
  3370. <div>
  3371. <input id=_search type=search placeholder=Search style="width: 10em; margin-left: 1em">
  3372. </div>
  3373. </li>
  3374. <li style="margin-left: -3px; margin-right: -3px; overflow-y: auto; padding-left: 3px; padding-right: 3px;">
  3375. <div id=_rules class=column>
  3376. <textarea rows=1 spellcheck=false></textarea>
  3377. </div>
  3378. </li>
  3379. <li>
  3380. <div hidden id=_installLoading>Loading...</div>
  3381. <div hidden id=_installHint>Double-click the rule (or select and press Enter) to add it
  3382. . Click <code>Apply</code> or <code>OK</code> to confirm.</div>
  3383. <a href="${MPIV_BASE_URL}more_host_rules.html" id=_install>Install rule from repository...</a>
  3384. </li>
  3385. </ul>
  3386. <div style="text-align:center">
  3387. <button id=_ok accesskey=s>OK</button>
  3388. <button id=_apply accesskey=a>Apply</button>
  3389. <button id=_import style="margin-right: 0">Import</button>
  3390. <button id=_export style="margin-left: 0">Export</button>
  3391. <button id=_cancel>Cancel</button>
  3392. <div id=_exportNotification hidden>Copied to clipboard.</div>
  3393. </div>
  3394. </main>`);
  3395. }
  3396.  
  3397. function createGlobalStyle() {
  3398. App.globalStyle = /*language=CSS*/ (String.raw`
  3399. #\mpiv-bar {
  3400. position: fixed;
  3401. z-index: 2147483647;
  3402. top: 0;
  3403. left: 0;
  3404. right: 0;
  3405. opacity: 0;
  3406. transition: opacity 1s ease .25s;
  3407. text-align: center;
  3408. font-family: sans-serif;
  3409. font-size: 15px;
  3410. font-weight: bold;
  3411. background: #0005;
  3412. color: white;
  3413. padding: 4px 10px;
  3414. text-shadow: .5px .5px 2px #000;
  3415. }
  3416. #\mpiv-bar.\mpiv-show {
  3417. opacity: 1;
  3418. }
  3419. #\mpiv-bar[data-zoom]::after {
  3420. content: " (" attr(data-zoom) ")";
  3421. opacity: .8;
  3422. }
  3423. #\mpiv-popup.\mpiv-show {
  3424. display: inline;
  3425. }
  3426. #\mpiv-popup {
  3427. display: none;
  3428. cursor: none;
  3429. ${cfg.uiFadein ? String.raw`
  3430. animation: .2s \mpiv-fadein both;
  3431. transition: box-shadow .25s, background-color .25s;
  3432. ` : ''}
  3433. ${App.popupStyleBase = `
  3434. border: none;
  3435. box-sizing: border-box;
  3436. position: fixed;
  3437. z-index: 2147483647;
  3438. padding: 0;
  3439. margin: 0;
  3440. top: 0;
  3441. left: 0;
  3442. width: auto;
  3443. height: auto;
  3444. transform-origin: center;
  3445. max-width: none;
  3446. max-height: none;
  3447. `}
  3448. }
  3449. #\mpiv-popup.\mpiv-show {
  3450. ${cfg.uiBorder ? `border: ${cfg.uiBorder}px solid ${Util.color('Border')};` : ''}
  3451. ${cfg.uiPadding ? `padding: ${cfg.uiPadding}px;` : ''}
  3452. ${cfg.uiMargin ? `margin: ${cfg.uiMargin}px;` : ''}
  3453. box-shadow: ${cfg.uiShadow ? `2px 4px ${cfg.uiShadow}px 4px transparent` : 'none'};
  3454. }
  3455. #\mpiv-popup.\mpiv-show[loaded] {
  3456. background-color: ${Util.color('Background')};
  3457. ${cfg.uiShadow ? `box-shadow: 2px 4px ${cfg.uiShadow}px 4px ${Util.color('Shadow')};` : ''}
  3458. }
  3459. #\mpiv-popup.\mpiv-zoom-max {
  3460. image-rendering: pixelated;
  3461. }
  3462. @keyframes \mpiv-fadein {
  3463. from {
  3464. opacity: 0;
  3465. border-color: transparent;
  3466. }
  3467. to {
  3468. opacity: 1;
  3469. }
  3470. }
  3471. ` + (cfg.globalStatus ? String.raw`
  3472. :root.\mpiv-loading:not(.\mpiv-preloading) *:hover {
  3473. cursor: progress !important;
  3474. }
  3475. :root.\mpiv-edge #\mpiv-popup {
  3476. cursor: default;
  3477. }
  3478. :root.\mpiv-error *:hover {
  3479. cursor: not-allowed !important;
  3480. }
  3481. :root.\mpiv-ready *:hover,
  3482. :root.\mpiv-large *:hover {
  3483. cursor: zoom-in !important;
  3484. }
  3485. :root.\mpiv-shift *:hover {
  3486. cursor: default !important;
  3487. }
  3488. ` : String.raw`
  3489. [\mpiv-status~="loading"]:not([\mpiv-status~="preloading"]):hover {
  3490. cursor: progress;
  3491. }
  3492. [\mpiv-status~="edge"]:hover {
  3493. cursor: default;
  3494. }
  3495. [\mpiv-status~="error"]:hover {
  3496. cursor: not-allowed;
  3497. }
  3498. [\mpiv-status~="ready"]:hover,
  3499. [\mpiv-status~="large"]:hover {
  3500. cursor: zoom-in;
  3501. }
  3502. [\mpiv-status~="shift"]:hover {
  3503. cursor: default;
  3504. }
  3505. `)).replace(/\\mpiv-status/g, STATUS_ATTR).replace(/\\mpiv-/g, PREFIX);
  3506. App.popupStyleBase = App.popupStyleBase.replace(/;/g, '!important;');
  3507. return App.globalStyle;
  3508. }
  3509.  
  3510. //#region Global utilities
  3511.  
  3512. const clamp = (v, min, max) =>
  3513. v < min ? min : v > max ? max : v;
  3514.  
  3515. const compareNumbers = (a, b) =>
  3516. a - b;
  3517.  
  3518. const flattenHtml = str =>
  3519. str.trim().replace(/\n\s*/g, '');
  3520.  
  3521. const dropEvent = e =>
  3522. (e.preventDefault(), e.stopPropagation());
  3523.  
  3524. const ensureArray = v =>
  3525. Array.isArray(v) ? v : [v];
  3526.  
  3527. /** @param {KeyboardEvent} e */
  3528. const eventModifiers = e =>
  3529. (e.altKey ? '!' : '') +
  3530. (e.ctrlKey ? '^' : '') +
  3531. (e.metaKey ? '#' : '') +
  3532. (e.shiftKey ? '+' : '');
  3533.  
  3534. const now = performance.now.bind(performance);
  3535.  
  3536. const sumProps = (...props) => {
  3537. let sum = 0;
  3538. for (const p of props)
  3539. sum += parseFloat(p) || 0;
  3540. return sum;
  3541. };
  3542.  
  3543. const tryCatch = function (fn, ...args) {
  3544. try {
  3545. return fn.apply(this, args);
  3546. } catch (e) {}
  3547. };
  3548.  
  3549. const $ = (sel, node = doc) =>
  3550. node.querySelector(sel) || false;
  3551.  
  3552. const $$ = (sel, node = doc) =>
  3553. node.querySelectorAll(sel);
  3554.  
  3555. const $create = (tag, props) =>
  3556. Object.assign(doc.createElement(tag), props);
  3557.  
  3558. const $css = (el, props) =>
  3559. Object.entries(props).forEach(([k, v]) =>
  3560. el.style.setProperty(k, v, 'important'));
  3561.  
  3562. const $many = (q, doc) => {
  3563. for (const selector of ensureArray(q)) {
  3564. const el = selector && $(selector, doc);
  3565. if (el)
  3566. return el;
  3567. }
  3568. };
  3569.  
  3570. const $prop = (sel, prop, node = doc) =>
  3571. (node = $(sel, node)) && node[prop] || '';
  3572.  
  3573. const $propUp = (node, prop) =>
  3574. (node = node.closest(`[${prop}]`)) &&
  3575. (prop.startsWith('data-') ? node.getAttribute(prop) : node[prop]) ||
  3576. '';
  3577.  
  3578. const $remove = node =>
  3579. node && node.remove();
  3580.  
  3581. //#endregion
  3582. //#region Init
  3583.  
  3584. cfg = new Config({save: true});
  3585.  
  3586. if (window === top)
  3587. GM_registerMenuCommand('MPIV: configure', setup);
  3588.  
  3589. if (doc.body) App.checkImageTab();
  3590. else doc.addEventListener('DOMContentLoaded', App.checkImageTab, {once: true});
  3591.  
  3592. doc.addEventListener('mouseover', Events.onMouseOver, {passive: true});
  3593. if (['greasyfork.org', 'w9p.co', 'github.com'].includes(hostname))
  3594. doc.addEventListener('click', setupClickedRule, {passive: true});
  3595. window.addEventListener('message', App.onMessage);
  3596.  
  3597. //#endregion