Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2024-06-04 提交的版本,查看 最新版本

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