Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-03-15 提交的版本。查看 最新版本

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