Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2024-05-19 提交的版本,查看 最新版本

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