Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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