Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-04-08 提交的版本。查看 最新版本

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