Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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