SE Preview on hover

Shows preview of the linked questions/answers on hover

当前为 2017-02-17 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 0.2.3
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @match *://*.stackoverflow.com/*
  9. // @match *://*.superuser.com/*
  10. // @match *://*.serverfault.com/*
  11. // @match *://*.askubuntu.com/*
  12. // @match *://*.stackapps.com/*
  13. // @match *://*.mathoverflow.net/*
  14. // @match *://*.stackexchange.com/*
  15. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  16. // @require https://cdnjs.cloudflare.com/ajax/libs/lz-string/1.4.4/lz-string.min.js
  17. // @grant GM_addStyle
  18. // @grant GM_xmlhttpRequest
  19. // @connect stackoverflow.com
  20. // @connect superuser.com
  21. // @connect serverfault.com
  22. // @connect askubuntu.com
  23. // @connect stackapps.com
  24. // @connect mathoverflow.net
  25. // @connect stackexchange.com
  26. // @connect cdn.sstatic.net
  27. // @run-at document-end
  28. // @noframes
  29. // ==/UserScript==
  30.  
  31. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  32.  
  33. const PREVIEW_DELAY = 200;
  34. const CACHE_DURATION = 1 * 60 * 1000; // 1 minute for the recently active posts, scales up logarithmically
  35. const COLORS = {
  36. question: {
  37. backRGB: '80, 133, 195',
  38. fore: '#265184',
  39. },
  40. answer: {
  41. backRGB: '112, 195, 80',
  42. fore: '#3f7722',
  43. foreInv: 'white',
  44. },
  45. deleted: {
  46. backRGB: '181, 103, 103',
  47. fore: 'rgb(181, 103, 103)',
  48. foreInv: 'white',
  49. },
  50. closed: {
  51. backRGB: '255, 206, 93',
  52. fore: 'rgb(204, 143, 0)',
  53. foreInv: 'white',
  54. },
  55. };
  56.  
  57. let xhr;
  58. let preview = {
  59. frame: null,
  60. link: null,
  61. hover: {x:0, y:0},
  62. timer: 0,
  63. cacheCSS: {},
  64. stylesOverride: '',
  65. };
  66.  
  67. const rxPreviewable = getURLregexForMatchedSites();
  68. const thisPageUrls = getPageBaseUrls(location.href);
  69.  
  70. initStyles();
  71. initPolyfills();
  72. setMutationHandler('a', onLinkAdded, {processExisting: true});
  73. setTimeout(cleanupCache, 10000);
  74.  
  75. /**************************************************************/
  76.  
  77. function onLinkAdded(links) {
  78. for (let i = 0, link; (link = links[i++]); ) {
  79. if (isLinkPreviewable(link)) {
  80. link.removeAttribute('title');
  81. $on('mouseover', link, onLinkHovered);
  82. }
  83. }
  84. }
  85.  
  86. function onLinkHovered(e) {
  87. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)
  88. return;
  89. preview.link = this;
  90. $on('mousemove', this, onLinkMouseMove);
  91. $on('mouseout', this, abortPreview);
  92. $on('mousedown', this, abortPreview);
  93. restartPreviewTimer(this);
  94. }
  95.  
  96. function onLinkMouseMove(e) {
  97. let stoppedMoving = Math.abs(preview.hover.x - e.clientX) < 2 &&
  98. Math.abs(preview.hover.y - e.clientY) < 2;
  99. if (!stoppedMoving)
  100. return;
  101. preview.hover.x = e.clientX;
  102. preview.hover.y = e.clientY;
  103. restartPreviewTimer(this);
  104. }
  105.  
  106. function restartPreviewTimer(link) {
  107. clearTimeout(preview.timer);
  108. preview.timer = setTimeout(() => {
  109. preview.timer = 0;
  110. $off('mousemove', link, onLinkMouseMove);
  111. if (link.matches(':hover'))
  112. downloadPreview(link.href);
  113. }, PREVIEW_DELAY);
  114. }
  115.  
  116. function abortPreview(e) {
  117. releaseLinkListeners(this);
  118. preview.timer = setTimeout(link => {
  119. if (link == preview.link && preview.frame && !preview.frame.matches(':hover')) {
  120. releaseLinkListeners(link);
  121. preview.frame.contentWindow.postMessage('SEpreview-hidden', '*');
  122. fadeOut(preview.frame);
  123. }
  124. }, PREVIEW_DELAY * 3, this);
  125. if (xhr)
  126. xhr.abort();
  127. }
  128.  
  129. function releaseLinkListeners(link) {
  130. $off('mousemove', link, onLinkMouseMove);
  131. $off('mouseout', link, abortPreview);
  132. $off('mousedown', link, abortPreview);
  133. clearTimeout(preview.timer);
  134. }
  135.  
  136. function fadeOut(element, transition) {
  137. if (transition) {
  138. element.style.transition = typeof transition == 'number' ? `opacity ${transition}s ease-in-out` : transition;
  139. return setTimeout(fadeOut, 0, element);
  140. }
  141. element.style.opacity = 0;
  142. $on('transitionend', element, function remove() {
  143. $off('transitionend', element, remove);
  144. if (+element.style.opacity === 0)
  145. element.style.display = 'none';
  146. });
  147. }
  148.  
  149. function downloadPreview(url) {
  150. let cached = readCache(url);
  151. if (cached)
  152. showPreview(cached);
  153. else {
  154. xhr = GM_xmlhttpRequest({
  155. method: 'GET',
  156. url: httpsUrl(url),
  157. onload: r => {
  158. let html = r.responseText;
  159. let lastActivity = showPreview({finalUrl: r.finalUrl, html});
  160. let inactiveDays = Math.max(0, (Date.now() - lastActivity) / (24 * 3600 * 1000));
  161. let cacheDuration = CACHE_DURATION * Math.pow(Math.log(inactiveDays + 1) + 1, 2);
  162. writeCache({url, finalUrl: r.finalUrl, html, cacheDuration});
  163. },
  164. });
  165. }
  166. }
  167.  
  168. function showPreview({finalUrl, html, doc}) {
  169. doc = doc || new DOMParser().parseFromString(html, 'text/html');
  170. if (!doc || !doc.head) {
  171. error('no HEAD in the document received for', finalUrl);
  172. return;
  173. }
  174.  
  175. if (!$('base', doc))
  176. doc.head.insertAdjacentHTML('afterbegin', `<base href="${finalUrl}">`);
  177.  
  178. const answerIdMatch = finalUrl.match(/questions\/\d+\/[^\/]+\/(\d+)/);
  179. const isQuestion = !answerIdMatch;
  180. const postId = answerIdMatch ? '#answer-' + answerIdMatch[1] : '#question';
  181. const post = $(postId + ' .post-text', doc);
  182. if (!post)
  183. return error('No parsable post found', doc);
  184. const isDeleted = post.closest('.deleted-answer');
  185. const title = $('meta[property="og:title"]', doc).content;
  186. const status = isQuestion && !$('.question-status', post) && $('.question-status', doc);
  187. const isClosed = $('.question-originals-of-duplicate, .close-as-off-topic-status-list, .close-status-suffix', doc);
  188. const comments = $(`${postId} .comments`, doc);
  189. const commentsHidden = +$('tbody', comments).dataset.remainingCommentsCount;
  190. const commentsShowLink = commentsHidden && $(`${postId} .js-show-link.comments-link`, doc);
  191. const finalUrlOfQuestion = getCacheableUrl(finalUrl);
  192.  
  193. const lastActivity = +doc.body.getAttribute('SEpreview-lastActivity')
  194. || tryCatch(() => new Date($('.lastactivity-link', doc).title).getTime())
  195. || Date.now();
  196. if (lastActivity)
  197. doc.body.setAttribute('SEpreview-lastActivity', lastActivity);
  198.  
  199. $$remove('script', doc);
  200.  
  201. // underline previewable links
  202. for (let link of $$('a:not(.SEpreviewable)', doc)) {
  203. if (rxPreviewable.test(link.href)) {
  204. link.removeAttribute('title');
  205. link.classList.add('SEpreviewable');
  206. }
  207. }
  208.  
  209. if (!preview.frame) {
  210. preview.frame = document.createElement('iframe');
  211. preview.frame.id = 'SEpreview';
  212. document.body.appendChild(preview.frame);
  213. }
  214.  
  215. let pvDoc, pvWin;
  216. preview.frame.setAttribute('SEpreview-type',
  217. isDeleted ? 'deleted' : isQuestion ? (isClosed ? 'closed' : 'question') : 'answer');
  218. onFrameReady(preview.frame).then(
  219. () => {
  220. pvDoc = preview.frame.contentDocument;
  221. pvWin = preview.frame.contentWindow;
  222. initPolyfills(pvWin);
  223. })
  224. .then(addStyles)
  225. .then(render)
  226. .then(show);
  227. return lastActivity;
  228.  
  229. function addStyles() {
  230. const SEpreviewStyles = $replaceOrCreate({
  231. id: 'SEpreviewStyles',
  232. tag: 'style', parent: pvDoc.head, className: 'SEpreview-reuse',
  233. innerHTML: preview.stylesOverride,
  234. });
  235.  
  236. $replaceOrCreate($$('style, link[rel="stylesheet"]', doc).map(e =>
  237. e.localName == 'style' ? {
  238. id: 'SEpreview' + e.innerHTML.replace(/\W+/g, '').length,
  239. tag: 'style', before: SEpreviewStyles, className: 'SEpreview-reuse',
  240. innerHTML: e.innerHTML,
  241. } : {
  242. id: e.href.replace(/\W+/g, ''),
  243. tag: 'link', before: SEpreviewStyles, className: 'SEpreview-reuse',
  244. href: e.href, rel: 'stylesheet',
  245. })
  246. );
  247.  
  248. return onStyleSheetsReady($$('link[rel="stylesheet"]', pvDoc));
  249. }
  250.  
  251. function render() {
  252. pvDoc.body.setAttribute('SEpreview-type', preview.frame.getAttribute('SEpreview-type'));
  253.  
  254. $replaceOrCreate([{
  255. // title
  256. id: 'SEpreview-title', tag: 'a',
  257. parent: pvDoc.body, className: 'SEpreviewable',
  258. href: finalUrlOfQuestion,
  259. textContent: title,
  260. }, {
  261. // vote count, date, views#
  262. id: 'SEpreview-meta',
  263. parent: pvDoc.body,
  264. innerHTML: [
  265. $text('.vote-count-post', post.closest('table')).replace(/(-?)(\d+)/,
  266. (s, sign, v) => s == '0' ? '' : `<b>${s}</b> vote${+v > 1 ? 's' : ''}, `),
  267. isQuestion
  268. ? $$('#qinfo tr', doc)
  269. .map(row => $$('.label-key', row).map($text).join(' '))
  270. .join(', ').replace(/^((.+?) (.+?), .+?), .+? \3$/, '$1')
  271. : [...$$('.user-action-time', post.closest('.answer'))]
  272. .reverse().map($text).join(', ')
  273. ].join('')
  274. }, {
  275. // content wrapper
  276. id: 'SEpreview-body',
  277. parent: pvDoc.body,
  278. className: isDeleted ? 'deleted-answer' : '',
  279. children: [post.parentElement, comments, commentsShowLink, status],
  280. }]);
  281.  
  282. renderCode();
  283.  
  284. // render bottom shelf
  285. const answers = $$('.answer', doc);
  286. if (answers.length > (isQuestion ? 0 : 1)) {
  287. $replaceOrCreate({
  288. id: 'SEpreview-answers',
  289. parent: pvDoc.body,
  290. innerHTML: answers.map(renderShelfAnswer).join(' '),
  291. });
  292. } else
  293. $$remove('#SEpreview-answers', pvDoc);
  294.  
  295. // cleanup leftovers from previously displayed post and foreign elements not injected by us
  296. $$('style, link, body script, html > *:not(head):not(body)', pvDoc).forEach(e => {
  297. if (e.classList.contains('SEpreview-reuse'))
  298. e.classList.remove('SEpreview-reuse');
  299. else
  300. e.remove();
  301. });
  302. }
  303.  
  304. function renderCode() {
  305. const codeBlocks = $$('pre code', pvDoc);
  306. if (codeBlocks.length) {
  307. codeBlocks.forEach(e => e.parentElement.classList.add('prettyprint'));
  308. if (!pvWin.StackExchange) {
  309. pvWin.StackExchange = {};
  310. let script = $scriptIn(pvDoc.head);
  311. script.text = 'StackExchange = {}';
  312. script = $scriptIn(pvDoc.head);
  313. script.src = 'https://cdn.sstatic.net/Js/prettify-full.en.js';
  314. script.setAttribute('onload', 'prettyPrint()');
  315. } else
  316. $scriptIn(pvDoc.body).text = 'prettyPrint()';
  317. }
  318. }
  319.  
  320. function renderShelfAnswer(e) {
  321. const shortUrl = $('.short-link', e).href.replace(/(\d+)\/\d+/, '$1');
  322. const extraClasses = (e.matches(postId) ? ' SEpreviewed' : '') +
  323. (e.matches('.deleted-answer') ? ' deleted-answer' : '');
  324. const author = $('.post-signature:last-child', e);
  325. const title = $text('.user-details a', author) + ' (rep ' +
  326. $text('.reputation-score', author) + ')\n' +
  327. $text('.user-action-time', author);
  328. const gravatar = $('img, .anonymous-gravatar, .community-wiki', author);
  329. const accepted = !!$('.vote-accepted-on', e);
  330. return (
  331. `<a href="${shortUrl}" title="${title}" class="SEpreviewable${extraClasses}">` +
  332. $text('.vote-count-post', e) + ' ' +
  333. (!accepted ? '' : '<span class="vote-accepted-on"></span>') +
  334. (!gravatar ? '' : gravatar.src ? `<img src="${gravatar.src}">` : gravatar.outerHTML) +
  335. '</a>');
  336. }
  337.  
  338. function show() {
  339. pvDoc.onmouseover = retainMainScrollPos;
  340. pvDoc.onclick = interceptLinks;
  341. pvWin.onmessage = e => {
  342. if (e.data == 'SEpreview-hidden') {
  343. pvWin.onmessage = null;
  344. pvDoc.onmouseover = null;
  345. pvDoc.onclick = null;
  346. }
  347. };
  348.  
  349. $('#SEpreview-body', pvDoc).scrollTop = 0;
  350. preview.frame.style.opacity = 1;
  351. preview.frame.style.display = '';
  352. }
  353.  
  354. function retainMainScrollPos(e) {
  355. let scrollPos = {x:scrollX, y:scrollY};
  356. $on('scroll', preventScroll);
  357. $on('mouseover', releaseScrollLock);
  358.  
  359. function preventScroll(e) {
  360. scrollTo(scrollPos.x, scrollPos.y);
  361. }
  362.  
  363. function releaseScrollLock(e) {
  364. $off('mouseout', releaseScrollLock);
  365. $off('scroll', preventScroll);
  366. }
  367. }
  368.  
  369. function interceptLinks(e) {
  370. const link = e.target.closest('a');
  371. if (!link)
  372. return;
  373. if (link.matches('.js-show-link.comments-link')) {
  374. fadeOut(link, 0.5);
  375. loadComments();
  376. }
  377. else if (e.button || e.ctrlKey || e.altKey || e.shiftKey || e.metaKey || !link.matches('.SEpreviewable'))
  378. return (link.target = '_blank');
  379. else if (link.matches('#SEpreview-answers a, a#SEpreview-title'))
  380. showPreview({
  381. finalUrl: finalUrlOfQuestion + (link.id == 'SEpreview-title' ? '' : '/' + link.pathname.match(/\/(\d+)/)[1]),
  382. doc
  383. });
  384. else
  385. downloadPreview(link.getAttribute('SEpreview-fullUrl') || link.href);
  386. e.preventDefault();
  387. }
  388.  
  389. function loadComments() {
  390. GM_xmlhttpRequest({
  391. method: 'GET',
  392. url: new URL(finalUrl).origin + '/posts/' + comments.id.match(/\d+/)[0] + '/comments',
  393. onload: r => {
  394. let tbody = $(`#${comments.id} tbody`, pvDoc);
  395. let oldIds = new Set([...tbody.rows].map(e => e.id));
  396. tbody.innerHTML = r.responseText;
  397. for (let tr of tbody.rows)
  398. if (!oldIds.has(tr.id))
  399. tr.classList.add('new-comment-highlight');
  400. },
  401. });
  402. }
  403. }
  404.  
  405. function getCacheableUrl(url) {
  406. // strips querys and hashes and anything after the main part https://site/questions/####/title/
  407. return url
  408. .replace(/(\/q(?:uestions)?\/\d+\/[^\/]+).*/, '$1')
  409. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  410. .replace(/[?#].*$/, '');
  411. }
  412.  
  413. function readCache(url) {
  414. keyUrl = getCacheableUrl(url);
  415. const meta = (localStorage[keyUrl] || '').split('\t');
  416. const expired = +meta[0] < Date.now();
  417. const finalUrl = meta[1] || url;
  418. const keyFinalUrl = meta[1] ? getCacheableUrl(finalUrl) : keyUrl;
  419. return !expired && {
  420. finalUrl,
  421. html: LZString.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  422. };
  423. }
  424.  
  425. function writeCache({url, finalUrl, html, cacheDuration = CACHE_DURATION, cleanupRetry}) {
  426. // keyUrl=expires
  427. // redirected keyUrl=expires+finalUrl, and an additional entry keyFinalUrl=expires is created
  428. // keyFinalUrl\thtml=html
  429. cacheDuration = Math.max(CACHE_DURATION, Math.min(0xDEADBEEF, Math.floor(cacheDuration)));
  430. finalUrl = finalUrl.replace(/[?#].*/, '');
  431. const keyUrl = getCacheableUrl(url);
  432. const keyFinalUrl = getCacheableUrl(finalUrl);
  433. const expires = Date.now() + cacheDuration;
  434. if (!tryCatch(() => localStorage[keyFinalUrl + '\thtml'] = LZString.compressToUTF16(html))) {
  435. if (cleanupRetry)
  436. return error('localStorage write error');
  437. cleanupCache({aggressive: true});
  438. setIimeout(writeCache, 0, {url, finalUrl, html, cacheDuration, cleanupRetry: true});
  439. }
  440. localStorage[keyFinalUrl] = expires;
  441. if (keyUrl != keyFinalUrl)
  442. localStorage[keyUrl] = expires + '\t' + finalUrl;
  443. setTimeout(() => {
  444. [keyUrl, keyFinalUrl, keyFinalUrl + '\thtml'].forEach(e => localStorage.removeItem(e));
  445. }, cacheDuration + 1000);
  446. }
  447.  
  448. function cleanupCache({aggressive = false} = {}) {
  449. Object.keys(localStorage).forEach(k => {
  450. if (k.match(/^https?:\/\/[^\t]+$/)) {
  451. let meta = (localStorage[k] || '').split('\t');
  452. if (+meta[0] > Date.now() && !aggressive)
  453. return;
  454. if (meta[1])
  455. localStorage.removeItem(meta[1]);
  456. localStorage.removeItem(`${meta[1] || k}\thtml`);
  457. localStorage.removeItem(k);
  458. }
  459. });
  460. }
  461.  
  462. function onFrameReady(frame) {
  463. if (frame.contentDocument.readyState == 'complete')
  464. return Promise.resolve();
  465. else
  466. return new Promise(resolve => {
  467. $on('load', frame, function onLoad() {
  468. $off('load', frame, onLoad);
  469. resolve();
  470. });
  471. });
  472. }
  473.  
  474. function onStyleSheetsReady(linkElements) {
  475. return new Promise(function retry(resolve) {
  476. if (linkElements.every(e => e.sheet && e.sheet.href == e.href))
  477. resolve();
  478. else
  479. setTimeout(retry, 0, resolve);
  480. });
  481. }
  482.  
  483. function getURLregexForMatchedSites() {
  484. return new RegExp('https?://(\\w*\\.)*(' + GM_info.script.matches.map(m =>
  485. m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')
  486. ).join('|') + ')/(questions|q|a)/\\d+');
  487. }
  488.  
  489. function isLinkPreviewable(link) {
  490. const inPreview = link.ownerDocument != document;
  491. if (!rxPreviewable.test(link.href) || link.matches('.short-link'))
  492. return false;
  493. const pageUrls = inPreview ? getPageBaseUrls(preview.link.href) : thisPageUrls;
  494. const url = httpsUrl(link.href);
  495. return !url.startsWith(pageUrls.base) &&
  496. !url.startsWith(pageUrls.short);
  497. }
  498.  
  499. function getPageBaseUrls(url) {
  500. const base = httpsUrl((url.match(rxPreviewable) || [])[0]);
  501. return base ? {
  502. base,
  503. short: base.replace('/questions/', '/q/'),
  504. } : {};
  505. }
  506.  
  507. function httpsUrl(url) {
  508. return (url || '').replace(/^http:/, 'https:');
  509. }
  510.  
  511. function $(selector, node = document) {
  512. return node.querySelector(selector);
  513. }
  514.  
  515. function $$(selector, node = document) {
  516. return node.querySelectorAll(selector);
  517. }
  518.  
  519. function $text(selector, node = document) {
  520. const e = typeof selector == 'string' ? node.querySelector(selector) : selector;
  521. return e ? e.textContent.trim() : '';
  522. }
  523.  
  524. function $$remove(selector, node = document) {
  525. node.querySelectorAll(selector).forEach(e => e.remove());
  526. }
  527.  
  528. function $appendChildren(newParent, elements) {
  529. const doc = newParent.ownerDocument;
  530. for (let e of elements)
  531. if (e)
  532. newParent.appendChild(e.ownerDocument == doc ? e : doc.importNode(e, true));
  533. }
  534.  
  535. function $replaceOrCreate(options) {
  536. if (options.length && typeof options[0] == 'object')
  537. return [].map.call(options, $replaceOrCreate);
  538. const doc = (options.parent || options.before).ownerDocument;
  539. const el = doc.getElementById(options.id) || doc.createElement(options.tag || 'div');
  540. for (let key of Object.keys(options)) {
  541. switch (key) {
  542. case 'tag':
  543. case 'parent':
  544. case 'before':
  545. break;
  546. case 'children':
  547. if (el.children.length)
  548. el.innerHTML = '';
  549. $appendChildren(el, options[key]);
  550. break;
  551. default:
  552. const value = options[key];
  553. if (key in el && el[key] != value)
  554. el[key] = value;
  555. }
  556. }
  557. if (!el.parentElement)
  558. (options.parent || options.before.parentElement).insertBefore(el, options.before);
  559. return el;
  560. }
  561.  
  562. function $scriptIn(element) {
  563. return element.appendChild(element.ownerDocument.createElement('script'));
  564. }
  565.  
  566. function $on(eventName, ...args) {
  567. // eventName, selector, node, callback, options
  568. // eventName, selector, callback, options
  569. // eventName, node, callback, options
  570. // eventName, callback, options
  571. const selector = typeof args[0] == 'string' ? args[0] : null;
  572. const node = args[0] instanceof Node ? args[0] : args[1] instanceof Node ? args[1] : document;
  573. const callback = args[typeof args[0] == 'function' ? 0 : typeof args[1] == 'function' ? 1 : 2];
  574. const options = args[args.length - 1] != callback ? args[args.length - 1] : undefined;
  575. const method = this == 'removeEventListener' ? this : 'addEventListener';
  576. (selector ? node.querySelector(selector) : node)[method](eventName, callback, options);
  577. }
  578.  
  579. function $off(eventName, ...args) {
  580. $on.apply('removeEventListener', arguments);
  581. }
  582.  
  583. function log(...args) {
  584. console.log(GM_info.script.name, ...args);
  585. }
  586.  
  587. function error(...args) {
  588. console.error(GM_info.script.name, ...args);
  589. }
  590.  
  591. function tryCatch(fn) {
  592. try { return fn() }
  593. catch(e) {}
  594. }
  595.  
  596. function initPolyfills(context = window) {
  597. for (let method of ['forEach', 'filter', 'map', 'every', context.Symbol.iterator])
  598. if (!context.NodeList.prototype[method])
  599. context.NodeList.prototype[method] = context.Array.prototype[method];
  600. }
  601.  
  602. function initStyles() {
  603. GM_addStyle(`
  604. #SEpreview {
  605. all: unset;
  606. box-sizing: content-box;
  607. width: 720px; /* 660px + 30px + 30px */
  608. height: 33%;
  609. min-height: 200px;
  610. position: fixed;
  611. opacity: 0;
  612. transition: opacity .5s cubic-bezier(.88,.02,.92,.66);
  613. right: 0;
  614. bottom: 0;
  615. padding: 0;
  616. margin: 0;
  617. background: white;
  618. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  619. z-index: 999999;
  620. border-width: 8px;
  621. border-style: solid;
  622. }
  623. `
  624. + Object.keys(COLORS).map(s => `
  625. #SEpreview[SEpreview-type="${s}"] {
  626. border-color: rgb(${COLORS[s].backRGB});
  627. }
  628. `).join('')
  629. );
  630.  
  631. preview.stylesOverride = `
  632. body, html {
  633. min-width: unset!important;
  634. box-shadow: none!important;
  635. padding: 0!important;
  636. margin: 0!important;
  637. }
  638. html, body {
  639. background: unset!important;;
  640. }
  641. body {
  642. display: flex;
  643. flex-direction: column;
  644. height: 100vh;
  645. }
  646. #SEpreview-body a.SEpreviewable a.SEpreviewable {
  647. text-decoration: underline !important;
  648. }
  649. #SEpreview-title {
  650. all: unset;
  651. display: block;
  652. padding: 20px 30px;
  653. font-weight: bold;
  654. font-size: 18px;
  655. line-height: 1.2;
  656. cursor: pointer;
  657. }
  658. #SEpreview-title:hover {
  659. text-decoration: underline;
  660. }
  661. #SEpreview-meta {
  662. position: absolute;
  663. top: .5ex;
  664. left: 30px;
  665. opacity: 0.5;
  666. }
  667. #SEpreview-title:hover + #SEpreview-meta {
  668. opacity: 1.0;
  669. }
  670.  
  671. #SEpreview-body {
  672. padding: 30px!important;
  673. overflow: auto;
  674. flex-grow: 2;
  675. }
  676. #SEpreview-body .post-menu {
  677. display: none!important;
  678. }
  679. #SEpreview-body > .question-status {
  680. margin: -10px -30px -30px;
  681. padding-left: 30px;
  682. }
  683. #SEpreview-body > .question-status h2 {
  684. font-weight: normal;
  685. }
  686. #SEpreview-body > a + .question-status {
  687. margin-top: 20px;
  688. }
  689.  
  690. #SEpreview-answers {
  691. all: unset;
  692. display: block;
  693. padding: 10px 30px;
  694. font-weight: bold;
  695. line-height: 1.0;
  696. border-top: 4px solid rgba(${COLORS.answer.backRGB}, 0.37);
  697. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  698. color: ${COLORS.answer.fore};
  699. word-break: break-word;
  700. }
  701. #SEpreview-answers:before {
  702. content: "Answers:";
  703. margin-right: 1ex;
  704. font-size: 20px;
  705. line-height: 48px;
  706. }
  707. #SEpreview-answers a {
  708. color: ${COLORS.answer.fore};
  709. text-decoration: none;
  710. font-size: 11px;
  711. font-family: monospace;
  712. width: 32px;
  713. display: inline-block;
  714. vertical-align: top;
  715. margin: 1ex 1ex 0 0;
  716. }
  717. #SEpreview-answers img {
  718. width: 32px;
  719. height: 32px;
  720. }
  721. #SEpreview-answers .vote-accepted-on {
  722. position: absolute;
  723. margin: -12px 0 0 6px;
  724. filter: drop-shadow(1px 2px 1px rgba(0,0,0,1));
  725. }
  726. #SEpreview-answers a.deleted-answer {
  727. color: ${COLORS.deleted.fore};
  728. background: transparent;
  729. opacity: 0.25;
  730. }
  731. #SEpreview-answers a.deleted-answer:hover {
  732. opacity: 1.0;
  733. }
  734. #SEpreview-answers a:hover:not(.SEpreviewed) {
  735. text-decoration: underline;
  736. }
  737. #SEpreview-answers a.SEpreviewed {
  738. background-color: ${COLORS.answer.fore};
  739. color: ${COLORS.answer.foreInv};
  740. position: relative;
  741. }
  742. #SEpreview-answers a.SEpreviewed:after {
  743. display: block;
  744. content: " ";
  745. position: absolute;
  746. left: -4px;
  747. top: -4px;
  748. right: -4px;
  749. bottom: -4px;
  750. border: 4px solid ${COLORS.answer.fore};
  751. }
  752.  
  753. .delete-tag,
  754. .comment-actions td:last-child {
  755. display: none;
  756. }
  757. .comments .new-comment-highlight {
  758. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  759. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  760. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  761. }
  762.  
  763. @-webkit-keyframes highlight {
  764. from {background-color: #ffcf78}
  765. to {background-color: none}
  766. }
  767. `
  768. + Object.keys(COLORS).map(s => `
  769. body[SEpreview-type="${s}"] #SEpreview-title {
  770. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  771. color: ${COLORS[s].fore};
  772. }
  773. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar {
  774. background-color: rgba(${COLORS[s].backRGB}, 0.1); }
  775. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb {
  776. background-color: rgba(${COLORS[s].backRGB}, 0.2); }
  777. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:hover {
  778. background-color: rgba(${COLORS[s].backRGB}, 0.3); }
  779. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:active {
  780. background-color: rgba(${COLORS[s].backRGB}, 0.75); }
  781. `).join('')
  782. + ['deleted', 'closed'].map(s => `
  783. body[SEpreview-type="${s}"] #SEpreview-answers {
  784. border-top-color: rgba(${COLORS[s].backRGB}, 0.37);
  785. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  786. color: ${COLORS[s].fore};
  787. }
  788. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed {
  789. background-color: ${COLORS[s].fore};
  790. color: ${COLORS[s].foreInv};
  791. }
  792. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed:after {
  793. border-color: ${COLORS[s].fore};
  794. }
  795. `).join('');
  796. }