Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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

QingJ © 2025

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