Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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