Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址