Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2023-08-19 提交的版本,查看 最新版本

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