Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2022-10-05 提交的版本,查看 最新版本

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