Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2021-11-23 提交的版本,查看 最新版本

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