Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2020-05-11 提交的版本,檢視 最新版本

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