Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-04-16 提交的版本,查看 最新版本

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