Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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