Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2021-12-31 提交的版本,查看 最新版本

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