Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-08-29 提交的版本。查看 最新版本

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