Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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