Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2021-04-15 提交的版本,查看 最新版本

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