Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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