Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2021-10-13 提交的版本,檢視 最新版本

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