Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2024-05-14 提交的版本,檢視 最新版本

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