Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2024-04-28 提交的版本,查看 最新版本

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