Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

  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.24
  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. s: (m, node) => {
  1727. const a = node.closest('a');
  1728. const url = Req.findImageUrl(a || node)
  1729. .replace(/\/i(\d+)\.(\w+\.\w+\/)\w+/, '/$2$1')
  1730. .replace(/^\w+:\/\/[^/]+((?:\/\d+){3})\/\w+(\/\w+\.\w+).*/, 'https://fastpic.org/view$1$2.html');
  1731. return a || url.includes('.png') ? url : [url, url.replace(/\.jpe?g/, '.png')];
  1732. },
  1733. q: 'img[src*="/big/"]',
  1734. },
  1735. {
  1736. u: '||facebook.com/',
  1737. r: /photo\.php|[^/]+\/photos\//,
  1738. s: (m, node) =>
  1739. node.id === 'fbPhotoImage' ? false :
  1740. /gradient\.png$/.test(m.input) ? '' :
  1741. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  1742. q: [
  1743. 'div + span > a:first-child:not([href*="tag_faces"])',
  1744. 'div + span > a[href*="tag_faces"] ~ a',
  1745. ],
  1746. rect: '#fbProfileCover',
  1747. },
  1748. {
  1749. u: '||fbcdn.',
  1750. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  1751. s: m =>
  1752. dotDomain.endsWith('.facebook.com') &&
  1753. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  1754. false,
  1755. manual: true,
  1756. },
  1757. {
  1758. u: ['||fbcdn-', 'fbcdn.net/'],
  1759. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  1760. s: (m, node) => {
  1761. if (node.id === 'fbPhotoImage') {
  1762. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  1763. if (a) return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  1764. }
  1765. if (m[4])
  1766. return false;
  1767. const pn = node.parentNode;
  1768. if (pn.outerHTML.includes('/hovercard/'))
  1769. return '';
  1770. if (node.outerHTML.includes('profile') && pn.parentNode.href.includes('/photo'))
  1771. return false;
  1772. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  1773. },
  1774. rect: '.photoWrap',
  1775. },
  1776. {
  1777. u: '||flickr.com/photos/',
  1778. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  1779. s: m =>
  1780. m.input.indexOf('/sizes/') < 0 ?
  1781. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  1782. false,
  1783. q: (text, doc) => {
  1784. const links = $$('.sizes-list a', doc);
  1785. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  1786. },
  1787. follow: true,
  1788. },
  1789. {
  1790. u: '||flickr.com/photos/',
  1791. r: /\/sizes\//,
  1792. q: '#allsizes-photo > img',
  1793. },
  1794. {
  1795. u: '||gfycat.com/',
  1796. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  1797. s: 'https://$1$3',
  1798. q: 'meta[content$=".webm"], #webmsource, source[src$=".webm"], .actual-gif-image',
  1799. },
  1800. {
  1801. u: [
  1802. '||googleusercontent.com/proxy',
  1803. '||googleusercontent.com/gadgets/proxy',
  1804. ],
  1805. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  1806. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  1807. },
  1808. {
  1809. u: [
  1810. '||googleusercontent.com/',
  1811. '||ggpht.com/',
  1812. ],
  1813. s: m => m.input.includes('webcache.') ? '' :
  1814. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  1815. .replace(/([&?]sz)?=[-\w]+([&#].*)?/, ''),
  1816. },
  1817. {
  1818. u: '||gravatar.com/',
  1819. r: /([a-z0-9]{32})/,
  1820. s: 'https://gravatar.com/avatar/$1?s=200',
  1821. },
  1822. {
  1823. u: '//gyazo.com/',
  1824. r: /\bgyazo\.com\/\w{32,}(\.\w+)?/,
  1825. s: (m, _, rule) => Ruler.toggle(rule, 'q', !m[1]) ? m.input : `https://i.${m[0]}`,
  1826. _q: 'link[rel="image_src"]',
  1827. },
  1828. {
  1829. u: '||hostingkartinok.com/show-image.php',
  1830. q: '.image img',
  1831. },
  1832. {
  1833. u: [
  1834. '||imagecurl.com/images/',
  1835. '||imagecurl.com/viewer.php',
  1836. ],
  1837. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1838. s: 'https://imagecurl.com/images/$1$2$3',
  1839. },
  1840. {
  1841. u: '||imagebam.com/image/',
  1842. q: 'meta[property="og:image"]',
  1843. tabfix: true,
  1844. xhr: hostname.includes('planetsuzy'),
  1845. },
  1846. {
  1847. u: '||imageban.ru/thumbs',
  1848. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1849. s: '$1out$2/$3/$4',
  1850. },
  1851. {
  1852. u: [
  1853. '||imageban.ru/show',
  1854. '||imageban.net/show',
  1855. '||ibn.im/',
  1856. ],
  1857. q: '#img_main',
  1858. },
  1859. {
  1860. u: '||imageshack.us/img',
  1861. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1862. s: 'https://$2/download/$1/$3$4',
  1863. },
  1864. {
  1865. u: '||imageshack.us/i/',
  1866. q: '#share-dl',
  1867. },
  1868. {
  1869. u: '||imageteam.org/img',
  1870. q: 'img[alt="image"]',
  1871. },
  1872. {
  1873. u: [
  1874. '||imagetwist.com/',
  1875. '||imageshimage.com/',
  1876. ],
  1877. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1878. q: 'img.pic',
  1879. xhr: true,
  1880. },
  1881. {
  1882. u: '||imageupper.com/i/',
  1883. q: '#img',
  1884. xhr: true,
  1885. },
  1886. {
  1887. u: '||imagevenue.com/',
  1888. q: 'a[data-toggle="full"] img',
  1889. },
  1890. {
  1891. u: '||imagezilla.net/show/',
  1892. q: '#photo',
  1893. xhr: true,
  1894. },
  1895. {
  1896. u: [
  1897. '||images-na.ssl-images-amazon.com/images/',
  1898. '||media-imdb.com/images/',
  1899. ],
  1900. r: /images\/.+?\.jpg/,
  1901. s: '/V1\\.?_.+?\\.//g',
  1902. },
  1903. {
  1904. u: '||imgbox.com/',
  1905. r: /\.com\/([a-z0-9]+)$/i,
  1906. q: '#img',
  1907. xhr: hostname !== 'imgbox.com',
  1908. },
  1909. {
  1910. u: '||imgclick.net/',
  1911. r: /\.net\/(\w+)/,
  1912. q: 'img.pic',
  1913. xhr: true,
  1914. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1915. },
  1916. {
  1917. u: '.imgcredit.xyz/',
  1918. r: /^https?(:.*\.xyz\/\d[\w/]+)\.md(.+)/,
  1919. s: ['https$1$2', 'https$1.png'],
  1920. },
  1921. {
  1922. u: [
  1923. '||imgflip.com/i/',
  1924. '||imgflip.com/gif/',
  1925. ],
  1926. r: /\/(i|gif)\/([^/?#]+)/,
  1927. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1928. },
  1929. {
  1930. u: [
  1931. '||imgur.com/a/',
  1932. '||imgur.com/gallery/',
  1933. ],
  1934. s: 'gallery', // suppressing an unused network request for remote `document`
  1935. g: async (text, doc, url, m, rule, node, cb) => {
  1936. let u = `https://imgur.com/ajaxalbums/getimages/${ai.url.split(/[/?#]/)[4]}/hit.json?all=true`;
  1937. let info = tryJSON((await Req.gmXhr(u)).responseText) || 0;
  1938. let images = (info.data || 0).images || [];
  1939. if (!images[0]) {
  1940. info = (await Req.gmXhr(ai.url)).responseText.match(/postDataJSON=(".*?")<|$/)[1];
  1941. info = tryJSON(tryJSON(info)) || 0;
  1942. images = info.media;
  1943. }
  1944. const items = [];
  1945. for (const img of images) {
  1946. const meta = img.metadata || img;
  1947. items.push({
  1948. url: img.url ||
  1949. (u = `https://i.imgur.com/${img.hash}`) && (
  1950. img.ext === '.gif' && img.animated !== false ?
  1951. [`${u}.webm`, `${u}.mp4`, u] :
  1952. u + img.ext
  1953. ),
  1954. desc: [meta.title, meta.description].filter(Boolean).join(' - '),
  1955. });
  1956. }
  1957. if (items[0] && info.title && !`${items[0].desc || ''}`.includes(info.title))
  1958. items.title = info.title;
  1959. cb(items);
  1960. },
  1961. css: '.post > .hover { display:none!important; }',
  1962. },
  1963. {
  1964. u: '||imgur.com/',
  1965. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1966. s: 'gallery',
  1967. g: (text, doc, url, m) =>
  1968. m[2].split(',').map(id => ({
  1969. url: `https://i.${m[1]}${id}.jpg`,
  1970. })),
  1971. },
  1972. {
  1973. u: '||imgur.com/',
  1974. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.(mp4|[a-z]+))/i,
  1975. s: (m, node) => {
  1976. if (/memegen|random|register|search|signin/.test(m.input))
  1977. return '';
  1978. const a = node.closest('a');
  1979. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1980. return false;
  1981. // postfixes: huge, large, medium, thumbnail, big square, small square
  1982. const id = m[3].replace(/(.{7})[hlmtbs]$/, '$1');
  1983. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1984. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1985. return ext === 'webm' ?
  1986. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1987. u + ext;
  1988. },
  1989. },
  1990. {
  1991. u: [
  1992. '||instagr.am/p/',
  1993. '||instagram.com/p/',
  1994. '||instagram.com/tv/',
  1995. ],
  1996. s: m => m.input.substr(0, m.input.lastIndexOf('/')).replace('/liked_by', '') + '/?__a=1',
  1997. q: m => (m = tryJSON(m)) && (
  1998. m = pick(m, 'graphql.shortcode_media') || pick(m, 'items[0]') || 0
  1999. ) && (
  2000. m.video_url ||
  2001. m.display_url ||
  2002. pick(m, 'video_versions[0].url') ||
  2003. pick(m, 'carousel_media[0].image_versions2.candidates[0].url') ||
  2004. pick(m, 'image_versions2.candidates[0].url')
  2005. ),
  2006. rect: 'div.PhotoGridMediaItem',
  2007. c: m => (m = tryJSON(m)) && (
  2008. pick(m, 'items[0].caption.text') ||
  2009. pick(m, 'graphql.shortcode_media.edge_media_to_caption.edges[0].node.text') ||
  2010. ''
  2011. ),
  2012. },
  2013. {
  2014. u: [
  2015. '||livememe.com/',
  2016. '||lvme.me/',
  2017. ],
  2018. r: /\.\w+\/([^.]+)$/,
  2019. s: 'http://i.lvme.me/$1.jpg',
  2020. },
  2021. {
  2022. u: '||lostpic.net/image',
  2023. q: '.image-viewer-image img',
  2024. },
  2025. {
  2026. u: '||makeameme.org/meme/',
  2027. r: /\/meme\/([^/?#]+)/,
  2028. s: 'https://media.makeameme.org/created/$1.jpg',
  2029. },
  2030. {
  2031. u: '||photobucket.com/',
  2032. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  2033. s: 'https://i$1$3',
  2034. xhr: !dotDomain.endsWith('.photobucket.com'),
  2035. },
  2036. {
  2037. u: '||piccy.info/view3/',
  2038. r: /(.+?\/view3)\/(.*)\//,
  2039. s: '$1/$2/orig/',
  2040. q: '#mainim',
  2041. },
  2042. {
  2043. u: '||pimpandhost.com/image/',
  2044. r: /(.+?\/image\/[0-9]+)/,
  2045. s: '$1?size=original',
  2046. q: 'img.original',
  2047. },
  2048. {
  2049. u: [
  2050. '||pixroute.com/',
  2051. '||imgspice.com/',
  2052. ],
  2053. r: /\.html$/,
  2054. q: 'img[id]',
  2055. xhr: true,
  2056. },
  2057. {
  2058. u: '||postima',
  2059. r: /postima?ge?\.org\/image\/\w+/,
  2060. q: [
  2061. 'a[href*="dl="]',
  2062. '#main-image',
  2063. ],
  2064. },
  2065. {
  2066. u: [
  2067. '||prntscr.com/',
  2068. '||prnt.sc/',
  2069. ],
  2070. r: /\.\w+\/.+/,
  2071. q: 'meta[property="og:image"]',
  2072. xhr: true,
  2073. },
  2074. {
  2075. u: '||radikal.ru/',
  2076. r: /\.ru\/(fp|.+?\.html)|^(.+?)t\.jpg/,
  2077. s: (m, node, rule) =>
  2078. m[2] && /radikal\.ru[\w%/]+?(\.\w+)/.test($propUp(node, 'href')) ? m[2] + RegExp.$1 :
  2079. Ruler.toggle(rule, 'q', m[1]) ? m.input : [m[2] + '.jpg', m[2] + '.png'],
  2080. _q: text => text.match(/https?:\/\/\w+\.radikal\.ru[\w/]+\.(jpg|gif|png)/i)[0],
  2081. },
  2082. {
  2083. u: '||tumblr.com',
  2084. r: /_500\.jpg/,
  2085. s: ['/_500/_1280/', ''],
  2086. },
  2087. {
  2088. u: '||twimg.com/media/',
  2089. r: /.+?format=(jpe?g|png|gif)/i,
  2090. s: '$0&name=orig',
  2091. },
  2092. {
  2093. u: '||twimg.com/media/',
  2094. r: /.+?\.(jpe?g|png|gif)/i,
  2095. s: '$0:orig',
  2096. },
  2097. {
  2098. u: '||twimg.com/1/proxy',
  2099. r: /t=([^&_]+)/i,
  2100. s: m => atob(m[1]).match(/http.+/),
  2101. },
  2102. {
  2103. u: '||twimg.com/',
  2104. r: /\/profile_images/i,
  2105. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  2106. },
  2107. {
  2108. u: '||pic.twitter.com/',
  2109. r: /\.com\/[a-z0-9]+/i,
  2110. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  2111. follow: true,
  2112. },
  2113. {
  2114. u: '||twitpic.com/',
  2115. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  2116. s: 'https://twitpic.com/show/large/$2',
  2117. },
  2118. {
  2119. u: '||wiki',
  2120. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  2121. s: '/\\/thumb(?=\\/)|' +
  2122. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  2123. '\\/revision\\/latest|\\/[^\\/]+$//g',
  2124. xhr: !hostname.includes('wiki'),
  2125. },
  2126. {
  2127. u: '||ytimg.com/vi/',
  2128. r: /(.+?\/vi\/[^/]+)/,
  2129. s: '$1/0.jpg',
  2130. rect: '.video-list-item',
  2131. },
  2132. {
  2133. u: '/viewer.php?file=',
  2134. r: /(.+?)\/viewer\.php\?file=(.+)/,
  2135. s: '$1/images/$2',
  2136. xhr: true,
  2137. },
  2138. {
  2139. u: '/thumb_',
  2140. r: /\/albums.+\/thumb_[^/]/,
  2141. s: '/thumb_//',
  2142. },
  2143. {
  2144. u: [
  2145. '.th.jp',
  2146. '.th.gif',
  2147. '.th.png',
  2148. ],
  2149. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  2150. s: '$1$2',
  2151. follow: true,
  2152. },
  2153. {
  2154. r: RX_MEDIA_URL,
  2155. },
  2156. ];
  2157.  
  2158. /** @type mpiv.HostRule[] */
  2159. (Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean))
  2160. .forEach(rule => {
  2161. if (Array.isArray(rule.e))
  2162. rule.e = rule.e.join(',');
  2163. });
  2164. },
  2165.  
  2166. format(rule, {expand} = {}) {
  2167. const s = Util.stringify(rule, null, ' ');
  2168. return expand ?
  2169. /* {"a": ...,
  2170. "b": ...,
  2171. "c": ...
  2172. } */
  2173. s.replace(/^{\s+/g, '{') :
  2174. /* {"a": ..., "b": ..., "c": ...} */
  2175. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  2176. },
  2177.  
  2178. fromElement(el) {
  2179. const text = el.textContent.trim();
  2180. if (text.startsWith('{') &&
  2181. text.endsWith('}') &&
  2182. /[{,]\s*"[degqrsu]"\s*:\s*"/.test(text)) {
  2183. const rule = tryJSON(text);
  2184. return rule && Object.keys(rule).some(k => /^[degqrsu]$/.test(k)) && rule;
  2185. }
  2186. },
  2187.  
  2188. isValidE2: ([k, v]) => k.trim() && typeof v === 'string' && v.trim(),
  2189.  
  2190. /** @returns mpiv.HostRule | Error | false | undefined */
  2191. parse(rule) {
  2192. const isBatchOp = this instanceof Map;
  2193. try {
  2194. if (typeof rule === 'string')
  2195. rule = JSON.parse(rule);
  2196. if ('d' in rule && typeof rule.d !== 'string')
  2197. rule.d = undefined;
  2198. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  2199. return false;
  2200. if ('e' in rule) {
  2201. let {e} = rule;
  2202. if (typeof e === 'string') {
  2203. e = e.trim();
  2204. } else if (
  2205. Array.isArray(e) && !e.every((s, i) => typeof s === 'string' && (e[i] = s.trim())) ||
  2206. e && !Object.entries(e).filter(Ruler.isValidE2).length
  2207. ) {
  2208. throw new Error('Invalid syntax for "e". Examples: ' +
  2209. '"e": ".image" or ' +
  2210. '"e": [".image1", ".image2"] or ' +
  2211. '"e": {".parent": ".image"} or ' +
  2212. '"e": {".parent1": ".image1", ".parent2": ".image2"}');
  2213. }
  2214. if (isBatchOp) rule.e = e || undefined;
  2215. }
  2216. let compileTo = isBatchOp ? rule : {};
  2217. if (rule.r)
  2218. compileTo.r = new RegExp(rule.r, 'i');
  2219. if (App.NOP)
  2220. compileTo = {};
  2221. for (const key of Object.keys(FN_ARGS)) {
  2222. if (RX_HAS_CODE.test(rule[key])) {
  2223. const fn = Util.newFunction(...FN_ARGS[key], rule[key]);
  2224. if (fn !== App.NOP || !isBatchOp) {
  2225. compileTo[key] = fn;
  2226. } else if (isBatchOp) {
  2227. this.set(rule, 'unsafe-eval');
  2228. }
  2229. }
  2230. }
  2231. return rule;
  2232. } catch (err) {
  2233. if (isBatchOp) {
  2234. this.set(rule, err);
  2235. return rule;
  2236. } else {
  2237. return err;
  2238. }
  2239. }
  2240. },
  2241.  
  2242. runC(text, doc = document) {
  2243. const fn = Ruler.runCHandler[typeof ai.rule.c] || Ruler.runCHandler.default;
  2244. ai.caption = fn(text, doc);
  2245. },
  2246.  
  2247. runCHandler: {
  2248. function: (text, doc) =>
  2249. ai.rule.c(text || doc.documentElement.outerHTML, doc, ai.node, ai.rule),
  2250. string: (text, doc) => {
  2251. const el = $many(ai.rule.c, doc);
  2252. return !el ? '' :
  2253. el.getAttribute('content') ||
  2254. el.getAttribute('title') ||
  2255. el.textContent;
  2256. },
  2257. default: () =>
  2258. (ai.tooltip || 0).text ||
  2259. ai.node.alt ||
  2260. $propUp(ai.node, 'title') ||
  2261. Req.getFileName(
  2262. ai.node.tagName === (ai.popup || 0).tagName
  2263. ? ai.url
  2264. : ai.node.src || $propUp(ai.node, 'href')),
  2265. },
  2266.  
  2267. runQ(text, doc, docUrl) {
  2268. let url;
  2269. if (isFunction(ai.rule.q)) {
  2270. url = ai.rule.q(text, doc, ai.node, ai.rule);
  2271. if (Array.isArray(url)) {
  2272. ai.urls = url.slice(1);
  2273. url = url[0];
  2274. }
  2275. } else {
  2276. const el = $many(ai.rule.q, doc);
  2277. url = Req.findImageUrl(el, docUrl);
  2278. }
  2279. return url;
  2280. },
  2281.  
  2282. /** @returns {?boolean|mpiv.RuleMatchInfo} */
  2283. runE(rule, node) {
  2284. const {e} = rule;
  2285. if (typeof e === 'string')
  2286. return node.matches(e);
  2287. let p, img, res, info;
  2288. for (const selParent in e) {
  2289. if ((p = node.closest(selParent)) && (img = $(e[selParent], p))) {
  2290. if (img === node)
  2291. res = true;
  2292. else if ((info = RuleMatcher.adaptiveFind(img, {rules: [rule]})))
  2293. return info;
  2294. }
  2295. }
  2296. return res;
  2297. },
  2298.  
  2299. /** @returns {?Array} if falsy then the rule should be skipped */
  2300. runS(node, rule, m) {
  2301. let urls = [];
  2302. for (const s of ensureArray(rule.s))
  2303. urls.push(
  2304. typeof s === 'string' ? Util.decodeUrl(Ruler.substituteSingle(s, m)) :
  2305. isFunction(s) ? s(m, node, rule) :
  2306. s);
  2307. if (rule.q && urls.length > 1) {
  2308. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  2309. return;
  2310. }
  2311. if (Array.isArray(urls[0]))
  2312. urls = urls[0];
  2313. // `false` returned by "s" property means "skip this rule", "" means "stop all rules"
  2314. return urls[0] !== false && Array.from(new Set(urls), Util.decodeUrl);
  2315. },
  2316.  
  2317. /** @returns {boolean} */
  2318. runU(rule, url) {
  2319. const u = rule[SYM_U] || (rule[SYM_U] = UrlMatcher(rule.u));
  2320. return u.fn.call(u.data, url);
  2321. },
  2322.  
  2323. substituteSingle(s, m) {
  2324. if (!m || m.input == null) return s;
  2325. if (s.startsWith('/') && !s.startsWith('//')) {
  2326. const mid = s.search(/[^\\]\//) + 1;
  2327. const end = s.lastIndexOf('/');
  2328. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  2329. return m.input.replace(re, s.slice(mid + 1, end));
  2330. }
  2331. if (m.length && s.includes('$')) {
  2332. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  2333. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  2334. for (let i = maxLength; i >= 0; i--) {
  2335. const part = num.slice(0, i) | 0;
  2336. if (part < m.length)
  2337. return (m[part] || '') + num.slice(i);
  2338. }
  2339. return text;
  2340. });
  2341. }
  2342. return s;
  2343. },
  2344.  
  2345. toggle(rule, prop, condition) {
  2346. rule[prop] = condition ? rule[`_${prop}`] : null;
  2347. return condition;
  2348. },
  2349. };
  2350.  
  2351. const RuleMatcher = {
  2352.  
  2353. /** @returns {Object} */
  2354. adaptiveFind(node, opts) {
  2355. const tn = node.tagName;
  2356. const src = node.currentSrc || node.src;
  2357. const isPic = tn === 'IMG' || tn === 'VIDEO' && Util.isVideoUrlExt(src);
  2358. let a, info, url;
  2359. // note that data URLs aren't passed to rules as those may have fatally ineffective regexps
  2360. if (tn !== 'A') {
  2361. url = isPic && !src.startsWith('data:') && Util.rel2abs(src);
  2362. info = RuleMatcher.find(url, node, opts);
  2363. }
  2364. if (!info && (a = node.closest('A'))) {
  2365. const ds = a.dataset;
  2366. url = ds.expandedUrl || ds.fullUrl || ds.url || a.href || '';
  2367. url = url.includes('//t.co/') ? 'https://' + a.textContent : url;
  2368. url = !url.startsWith('data:') && url;
  2369. info = RuleMatcher.find(url, a, opts);
  2370. }
  2371. if (!info && isPic)
  2372. info = {node, rule: {}, url: src};
  2373. return info;
  2374. },
  2375.  
  2376. /** @returns ?mpiv.RuleMatchInfo */
  2377. find(url, node, {noHtml, rules, skipRules} = {}) {
  2378. const tn = node.tagName;
  2379. const isPic = tn === 'IMG' || tn === 'VIDEO';
  2380. const isPicOrLink = isPic || tn === 'A';
  2381. let m, _m, html, info, _rule;
  2382. for (const rule of rules || Ruler.rules) {
  2383. if (skipRules && skipRules.includes(rule) ||
  2384. rule.u && (!url || !Ruler.runU(rule, url)) ||
  2385. rule.e && !rules && !(info = Ruler.runE(rule, node)))
  2386. continue;
  2387. if (info && info.url)
  2388. return info;
  2389. if (rule.r)
  2390. m = !noHtml && rule.html && (isPicOrLink || rule.e)
  2391. ? rule.r.exec(html || (html = node.outerHTML))
  2392. : url && rule.r.exec(url);
  2393. else if (url)
  2394. m = Object.assign([url], {index: 0, input: url});
  2395. else
  2396. m = [];
  2397. if (!m)
  2398. continue;
  2399. if (rule.s === '')
  2400. return {};
  2401. _m = m;
  2402. _rule = rule;
  2403. // a rule with follow:true for the currently hovered IMG produced a URL,
  2404. // but we'll only allow it to match rules without 's' in the nested find call
  2405. if (!isPic || rule.s != null || skipRules)
  2406. break;
  2407. }
  2408. if (!_m)
  2409. return;
  2410. const hasS = _rule.s != null && _rule.s !== 'gallery';
  2411. const urls = hasS ? Ruler.runS(node, _rule, _m) : [_m.input];
  2412. if (urls)
  2413. return RuleMatcher.makeInfo(hasS, _rule, _m, node, skipRules, urls);
  2414. },
  2415.  
  2416. /** @returns ?mpiv.RuleMatchInfo */
  2417. makeInfo(hasS, rule, match, node, skipRules, urls) {
  2418. let info;
  2419. let url = `${urls[0]}`;
  2420. const follow = url && hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule);
  2421. if (url)
  2422. url = Util.rel2abs(url);
  2423. else
  2424. info = {};
  2425. if (follow)
  2426. info = RuleMatcher.find(url, node, {skipRules: [...skipRules || [], rule]});
  2427. if (!info && (!follow || RX_MEDIA_URL.test(url))) {
  2428. const xhr = cfg.xhr && rule.xhr;
  2429. info = {
  2430. match,
  2431. node,
  2432. rule,
  2433. url,
  2434. urls: urls.length > 1 ? urls.slice(1) : null,
  2435. gallery: rule.g && Gallery.makeParser(rule.g),
  2436. post: isFunction(rule.post) ? rule.post(match) : rule.post,
  2437. xhr: xhr != null ? xhr : isSecureContext && !url.startsWith(location.protocol),
  2438. };
  2439. }
  2440. return info;
  2441. },
  2442.  
  2443. isFollowableUrl(url, rule) {
  2444. const f = rule.follow;
  2445. return isFunction(f) ? f(url) : f;
  2446. },
  2447. };
  2448.  
  2449. const Req = {
  2450.  
  2451. gmXhr(url, opts = {}) {
  2452. if (ai.req)
  2453. tryCatch.call(ai.req, ai.req.abort);
  2454. return new Promise((resolve, reject) => {
  2455. const {anonymous} = ai.rule || {};
  2456. ai.req = GM.xmlHttpRequest(Object.assign({
  2457. url,
  2458. anonymous,
  2459. withCredentials: !anonymous,
  2460. method: 'GET',
  2461. timeout: 30e3,
  2462. }, opts, {
  2463. onload: done,
  2464. onerror: done,
  2465. ontimeout() {
  2466. ai.req = null;
  2467. reject(`Timeout fetching ${url}`);
  2468. },
  2469. }));
  2470. function done(r) {
  2471. ai.req = null;
  2472. if (r.status < 400 && !r.error)
  2473. resolve(r);
  2474. else
  2475. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2476. }
  2477. });
  2478. },
  2479.  
  2480. async getDoc(url) {
  2481. if (!url) {
  2482. // current document
  2483. return {
  2484. doc,
  2485. finalUrl: location.href,
  2486. responseText: doc.documentElement.outerHTML,
  2487. };
  2488. }
  2489. const r = await (!ai.post ?
  2490. Req.gmXhr(url) :
  2491. Req.gmXhr(url, {
  2492. method: 'POST',
  2493. data: ai.post,
  2494. headers: {
  2495. 'Content-Type': 'application/x-www-form-urlencoded',
  2496. 'Referer': url,
  2497. },
  2498. }));
  2499. r.doc = $parseHtml(r.responseText);
  2500. return r;
  2501. },
  2502.  
  2503. async getImage(url, pageUrl, xhr = ai.xhr) {
  2504. ai.bufBar = false;
  2505. ai.bufStart = now();
  2506. const response = await Req.gmXhr(url, {
  2507. responseType: 'blob',
  2508. headers: {
  2509. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2510. Referer: pageUrl || (isFunction(xhr) ? xhr() : url),
  2511. },
  2512. onprogress: Req.getImageProgress,
  2513. });
  2514. Bar.set(false);
  2515. const type = Req.guessMimeType(response);
  2516. let b = response.response;
  2517. if (!b) throw 'Empty response';
  2518. if (b.type !== type)
  2519. b = b.slice(0, b.size, type);
  2520. const res = xhr === 'blob'
  2521. ? (ai.blobUrl = URL.createObjectURL(b))
  2522. : await Req.blobToDataUrl(b);
  2523. return [res, type.startsWith('video')];
  2524. },
  2525.  
  2526. getImageProgress(e) {
  2527. if (!ai.bufBar && now() - ai.bufStart > 3000 && e.loaded / e.total < 0.5)
  2528. ai.bufBar = true;
  2529. if (ai.bufBar) {
  2530. const pct = e.loaded / e.total * 100 | 0;
  2531. const size = e.total / 1024 | 0;
  2532. Bar.set(`${pct}% of ${size} kiB`, 'xhr');
  2533. }
  2534. },
  2535.  
  2536. async findRedirect() {
  2537. try {
  2538. const {finalUrl} = await Req.gmXhr(ai.url, {
  2539. method: 'HEAD',
  2540. headers: {
  2541. 'Referer': location.href.split('#', 1)[0],
  2542. },
  2543. });
  2544. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2545. if (!info || !info.url)
  2546. throw `Couldn't follow redirection target: ${finalUrl}`;
  2547. Object.assign(ai, info);
  2548. App.startSingle();
  2549. } catch (e) {
  2550. App.handleError(e);
  2551. }
  2552. },
  2553.  
  2554. async saveFile() {
  2555. const url = ai.popup.src || ai.popup.currentSrc;
  2556. let name = Req.getFileName(ai.imageUrl || url);
  2557. if (!name.includes('.'))
  2558. name += '.jpg';
  2559. if (url.startsWith('blob:') || url.startsWith('data:')) {
  2560. $new('a', {href: url, download: name})
  2561. .dispatchEvent(new MouseEvent('click'));
  2562. } else {
  2563. Status.set('+loading');
  2564. const onload = () => Status.set('-loading');
  2565. const gmDL = typeof GM_download === 'function';
  2566. (gmDL ? GM_download : GM.xmlHttpRequest)({
  2567. url,
  2568. name,
  2569. headers: {Referer: url},
  2570. method: 'get', // polyfilling GM_download
  2571. responseType: 'blob', // polyfilling GM_download
  2572. overrideMimeType: 'application/octet-stream', // polyfilling GM_download
  2573. onerror: e => {
  2574. Bar.set(`Could not download ${name}: ${e.error || e.message || e}.`, 'error');
  2575. onload();
  2576. },
  2577. onprogress: Req.getImageProgress,
  2578. onload({response}) {
  2579. onload();
  2580. if (!gmDL) { // polyfilling GM_download
  2581. const a = Object.assign(document.createElement('a'), {
  2582. href: URL.createObjectURL(response),
  2583. download: name,
  2584. });
  2585. a.dispatchEvent(new MouseEvent('click'));
  2586. setTimeout(URL.revokeObjectURL, 10e3, a.href);
  2587. }
  2588. },
  2589. });
  2590. }
  2591. },
  2592.  
  2593. getFileName(url) {
  2594. return decodeURIComponent(url).split(/[#?&]/, 1)[0].split('/').pop();
  2595. },
  2596.  
  2597. blobToDataUrl(blob) {
  2598. return new Promise((resolve, reject) => {
  2599. const fr = new FileReader();
  2600. fr.onload = () => resolve(fr.result);
  2601. fr.onerror = reject;
  2602. fr.readAsDataURL(blob);
  2603. });
  2604. },
  2605.  
  2606. guessMimeType({responseHeaders, finalUrl}) {
  2607. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2608. !RegExp.$1.includes('text/plain'))
  2609. return RegExp.$1;
  2610. const ext = Util.extractFileExt(finalUrl) || 'jpg';
  2611. switch (ext.toLowerCase()) {
  2612. case 'bmp': return 'image/bmp';
  2613. case 'gif': return 'image/gif';
  2614. case 'jpe': return 'image/jpeg';
  2615. case 'jpeg': return 'image/jpeg';
  2616. case 'jpg': return 'image/jpeg';
  2617. case 'mp4': return 'video/mp4';
  2618. case 'png': return 'image/png';
  2619. case 'svg': return 'image/svg+xml';
  2620. case 'tif': return 'image/tiff';
  2621. case 'tiff': return 'image/tiff';
  2622. case 'webm': return 'video/webm';
  2623. default: return 'application/octet-stream';
  2624. }
  2625. },
  2626.  
  2627. findImageUrl(n, url) {
  2628. if (!n) return;
  2629. let html;
  2630. const path =
  2631. n.getAttribute('data-src') || // lazy loaded src, whereas current `src` is an empty 1x1 pixel
  2632. n.getAttribute('src') ||
  2633. n.getAttribute('data-m4v') ||
  2634. n.getAttribute('href') ||
  2635. n.getAttribute('content') ||
  2636. (html = n.outerHTML).includes('http') &&
  2637. html.match(/https?:\/\/[^\s"<>]+?\.(jpe?g|gif|png|svg|web[mp]|mp4)[^\s"<>]*|$/i)[0];
  2638. return !!path && Util.rel2abs(Util.decodeHtmlEntities(path),
  2639. $prop('base[href]', 'href', n.ownerDocument) || url);
  2640. },
  2641. };
  2642.  
  2643. const Status = {
  2644.  
  2645. set(status) {
  2646. if (!status && !cfg.globalStatus) {
  2647. if (ai.node) ai.node.removeAttribute(STATUS_ATTR);
  2648. return;
  2649. }
  2650. const prefix = cfg.globalStatus ? PREFIX : '';
  2651. const action = status && /^[+-]/.test(status) && status[0];
  2652. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  2653. const el = cfg.globalStatus ? doc.documentElement :
  2654. name === 'edge' ? ai.popup :
  2655. ai.node;
  2656. if (!el) return;
  2657. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  2658. const oldValue = (el.getAttribute(attr) || '').trim();
  2659. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  2660. switch (action) {
  2661. case '-':
  2662. cls.delete(name);
  2663. break;
  2664. case false:
  2665. for (const c of cls)
  2666. if (c.startsWith(prefix) && c !== name)
  2667. cls.delete(c);
  2668. // fallthrough to +
  2669. case '+':
  2670. if (name)
  2671. cls.add(name);
  2672. break;
  2673. }
  2674. const newValue = [...cls].join(' ');
  2675. if (newValue !== oldValue)
  2676. el.setAttribute(attr, newValue);
  2677. },
  2678.  
  2679. loading(force) {
  2680. if (!force) {
  2681. clearTimeout(ai.timerStatus);
  2682. ai.timerStatus = setTimeout(Status.loading, SETTLE_TIME, true);
  2683. } else if (!ai.popupLoaded) {
  2684. Status.set('+loading');
  2685. }
  2686. },
  2687. };
  2688.  
  2689. const UrlMatcher = (() => {
  2690. // string-to-regexp escaped chars
  2691. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  2692. // rx for '^' symbol in simple url match
  2693. const RX_SEP = /[^\w%._-]/y;
  2694. const RXS_SEP = RX_SEP.source;
  2695. return match => {
  2696. const results = [];
  2697. for (const s of ensureArray(match)) {
  2698. const pinDomain = s.startsWith('||');
  2699. const pinStart = !pinDomain && s.startsWith('|');
  2700. const endSep = s.endsWith('^');
  2701. let fn;
  2702. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  2703. if (needle.includes('^')) {
  2704. let plain = '';
  2705. for (const part of needle.split('^'))
  2706. if (part.length > plain.length)
  2707. plain = part;
  2708. const rx = new RegExp(
  2709. (pinStart ? '^' : '') +
  2710. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  2711. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  2712. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  2713. needle = [plain, rx];
  2714. fn = regexp;
  2715. } else if (pinStart) {
  2716. fn = endSep ? equals : starts;
  2717. } else if (pinDomain) {
  2718. const slashPos = needle.indexOf('/');
  2719. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  2720. needle = [needle, domain, slashPos > 0, endSep];
  2721. fn = startsDomainPrescreen;
  2722. } else if (endSep) {
  2723. fn = ends;
  2724. } else {
  2725. fn = has;
  2726. }
  2727. results.push({fn, data: needle});
  2728. }
  2729. return results.length > 1 ?
  2730. {fn: checkArray, data: results} :
  2731. results[0];
  2732. };
  2733. function checkArray(s) {
  2734. return this.some(checkArrayItem, s);
  2735. }
  2736. function checkArrayItem(item) {
  2737. return item.fn.call(item.data, this);
  2738. }
  2739. function ends(s) {
  2740. return s.endsWith(this) || (
  2741. s.length > this.length &&
  2742. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  2743. endsWithSep(s));
  2744. }
  2745. function endsWithSep(s, pos = s.length - 1) {
  2746. RX_SEP.lastIndex = pos;
  2747. return RX_SEP.test(s);
  2748. }
  2749. function equals(s) {
  2750. return s.startsWith(this) && (
  2751. s.length === this.length ||
  2752. s.length === this.length + 1 && endsWithSep(s));
  2753. }
  2754. function has(s) {
  2755. return s.includes(this);
  2756. }
  2757. function regexp(s) {
  2758. return s.includes(this[0]) && this[1].test(s);
  2759. }
  2760. function starts(s) {
  2761. return s.startsWith(this);
  2762. }
  2763. function startsDomainPrescreen(url) {
  2764. return url.includes(this[0]) && startsDomain.call(this, url);
  2765. }
  2766. function startsDomain(url) {
  2767. let hostStart = url.indexOf('//');
  2768. if (hostStart && url[hostStart - 1] !== ':')
  2769. return;
  2770. hostStart = hostStart < 0 ? 0 : hostStart + 2;
  2771. const host = url.slice(hostStart, (url.indexOf('/', hostStart) + 1 || url.length + 1) - 1);
  2772. const [needle, domain, pinDomainEnd, endSep] = this;
  2773. let start = pinDomainEnd ? host.length - domain.length : 0;
  2774. for (; ; start++) {
  2775. start = host.indexOf(domain, start);
  2776. if (start < 0)
  2777. return;
  2778. if (!start || host[start - 1] === '.')
  2779. break;
  2780. }
  2781. start += hostStart;
  2782. if (url.lastIndexOf(needle, start) !== start)
  2783. return;
  2784. const end = start + needle.length;
  2785. return !endSep || end === host.length || end === url.length || endsWithSep(url, end);
  2786. }
  2787. })();
  2788.  
  2789. const Util = {
  2790.  
  2791. addStyle(name, css) {
  2792. const id = `${PREFIX}style:${name}`;
  2793. const el = doc.getElementById(id) ||
  2794. css && $new('style', {id});
  2795. if (!el) return;
  2796. if (el.textContent !== css)
  2797. el.textContent = css;
  2798. if (el.parentElement !== doc.head)
  2799. doc.head.appendChild(el);
  2800. return el;
  2801. },
  2802.  
  2803. color(color, opacity = cfg[`ui${color}Opacity`]) {
  2804. return (color.startsWith('#') ? color : cfg[`ui${color}Color`]) +
  2805. (0x100 + Math.round(opacity / 100 * 255)).toString(16).slice(1);
  2806. },
  2807.  
  2808. decodeHtmlEntities(s) {
  2809. return s
  2810. .replace(/&quot;/g, '"')
  2811. .replace(/&apos;/g, '\'')
  2812. .replace(/&lt;/g, '<')
  2813. .replace(/&gt;/g, '>')
  2814. .replace(/&amp;/g, '&');
  2815. },
  2816.  
  2817. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2818. decodeUrl(url) {
  2819. if (!url || typeof url !== 'string') return url;
  2820. const iPct = url.indexOf('%');
  2821. const iColon = url.indexOf(':');
  2822. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2823. decodeURIComponent(url) :
  2824. url;
  2825. },
  2826.  
  2827. deepEqual(a, b) {
  2828. if (!a || !b || typeof a !== 'object' || typeof a !== typeof b)
  2829. return a === b;
  2830. if (Array.isArray(a)) {
  2831. return Array.isArray(b) &&
  2832. a.length === b.length &&
  2833. a.every((v, i) => Util.deepEqual(v, b[i]));
  2834. }
  2835. const keys = Object.keys(a);
  2836. return keys.length === Object.keys(b).length &&
  2837. keys.every(k => Util.deepEqual(a[k], b[k]));
  2838. },
  2839.  
  2840. extractFileExt: url => (url = RX_MEDIA_URL.exec(url)) && url[1],
  2841.  
  2842. forceLayout(node) {
  2843. // eslint-disable-next-line no-unused-expressions
  2844. node.clientHeight;
  2845. },
  2846.  
  2847. formatError(e, rule) {
  2848. const message =
  2849. e.message ||
  2850. e.readyState && 'Request failed.' ||
  2851. e.type === 'error' && `File can't be displayed.${
  2852. $('div[bgactive*="flashblock"]', doc) ? ' Check Flashblock settings.' : ''
  2853. }` ||
  2854. e;
  2855. const m = [
  2856. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold'],
  2857. ['', 'font-weight:normal'],
  2858. ];
  2859. m.push(...[
  2860. ['Node: %o', ai.node],
  2861. ['Rule: %o', rule],
  2862. ai.url && ['URL: %s', ai.url],
  2863. ai.imageUrl && ai.imageUrl !== ai.url && ['File: %s', ai.imageUrl],
  2864. ].filter(Boolean));
  2865. return {
  2866. message,
  2867. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2868. consoleArgs: m.map(([, v]) => v),
  2869. };
  2870. },
  2871.  
  2872. isHovered(el) {
  2873. // doesn't work in image tabs, browser bug?
  2874. return App.isImageTab || el.closest(':hover');
  2875. },
  2876.  
  2877. isVideoUrl: url => url.startsWith('data:video') || Util.isVideoUrlExt(url),
  2878.  
  2879. isVideoUrlExt: url => (url = Util.extractFileExt(url)) && /^(webm|mp4)$/i.test(url),
  2880.  
  2881. newFunction(...args) {
  2882. try {
  2883. return App.NOP || new Function(...args);
  2884. } catch (e) {
  2885. if (!RX_EVAL_BLOCKED.test(e.message))
  2886. throw e;
  2887. App.NOP = () => {};
  2888. return App.NOP;
  2889. }
  2890. },
  2891.  
  2892. rel2abs(rel, abs = location.href) {
  2893. try {
  2894. return /^(data:|blob:|[-\w]+:\/\/)/.test(rel) ? rel :
  2895. new URL(rel, abs).href;
  2896. } catch (e) {
  2897. return rel;
  2898. }
  2899. },
  2900.  
  2901. stringify(...args) {
  2902. const p = Array.prototype;
  2903. const {toJSON} = p;
  2904. if (toJSON) p.toJSON = null;
  2905. const res = JSON.stringify(...args);
  2906. if (toJSON) p.toJSON = toJSON;
  2907. return res;
  2908. },
  2909.  
  2910. suppressTooltip() {
  2911. for (const node of [
  2912. ai.node.parentNode,
  2913. ai.node,
  2914. ai.node.firstElementChild,
  2915. ]) {
  2916. const t = (node || 0).title;
  2917. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2918. ai.tooltip = {node, text: t};
  2919. node.title = '';
  2920. break;
  2921. }
  2922. }
  2923. },
  2924.  
  2925. tabFixUrl() {
  2926. return ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  2927. flattenHtml(`data:text/html;charset=utf8,
  2928. <style>
  2929. body {
  2930. margin: 0;
  2931. padding: 0;
  2932. background: #222;
  2933. }
  2934. .fit {
  2935. overflow: hidden
  2936. }
  2937. .fit > img {
  2938. max-width: 100vw;
  2939. max-height: 100vh;
  2940. }
  2941. body > img {
  2942. margin: auto;
  2943. position: absolute;
  2944. left: 0;
  2945. right: 0;
  2946. top: 0;
  2947. bottom: 0;
  2948. }
  2949. </style>
  2950. <body class=fit>
  2951. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2952. </body>
  2953. `).replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2954. },
  2955. };
  2956.  
  2957. async function setup({rule} = {}) {
  2958. if (!isFunction(doc.body.attachShadow)) {
  2959. alert('Cannot show MPIV config dialog: the browser is probably too old.\n' +
  2960. 'You can edit the script\'s storage directly in your userscript manager.');
  2961. return;
  2962. }
  2963. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2964. let uiCfg;
  2965. let root = (elSetup || 0).shadowRoot;
  2966. let {blankRuleElement} = setup;
  2967. /** @type NodeList */
  2968. const UI = new Proxy({}, {
  2969. get(_, id) {
  2970. return root.getElementById(id);
  2971. },
  2972. });
  2973. if (!rule || !elSetup)
  2974. init(await Config.load({save: true}));
  2975. if (rule)
  2976. installRule(rule);
  2977.  
  2978. function init(data) {
  2979. uiCfg = data;
  2980. $remove(elSetup);
  2981. elSetup = $new('div', {contentEditable: true});
  2982. root = elSetup.attachShadow({mode: 'open'});
  2983. root.append(...createSetupElement());
  2984. initEvents();
  2985. renderAll();
  2986. renderCustomScales();
  2987. renderRules();
  2988. doc.body.appendChild(elSetup);
  2989. requestAnimationFrame(() => {
  2990. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, elSetup.clientHeight / 4) + 'px';
  2991. });
  2992. }
  2993.  
  2994. function initEvents() {
  2995. UI._apply.onclick = UI._cancel.onclick = UI._ok.onclick = UI._x.onclick = closeSetup;
  2996. UI._export.onclick = e => {
  2997. dropEvent(e);
  2998. GM.setClipboard(Util.stringify(collectConfig(), null, ' '));
  2999. UI._exportNotification.hidden = false;
  3000. setTimeout(() => (UI._exportNotification.hidden = true), 1000);
  3001. };
  3002. UI._import.onclick = e => {
  3003. dropEvent(e);
  3004. const s = prompt('Paste settings:');
  3005. if (s)
  3006. init(new Config({data: s}));
  3007. };
  3008. UI._install.onclick = setupRuleInstaller;
  3009. const /** @type {HTMLTextAreaElement} */ cssApp = UI._cssApp;
  3010. UI._reveal.onclick = e => {
  3011. e.preventDefault();
  3012. cssApp.hidden = !cssApp.hidden;
  3013. if (!cssApp.hidden) {
  3014. if (!cssApp.value) {
  3015. App.updateStyles();
  3016. cssApp.value = App.globalStyle.trim();
  3017. cssApp.setSelectionRange(0, 0);
  3018. }
  3019. cssApp.focus();
  3020. }
  3021. };
  3022. UI.start.onchange = function () {
  3023. UI.delay.closest('label').hidden =
  3024. UI.preload.closest('label').hidden =
  3025. this.value !== 'auto';
  3026. };
  3027. UI.start.onchange();
  3028. UI.xhr.onclick = ({target: el}) => el.checked || confirm($propUp(el, 'title'));
  3029. // color
  3030. for (const el of $$('[type="color"]', root)) {
  3031. el.oninput = colorOnInput;
  3032. el.elSwatch = el.nextElementSibling;
  3033. el.elOpacity = UI[el.id.replace('Color', 'Opacity')];
  3034. el.elOpacity.elColor = el;
  3035. }
  3036. function colorOnInput() {
  3037. this.elSwatch.style.setProperty('--color',
  3038. Util.color(this.value, this.elOpacity.valueAsNumber));
  3039. }
  3040. // range
  3041. for (const el of $$('[type="range"]', root)) {
  3042. el.oninput = rangeOnInput;
  3043. el.onblur = rangeOnBlur;
  3044. el.addEventListener('focusin', rangeOnFocus);
  3045. }
  3046. function rangeOnBlur(e) {
  3047. if (this.elEdit && e.relatedTarget !== this.elEdit)
  3048. this.elEdit.onblur(e);
  3049. }
  3050. function rangeOnFocus() {
  3051. if (this.elEdit) return;
  3052. const {min, max, step, value} = this;
  3053. this.elEdit = $new('input', {
  3054. value, min, max, step,
  3055. className: 'range-edit',
  3056. style: `left: ${this.offsetLeft}px; margin-top: ${this.offsetHeight + 1}px`,
  3057. type: 'number',
  3058. elRange: this,
  3059. onblur: rangeEditOnBlur,
  3060. oninput: rangeEditOnInput,
  3061. });
  3062. this.insertAdjacentElement('afterend', this.elEdit);
  3063. }
  3064. function rangeOnInput() {
  3065. this.title = (this.dataset.title || '').replace('$', this.value);
  3066. if (this.elColor) this.elColor.oninput();
  3067. if (this.elEdit) this.elEdit.valueAsNumber = this.valueAsNumber;
  3068. }
  3069. // range-edit
  3070. function rangeEditOnBlur(e) {
  3071. if (e.relatedTarget !== this.elRange) {
  3072. this.remove();
  3073. this.elRange.elEdit = null;
  3074. }
  3075. }
  3076. function rangeEditOnInput() {
  3077. this.elRange.valueAsNumber = this.valueAsNumber;
  3078. this.elRange.oninput();
  3079. }
  3080. // prevent the main page from interpreting key presses in inputs as hotkeys
  3081. // which may happen since it sees only the outer <div> in the event |target|
  3082. root.addEventListener('keydown', e => !e.altKey && !e.metaKey && e.stopPropagation(), true);
  3083. }
  3084.  
  3085. function closeSetup(event) {
  3086. const isApply = this.id === '_apply';
  3087. if (event && (this.id === '_ok' || isApply)) {
  3088. cfg = uiCfg = collectConfig({save: true, clone: isApply});
  3089. Ruler.init();
  3090. Menu.reRegisterAlt();
  3091. if (isApply) {
  3092. renderCustomScales();
  3093. UI._css.textContent = cfg._getCss();
  3094. return;
  3095. }
  3096. }
  3097. $remove(elSetup);
  3098. elSetup = null;
  3099. }
  3100.  
  3101. function collectConfig({save, clone} = {}) {
  3102. let data = {};
  3103. for (const el of $$('input[id], select[id]', root))
  3104. data[el.id] = el.type === 'checkbox' ? el.checked :
  3105. (el.type === 'number' || el.type === 'range') ? el.valueAsNumber :
  3106. el.value || '';
  3107. Object.assign(data, {
  3108. css: UI.css.value.trim(),
  3109. delay: UI.delay.valueAsNumber * 1000,
  3110. hosts: collectRules(),
  3111. scale: clamp(UI.scale.valueAsNumber / 100, 0, 1) + 1,
  3112. scales: UI.scales.value
  3113. .trim()
  3114. .split(/[,;]*\s+/)
  3115. .map(x => x.replace(',', '.'))
  3116. .filter(x => !isNaN(parseFloat(x))),
  3117. });
  3118. if (clone)
  3119. data = JSON.parse(Util.stringify(data));
  3120. return new Config({data, save});
  3121. }
  3122.  
  3123. function collectRules() {
  3124. return [...UI._rules.children]
  3125. .map(el => [el.value.trim(), el[RULE]])
  3126. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  3127. .map(([s, json]) => json || s)
  3128. .filter(Boolean);
  3129. }
  3130.  
  3131. function checkRule({target: el}) {
  3132. let json, error, title;
  3133. const prev = el.previousElementSibling;
  3134. if (el.value) {
  3135. json = Ruler.parse(el.value);
  3136. error = json instanceof Error && (json.message || String(json));
  3137. const invalidDomain = !error && json && typeof json.d === 'string' &&
  3138. !/^[-.a-z0-9]*$/i.test(json.d);
  3139. title = [invalidDomain && 'Disabled due to invalid characters in "d"', error]
  3140. .filter(Boolean).join('\n');
  3141. el.classList.toggle('invalid-domain', invalidDomain);
  3142. el.classList.toggle('matching-domain', !!json.d && hostname.includes(json.d));
  3143. if (!prev)
  3144. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  3145. } else if (prev) {
  3146. prev.focus();
  3147. el.remove();
  3148. }
  3149. el[RULE] = !error && json;
  3150. el.title = title;
  3151. el.setCustomValidity(error || '');
  3152. }
  3153.  
  3154. async function focusRule({target: el, relatedTarget: from}) {
  3155. if (el === this)
  3156. return;
  3157. await new Promise(setTimeout);
  3158. if (el[RULE] && el.rows < 2) {
  3159. let i = el.selectionStart;
  3160. const txt = el.value = Ruler.format(el[RULE], {expand: true});
  3161. i += txt.slice(0, i).match(/^\s*/gm).reduce((len, s) => len + s.length, 0);
  3162. el.setSelectionRange(i, i);
  3163. el.rows = txt.match(/^/gm).length;
  3164. }
  3165. if (!this.contains(from))
  3166. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  3167. }
  3168.  
  3169. function installRule(rule) {
  3170. const inputs = UI._rules.children;
  3171. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  3172. if (!el) {
  3173. el = inputs[0];
  3174. el[RULE] = rule;
  3175. el.value = Ruler.format(rule);
  3176. el.hidden = false;
  3177. const i = Math.max(0, collectRules().indexOf(rule));
  3178. inputs[i].insertAdjacentElement('afterend', el);
  3179. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  3180. }
  3181. const rect = el.getBoundingClientRect();
  3182. if (rect.bottom < 0 ||
  3183. rect.bottom > el.parentNode.offsetHeight)
  3184. el.scrollIntoView();
  3185. el.classList.add('highlight');
  3186. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  3187. el.focus();
  3188. }
  3189.  
  3190. function renderRules() {
  3191. const rules = UI._rules;
  3192. rules.addEventListener('input', checkRule);
  3193. rules.addEventListener('focusin', focusRule);
  3194. rules.addEventListener('paste', focusRule);
  3195. blankRuleElement =
  3196. setup.blankRuleElement =
  3197. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  3198. for (const rule of uiCfg.hosts || []) {
  3199. const el = blankRuleElement.cloneNode();
  3200. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  3201. rules.appendChild(el);
  3202. checkRule({target: el});
  3203. }
  3204. const search = UI._search;
  3205. search.oninput = () => {
  3206. setup.search = search.value;
  3207. const s = search.value.toLowerCase();
  3208. for (const el of rules.children)
  3209. el.hidden = s && !el.value.toLowerCase().includes(s);
  3210. };
  3211. search.value = setup.search || '';
  3212. if (search.value)
  3213. search.oninput();
  3214. }
  3215.  
  3216. function renderCustomScales() {
  3217. UI.scales.value = uiCfg.scales.join(' ').trim() || Config.DEFAULTS.scales.join(' ');
  3218. }
  3219.  
  3220. function renderAll() {
  3221. for (const el of $$('input[id], select[id], textarea[id]', root))
  3222. if (el.id in uiCfg)
  3223. el[el.type === 'checkbox' ? 'checked' : 'value'] = uiCfg[el.id];
  3224. for (const el of $$('input[type="range"]', root))
  3225. el.oninput();
  3226. for (const el of $$('a[href^="http"]', root))
  3227. Object.assign(el, {target: '_blank', rel: 'noreferrer noopener external'});
  3228. UI.delay.valueAsNumber = uiCfg.delay / 1000;
  3229. UI.scale.valueAsNumber = Math.round(clamp(uiCfg.scale - 1, 0, 1) * 100);
  3230. }
  3231. }
  3232.  
  3233. function setupClickedRule(event) {
  3234. let rule;
  3235. const el = event.target.closest('blockquote, code, pre');
  3236. if (el && !event.button && !eventModifiers(event) && (rule = Ruler.fromElement(el))) {
  3237. dropEvent(event);
  3238. setup({rule});
  3239. }
  3240. }
  3241.  
  3242. async function setupRuleInstaller(e) {
  3243. dropEvent(e);
  3244. const parent = this.parentElement;
  3245. parent.children._installLoading.hidden = false;
  3246. this.remove();
  3247. let rules;
  3248.  
  3249. try {
  3250. rules = extractRules(await Req.getDoc(this.href));
  3251. const selector = $new('select', {
  3252. size: 8,
  3253. style: 'width: 100%',
  3254. selectedIndex: findMatchingRuleIndex(),
  3255. ondblclick: e => e.target !== selector && maybeSetup(e),
  3256. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  3257. }, rules.map(renderRule));
  3258. parent.children._installLoading.remove();
  3259. parent.children._installHint.hidden = false;
  3260. parent.appendChild(selector);
  3261. requestAnimationFrame(() => {
  3262. const optY = selector.selectedOptions[0].offsetTop - selector.offsetTop;
  3263. selector.scrollTo(0, optY - selector.offsetHeight / 2);
  3264. selector.focus();
  3265. });
  3266. } catch (e) {
  3267. parent.textContent = 'Error loading rules: ' + (e.message || e);
  3268. }
  3269.  
  3270. function extractRules({doc}) {
  3271. // sort by name
  3272. return [...$$('#wiki-body tr', doc)]
  3273. .map(tr => [
  3274. tr.cells[0].textContent.trim(),
  3275. Ruler.fromElement(tr.cells[1]),
  3276. ])
  3277. .filter(([name, r]) =>
  3278. name && r && (!r.d || hostname.includes(r.d)))
  3279. .sort(([a], [b]) =>
  3280. (a = a.toLowerCase()) < (b = b.toLowerCase()) ? -1 :
  3281. a > b ? 1 :
  3282. 0);
  3283. }
  3284.  
  3285. function findMatchingRuleIndex() {
  3286. const dottedHost = `.${hostname}.`;
  3287. let maxCount = 0, maxIndex = 0, index = 0;
  3288. for (const [name, {d}] of rules) {
  3289. let count = !!(d && hostname.includes(d)) * 10;
  3290. for (const part of name.toLowerCase().split(/[^a-z\d.-]+/i))
  3291. count += dottedHost.includes(`.${part}.`) && part.length;
  3292. if (count > maxCount) {
  3293. maxCount = count;
  3294. maxIndex = index;
  3295. }
  3296. index++;
  3297. }
  3298. return maxIndex;
  3299. }
  3300.  
  3301. function renderRule([name, rule]) {
  3302. return $new('option', {
  3303. textContent: name,
  3304. title: Ruler.format(rule, {expand: true})
  3305. .replace(/^{|\s*}$/g, '')
  3306. .split('\n')
  3307. .slice(0, 12)
  3308. .map(renderTitleLine)
  3309. .filter(Boolean)
  3310. .join('\n'),
  3311. });
  3312. }
  3313.  
  3314. function renderTitleLine(line, i, arr) {
  3315. return (
  3316. // show ... on 10th line if there are more lines
  3317. i === 9 && arr.length > 10 ? '...' :
  3318. i > 10 ? '' :
  3319. // truncate to 100 chars
  3320. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  3321. // strip the leading space
  3322. .replace(/^\s/, ''));
  3323. }
  3324.  
  3325. function maybeSetup(e) {
  3326. if (!eventModifiers(e))
  3327. setup({rule: rules[e.currentTarget.selectedIndex][1]});
  3328. }
  3329. }
  3330.  
  3331. const CSS_SETUP = /*language=css*/ `
  3332. :host {
  3333. all: initial !important;
  3334. position: fixed !important;
  3335. z-index: 2147483647 !important;
  3336. top: 20px !important;
  3337. right: 20px !important;
  3338. padding: 1.5em !important;
  3339. color: #000 !important;
  3340. background: #eee !important;
  3341. box-shadow: 5px 5px 25px 2px #000 !important;
  3342. width: 33em !important;
  3343. border: 1px solid black !important;
  3344. display: flex !important;
  3345. flex-direction: column !important;
  3346. }
  3347. main {
  3348. font: 12px/15px sans-serif;
  3349. }
  3350. table {
  3351. text-align:left;
  3352. }
  3353. ul {
  3354. max-height: calc(100vh - 200px);
  3355. margin: 0 0 15px 0;
  3356. padding: 0;
  3357. list-style: none;
  3358. }
  3359. li {
  3360. margin: 0;
  3361. padding: .25em 0;
  3362. }
  3363. li.options {
  3364. display: flex;
  3365. align-items: center;
  3366. justify-content: space-between;
  3367. }
  3368. li.row {
  3369. align-items: start;
  3370. flex-wrap: wrap;
  3371. }
  3372. li.row label {
  3373. display: flex;
  3374. flex-direction: row;
  3375. align-items: center;
  3376. }
  3377. li.row input {
  3378. margin-right: .25em;
  3379. }
  3380. li.stretch label {
  3381. flex: 1;
  3382. white-space: nowrap;
  3383. }
  3384. li.stretch label > span {
  3385. display: flex;
  3386. flex-direction: row;
  3387. flex: 1;
  3388. }
  3389. label {
  3390. display: inline-flex;
  3391. flex-direction: column;
  3392. }
  3393. label:not(:last-child) {
  3394. margin-right: 1em;
  3395. }
  3396. input, select {
  3397. min-height: 1.3em;
  3398. box-sizing: border-box;
  3399. }
  3400. input[type=checkbox] {
  3401. margin-left: 0;
  3402. }
  3403. input[type=number] {
  3404. width: 4em;
  3405. }
  3406. input:not([type=checkbox]) {
  3407. padding: 0 .25em;
  3408. }
  3409. input[type=range] {
  3410. flex: 1;
  3411. width: 100%;
  3412. margin: 0 .25em;
  3413. padding: 0;
  3414. filter: saturate(0);
  3415. opacity: .5;
  3416. }
  3417. u + input[type=range] {
  3418. max-width: 3em;
  3419. }
  3420. input[type=range]:hover {
  3421. filter: none;
  3422. opacity: 1;
  3423. }
  3424. input[type=color] {
  3425. position: absolute;
  3426. width: calc(1.5em + 2px);
  3427. opacity: 0;
  3428. cursor: pointer;
  3429. }
  3430. u {
  3431. position: relative;
  3432. flex: 0 0 1.5em;
  3433. height: 1.5em;
  3434. border: 1px solid #888;
  3435. pointer-events: none;
  3436. color: #888;
  3437. background-image:
  3438. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%),
  3439. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%);
  3440. background-size: .5em .5em;
  3441. background-position: 0 0, .25em .25em;
  3442. }
  3443. u::after {
  3444. position: absolute;
  3445. top: 0;
  3446. left: 0;
  3447. right: 0;
  3448. bottom: 0;
  3449. content: "";
  3450. background-color: var(--color);
  3451. }
  3452. .range-edit {
  3453. position: absolute;
  3454. box-shadow: 0 0.25em 1em #000;
  3455. z-index: 99;
  3456. }
  3457. textarea {
  3458. resize: vertical;
  3459. margin: 1px 0;
  3460. font: 11px/1.25 Consolas, monospace;
  3461. }
  3462. :invalid {
  3463. background-color: #f002;
  3464. border-color: #800;
  3465. }
  3466. code {
  3467. font-weight: bold;
  3468. }
  3469. a {
  3470. text-decoration: none;
  3471. color: LinkText;
  3472. cursor: pointer;
  3473. }
  3474. a:hover {
  3475. text-decoration: underline;
  3476. }
  3477. button {
  3478. padding: .2em 1em;
  3479. margin: 0 1em;
  3480. }
  3481. kbd {
  3482. padding: 1px 6px;
  3483. font-weight: bold;
  3484. font-family: Consolas, monospace;
  3485. border: 1px solid #888;
  3486. border-radius: 3px;
  3487. box-shadow: inset 1px 1px 5px #8888, .25px .5px 2px #0008;
  3488. }
  3489. .column {
  3490. display: flex;
  3491. flex-direction: column;
  3492. }
  3493. .highlight {
  3494. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  3495. animation-fill-mode: both;
  3496. }
  3497. #_rules > * {
  3498. word-break: break-all;
  3499. }
  3500. #_rules > :not(:focus) {
  3501. overflow: hidden; /* prevents wrapping in FF */
  3502. }
  3503. .invalid-domain {
  3504. opacity: .5;
  3505. }
  3506. .matching-domain {
  3507. border-color: #56b8ff;
  3508. background: #d7eaff;
  3509. }
  3510. #_x {
  3511. position: absolute;
  3512. top: 0;
  3513. right: 0;
  3514. padding: 4px 8px;
  3515. cursor: pointer;
  3516. user-select: none;
  3517. }
  3518. #_x:hover {
  3519. background-color: #8884;
  3520. }
  3521. #_cssApp {
  3522. color: seagreen;
  3523. }
  3524. #_exportNotification {
  3525. color: green;
  3526. font-weight: bold;
  3527. position: absolute;
  3528. left: 0;
  3529. right: 0;
  3530. bottom: 2px;
  3531. }
  3532. #_installHint {
  3533. color: green;
  3534. }
  3535. #_usage, #_usage * {
  3536. font: inherit;
  3537. color: inherit;
  3538. }
  3539. #_usage th, #_usage kbd {
  3540. font-weight: bold;
  3541. white-space: pre-line;
  3542. }
  3543. @keyframes fade-in {
  3544. from { background-color: deepskyblue }
  3545. to {}
  3546. }
  3547. @media (prefers-color-scheme: dark) {
  3548. :host {
  3549. color: #aaa !important;
  3550. background: #333 !important;
  3551. }
  3552. a {
  3553. color: deepskyblue;
  3554. }
  3555. button {
  3556. background: linear-gradient(-5deg, #333, #555);
  3557. border: 1px solid #000;
  3558. box-shadow: 0 2px 6px #181818;
  3559. border-radius: 3px;
  3560. cursor: pointer;
  3561. }
  3562. button:hover {
  3563. background: linear-gradient(-5deg, #333, #666);
  3564. }
  3565. textarea, input, select {
  3566. background: #111;
  3567. color: #BBB;
  3568. border: 1px solid #555;
  3569. }
  3570. input[type=checkbox] {
  3571. filter: invert(1);
  3572. }
  3573. input[type=range] {
  3574. filter: invert(1) saturate(0);
  3575. }
  3576. input[type=range]:hover {
  3577. filter: invert(1);
  3578. }
  3579. kbd {
  3580. border-color: #666;
  3581. }
  3582. @supports (-moz-appearance: none) {
  3583. input[type=checkbox],
  3584. input[type=range],
  3585. input[type=range]:hover {
  3586. filter: none;
  3587. }
  3588. }
  3589. .range-edit {
  3590. box-shadow: 0 .5em 1em .5em #000;
  3591. }
  3592. .matching-domain {
  3593. border-color: #0065af;
  3594. background: #032b58;
  3595. color: #ddd;
  3596. }
  3597. #_cssApp {
  3598. color: darkseagreen;
  3599. }
  3600. #_installHint {
  3601. color: greenyellow;
  3602. }
  3603. ::-webkit-scrollbar {
  3604. width: 14px;
  3605. height: 14px;
  3606. background: #333;
  3607. }
  3608. ::-webkit-scrollbar-button:single-button {
  3609. background: radial-gradient(circle at center, #555 40%, #333 40%)
  3610. }
  3611. ::-webkit-scrollbar-track-piece {
  3612. background: #444;
  3613. border: 4px solid #333;
  3614. border-radius: 8px;
  3615. }
  3616. ::-webkit-scrollbar-thumb {
  3617. border: 3px solid #333;
  3618. border-radius: 8px;
  3619. background: #666;
  3620. }
  3621. ::-webkit-resizer {
  3622. background: #111 linear-gradient(-45deg, transparent 3px, #888 3px, #888 4px, transparent 4px, transparent 6px, #888 6px, #888 7px, transparent 7px) no-repeat;
  3623. border: 2px solid transparent;
  3624. }
  3625. }
  3626. `;
  3627.  
  3628. function createSetupElement() {
  3629. const MPIV_BASE_URL = 'https://github.com/tophf/mpiv/wiki/';
  3630. const scalesHint = 'Leave it empty and click Apply or OK to restore the default values.';
  3631. const $newLink = (text, href, props) =>
  3632. $new('a', Object.assign({target: '_blank'}, href && {href}, props), text);
  3633. const $newCheck = (label, id, title, props) =>
  3634. $new('label', Object.assign({title}, props), [
  3635. $new('input', {id, type: 'checkbox'}),
  3636. label,
  3637. ]);
  3638. const $newKbd = (str, tag = 'fragment') =>
  3639. $new(tag, str.split(/({.+?})/).map(s => s[0] === '{' ? $new('kbd', s.slice(1, -1)) : s));
  3640. const $newRange = (id, title, min = 0, max = 100, step = 1, type = 'range') =>
  3641. $new('input', {id, min, max, step, type, 'data-title': title});
  3642. const $newSelect = (label, id, values) =>
  3643. $new('label', [
  3644. label,
  3645. $new('select', {id}, Object.entries(values).map(([k, v]) =>
  3646. $new('option', Object.assign({value: k}, typeof v === 'object' ? v : {textContent: v})))),
  3647. ]);
  3648. const $newTable = obj =>
  3649. $new('table#_usage', Object.entries(obj).map(([name, val]) =>
  3650. $new('tr', name.startsWith('---') ? $new('td', '\xA0') : [
  3651. $new('th', name),
  3652. ...ensureArray(val).map(cell => cell instanceof Node ? cell : $newKbd(cell, 'td')),
  3653. ])));
  3654. return [
  3655. $new('style', CSS_SETUP),
  3656. $new('style#_css', cfg._getCss()),
  3657. $new(`main#${PREFIX}setup`, [
  3658. $new('div#_x'),
  3659. $new('ul.column', [
  3660. $new('details', {style: 'margin: -1em 0 0'}, [
  3661. $new('summary', {style: 'cursor: pointer; font: bold 16px normal; margin-bottom: .5em'},
  3662. $new('b', 'MPIV Help & hotkeys')),
  3663. $newTable({
  3664. 'Activate': 'move mouse cursor over thumbnail',
  3665. 'Deactivate': 'move cursor off thumbnail, or click, or zoom out fully',
  3666. 'Prevent/freeze': 'hold down {Shift} while entering/leaving thumbnail',
  3667. 'Force-activate\n(videos or small pics)': 'hold {Ctrl} while entering image element',
  3668. '---1': '',
  3669. 'Start zooming':
  3670. 'configurable: automatic or via right-click / {Shift} while popup is visible',
  3671. 'Zoom': 'mouse wheel',
  3672. 'Rotate': '{L} {r} keys (left or right)',
  3673. 'Flip/mirror': '{h} {v} keys (horizontally or vertically)',
  3674. 'Previous/next\nin album': 'mouse wheel, {j} {k} or {←} {→} keys',
  3675. '---2': '',
  3676. }),
  3677. $newTable({
  3678. 'Antialiasing on/off': ['{a}', $new('td', {rowSpan: 4}, 'key while popup is visible')],
  3679. 'Download': '{d}',
  3680. 'Mute/unmute': '{m}',
  3681. 'Open in tab': '{t}',
  3682. }),
  3683. ]),
  3684. $new('li.options.stretch', [
  3685. $newSelect('Popup shows on', 'start', {
  3686. context: 'Right-click / \u2261 / Ctrl',
  3687. contextMK: 'Right-click / \u2261',
  3688. contextM: 'Right-click',
  3689. contextK: {
  3690. textContent: '\u2261 key',
  3691. title: '\u2261 is the Menu key (near the right Ctrl)',
  3692. },
  3693. ctrl: 'Ctrl',
  3694. auto: 'automatically',
  3695. }),
  3696. $new('label', ['after, sec', $newRange('delay', 'seconds', .05, 10, .05, 'number')]),
  3697. $new('label', {title: '(if the full version of the hovered image is ...% larger)'},
  3698. ['if larger, %', $newRange('scale', null, 0, 100, 1, 'number')]),
  3699. $newSelect('Zoom activates on', 'zoom', {
  3700. context: 'Right click / Shift',
  3701. wheel: 'Wheel up / Shift',
  3702. shift: 'Shift',
  3703. auto: 'automatically',
  3704. }),
  3705. $newSelect('...and zooms to', 'fit', {
  3706. 'all': 'fit to window',
  3707. 'large': 'fit if larger',
  3708. 'no': '100%',
  3709. '': {textContent: 'custom', title: 'Use custom scale factors'},
  3710. }),
  3711. ]),
  3712. $new('li.options', [
  3713. $new('label', ['Zoom step, %', $newRange('zoomStep', null, 100, 400, 1, 'number')]),
  3714. $newSelect('When fully zoomed out:', 'zoomOut', {
  3715. stay: 'stay in zoom mode',
  3716. auto: 'stay if still hovered',
  3717. unzoom: 'undo zoom mode',
  3718. close: 'close popup',
  3719. }),
  3720. $new('label', {
  3721. style: 'flex: 1',
  3722. title: `
  3723. Scale factors to use when zooms to selector is set to custom”.
  3724. 0 = fit to window,
  3725. 0! = same as 0 but also removes smaller values,
  3726. * after a value marks the default zoom factor, for example: 1*
  3727. The popup won't shrink below the image's natural size or window size for bigger mages.
  3728. ${scalesHint}
  3729. `.trim().replace(/\n\s+/g, '\r'),
  3730. }, ['Custom scale factors:', $new('input#scales', {placeholder: scalesHint})]),
  3731. ]),
  3732. $new('li.options.row', [
  3733. $new([
  3734. $newCheck('Centered*', 'center',
  3735. '...or try to keep the original link/thumbnail unobscured by the popup'),
  3736. $newCheck('Preload on hover*', 'preload',
  3737. 'Provides smoother experience but increases network traffic'),
  3738. $newCheck('Run in image tabs', 'imgtab'),
  3739. $newCheck('Require Ctrl key for <video>', 'videoCtrl'),
  3740. $newCheck('Keep preview on blur*', 'keepOnBlur',
  3741. 'i.e. when mouse pointer moves outside the page'),
  3742. ]),
  3743. $new([
  3744. $newCheck('Mute videos', 'mute'),
  3745. $newCheck('Spoof hotlinking*`, ', 'xhr',
  3746. 'Disable only if you spoof the HTTP headers yourself'),
  3747. $newCheck('Set status on <html>*', 'globalStatus',
  3748. "Causes slowdowns so don't enable unless you explicitly use it in your custom CSS"),
  3749. $newCheck('Keep playing video*', 'keepVids',
  3750. '...until you press Esc key or click elsewhere'),
  3751. ]),
  3752. $new([
  3753. $newCheck('Show when fully loaded*', 'waitLoad',
  3754. '...or show a partial image while still loading'),
  3755. $newCheck('Fade-in transition', 'uiFadein'),
  3756. $newCheck('Fade-in transition in gallery', 'uiFadeinGallery'),
  3757. $newCheck('Auto-start switch in menu*', 'startAltShown',
  3758. "Show a switch for 'auto-start' mode in userscript manager menu"),
  3759. ]),
  3760. ]),
  3761. $new('li.options.stretch', [
  3762. $new('label', [
  3763. 'Background',
  3764. $new('span', [
  3765. $new('input#uiBackgroundColor', {type: 'color'}), $new('u'),
  3766. $newRange('uiBackgroundOpacity', 'Opacity: $%'),
  3767. ]),
  3768. ]),
  3769. $new('label', [
  3770. 'Border color, opacity, size',
  3771. $new('span', [
  3772. $new('input#uiBorderColor', {type: 'color'}), $new('u'),
  3773. $newRange('uiBorderOpacity', 'Opacity: $%'),
  3774. $newRange('uiBorder', 'Border size: $px', 0, 20),
  3775. ]),
  3776. ]),
  3777. $new('label', [
  3778. 'Shadow color, opacity, size',
  3779. $new('span', [
  3780. $new('input#uiShadowColor', {type: 'color'}), $new('u'),
  3781. $newRange('uiShadowOpacity', 'Opacity: $%'),
  3782. $newRange('uiShadow', 'Shadow blur radius: $px\n"0" disables the shadow.', 0, 20),
  3783. ]),
  3784. ]),
  3785. $new('label', ['Padding', $new('span', $newRange('uiPadding', 'Padding: $px'))]),
  3786. $new('label', ['Margin', $new('span', $newRange('uiMargin', 'Margin: $px'))]),
  3787. ]),
  3788. $new('li', [
  3789. $newLink('Custom CSS:', `${MPIV_BASE_URL}Custom-CSS`),
  3790. ' e.g. ', $new('b', '#mpiv-popup { animation: none !important }'),
  3791. $newLink('View the built-in CSS', '', {
  3792. id: '_reveal',
  3793. tabIndex: 0,
  3794. style: 'float: right',
  3795. title: 'You can copy parts of it to override them in your custom CSS',
  3796. }),
  3797. $new('.column', [
  3798. $new('textarea#css', {spellcheck: false}),
  3799. $new('textarea#_cssApp', {spellcheck: false, hidden: true, readOnly: true, rows: 30}),
  3800. ]),
  3801. ]),
  3802. $new('li', {style: 'display: flex; justify-content: space-between;'}, [
  3803. $new('div',
  3804. $newLink('Custom host rules:', `${MPIV_BASE_URL}Custom-host-rules`)),
  3805. $new('div', {style: 'white-space: pre-line'}, [
  3806. 'To disable, put any symbol except ', $new('code', 'a..z 0..9 - .'),
  3807. '\nin "d" value, for example ', $new('code', '"d": "!foo.com"'),
  3808. ]),
  3809. $new('div',
  3810. $new('input#_search',
  3811. {type: 'search', placeholder: 'Search', style: 'width: 10em; margin-left: 1em'})),
  3812. ]),
  3813. $new('li', {
  3814. style: 'margin-left: -3px; margin-right: -3px; overflow-y: auto; ' +
  3815. 'padding-left: 3px; padding-right: 3px;',
  3816. }, [
  3817. $new('div#_rules.column',
  3818. $new('textarea#css', {spellcheck: false, rows: 1})),
  3819. ]),
  3820. $new('li', [
  3821. $new('div#_installLoading', {hidden: true}, 'Loading...'),
  3822. $new('div#_installHint', {hidden: true}, [
  3823. 'Double-click the rule (or select and press Enter) to add it. ',
  3824. 'Click ', $new('code', 'Apply'), ' or ', $new('code', 'OK'), ' to confirm.',
  3825. ]),
  3826. $newLink('Install rule from repository...', `${MPIV_BASE_URL}Rules`, {id: '_install'}),
  3827. ]),
  3828. ]),
  3829. $new('div', {style: 'text-align:center'}, [
  3830. $new('button#_ok', {accessKey: 'o'}, 'OK'),
  3831. $new('button#_apply', {accessKey: 'a'}, 'Apply'),
  3832. $new('button#_import', {style: 'margin-right: 0'}, 'Import'),
  3833. $new('button#_export', {style: 'margin-left: 0'}, 'Export'),
  3834. $new('button#_cancel', 'Cancel'),
  3835. $new('div#_exportNotification', {hidden: true}, 'Copied to clipboard'),
  3836. ]),
  3837. ]),
  3838. ];
  3839. }
  3840.  
  3841. function createGlobalStyle() {
  3842. App.globalStyle = /*language=CSS*/ (String.raw`
  3843. #\mpiv-bar {
  3844. position: fixed;
  3845. z-index: 2147483647;
  3846. top: 0;
  3847. left: 0;
  3848. right: 0;
  3849. opacity: 0;
  3850. transition: opacity 1s ease .25s;
  3851. text-align: center;
  3852. font-family: sans-serif;
  3853. font-size: 15px;
  3854. font-weight: bold;
  3855. background: #0005;
  3856. color: white;
  3857. padding: 4px 10px;
  3858. text-shadow: .5px .5px 2px #000;
  3859. }
  3860. #\mpiv-bar.\mpiv-show,
  3861. #\mpiv-bar[data-force] {
  3862. opacity: 1;
  3863. }
  3864. #\mpiv-bar[data-zoom]::after {
  3865. content: " (" attr(data-zoom) ")";
  3866. opacity: .8;
  3867. }
  3868. #\mpiv-popup.\mpiv-show {
  3869. display: inline;
  3870. }
  3871. #\mpiv-popup {
  3872. display: none;
  3873. cursor: none;
  3874. ${cfg.uiFadein ? String.raw`
  3875. animation: .2s \mpiv-fadein both;
  3876. transition: box-shadow .25s, background-color .25s;
  3877. ` : ''}
  3878. ${App.popupStyleBase = `
  3879. border: none;
  3880. box-sizing: border-box;
  3881. background-size: cover;
  3882. position: fixed;
  3883. z-index: 2147483647;
  3884. padding: 0;
  3885. margin: 0;
  3886. top: 0;
  3887. left: 0;
  3888. width: auto;
  3889. height: auto;
  3890. transform-origin: center;
  3891. max-width: none;
  3892. max-height: none;
  3893. `}
  3894. }
  3895. #\mpiv-popup.\mpiv-show {
  3896. ${cfg.uiBorder ? `border: ${cfg.uiBorder}px solid ${Util.color('Border')};` : ''}
  3897. ${cfg.uiPadding ? `padding: ${cfg.uiPadding}px;` : ''}
  3898. ${cfg.uiMargin ? `margin: ${cfg.uiMargin}px;` : ''}
  3899. box-shadow: ${cfg.uiShadow ? `2px 4px ${cfg.uiShadow}px 4px transparent` : 'none'};
  3900. }
  3901. #\mpiv-popup.\mpiv-show[loaded] {
  3902. background-color: ${Util.color('Background')};
  3903. ${cfg.uiShadow ? `box-shadow: 2px 4px ${cfg.uiShadow}px 4px ${Util.color('Shadow')};` : ''}
  3904. }
  3905. #\mpiv-popup[data-gallery-flip] {
  3906. animation: none;
  3907. transition: none;
  3908. }
  3909. #\mpiv-popup[data-no-aa],
  3910. #\mpiv-popup.\mpiv-zoom-max {
  3911. image-rendering: pixelated;
  3912. }
  3913. #\mpiv-setup {
  3914. }
  3915. @keyframes \mpiv-fadein {
  3916. from {
  3917. opacity: 0;
  3918. border-color: transparent;
  3919. }
  3920. to {
  3921. opacity: 1;
  3922. }
  3923. }
  3924. ` + (cfg.globalStatus ? String.raw`
  3925. :root.\mpiv-loading:not(.\mpiv-preloading) *:hover {
  3926. cursor: progress !important;
  3927. }
  3928. :root.\mpiv-edge #\mpiv-popup {
  3929. cursor: default;
  3930. }
  3931. :root.\mpiv-error *:hover {
  3932. cursor: not-allowed !important;
  3933. }
  3934. :root.\mpiv-ready *:hover,
  3935. :root.\mpiv-large *:hover {
  3936. cursor: zoom-in !important;
  3937. }
  3938. :root.\mpiv-shift *:hover {
  3939. cursor: default !important;
  3940. }
  3941. ` : String.raw`
  3942. [\mpiv-status~="loading"]:not([\mpiv-status~="preloading"]):hover {
  3943. cursor: progress;
  3944. }
  3945. [\mpiv-status~="edge"]:hover {
  3946. cursor: default;
  3947. }
  3948. [\mpiv-status~="error"]:hover {
  3949. cursor: not-allowed;
  3950. }
  3951. [\mpiv-status~="ready"]:hover,
  3952. [\mpiv-status~="large"]:hover {
  3953. cursor: zoom-in;
  3954. }
  3955. [\mpiv-status~="shift"]:hover {
  3956. cursor: default;
  3957. }
  3958. `)).replace(/\\mpiv-status/g, STATUS_ATTR).replace(/\\mpiv-/g, PREFIX);
  3959. App.popupStyleBase = App.popupStyleBase.replace(/;/g, '!important;');
  3960. return App.globalStyle;
  3961. }
  3962.  
  3963. //#region Global utilities
  3964.  
  3965. const clamp = (v, min, max) =>
  3966. v < min ? min : v > max ? max : v;
  3967.  
  3968. const compareNumbers = (a, b) =>
  3969. a - b;
  3970.  
  3971. const flattenHtml = str =>
  3972. str.trim().replace(/\n\s*/g, '');
  3973.  
  3974. const dropEvent = e =>
  3975. (e.preventDefault(), e.stopPropagation());
  3976.  
  3977. const ensureArray = v =>
  3978. Array.isArray(v) ? v : [v];
  3979.  
  3980. /** @param {KeyboardEvent} e */
  3981. const eventModifiers = e =>
  3982. (e.altKey ? '!' : '') +
  3983. (e.ctrlKey ? '^' : '') +
  3984. (e.metaKey ? '#' : '') +
  3985. (e.shiftKey ? '+' : '');
  3986.  
  3987. /** @param {KeyboardEvent} e */
  3988. const describeKey = e => eventModifiers(e) + (e.key && e.key.length > 1 ? e.key : e.code);
  3989.  
  3990. const isFunction = val => typeof val === 'function';
  3991.  
  3992. const isVideo = el => el && el.tagName === 'VIDEO';
  3993.  
  3994. const now = performance.now.bind(performance);
  3995.  
  3996. const sumProps = (...props) => {
  3997. let sum = 0;
  3998. for (const p of props)
  3999. sum += parseFloat(p) || 0;
  4000. return sum;
  4001. };
  4002.  
  4003. const tryCatch = function (fn, ...args) {
  4004. try {
  4005. return fn.apply(this, args);
  4006. } catch (e) {}
  4007. };
  4008.  
  4009. const tryJSON = str =>
  4010. tryCatch(JSON.parse, str);
  4011.  
  4012. const pick = (obj, path, fn) => (
  4013. obj = path.split(/[[.]/).reduce((res, k) => res && res[k.endsWith(']') ? k.slice(0, -1) : k], obj)
  4014. ) && (fn ? fn(obj) : obj);
  4015.  
  4016. const $ = (sel, node = doc) =>
  4017. node.querySelector(sel) || false;
  4018.  
  4019. const $$ = (sel, node = doc) =>
  4020. node.querySelectorAll(sel);
  4021.  
  4022. const $new = (sel, props, children) => {
  4023. if (typeof sel !== 'string') {
  4024. children = props;
  4025. props = sel;
  4026. sel = '';
  4027. }
  4028. if (!children && props != null && ({}).toString.call(props) !== '[object Object]') {
  4029. children = props;
  4030. props = null;
  4031. }
  4032. const isFrag = sel === 'fragment';
  4033. const [, tag, id, cls] = sel.match(/^(\w*)(?:#([^.]+))?(?:\.(.+))?$/);
  4034. const el = isFrag ? doc.createDocumentFragment() : doc.createElement(tag || 'div');
  4035. if (id) el.id = id;
  4036. if (cls) el.className = cls.replace(/\./g, ' ');
  4037. if (props) {
  4038. for (const [k, v] of Object.entries(props)) {
  4039. if (!k.startsWith('data-')) {
  4040. el[k] = v;
  4041. } else if (v != null) {
  4042. el.setAttribute(k, v);
  4043. }
  4044. }
  4045. }
  4046. if (children != null) {
  4047. if (Array.isArray(children))
  4048. el.append(...children.filter(Boolean));
  4049. else if (children instanceof Node)
  4050. el.appendChild(children);
  4051. else
  4052. el.textContent = children;
  4053. }
  4054. return el;
  4055. };
  4056.  
  4057. const $css = (el, props) =>
  4058. Object.entries(props).forEach(([k, v]) =>
  4059. el.style.setProperty(k, v, 'important'));
  4060.  
  4061. const $parseHtml = str =>
  4062. new DOMParser().parseFromString(str, 'text/html');
  4063.  
  4064. const $many = (q, doc) => {
  4065. for (const selector of ensureArray(q)) {
  4066. const el = selector && $(selector, doc);
  4067. if (el)
  4068. return el;
  4069. }
  4070. };
  4071.  
  4072. const $prop = (sel, prop, node = doc) =>
  4073. (node = $(sel, node)) && node[prop] || '';
  4074.  
  4075. const $propUp = (node, prop) =>
  4076. (node = node.closest(`[${prop}]`)) &&
  4077. (prop.startsWith('data-') ? node.getAttribute(prop) : node[prop]) ||
  4078. '';
  4079.  
  4080. const $remove = node =>
  4081. node && node.remove();
  4082.  
  4083. //#endregion
  4084. //#region Init
  4085.  
  4086. nonce = ($('script[nonce]') || {}).nonce || '';
  4087.  
  4088. Config.load({save: true}).then(res => {
  4089. cfg = res;
  4090. if (Menu) Menu.register();
  4091.  
  4092. if (doc.body) App.checkImageTab();
  4093. else addEventListener('DOMContentLoaded', App.checkImageTab, {once: true});
  4094.  
  4095. addEventListener('mouseover', Events.onMouseOver, true);
  4096. addEventListener('contextmenu', Events.onContext, true);
  4097. addEventListener('keydown', Events.onKeyDown, true);
  4098. addEventListener('visibilitychange', Events.onVisibility, true);
  4099. addEventListener('blur', Events.onVisibility, true);
  4100. if (['greasyfork.org', 'github.com'].includes(hostname))
  4101. addEventListener('click', setupClickedRule, true);
  4102. addEventListener('message', App.onMessage, true);
  4103. });
  4104.  
  4105. //#endregion