Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2024-09-22 提交的版本,查看 最新版本

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

QingJ © 2025

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