Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2021-10-03 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址