Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2022-03-02 提交的版本,查看 最新版本

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

QingJ © 2025

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