Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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