SE Preview on hover

Shows preview of the linked questions/answers on hover

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

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 1.0.7
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. //
  9. // please use only matches for the previewable targets and make sure the domain
  10. // is extractable via [-.\w] so that it starts with . like .stackoverflow.com
  11. // @match *://*.stackoverflow.com/*
  12. // @match *://*.superuser.com/*
  13. // @match *://*.serverfault.com/*
  14. // @match *://*.askubuntu.com/*
  15. // @match *://*.stackapps.com/*
  16. // @match *://*.mathoverflow.net/*
  17. // @match *://*.stackexchange.com/*
  18. //
  19. // please use only includes for the container sites
  20. // @include *://www.google.com/search*/
  21. // @include /https?:\/\/(www\.)?google(\.com?)?(\.\w\w)?\/(webhp|q|.*?[?#]q=|search).*/
  22. // @include *://*.bing.com/*
  23. // @include *://*.yahoo.com/*
  24. // @include /https?:\/\/(\w+\.)*yahoo.(com|\w\w(\.\w\w)?)\/.*/
  25. //
  26. // @require https://greasyfork.org/scripts/27531/code/LZStringUnsafe.js
  27. // @require https://greasyfork.org/scripts/375977/code/StackOverflow-code-prettify-bundle.js
  28. //
  29. // @grant GM_addStyle
  30. // @grant GM_xmlhttpRequest
  31. // @grant GM_getValue
  32. // @grant GM_setValue
  33. // @grant GM_getResourceText
  34. //
  35. // @connect stackoverflow.com
  36. // @connect superuser.com
  37. // @connect serverfault.com
  38. // @connect askubuntu.com
  39. // @connect stackapps.com
  40. // @connect mathoverflow.net
  41. // @connect stackexchange.com
  42. // @connect sstatic.net
  43. // @connect gravatar.com
  44. // @connect imgur.com
  45. // @connect self
  46. //
  47. // @noframes
  48. // ==/UserScript==
  49.  
  50. /* global initPrettyPrint LZStringUnsafe */
  51. 'use strict';
  52.  
  53. Promise.resolve().then(() => {
  54. Detector.init();
  55. Security.init();
  56. Urler.init();
  57. Cache.init();
  58. });
  59.  
  60. const PREVIEW_DELAY = 200;
  61. const AUTOHIDE_DELAY = 1000;
  62. const BUSY_CURSOR_DELAY = 300;
  63. // 1 minute for the recently active posts, scales up logarithmically
  64. const CACHE_DURATION = 60e3;
  65.  
  66. const PADDING = 24;
  67. const QUESTION_WIDTH = 677; // unconstrained width of a question's .post_text
  68. const ANSWER_WIDTH = 657; // unconstrained width of an answer's .post_text
  69. const WIDTH = Math.max(QUESTION_WIDTH, ANSWER_WIDTH) + PADDING * 2;
  70. const BORDER = 8;
  71. const TOP_BORDER = 24;
  72. const MIN_HEIGHT = 200;
  73. let colors;
  74. const COLORS_LIGHT = {
  75. body: {
  76. back: '#ffffff',
  77. fore: '#000000',
  78. },
  79. question: {
  80. back: '#5894d8',
  81. fore: '#265184',
  82. foreInv: '#fff',
  83. },
  84. answer: {
  85. back: '#70c350',
  86. fore: '#3f7722',
  87. foreInv: '#fff',
  88. },
  89. deleted: {
  90. back: '#cd9898',
  91. fore: '#b56767',
  92. foreInv: '#fff',
  93. },
  94. closed: {
  95. back: '#ffce5d',
  96. fore: '#c28800',
  97. foreInv: '#fff',
  98. },
  99. };
  100. const COLORS_DARK = {
  101. body: {
  102. back: '#222222',
  103. fore: '#cccccc',
  104. },
  105. question: {
  106. back: '#004696',
  107. fore: '#6abaff',
  108. foreInv: '#004696',
  109. },
  110. answer: {
  111. back: '#004c1b',
  112. fore: '#39c466',
  113. foreInv: '#004c1b',
  114. },
  115. deleted: {
  116. back: '#4d0a0b',
  117. fore: '#b56767',
  118. foreInv: '#fff',
  119. },
  120. closed: {
  121. back: '#4b360a',
  122. fore: '#c28800',
  123. foreInv: '#fff',
  124. },
  125. };
  126. const ID = 'SEpreview';
  127. const EXPANDO = Symbol(ID);
  128.  
  129. const pv = {
  130. /** @type {Target} */
  131. target: null,
  132. /** @type {Element} */
  133. _frame: null,
  134. /** @type {Element} */
  135. get frame() {
  136. if (!this._frame)
  137. Preview.init();
  138. if (!document.contains(this._frame))
  139. document.body.appendChild(this._frame);
  140. return this._frame;
  141. },
  142. set frame(element) {
  143. this._frame = element;
  144. return element;
  145. },
  146. /** @type {Post} */
  147. post: {},
  148. hover: {x: 0, y: 0},
  149. stylesOverride: '',
  150. };
  151.  
  152. class Detector {
  153.  
  154. static init() {
  155. const sites = GM_info.script.matches.map(m => m.match(/[-.\w]+/)[0]);
  156. const rxsSites = 'https?://(\\w*\\.)*(' +
  157. GM_info.script.matches
  158. .map(m => m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.'))
  159. .join('|') +
  160. ')/';
  161. Detector.rxPreviewableSite = new RegExp(rxsSites);
  162. Detector.rxPreviewablePost = new RegExp(rxsSites + '(questions|q|a|posts/comments)/\\d+');
  163. Detector.pageUrls = getBaseUrls(location, Detector.rxPreviewablePost);
  164. Detector.isStackExchangePage = Detector.rxPreviewableSite.test(location);
  165.  
  166. const {
  167. rxPreviewablePost,
  168. isStackExchangePage: isSE,
  169. pageUrls: {base, baseShort},
  170. } = Detector;
  171.  
  172. // array of target elements accumulated in mutation observer
  173. // cleared in attachHoverListener
  174. const moQueue = [];
  175.  
  176. onMutation([{
  177. addedNodes: [document.body],
  178. }]);
  179.  
  180. new MutationObserver(onMutation)
  181. .observe(document.body, {
  182. childList: true,
  183. subtree: true,
  184. });
  185.  
  186. Detector.init = true;
  187.  
  188. function onMutation(mutations) {
  189. const alreadyScheduled = moQueue.length > 0;
  190. for (const {addedNodes} of mutations) {
  191. for (const n of addedNodes) {
  192. if (!n.localName)
  193. continue;
  194. if (n.localName === 'a') {
  195. moQueue.push(n);
  196. continue;
  197. }
  198. // not using ..spreading since there could be 100k links for all we know
  199. // and that might exceed JS engine stack limit which can be pretty low
  200. const targets = n.getElementsByTagName('a');
  201. for (let k = 0, len = targets.length; k < len; k++)
  202. moQueue.push(targets[k]);
  203. if (!isSE)
  204. continue;
  205. if (n.classList.contains('question-summary')) {
  206. moQueue.push(...n.getElementsByClassName('answered'));
  207. moQueue.push(...n.getElementsByClassName('answered-accepted'));
  208. continue;
  209. }
  210. for (const el of n.getElementsByClassName('question-summary')) {
  211. moQueue.push(...el.getElementsByClassName('answered'));
  212. moQueue.push(...el.getElementsByClassName('answered-accepted'));
  213. }
  214. }
  215. }
  216. if (!alreadyScheduled && moQueue.length)
  217. setTimeout(hoverize);
  218. }
  219.  
  220. function hoverize() {
  221. for (const el of moQueue) {
  222. if (el[EXPANDO] instanceof Target)
  223. continue;
  224. if (el.localName === 'a') {
  225. if (isSE && el.classList.contains('js-share-link'))
  226. continue;
  227. const previewable = isPreviewable(el) || !isSE && isEmbeddedUrlPreviewable(el);
  228. if (!previewable)
  229. continue;
  230. const url = Urler.makeHttps(el.href);
  231. if (url.startsWith(base) || url.startsWith(baseShort))
  232. continue;
  233. }
  234. Target.createHoverable(el);
  235. }
  236. moQueue.length = 0;
  237. }
  238.  
  239. function isPreviewable(a) {
  240. let href = false;
  241. const host = '.' + a.hostname;
  242. const hostLen = host.length;
  243. for (const stackSite of sites) {
  244. if (host[hostLen - stackSite.length] === '.' &&
  245. host.endsWith(stackSite) &&
  246. rxPreviewablePost.test(href || (href = a.href)))
  247. return true;
  248. }
  249. }
  250.  
  251. function isEmbeddedUrlPreviewable(a) {
  252. const url = a.href;
  253. let i = url.indexOf('http', 1);
  254. if (i < 0)
  255. return false;
  256. i = (
  257. url.indexOf('http://', i) + 1 ||
  258. url.indexOf('https://', i) + 1 ||
  259. url.indexOf('http%3A%2F%2F', i) + 1 ||
  260. url.indexOf('https%3A%2F%2F', i) + 1
  261. ) - 1;
  262. if (i < 0)
  263. return false;
  264. const j = url.indexOf('&', i);
  265. const embeddedUrl = url.slice(i, j > 0 ? j : undefined);
  266. return rxPreviewablePost.test(embeddedUrl);
  267. }
  268.  
  269. function getBaseUrls(url, rx) {
  270. if (!rx.test(url))
  271. return {};
  272. const base = Urler.makeHttps(RegExp.lastMatch);
  273. return {
  274. base,
  275. baseShort: base.replace('/questions/', '/q/'),
  276. };
  277. }
  278. }
  279. }
  280.  
  281. /**
  282. * @property {Element} element
  283. * @property {Boolean} isLink
  284. * @property {String} url
  285. * @property {Number} timer
  286. * @property {Number} timerCursor
  287. * @property {String} savedCursor
  288. */
  289. class Target {
  290.  
  291. /** @param {Element} el */
  292. static createHoverable(el) {
  293. const target = new Target(el);
  294. Object.defineProperty(el, EXPANDO, {value: target});
  295. el.removeAttribute('title');
  296. el.addEventListener('mouseover', Target._onMouseOver);
  297. return target;
  298. }
  299.  
  300. /** @param {Element} el */
  301. constructor(el) {
  302. this.element = el;
  303. this.isLink = el.localName === 'a';
  304. }
  305.  
  306. release() {
  307. $.off('mousemove', this.element, Target._onMove);
  308. $.off('mouseout', this.element, Target._onHoverEnd);
  309. $.off('mousedown', this.element, Target._onHoverEnd);
  310.  
  311. for (const k in this) {
  312. if (k.startsWith('timer') && this[k] >= 1) {
  313. clearTimeout(this[k]);
  314. this[k] = 0;
  315. }
  316. }
  317. BusyCursor.hide(this);
  318. pv.target = null;
  319. }
  320.  
  321. get url() {
  322. const el = this.element;
  323. if (this.isLink)
  324. return el.href;
  325. const a = $('a', el.closest('.question-summary'));
  326. if (a)
  327. return a.href;
  328. }
  329.  
  330. /** @param {MouseEvent} e */
  331. static _onMouseOver(e) {
  332. if (Util.hasKeyModifiers(e))
  333. return;
  334. const self = /** @type {Target} */ this[EXPANDO];
  335. if (self === Preview.target && Preview.shown() ||
  336. self === pv.target)
  337. return;
  338.  
  339. if (pv.target)
  340. pv.target.release();
  341. pv.target = self;
  342.  
  343. pv.hover.x = e.pageX;
  344. pv.hover.y = e.pageY;
  345.  
  346. $.on('mousemove', this, Target._onMove);
  347. $.on('mouseout', this, Target._onHoverEnd);
  348. $.on('mousedown', this, Target._onHoverEnd);
  349.  
  350. Target._restartTimer(self);
  351. }
  352.  
  353. /** @param {MouseEvent} e */
  354. static _onHoverEnd(e) {
  355. if (e.type === 'mouseout' && e.target !== this)
  356. return;
  357. const self = /** @type {Target} */ this[EXPANDO];
  358. if (pv.xhr && pv.target === self) {
  359. pv.xhr.abort();
  360. pv.xhr = null;
  361. }
  362. self.release();
  363. self.timer = setTimeout(Target._onAbortTimer, AUTOHIDE_DELAY, self);
  364. }
  365.  
  366. /** @param {MouseEvent} e */
  367. static _onMove(e) {
  368. const stoppedMoving =
  369. Math.abs(pv.hover.x - e.pageX) < 2 &&
  370. Math.abs(pv.hover.y - e.pageY) < 2;
  371. if (stoppedMoving) {
  372. pv.hover.x = e.pageX;
  373. pv.hover.y = e.pageY;
  374. Target._restartTimer(this[EXPANDO]);
  375. }
  376. }
  377.  
  378. /** @param {Target} self */
  379. static _restartTimer(self) {
  380. if (self.timer)
  381. clearTimeout(self.timer);
  382. self.timer = setTimeout(Target._onTimer, PREVIEW_DELAY, self);
  383. }
  384.  
  385. /** @param {Target} self */
  386. static _onTimer(self) {
  387. self.timer = 0;
  388. const el = self.element;
  389. if (!el.matches(':hover')) {
  390. self.release();
  391. return;
  392. }
  393. $.off('mousemove', el, Target._onMove);
  394.  
  395. if (self.url)
  396. Preview.start(self);
  397. }
  398.  
  399. /** @param {Target} self */
  400. static _onAbortTimer(self) {
  401. if ((self === pv.target || self === Preview.target) &&
  402. pv.frame && !pv.frame.matches(':hover')) {
  403. pv.target = null;
  404. Preview.hide({fade: true});
  405. }
  406. }
  407. }
  408.  
  409.  
  410. class BusyCursor {
  411.  
  412. /** @param {Target} target */
  413. static schedule(target) {
  414. target.timerCursor = setTimeout(BusyCursor._onTimer, BUSY_CURSOR_DELAY, target);
  415. }
  416.  
  417. /** @param {Target} target */
  418. static hide(target) {
  419. if (target.timerCursor) {
  420. clearTimeout(target.timerCursor);
  421. target.timerCursor = 0;
  422. }
  423. const style = target.element.style;
  424. if (style.cursor === 'wait')
  425. style.cursor = target.savedCursor;
  426. }
  427.  
  428. /** @param {Target} target */
  429. static _onTimer(target) {
  430. target.timerCursor = 0;
  431. target.savedCursor = target.element.style.cursor;
  432. $.setStyle(target.element, ['cursor', 'wait']);
  433. }
  434. }
  435.  
  436.  
  437. class Preview {
  438.  
  439. static init() {
  440. pv.frame = $.create(`#${ID}`, {parent: document.body});
  441. pv.shadow = pv.frame.attachShadow({mode: 'open'});
  442. pv.body = $.create(`body#${ID}-body`, {parent: pv.shadow});
  443.  
  444. const WRAP_AROUND = '(or wrap around to the question)';
  445. const TITLE_PREV = 'Previous answer\n' + WRAP_AROUND;
  446. const TITLE_NEXT = 'Next answer\n' + WRAP_AROUND;
  447. const TITLE_ENTER = 'Return to the question\n(Enter was Return initially)';
  448.  
  449. pv.answersTitle =
  450. $.create(`#${ID}-answers-title`, [
  451. 'Answers:',
  452. $.create('p', [
  453. 'Use ',
  454. $.create('b', {title: TITLE_PREV}),
  455. $.create('b', {title: TITLE_NEXT, attributes: {mirrored: ''}}),
  456. $.create('label', {title: TITLE_ENTER}, 'Enter'),
  457. ' to switch entries',
  458. ]),
  459. ]);
  460.  
  461. $.on('keydown', pv.frame, Preview.onKey);
  462. $.on('keyup', pv.frame, Util.consumeEsc);
  463.  
  464. $.on('mouseover', pv.body, ScrollLock.enable);
  465. $.on('click', pv.body, Preview.onClick);
  466.  
  467. Sizer.init();
  468. Styles.init();
  469. Preview.init = true;
  470. }
  471.  
  472. /** @param {Target} target */
  473. static async start(target) {
  474. Preview.target = target;
  475.  
  476. if (!Security.checked)
  477. Security.check();
  478.  
  479. const {url} = target;
  480.  
  481. let data = Cache.read(url);
  482. if (data) {
  483. const r = await Urler.get(url, {method: 'HEAD'});
  484. const postTime = Util.getResponseDate(r.responseHeaders);
  485. if (postTime >= data.time)
  486. data = null;
  487. }
  488.  
  489. if (!data) {
  490. BusyCursor.schedule(target);
  491. const {finalUrl, responseText: html} = await Urler.get(target.url);
  492. data = {finalUrl, html, unsaved: true};
  493. BusyCursor.hide(target);
  494. }
  495.  
  496. data.url = url;
  497. data.showAnswer = !target.isLink;
  498.  
  499. if (!Preview.prepare(data))
  500. Preview.target = null;
  501. else if (data.unsaved && data.lastActivity >= 1)
  502. Preview.save(data);
  503. }
  504.  
  505. static save({url, finalUrl, html, lastActivity}) {
  506. const inactiveDays = Math.max(0, (Date.now() - lastActivity) / (24 * 3600e3));
  507. const cacheDuration = CACHE_DURATION * Math.pow(Math.log(inactiveDays + 1) + 1, 2);
  508. setTimeout(Cache.write, 1000, {url, finalUrl, html, cacheDuration});
  509. }
  510.  
  511. // data is mutated: its lastActivity property is assigned!
  512. static prepare(data) {
  513. const {finalUrl, html, showAnswer, doc = Util.parseHtml(html)} = data;
  514.  
  515. if (!doc || !doc.head)
  516. return Util.error('no HEAD in the document received for', finalUrl);
  517.  
  518. if (!$('base', doc))
  519. $.create('base', {href: finalUrl, parent: doc.head});
  520.  
  521. let answerId;
  522. if (showAnswer) {
  523. const el = $('[id^="answer-"]', doc);
  524. answerId = el && el.id.match(/\d+/)[0];
  525. } else {
  526. answerId = finalUrl.match(/questions\/\d+\/[^/]+\/(\d+)|$/)[1];
  527. }
  528. const selector = answerId ? '#answer-' + answerId : '#question';
  529. const core = $(selector + ' .post-layout', doc);
  530. if (!core)
  531. return Util.error('No parsable post found', doc);
  532.  
  533. const isQuestion = !answerId;
  534. const status = isQuestion && $('[role="status"]', core);
  535. const isClosed = status && $('[href*="closed"]', status);
  536. const isDeleted = Boolean(core.closest('.deleted-answer'));
  537. const type = [
  538. isQuestion && 'question' || 'answer',
  539. isDeleted && 'deleted',
  540. isClosed && 'closed',
  541. ].filter(Boolean).join(' ');
  542. const answers = $.all('.answer', doc);
  543. const comments = $(`${selector} .comments`, doc);
  544. const commentsParent = comments.parentElement;
  545. const showMoreComments = $(`${selector} .js-show-link.comments-link`, doc);
  546. const lastActivity = Util.tryCatch(Util.extractTime, $('.lastactivity-link', doc)) ||
  547. Date.now();
  548. Object.assign(pv, {
  549. finalUrl,
  550. finalUrlOfQuestion: Urler.makeCacheable(finalUrl),
  551. });
  552. /** @typedef Post
  553. * @property {Document} doc
  554. * @property {String} html
  555. * @property {String} selector
  556. * @property {String} type
  557. * @property {String} id
  558. * @property {String} title
  559. * @property {Boolean} isQuestion
  560. * @property {Boolean} isDeleted
  561. * @property {Number} lastActivity
  562. * @property {Number} numAnswers
  563. * @property {Element} core
  564. * @property {Element} comments
  565. * @property {Element[]} answers
  566. * @property {Element[]} renderParts
  567. */
  568. Object.assign(pv.post, {
  569. doc,
  570. html,
  571. core,
  572. selector,
  573. answers,
  574. comments,
  575. type,
  576. isQuestion,
  577. isDeleted,
  578. lastActivity,
  579. id: isQuestion ? Urler.getFirstNumber(finalUrl) : answerId,
  580. title: $('meta[property="og:title"]', doc).content,
  581. numAnswers: answers.length,
  582. renderParts: [
  583. // including the parent so the right CSS kicks in
  584. core.parentElement,
  585. commentsParent,
  586. ],
  587. });
  588.  
  589. $.remove('script', doc);
  590. // remove the comment actions block
  591. $.remove('.comment-form, [id^="comments-link-"], .hover-only-label', commentsParent);
  592. if (!commentsParent.contains(showMoreComments))
  593. commentsParent.appendChild(showMoreComments);
  594.  
  595. Promise.all([
  596. pv.frame,
  597. Preview.addStyles(),
  598. Security.ready(),
  599. ]).then(Preview.show);
  600.  
  601. data.lastActivity = lastActivity;
  602. return true;
  603. }
  604.  
  605. static show() {
  606. Render.all();
  607.  
  608. const style = getComputedStyle(pv.frame);
  609. if (style.opacity !== '1' || style.display !== 'block') {
  610. $.setStyle(pv.frame, ['display', 'block']);
  611. setTimeout($.setStyle, 0, pv.frame, ['opacity', '1']);
  612. }
  613.  
  614. pv.parts.focus();
  615. }
  616.  
  617. static hide({fade = false} = {}) {
  618. if (Preview.target) {
  619. Preview.target.release();
  620. Preview.target = null;
  621. }
  622.  
  623. pv.body.onmouseover = null;
  624. pv.body.onclick = null;
  625. pv.body.onkeydown = null;
  626.  
  627. if (fade) {
  628. Util.fadeOut(pv.frame)
  629. .then(Preview.eraseBoxIfHidden);
  630. } else {
  631. $.setStyle(pv.frame,
  632. ['opacity', '0'],
  633. ['display', 'none']);
  634. Preview.eraseBoxIfHidden();
  635. }
  636. }
  637.  
  638. static shown() {
  639. return pv.frame.style.opacity === '1';
  640. }
  641.  
  642. /** @param {KeyboardEvent} e */
  643. static onKey(e) {
  644. switch (e.key) {
  645. case 'Escape':
  646. Preview.hide({fade: true});
  647. break;
  648. case 'ArrowUp':
  649. case 'PageUp':
  650. if (pv.parts.scrollTop)
  651. return;
  652. break;
  653. case 'ArrowDown':
  654. case 'PageDown': {
  655. const {scrollTop: t, clientHeight: h, scrollHeight} = pv.parts;
  656. if (t + h < scrollHeight)
  657. return;
  658. break;
  659. }
  660. case 'ArrowLeft':
  661. case 'ArrowRight': {
  662. if (!pv.post.numAnswers)
  663. return;
  664. // current is 0 if isQuestion, 1 is the first answer
  665. const answers = $.all(`#${ID}-answers a`);
  666. const current = pv.post.numAnswers ?
  667. answers.indexOf($('.SEpreviewed')) + 1 :
  668. pv.post.isQuestion ? 0 : 1;
  669. const num = pv.post.numAnswers + 1;
  670. const dir = e.key === 'ArrowLeft' ? -1 : 1;
  671. const toShow = (current + dir + num) % num;
  672. const a = toShow ? answers[toShow - 1] : $(`#${ID}-title`);
  673. a.click();
  674. break;
  675. }
  676. case 'Enter':
  677. if (pv.post.isQuestion)
  678. return;
  679. $(`#${ID}-title`).click();
  680. break;
  681. default:
  682. return;
  683. }
  684. e.preventDefault();
  685. }
  686.  
  687. /** @param {MouseEvent} e */
  688. static onClick(e) {
  689. if (e.target.id === `${ID}-close`) {
  690. Preview.hide();
  691. return;
  692. }
  693.  
  694. const link = e.target.closest('a');
  695. if (!link)
  696. return;
  697.  
  698. if (link.matches('.js-show-link.comments-link')) {
  699. Util.fadeOut(link, 0.5);
  700. Preview.loadComments();
  701. e.preventDefault();
  702. return;
  703. }
  704.  
  705. if (e.button ||
  706. Util.hasKeyModifiers(e) ||
  707. !link.matches('.SEpreviewable')) {
  708. link.target = '_blank';
  709. return;
  710. }
  711.  
  712. e.preventDefault();
  713.  
  714. const {doc} = pv.post;
  715. if (link.id === `${ID}-title`)
  716. Preview.prepare({doc, finalUrl: pv.finalUrlOfQuestion});
  717. else if (link.matches(`#${ID}-answers a`))
  718. Preview.prepare({doc, finalUrl: pv.finalUrlOfQuestion + '/' + Urler.getFirstNumber(link)});
  719. else
  720. Preview.start(new Target(link));
  721. }
  722.  
  723. static eraseBoxIfHidden() {
  724. if (!Preview.shown())
  725. pv.body.textContent = '';
  726. }
  727.  
  728. static setHeight(height) {
  729. const currentHeight = pv.frame.clientHeight;
  730. const borderHeight = pv.frame.offsetHeight - currentHeight;
  731. const newHeight = Math.max(MIN_HEIGHT, Math.min(innerHeight - borderHeight, height));
  732. if (newHeight !== currentHeight)
  733. $.setStyle(pv.frame, ['height', newHeight + 'px']);
  734. }
  735.  
  736. static async addStyles() {
  737. const isDark = matchMedia('(prefers-color-scheme: dark)').matches;
  738. colors = isDark ? COLORS_DARK : COLORS_LIGHT;
  739. pv.body.className = isDark ? 'theme-dark' : '';
  740. Styles.init(isDark);
  741.  
  742. let last = $.create(`style#${ID}-styles.${Styles.REUSABLE}`, {
  743. textContent: pv.stylesOverride,
  744. before: pv.shadow.firstChild,
  745. });
  746.  
  747. if (!pv.styles)
  748. pv.styles = new Map();
  749.  
  750. const toDownload = [];
  751. const sourceElements = $.all('link[rel="stylesheet"], style', pv.post.doc);
  752.  
  753. for (const {href, textContent, localName} of sourceElements) {
  754. const isLink = localName === 'link';
  755. const id = ID + '-style-' + (isLink ? href : await Util.sha256(textContent));
  756. const el = pv.styles.get(id);
  757. if (!el && isLink)
  758. toDownload.push(Urler.get({url: href, context: id}));
  759. last = $.create('style', {
  760. id,
  761. className: Styles.REUSABLE,
  762. textContent: isLink ? $.text(el) : textContent,
  763. after: last,
  764. });
  765. pv.styles.set(id, last);
  766. }
  767.  
  768. const downloaded = await Promise.all(toDownload);
  769.  
  770. for (const {responseText, context: id} of downloaded)
  771. pv.shadow.getElementById(id).textContent = responseText;
  772. }
  773.  
  774. static async loadComments() {
  775. const list = $(`#${pv.post.comments.id} .comments-list`);
  776. const url = new URL(pv.finalUrl).origin +
  777. '/posts/' + pv.post.comments.id.match(/\d+/)[0] + '/comments';
  778. list.innerHTML = (await Urler.get(url)).responseText;
  779. $.remove('.hover-only-label', list);
  780.  
  781. const oldIds = new Set([...list.children].map(e => e.id));
  782. for (const cmt of list.children) {
  783. if (!oldIds.has(cmt.id))
  784. cmt.classList.add('new-comment-highlight');
  785. }
  786.  
  787. $.setStyle(list.closest('.comments'), ['display', 'block']);
  788. Render.previewableLinks(list);
  789. Render.hoverableUsers(list);
  790. }
  791. }
  792.  
  793.  
  794. class Render {
  795.  
  796. static all() {
  797. pv.frame.classList.toggle(`${ID}-hasAnswerShelf`, pv.post.numAnswers > 0);
  798. pv.frame.setAttribute(`${ID}-type`, pv.post.type);
  799. pv.body.setAttribute(`${ID}-type`, pv.post.type);
  800.  
  801. $.create(`a#${ID}-title.SEpreviewable`, {
  802. href: pv.finalUrlOfQuestion,
  803. textContent: pv.post.title,
  804. parent: pv.body,
  805. });
  806.  
  807. $.create(`#${ID}-close`, {
  808. title: 'Or press Esc key while the preview is focused (also when just shown)',
  809. parent: pv.body,
  810. });
  811.  
  812. $.create(`#${ID}-meta`, {
  813. parent: pv.body,
  814. onmousedown: Sizer.onMouseDown,
  815. children: [
  816. Render._votes(),
  817. pv.post.isQuestion
  818. ? Render._questionMeta()
  819. : Render._answerMeta(),
  820. ],
  821. });
  822.  
  823. Render.previewableLinks(pv.post.doc);
  824.  
  825. pv.post.answerShelf = pv.post.answers.map(Render._answer);
  826. if (Security.noImages)
  827. Security.embedImages(...pv.post.renderParts);
  828.  
  829. pv.parts = $.create(`#${ID}-parts`, {
  830. className: pv.post.isDeleted ? 'deleted-answer' : '',
  831. tabIndex: 0,
  832. scrollTop: 0,
  833. parent: pv.body,
  834. children: pv.post.renderParts,
  835. });
  836.  
  837. Render.hoverableUsers(pv.parts);
  838.  
  839. if (pv.post.numAnswers) {
  840. $.create(`#${ID}-answers`, {parent: pv.body}, [
  841. pv.answersTitle,
  842. pv.post.answerShelf,
  843. ]);
  844. } else {
  845. $.remove(`#${ID}-answers`, pv.body);
  846. }
  847.  
  848. // delinkify/remove non-functional items in post-menu
  849. $.remove('.js-share-link, .flag-post-link', pv.body);
  850. for (const a of $.all('.post-menu a:not(.edit-post)')) {
  851. if (a.children.length)
  852. $.create('span', {before: a}, a.childNodes);
  853. a.remove();
  854. }
  855.  
  856. // add a timeline link
  857. $.appendChildren($('.post-menu'), [
  858. $.create('span.lsep'),
  859. $.create('a', {href: `/posts/${pv.post.id}/timeline`}, 'timeline'),
  860. ]);
  861.  
  862. // prettify code blocks
  863. const codeBlocks = $.all('pre code');
  864. if (codeBlocks.length) {
  865. codeBlocks.forEach(e =>
  866. e.parentElement.classList.add('prettyprint'));
  867. if (!pv.prettify)
  868. initPrettyPrint((pv.prettify = {}));
  869. if (typeof pv.prettify.prettyPrint === 'function')
  870. pv.prettify.prettyPrint(null, pv.body);
  871. }
  872.  
  873. const leftovers = $.all('style, link, script, .post-menu .lsep + .lsep');
  874. for (const el of leftovers) {
  875. if (el.classList.contains(Styles.REUSABLE))
  876. el.classList.remove(Styles.REUSABLE);
  877. else
  878. el.remove();
  879. }
  880.  
  881. pv.post.html = null;
  882. pv.post.core = null;
  883. pv.post.renderParts = null;
  884. pv.post.answers = null;
  885. pv.post.answerShelf = null;
  886. }
  887.  
  888. /** @param {Element} container */
  889. static previewableLinks(container) {
  890. for (const a of $.all('a:not(.SEpreviewable)', container)) {
  891. let href = a.getAttribute('href');
  892. if (!href)
  893. continue;
  894. if (!href.includes('://')) {
  895. href = a.href;
  896. a.setAttribute('href', href);
  897. }
  898. if (Detector.rxPreviewablePost.test(href)) {
  899. a.removeAttribute('title');
  900. a.classList.add('SEpreviewable');
  901. }
  902. }
  903. }
  904.  
  905. /** @param {Element} container */
  906. static hoverableUsers(container) {
  907. for (const a of $.all('a[href*="/users/"]', container)) {
  908. if (Detector.rxPreviewableSite.test(a.href) &&
  909. a.pathname.match(/^\/users\/\d+/)) {
  910. a.onmouseover = UserCard.onUserLinkHovered;
  911. a.classList.add(`${ID}-userLink`);
  912. }
  913. }
  914. }
  915.  
  916. /** @param {Element} el */
  917. static _answer(el) {
  918. const shortUrl = $('.js-share-link', el).href.replace(/(\d+)\/\d+/, '$1');
  919. const extraClasses =
  920. (el.matches(pv.post.selector) ? ' SEpreviewed' : '') +
  921. (el.matches('.deleted-answer') ? ' deleted-answer' : '') +
  922. (el.matches('.accepted-answer') ? ` ${ID}-accepted` : '');
  923. const author = $('.post-signature:last-child', el);
  924. const title =
  925. $.text('.user-details a', author) +
  926. ' (rep ' +
  927. $.text('.reputation-score', author) +
  928. ')\n' +
  929. $.text('.user-action-time', author);
  930. let gravatar = $('img, .anonymous-gravatar, .community-wiki', author);
  931. if (gravatar && Security.noImages)
  932. Security.embedImages(gravatar);
  933. if (gravatar && gravatar.src)
  934. gravatar = $.create('img', {src: gravatar.src});
  935. const a = $.create('a', {
  936. href: shortUrl,
  937. title: title,
  938. className: 'SEpreviewable' + extraClasses,
  939. textContent: $.text('.js-vote-count', el).replace(/^0$/, '\xA0') + ' ',
  940. children: gravatar,
  941. });
  942. return [a, ' '];
  943. }
  944.  
  945. static _votes() {
  946. const votes = $.text('.js-vote-count', pv.post.core.closest('.post-layout'));
  947. if (Number(votes))
  948. return $.create('b', `${votes} vote${Math.abs(votes) >= 2 ? 's' : ''}`);
  949. }
  950. static _questionMeta() {
  951. try {
  952. return [...$('time', pv.post.doc).closest('.grid').children]
  953. .map(el => el.textContent.trim())
  954. .map((s, i) => (i ? s.toLowerCase() : s))
  955. .join(', ');
  956. } catch (e) {
  957. return '';
  958. }
  959. }
  960.  
  961. static _answerMeta() {
  962. return $.all('.user-action-time', pv.post.core.closest('.answer'))
  963. .reverse()
  964. .map($.text)
  965. .join(', ');
  966. }
  967. }
  968.  
  969.  
  970. class UserCard {
  971.  
  972. _fadeIn() {
  973. this._retakeId(this);
  974. $.setStyle(this.element,
  975. ['opacity', '0'],
  976. ['display', 'block']);
  977. this.timer = setTimeout(() => {
  978. if (this.timer)
  979. $.setStyle(this.element, ['opacity', '1']);
  980. });
  981. }
  982.  
  983. _retakeId() {
  984. if (this.element.id !== 'user-menu') {
  985. const oldCard = $('#user-menu');
  986. if (oldCard)
  987. oldCard.id = oldCard.style.display = '';
  988. this.element.id = 'user-menu';
  989. }
  990. }
  991.  
  992. // 'this' is the hoverable link enclosing the user's name/avatar
  993. static onUserLinkHovered() {
  994. clearTimeout(this[EXPANDO]);
  995. this[EXPANDO] = setTimeout(UserCard._show, PREVIEW_DELAY * 2, this);
  996. }
  997.  
  998. /** @param {HTMLAnchorElement} a */
  999. static async _show(a) {
  1000. if (!a.matches(':hover'))
  1001. return;
  1002. const el = a.nextElementSibling;
  1003. const card = el && el.matches(`.${ID}-userCard`) && el[EXPANDO] ||
  1004. await UserCard._create(a);
  1005. card._fadeIn();
  1006. }
  1007.  
  1008. /** @param {HTMLAnchorElement} a */
  1009. static async _create(a) {
  1010. const url = a.origin + '/users/user-info/' + Urler.getFirstNumber(a);
  1011. let {html} = Cache.read(url) || {};
  1012. if (!html) {
  1013. html = (await Urler.get(url)).responseText;
  1014. Cache.write({url, html, cacheDuration: CACHE_DURATION * 100});
  1015. }
  1016.  
  1017. const dom = Util.parseHtml(html);
  1018. if (Security.noImages)
  1019. Security.embedImages(dom);
  1020.  
  1021. const b = a.getBoundingClientRect();
  1022. const pb = pv.parts.getBoundingClientRect();
  1023. const left = Math.min(b.left - 20, pb.right - 350) - pb.left + 'px';
  1024. const isClipped = b.bottom + 100 > pb.bottom;
  1025.  
  1026. const el = $.create(`#user-menu-tmp.${ID}-userCard`, {
  1027. attributes: {
  1028. style: `left: ${left} !important;` +
  1029. (isClipped ? 'margin-top: -5rem !important;' : ''),
  1030. },
  1031. onmouseout: UserCard._onMouseOut,
  1032. children: dom.body.children,
  1033. after: a,
  1034. });
  1035.  
  1036. const card = new UserCard(el);
  1037. Object.defineProperty(el, EXPANDO, {value: card});
  1038. card.element = el;
  1039. return card;
  1040. }
  1041.  
  1042. /** @param {MouseEvent} e */
  1043. static _onMouseOut(e) {
  1044. if (this.matches(':hover') ||
  1045. this.style.opacity === '0' /* fading out already */)
  1046. return;
  1047.  
  1048. const self = /** @type {UserCard} */ this[EXPANDO];
  1049. clearTimeout(self.timer);
  1050. self.timer = 0;
  1051.  
  1052. Util.fadeOut(this);
  1053. }
  1054. }
  1055.  
  1056.  
  1057. class Sizer {
  1058.  
  1059. static init() {
  1060. Preview.setHeight(GM_getValue('height', innerHeight / 3) >> 0);
  1061. }
  1062.  
  1063. /** @param {MouseEvent} e */
  1064. static onMouseDown(e) {
  1065. if (e.button !== 0 || Util.hasKeyModifiers(e))
  1066. return;
  1067. Sizer._heightDelta = innerHeight - e.clientY - pv.frame.clientHeight;
  1068. $.on('mousemove', document, Sizer._onMouseMove);
  1069. $.on('mouseup', document, Sizer._onMouseUp);
  1070. }
  1071.  
  1072. /** @param {MouseEvent} e */
  1073. static _onMouseMove(e) {
  1074. Preview.setHeight(innerHeight - e.clientY - Sizer._heightDelta);
  1075. getSelection().removeAllRanges();
  1076. }
  1077.  
  1078. /** @param {MouseEvent} e */
  1079. static _onMouseUp(e) {
  1080. GM_setValue('height', pv.frame.clientHeight);
  1081. $.off('mouseup', document, Sizer._onMouseUp);
  1082. $.off('mousemove', document, Sizer._onMouseMove);
  1083. }
  1084. }
  1085.  
  1086.  
  1087. class ScrollLock {
  1088.  
  1089. static enable() {
  1090. if (ScrollLock.active)
  1091. return;
  1092. ScrollLock.active = true;
  1093. ScrollLock.x = scrollX;
  1094. ScrollLock.y = scrollY;
  1095. $.on('mouseover', document.body, ScrollLock._onMouseOver);
  1096. $.on('scroll', document, ScrollLock._onScroll);
  1097. }
  1098.  
  1099. static disable() {
  1100. ScrollLock.active = false;
  1101. $.off('mouseover', document.body, ScrollLock._onMouseOver);
  1102. $.off('scroll', document, ScrollLock._onScroll);
  1103. }
  1104.  
  1105. static _onMouseOver() {
  1106. if (ScrollLock.active)
  1107. ScrollLock.disable();
  1108. }
  1109.  
  1110. static _onScroll() {
  1111. scrollTo(ScrollLock.x, ScrollLock.y);
  1112. }
  1113. }
  1114.  
  1115.  
  1116. class Security {
  1117.  
  1118. static init() {
  1119. if (Detector.isStackExchangePage) {
  1120. Security.checked = true;
  1121. Security.check = null;
  1122. }
  1123. Security.init = true;
  1124. }
  1125.  
  1126. static async check() {
  1127. Security.noImages = false;
  1128. Security._resolveOnReady = [];
  1129. Security._imageCache = new Map();
  1130.  
  1131. const {headers} = await fetch(location.href, {
  1132. method: 'HEAD',
  1133. cache: 'force-cache',
  1134. mode: 'same-origin',
  1135. credentials: 'same-origin',
  1136. });
  1137. const csp = headers.get('Content-Security-Policy');
  1138. const imgSrc = /(?:^|[\s;])img-src\s+([^;]+)/i.test(csp) && RegExp.$1.trim();
  1139. if (imgSrc)
  1140. Security.noImages = !/(^\s)(\*|https?:)(\s|$)/.test(imgSrc);
  1141.  
  1142. Security._resolveOnReady.forEach(fn => fn());
  1143. Security._resolveOnReady = null;
  1144. Security.checked = true;
  1145. Security.check = null;
  1146. }
  1147.  
  1148. /** @return Promise<void> */
  1149. static ready() {
  1150. return Security.checked ?
  1151. Promise.resolve() :
  1152. new Promise(done => Security._resolveOnReady.push(done));
  1153. }
  1154.  
  1155. static embedImages(...containers) {
  1156. for (const container of containers) {
  1157. if (!container)
  1158. continue;
  1159. if (Util.isIterable(container)) {
  1160. Security.embedImages(...container);
  1161. continue;
  1162. }
  1163. if (container.localName === 'img') {
  1164. Security._embedImage(container);
  1165. continue;
  1166. }
  1167. for (const img of container.getElementsByTagName('img'))
  1168. Security._embedImage(img);
  1169. }
  1170. }
  1171.  
  1172. static _embedImage(img) {
  1173. const src = img.src;
  1174. if (!src || src.startsWith('data:'))
  1175. return;
  1176. const data = Security._imageCache.get(src);
  1177. const alreadyFetching = Array.isArray(data);
  1178. if (alreadyFetching) {
  1179. data.push(img);
  1180. } else if (data) {
  1181. img.src = data;
  1182. return;
  1183. } else {
  1184. Security._imageCache.set(src, [img]);
  1185. Security._fetchImage(src);
  1186. }
  1187. $.setStyle(img, ['visibility', 'hidden']);
  1188. img.dataset.src = src;
  1189. img.removeAttribute('src');
  1190. }
  1191.  
  1192. static async _fetchImage(src) {
  1193. const r = await Urler.get({url: src, responseType: 'blob'});
  1194. const type = Util.getResponseMimeType(r.responseHeaders);
  1195. const blob = r.response;
  1196. const blobType = blob.type;
  1197. let dataUri = await Util.blobToBase64(blob);
  1198. if (blobType !== type)
  1199. dataUri = 'data:' + type + dataUri.slice(dataUri.indexOf(';'));
  1200.  
  1201. const images = Security._imageCache.get(src);
  1202. Security._imageCache.set(src, dataUri);
  1203.  
  1204. let detached = false;
  1205. for (const el of images) {
  1206. el.src = dataUri;
  1207. el.style.removeProperty('visibility');
  1208. if (!detached && el.ownerDocument !== document)
  1209. detached = true;
  1210. }
  1211.  
  1212. if (detached) {
  1213. for (const el of $.all(`img[data-src="${src}"]`)) {
  1214. el.src = dataUri;
  1215. el.style.removeProperty('visibility');
  1216. }
  1217. }
  1218. }
  1219. }
  1220.  
  1221.  
  1222. // eslint-disable-next-line no-redeclare
  1223. class Cache {
  1224.  
  1225. static init() {
  1226. Cache.timers = new Map();
  1227. setTimeout(Cache._cleanup, 10e3);
  1228. }
  1229.  
  1230. static read(url) {
  1231. const keyUrl = Urler.makeCacheable(url);
  1232. const [time, expires, finalUrl = url] = (localStorage[keyUrl] || '').split('\t');
  1233. const keyFinalUrl = Urler.makeCacheable(finalUrl);
  1234. return expires > Date.now() && {
  1235. time,
  1236. finalUrl,
  1237. html: LZStringUnsafe.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  1238. };
  1239. }
  1240.  
  1241. // standard keyUrl = time,expiry
  1242. // keyUrl\thtml = html
  1243. // redirected keyUrl = time,expiry,finalUrl
  1244. // keyFinalUrl = time,expiry
  1245. // keyFinalUrl\thtml = html
  1246. static write({url, finalUrl, html, cacheDuration = CACHE_DURATION}) {
  1247.  
  1248. cacheDuration = Math.max(CACHE_DURATION, Math.min(0x7FFF0000, cacheDuration >> 0));
  1249. finalUrl = (finalUrl || url).replace(/[?#].*/, '');
  1250.  
  1251. const keyUrl = Urler.makeCacheable(url);
  1252. const keyFinalUrl = Urler.makeCacheable(finalUrl);
  1253. const lz = LZStringUnsafe.compressToUTF16(html);
  1254.  
  1255. if (!Util.tryCatch(Cache._writeRaw, keyFinalUrl + '\thtml', lz)) {
  1256. Cache._cleanup({aggressive: true});
  1257. if (!Util.tryCatch(Cache._writeRaw, keyFinalUrl + '\thtml', lz))
  1258. return Util.error('localStorage write error');
  1259. }
  1260.  
  1261. const time = Date.now();
  1262. const expiry = time + cacheDuration;
  1263. localStorage[keyFinalUrl] = time + '\t' + expiry;
  1264. if (keyUrl !== keyFinalUrl)
  1265. localStorage[keyUrl] = time + '\t' + expiry + '\t' + finalUrl;
  1266.  
  1267. const t = setTimeout(Cache._delete, cacheDuration + 1000,
  1268. keyUrl,
  1269. keyFinalUrl,
  1270. keyFinalUrl + '\thtml');
  1271.  
  1272. for (const url of [keyUrl, keyFinalUrl]) {
  1273. clearTimeout(Cache.timers.get(url));
  1274. Cache.timers.set(url, t);
  1275. }
  1276. }
  1277.  
  1278. static _writeRaw(k, v) {
  1279. localStorage[k] = v;
  1280. return true;
  1281. }
  1282.  
  1283. static _delete(...keys) {
  1284. for (const k of keys) {
  1285. delete localStorage[k];
  1286. Cache.timers.delete(k);
  1287. }
  1288. }
  1289.  
  1290. static _cleanup({aggressive = false} = {}) {
  1291. for (const k in localStorage) {
  1292. if ((k.startsWith('http://') || k.startsWith('https://')) &&
  1293. !k.includes('\t')) {
  1294. const [, expires, url] = (localStorage[k] || '').split('\t');
  1295. if (Number(expires) > Date.now() && !aggressive)
  1296. break;
  1297. if (url) {
  1298. delete localStorage[url];
  1299. Cache.timers.delete(url);
  1300. }
  1301. delete localStorage[(url || k) + '\thtml'];
  1302. delete localStorage[k];
  1303. Cache.timers.delete(k);
  1304. }
  1305. }
  1306. }
  1307. }
  1308.  
  1309.  
  1310. class Urler {
  1311.  
  1312. static init() {
  1313. Urler.xhr = null;
  1314. Urler.xhrNoSSL = new Set();
  1315. Urler.init = true;
  1316. }
  1317.  
  1318. static getFirstNumber(url) {
  1319. if (typeof url === 'string')
  1320. url = new URL(url);
  1321. return url.pathname.match(/\/(\d+)/)[1];
  1322. }
  1323.  
  1324. static makeHttps(url) {
  1325. if (!url)
  1326. return '';
  1327. if (url.startsWith('http:'))
  1328. return 'https:' + url.slice(5);
  1329. return url;
  1330. }
  1331.  
  1332. // strips queries and hashes and anything after the main part
  1333. // https://site/questions/NNNNNN/title/
  1334. static makeCacheable(url) {
  1335. return url
  1336. .replace(/(\/q(?:uestions)?\/\d+\/[^/]+).*/, '$1')
  1337. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  1338. .replace(/[?#].*$/, '');
  1339. }
  1340.  
  1341. static get(options) {
  1342. if (!options.url)
  1343. options = {url: options, method: 'GET'};
  1344. if (!options.method)
  1345. options = Object.assign({method: 'GET'}, options);
  1346.  
  1347. let url = options.url;
  1348. const hostname = new URL(url).hostname;
  1349.  
  1350. if (Urler.xhrNoSSL.has(hostname)) {
  1351. url = url.replace(/^https/, 'http');
  1352. } else {
  1353. url = Urler.makeHttps(url);
  1354. const _onerror = options.onerror;
  1355. options.onerror = () => {
  1356. options.onerror = _onerror;
  1357. options.url = url.replace(/^https/, 'http');
  1358. Urler.xhrNoSSL.add(hostname);
  1359. return Urler.get(options);
  1360. };
  1361. }
  1362.  
  1363. return new Promise(resolve => {
  1364. let xhr;
  1365. options.onload = r => {
  1366. if (pv.xhr === xhr)
  1367. pv.xhr = null;
  1368. resolve(r);
  1369. };
  1370. options.url = url;
  1371. xhr = pv.xhr = GM_xmlhttpRequest(options);
  1372. });
  1373. }
  1374. }
  1375.  
  1376.  
  1377. class Util {
  1378.  
  1379. static tryCatch(fn, ...args) {
  1380. try {
  1381. return fn(...args);
  1382. } catch (e) {}
  1383. }
  1384.  
  1385. static isIterable(o) {
  1386. return typeof o === 'object' && Symbol.iterator in o;
  1387. }
  1388.  
  1389. static parseHtml(html) {
  1390. if (!Util.parser)
  1391. Util.parser = new DOMParser();
  1392. return Util.parser.parseFromString(html, 'text/html');
  1393. }
  1394.  
  1395. static extractTime(element) {
  1396. return new Date(element.title).getTime();
  1397. }
  1398.  
  1399. static getResponseMimeType(headers) {
  1400. return headers.match(/^\s*content-type:\s*(.*)|$/mi)[1] ||
  1401. 'image/png';
  1402. }
  1403.  
  1404. static getResponseDate(headers) {
  1405. try {
  1406. return new Date(headers.match(/^\s*date:\s*(.*)/mi)[1]);
  1407. } catch (e) {}
  1408. }
  1409.  
  1410. static blobToBase64(blob) {
  1411. return new Promise((resolve, reject) => {
  1412. const reader = new FileReader();
  1413. reader.onerror = reject;
  1414. reader.onload = e => resolve(e.target.result);
  1415. reader.readAsDataURL(blob);
  1416. });
  1417. }
  1418.  
  1419. static async sha256(str) {
  1420. if (!pv.utf8encoder)
  1421. pv.utf8encoder = new TextEncoder('utf-8');
  1422. const buf = await crypto.subtle.digest('SHA-256', pv.utf8encoder.encode(str));
  1423. const blob = new Blob([buf]);
  1424. const url = await Util.blobToBase64(blob);
  1425. return url.slice(url.indexOf(',') + 1);
  1426. }
  1427.  
  1428. /** @param {KeyboardEvent} e */
  1429. static hasKeyModifiers(e) {
  1430. return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey;
  1431. }
  1432.  
  1433. static fadeOut(el, transition) {
  1434. return new Promise(resolve => {
  1435. if (transition) {
  1436. if (typeof transition === 'number')
  1437. transition = `opacity ${transition}s ease-in-out`;
  1438. $.setStyle(el, ['transition', transition]);
  1439. setTimeout(doFadeOut);
  1440. } else {
  1441. doFadeOut();
  1442. }
  1443. function doFadeOut() {
  1444. $.setStyle(el, ['opacity', '0']);
  1445. $.on('transitionend', el, done);
  1446. $.on('visibilitychange', el, done);
  1447. }
  1448. function done() {
  1449. $.off('transitionend', el, done);
  1450. $.off('visibilitychange', el, done);
  1451. if (el.style.opacity === '0')
  1452. $.setStyle(el, ['display', 'none']);
  1453. resolve();
  1454. }
  1455. });
  1456. }
  1457.  
  1458. /** @param {KeyboardEvent} e */
  1459. static consumeEsc(e) {
  1460. if (e.key === 'Escape')
  1461. e.preventDefault();
  1462. }
  1463.  
  1464. static error(...args) {
  1465. console.error(GM_info.script.name, ...args);
  1466. }
  1467. }
  1468.  
  1469.  
  1470. class Styles {
  1471.  
  1472. static init(isDark) {
  1473. if (Styles.isDark === isDark)
  1474. return;
  1475.  
  1476. Styles.isDark = isDark;
  1477. Styles.REUSABLE = `${ID}-reusable`;
  1478.  
  1479. const KBD_COLOR = '#0008';
  1480.  
  1481. // language=HTML
  1482. const SVG_ARROW = btoa(`
  1483. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
  1484. <path stroke="${KBD_COLOR}" stroke-width="3" fill="none"
  1485. d="M2.5,8.5H15 M9,2L2.5,8.5L9,15"/>
  1486. </svg>`
  1487. .replace(/>\s+</g, '><')
  1488. .replace(/[\r\n]/g, ' ')
  1489. .replace(/\s\s+/g, ' ')
  1490. .trim()
  1491. );
  1492.  
  1493. const IMPORTANT = '!important;';
  1494.  
  1495. // language=CSS
  1496. pv.stylesOverride = [
  1497. `
  1498. :host {
  1499. all: initial;
  1500. border-color: transparent;
  1501. display: none;
  1502. opacity: 0;
  1503. height: 33%;
  1504. transition: opacity .25s cubic-bezier(.88,.02,.92,.66),
  1505. border-color .25s ease-in-out;
  1506. }
  1507. `,
  1508.  
  1509. `
  1510. :host {
  1511. box-sizing: content-box;
  1512. width: ${WIDTH}px;
  1513. min-height: ${MIN_HEIGHT}px;
  1514. position: fixed;
  1515. right: 0;
  1516. bottom: 0;
  1517. padding: 0;
  1518. margin: 0;
  1519. background: white;
  1520. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  1521. z-index: 999999;
  1522. border-width: ${TOP_BORDER}px ${BORDER}px ${BORDER}px;
  1523. border-style: solid;
  1524. }
  1525. :host(:not([style*="opacity: 1"])) {
  1526. pointer-events: none;
  1527. }
  1528. :host([\\type$="question"].\\hasAnswerShelf) {
  1529. border-image: linear-gradient(
  1530. ${colors.question.back} 66%,
  1531. ${colors.answer.back}) 1 1;
  1532. }
  1533. `.replace(/;/g, IMPORTANT),
  1534.  
  1535. ...Object.entries(colors).map(([type, colors]) => `
  1536. :host([\\type$="${type}"]) {
  1537. border-color: ${colors.back} !important;
  1538. }
  1539. `),
  1540.  
  1541. `
  1542. #\\body {
  1543. min-width: unset!important;
  1544. box-shadow: none!important;
  1545. padding: 0!important;
  1546. margin: 0!important;
  1547. background: ${colors.body.back}!important;
  1548. color: ${colors.body.fore}!important;
  1549. display: flex;
  1550. flex-direction: column;
  1551. height: 100%;
  1552. }
  1553.  
  1554. #\\title {
  1555. all: unset;
  1556. display: block;
  1557. padding: 12px ${PADDING}px;
  1558. font-weight: bold;
  1559. font-size: 18px;
  1560. line-height: 1.2;
  1561. cursor: pointer;
  1562. }
  1563. #\\title:hover {
  1564. text-decoration: underline;
  1565. text-decoration-skip: ink;
  1566. }
  1567. #\\title:hover + #\\meta {
  1568. opacity: 1.0;
  1569. }
  1570.  
  1571. #\\meta {
  1572. position: absolute;
  1573. font: bold 14px/${TOP_BORDER}px sans-serif;
  1574. height: ${TOP_BORDER}px;
  1575. top: -${TOP_BORDER}px;
  1576. left: -${BORDER}px;
  1577. right: ${BORDER * 2}px;
  1578. padding: 0 0 0 ${BORDER + PADDING}px;
  1579. display: flex;
  1580. align-items: center;
  1581. cursor: s-resize;
  1582. }
  1583. #\\meta b {
  1584. height: ${TOP_BORDER}px;
  1585. display: inline-block;
  1586. padding: 0 6px;
  1587. margin-left: -6px;
  1588. margin-right: 3px;
  1589. }
  1590.  
  1591. #\\close {
  1592. position: absolute;
  1593. top: -${TOP_BORDER}px;
  1594. right: -${BORDER}px;
  1595. width: ${BORDER * 3}px;
  1596. flex: none;
  1597. cursor: pointer;
  1598. padding: .5ex 1ex;
  1599. font: normal 15px/1.0 sans-serif;
  1600. color: #fff8;
  1601. }
  1602. #\\close:after {
  1603. content: "x";
  1604. }
  1605. #\\close:active {
  1606. background-color: rgba(0,0,0,.2);
  1607. }
  1608. #\\close:hover {
  1609. background-color: rgba(0,0,0,.1);
  1610. }
  1611.  
  1612. #\\parts {
  1613. position: relative;
  1614. overflow-y: overlay; /* will replace with scrollbar-gutter once it's implemented */
  1615. overflow-x: hidden;
  1616. flex-grow: 2;
  1617. outline: none;
  1618. margin: 0;
  1619. }
  1620. [\\type^="question"] #\\parts {
  1621. padding: ${(WIDTH - QUESTION_WIDTH) / 2}px !important;
  1622. }
  1623. [\\type^="answer"] #\\parts {
  1624. padding: ${(WIDTH - ANSWER_WIDTH) / 2}px !important;
  1625. }
  1626. #\\parts > .question-status {
  1627. margin: -${PADDING}px -${PADDING}px ${PADDING}px;
  1628. padding-left: ${PADDING}px;
  1629. }
  1630. #\\parts .question-originals-of-duplicate {
  1631. margin: -${PADDING}px -${PADDING}px ${PADDING}px;
  1632. padding: ${PADDING / 2 >> 0}px ${PADDING}px;
  1633. }
  1634. #\\parts > .question-status h2 {
  1635. font-weight: normal;
  1636. }
  1637. #\\parts a.SEpreviewable {
  1638. text-decoration: underline !important;
  1639. text-decoration-skip: ink;
  1640. }
  1641.  
  1642. #\\parts .comment-actions {
  1643. width: 20px !important;
  1644. }
  1645. #\\parts .comment-edit,
  1646. #\\parts .delete-tag,
  1647. #\\parts .comment-actions > :not(.comment-score) {
  1648. display: none;
  1649. }
  1650. #\\parts .comments {
  1651. border-top: none;
  1652. }
  1653. #\\parts .comments .comment:last-child .comment-text {
  1654. border-bottom: none;
  1655. }
  1656. #\\parts .comments .new-comment-highlight .comment-text {
  1657. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1658. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1659. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1660. }
  1661. #\\parts .post-menu > span {
  1662. opacity: .35;
  1663. }
  1664.  
  1665. #\\parts #user-menu {
  1666. position: absolute;
  1667. }
  1668. .\\userCard {
  1669. position: absolute;
  1670. display: none;
  1671. transition: opacity .25s cubic-bezier(.88,.02,.92,.66) .5s;
  1672. margin-top: -3rem;
  1673. }
  1674. #\\parts .wmd-preview a:not(.post-tag),
  1675. #\\parts .post-layout a:not(.post-tag),
  1676. #\\parts .comment-copy a:not(.post-tag) {
  1677. border-bottom: none;
  1678. }
  1679.  
  1680. #\\answers-title {
  1681. margin: .5ex 1ex 0 0;
  1682. font-size: 18px;
  1683. line-height: 1.0;
  1684. float: left;
  1685. }
  1686. #\\answers-title p {
  1687. font-size: 11px;
  1688. font-weight: normal;
  1689. max-width: 8em;
  1690. line-height: 1.0;
  1691. margin: 1ex 0 0 0;
  1692. padding: 0;
  1693. }
  1694. #\\answers-title b,
  1695. #\\answers-title label {
  1696. background: linear-gradient(#fff8 30%, #fff);
  1697. width: 10px;
  1698. height: 10px;
  1699. padding: 2px;
  1700. margin-right: 2px;
  1701. box-shadow: 0 1px 3px #0008;
  1702. border-radius: 3px;
  1703. font-weight: normal;
  1704. display: inline-block;
  1705. vertical-align: middle;
  1706. }
  1707. #\\answers-title b::after {
  1708. content: "";
  1709. display: block;
  1710. width: 100%;
  1711. height: 100%;
  1712. background: url('data:image/svg+xml;base64,${SVG_ARROW}') no-repeat center;
  1713. }
  1714. #\\answers-title b[mirrored]::after {
  1715. transform: scaleX(-1);
  1716. }
  1717. #\\answers-title label {
  1718. width: auto;
  1719. color: ${KBD_COLOR};
  1720. }
  1721.  
  1722. #\\answers {
  1723. all: unset;
  1724. display: block;
  1725. padding: 10px 10px 10px ${PADDING}px;
  1726. font-weight: bold;
  1727. line-height: 1.0;
  1728. border-top: 4px solid ${colors.answer.back}5e;
  1729. background-color: ${colors.answer.back}5e;
  1730. color: ${colors.answer.fore};
  1731. word-break: break-word;
  1732. }
  1733. #\\answers a {
  1734. color: ${colors.answer.fore};
  1735. text-decoration: none;
  1736. font-size: 11px;
  1737. font-family: monospace;
  1738. width: 32px !important;
  1739. display: inline-block;
  1740. position: relative;
  1741. vertical-align: top;
  1742. margin: 0 1ex 1ex 0;
  1743. padding: 0 0 1.1ex 0;
  1744. }
  1745. [\\type*="deleted"] #\\answers a {
  1746. color: ${colors.deleted.fore};
  1747. }
  1748. #\\answers img {
  1749. width: 32px;
  1750. height: 32px;
  1751. }
  1752. #\\answers a.deleted-answer {
  1753. color: ${colors.deleted.fore};
  1754. background: transparent;
  1755. opacity: 0.25;
  1756. }
  1757. #\\answers a.deleted-answer:hover {
  1758. opacity: 1.0;
  1759. }
  1760. #\\answers a:hover:not(.SEpreviewed) {
  1761. text-decoration: underline;
  1762. text-decoration-skip: ink;
  1763. }
  1764. #\\answers a.SEpreviewed {
  1765. background-color: ${colors.answer.fore};
  1766. color: ${colors.answer.foreInv};
  1767. outline: 4px solid ${colors.answer.fore};
  1768. }
  1769. #\\answers a::after {
  1770. white-space: nowrap;
  1771. overflow: hidden;
  1772. text-overflow: ellipsis;
  1773. max-width: 40px;
  1774. position: absolute;
  1775. content: attr(title);
  1776. top: 44px;
  1777. left: 0;
  1778. font: normal .75rem/1.0 sans-serif;
  1779. opacity: .7;
  1780. }
  1781. #\\answers a:only-child::after {
  1782. max-width: calc(${WIDTH}px - 10em);
  1783. }
  1784. #\\answers a:hover::after {
  1785. opacity: 1;
  1786. }
  1787. .\\accepted::before {
  1788. content: "✔";
  1789. position: absolute;
  1790. display: block;
  1791. top: 1.3ex;
  1792. right: -0.7ex;
  1793. font-size: 32px;
  1794. color: #4bff2c;
  1795. text-shadow: 1px 2px 2px rgba(0,0,0,0.5);
  1796. }
  1797.  
  1798. @-webkit-keyframes highlight {
  1799. from {background: #ffcf78}
  1800. to {background: none}
  1801. }
  1802. `,
  1803.  
  1804. ...Object.keys(colors).map(s => `
  1805. #\\title {
  1806. background-color: ${colors[s].back}5e;
  1807. color: ${colors[s].fore};
  1808. }
  1809. #\\meta {
  1810. color: ${colors[s].fore};
  1811. }
  1812. #\\meta b {
  1813. color: ${colors[s].foreInv};
  1814. background: ${colors[s].fore};
  1815. }
  1816. #\\close {
  1817. color: ${colors[s].fore};
  1818. }
  1819. #\\parts::-webkit-scrollbar {
  1820. background-color: ${colors[s].back}19;
  1821. }
  1822. #\\parts::-webkit-scrollbar-thumb {
  1823. background-color: ${colors[s].back}32;
  1824. }
  1825. #\\parts::-webkit-scrollbar-thumb:hover {
  1826. background-color: ${colors[s].back}4b;
  1827. }
  1828. #\\parts::-webkit-scrollbar-thumb:active {
  1829. background-color: ${colors[s].back}c0;
  1830. }
  1831. `
  1832. // language=JS
  1833. .replace(/#\\/g, `[\\type$="${s}"] $&`)
  1834. ),
  1835.  
  1836. ...['deleted', 'closed'].map(s => /* language=CSS */ `
  1837. #\\answers {
  1838. border-top-color: ${colors[s].back}5e;
  1839. background-color: ${colors[s].back}5e;
  1840. color: ${colors[s].fore};
  1841. }
  1842. #\\answers a.SEpreviewed {
  1843. background-color: ${colors[s].fore};
  1844. color: ${colors[s].foreInv};
  1845. }
  1846. #\\answers a.SEpreviewed:after {
  1847. border-color: ${colors[s].fore};
  1848. }
  1849. `
  1850. // language=JS
  1851. .replace(/#\\/g, `[\\type$="${s}"] $&`)
  1852. ),
  1853. ].join('\n').replace(/\\/g, `${ID}-`);
  1854. }
  1855. }
  1856.  
  1857. function $(selector, node = pv.shadow) {
  1858. return node && node.querySelector(selector);
  1859. }
  1860.  
  1861. Object.assign($, {
  1862.  
  1863. all(selector, node = pv.shadow) {
  1864. return node ? [...node.querySelectorAll(selector)] : [];
  1865. },
  1866.  
  1867. on(eventName, node, fn, options) {
  1868. return node.addEventListener(eventName, fn, options);
  1869. },
  1870.  
  1871. off(eventName, node, fn, options) {
  1872. return node.removeEventListener(eventName, fn, options);
  1873. },
  1874.  
  1875. remove(selector, node = pv.shadow) {
  1876. for (const el of node.querySelectorAll(selector))
  1877. el.remove();
  1878. },
  1879.  
  1880. text(selector, node = pv.shadow) {
  1881. const el = typeof selector === 'string' ?
  1882. node && node.querySelector(selector) :
  1883. selector;
  1884. return el ? el.textContent.trim() : '';
  1885. },
  1886.  
  1887. create(
  1888. selector,
  1889. opts = {},
  1890. children = opts.children ||
  1891. (typeof opts !== 'object' || Util.isIterable(opts)) && opts
  1892. ) {
  1893. const EOL = selector.length;
  1894. const idStart = (selector.indexOf('#') + 1 || EOL + 1) - 1;
  1895. const clsStart = (selector.indexOf('.', idStart < EOL ? idStart : 0) + 1 || EOL + 1) - 1;
  1896. const tagEnd = Math.min(idStart, clsStart);
  1897. const tag = (tagEnd < EOL ? selector.slice(0, tagEnd) : selector) || opts.tag || 'div';
  1898. const id = idStart < EOL && selector.slice(idStart + 1, clsStart) || opts.id || '';
  1899. const cls = clsStart < EOL && selector.slice(clsStart + 1).replace(/\./g, ' ') ||
  1900. opts.className ||
  1901. '';
  1902. const el = id && pv.shadow && pv.shadow.getElementById(id) ||
  1903. document.createElement(tag);
  1904. if (el.id !== id)
  1905. el.id = id;
  1906. if (el.className !== cls)
  1907. el.className = cls;
  1908. const hasOwnProperty = Object.hasOwnProperty;
  1909. for (const key in opts) {
  1910. if (!hasOwnProperty.call(opts, key))
  1911. continue;
  1912. const value = opts[key];
  1913. switch (key) {
  1914. case 'tag':
  1915. case 'id':
  1916. case 'className':
  1917. case 'children':
  1918. break;
  1919. case 'dataset': {
  1920. const dataset = el.dataset;
  1921. for (const k in value) {
  1922. if (hasOwnProperty.call(value, k)) {
  1923. const v = value[k];
  1924. if (dataset[k] !== v)
  1925. dataset[k] = v;
  1926. }
  1927. }
  1928. break;
  1929. }
  1930. case 'attributes': {
  1931. for (const k in value) {
  1932. if (hasOwnProperty.call(value, k)) {
  1933. const v = value[k];
  1934. if (el.getAttribute(k) !== v)
  1935. el.setAttribute(k, v);
  1936. }
  1937. }
  1938. break;
  1939. }
  1940. default:
  1941. if (el[key] !== value)
  1942. el[key] = value;
  1943. }
  1944. }
  1945. if (children) {
  1946. if (!hasOwnProperty.call(opts, 'textContent'))
  1947. el.textContent = '';
  1948. $.appendChildren(el, children);
  1949. }
  1950. let before, after, parent;
  1951. if ((before = opts.before) && before !== el.nextSibling && before !== el)
  1952. before.insertAdjacentElement('beforebegin', el);
  1953. else if ((after = opts.after) && after !== el.previousSibling && after !== el)
  1954. after.insertAdjacentElement('afterend', el);
  1955. else if ((parent = opts.parent) && parent !== el.parentNode)
  1956. parent.appendChild(el);
  1957. return el;
  1958. },
  1959.  
  1960. appendChild(parent, child, shouldClone = true) {
  1961. if (!child)
  1962. return;
  1963. if (child.nodeType)
  1964. return parent.appendChild(shouldClone ? document.importNode(child, true) : child);
  1965. if (Util.isIterable(child))
  1966. return $.appendChildren(parent, child, shouldClone);
  1967. else
  1968. return parent.appendChild(document.createTextNode(child));
  1969. },
  1970.  
  1971. appendChildren(newParent, children) {
  1972. if (!Util.isIterable(children))
  1973. return $.appendChild(newParent, children);
  1974. const fragment = document.createDocumentFragment();
  1975. for (const el of children)
  1976. $.appendChild(fragment, el);
  1977. return newParent.appendChild(fragment);
  1978. },
  1979.  
  1980. setStyle(el, ...props) {
  1981. const style = el.style;
  1982. const s0 = style.cssText;
  1983. let s = s0;
  1984.  
  1985. for (const p of props) {
  1986. if (!p)
  1987. continue;
  1988.  
  1989. const [name, value, important = true] = p;
  1990. const rValue = value + (important && value ? ' !important' : '');
  1991. const rx = new RegExp(`(^|[\\s;])${name}(\\s*:\\s*)([^;]*?)(\\s*(?:;|$))`, 'i');
  1992. const m = rx.exec(s);
  1993.  
  1994. if (!m && value) {
  1995. const rule = name + ': ' + rValue;
  1996. s += !s || s.endsWith(';') ? rule : '; ' + rule;
  1997. continue;
  1998. }
  1999.  
  2000. if (!m && !value)
  2001. continue;
  2002.  
  2003. const [, sep1, sep2, oldValue, sep3] = m;
  2004. if (value !== oldValue) {
  2005. s = s.slice(0, m.index) +
  2006. sep1 + (rValue ? name + sep2 + rValue + sep3 : '') +
  2007. s.slice(m.index + m[0].length);
  2008. }
  2009. }
  2010.  
  2011. if (s !== s0)
  2012. style.cssText = s;
  2013. },
  2014. });