Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-03-19 提交的版本,查看 最新版本

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

QingJ © 2025

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