Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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