Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2024-04-30 提交的版本,查看 最新版本

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