Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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