Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

QingJ © 2025

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