Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2021-04-04 提交的版本,檢視 最新版本

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