Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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