Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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