SE Preview on hover

Shows preview of the linked questions/answers on hover

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

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 0.1.5
  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. // @grant GM_addStyle
  17. // @grant GM_xmlhttpRequest
  18. // @connect stackoverflow.com
  19. // @connect superuser.com
  20. // @connect serverfault.com
  21. // @connect askubuntu.com
  22. // @connect stackapps.com
  23. // @connect mathoverflow.net
  24. // @connect stackexchange.com
  25. // @connect cdn.sstatic.net
  26. // @run-at document-end
  27. // @noframes
  28. // ==/UserScript==
  29.  
  30. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  31.  
  32. const PREVIEW_DELAY = 100;
  33. const COLORS = {
  34. question: {
  35. backRGB: '80, 133, 195',
  36. foreRGB: '#265184',
  37. },
  38. answer: {
  39. backRGB: '112, 195, 80',
  40. foreRGB: '#3f7722',
  41. foreInv: 'white',
  42. },
  43. };
  44.  
  45. let xhr;
  46. let preview = {
  47. frame: null,
  48. link: null,
  49. hover: {x:0, y:0},
  50. timer: 0,
  51. CSScache: {},
  52. stylesOverride: '',
  53. };
  54.  
  55. const rxPreviewable = getURLregexForMatchedSites();
  56. const thisPageUrls = getPageBaseUrls(location.href);
  57.  
  58. initStyles();
  59. initPolyfills();
  60. setMutationHandler('a', onLinkAdded, {processExisting: true});
  61.  
  62. /**************************************************************/
  63.  
  64. function onLinkAdded(links) {
  65. for (let i = 0, link; (link = links[i++]); ) {
  66. if (isLinkPreviewable(link)) {
  67. link.removeAttribute('title');
  68. link.addEventListener('mouseover', onLinkHovered);
  69. }
  70. }
  71. }
  72.  
  73. function onLinkHovered(e) {
  74. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)
  75. return;
  76. preview.link = this;
  77. preview.link.addEventListener('mousemove', onLinkMouseMove);
  78. preview.link.addEventListener('mouseout', abortPreview);
  79. preview.link.addEventListener('mousedown', abortPreview);
  80. restartPreviewTimer(this);
  81. }
  82.  
  83. function onLinkMouseMove(e) {
  84. let stoppedMoving = Math.abs(preview.hover.x - e.clientX) < 2 &&
  85. Math.abs(preview.hover.y - e.clientY) < 2;
  86. if (!stoppedMoving)
  87. return;
  88. preview.hover.x = e.clientX;
  89. preview.hover.y = e.clientY;
  90. restartPreviewTimer(this);
  91. }
  92.  
  93. function restartPreviewTimer(link) {
  94. clearTimeout(preview.timer);
  95. preview.timer = setTimeout(() => {
  96. preview.timer = 0;
  97. link.removeEventListener('mousemove', onLinkMouseMove);
  98. if (link.matches(':hover'))
  99. downloadPreview(link.href);
  100. }, PREVIEW_DELAY);
  101. }
  102.  
  103. function abortPreview(e) {
  104. releaseLinkListeners(this);
  105. preview.timer = setTimeout(link => {
  106. if (link == preview.link && preview.frame && !preview.frame.matches(':hover')) {
  107. releaseLinkListeners(link);
  108. hideAndRemove(preview.frame);
  109. }
  110. }, PREVIEW_DELAY * 3, this);
  111. if (xhr)
  112. xhr.abort();
  113. }
  114.  
  115. function releaseLinkListeners(link) {
  116. link.removeEventListener('mousemove', onLinkMouseMove);
  117. link.removeEventListener('mouseout', abortPreview);
  118. link.removeEventListener('mousedown', abortPreview);
  119. clearTimeout(preview.timer);
  120. }
  121.  
  122. function hideAndRemove(element, transition) {
  123. if (transition) {
  124. element.style.transition = typeof transition == 'number' ? `opacity ${transition}s ease-in-out` : transition;
  125. return setTimeout(hideAndRemove, 0, element);
  126. }
  127. element.style.opacity = 0;
  128. element.addEventListener('transitionend', function remove() {
  129. element.removeEventListener('transitionend', remove);
  130. if (+element.style.opacity === 0)
  131. element.remove();
  132. });
  133. }
  134.  
  135. function downloadPreview(url) {
  136. xhr = GM_xmlhttpRequest({
  137. method: 'GET',
  138. url: httpsUrl(url),
  139. onload: showPreview,
  140. });
  141. }
  142.  
  143. function showPreview(data) {
  144. let doc = data.SEpreviewDoc || new DOMParser().parseFromString(data.responseText, 'text/html');
  145. if (!doc || !doc.head) {
  146. error('empty document received:', data);
  147. return;
  148. }
  149.  
  150. if (!$(doc, 'base'))
  151. doc.head.insertAdjacentHTML('afterbegin', `<base href="${data.finalUrl}">`);
  152.  
  153. const answerIdMatch = data.finalUrl.match(/questions\/.+?\/(\d+)/);
  154. const isQuestion = !answerIdMatch;
  155. let postId = answerIdMatch ? '#answer-' + answerIdMatch[1] : '#question';
  156. let post = $(doc, postId + ' .post-text');
  157. if (!post)
  158. return error('No parsable post found', doc);
  159. const title = $(doc, 'meta[property="og:title"]').content;
  160. let status = isQuestion && $(doc, '.question-status');
  161. let comments = $(doc, `${postId} .comments`);
  162. let commentsHidden = +$(comments, 'tbody').dataset.remainingCommentsCount;
  163. let commentsShowLink = commentsHidden && $(doc, `${postId} .js-show-link.comments-link`);
  164.  
  165. let externalsReady = [preview.stylesOverride];
  166. let externalsToGet = new Set();
  167. let afterBodyHtml = '';
  168.  
  169. fetchExternals();
  170. maybeRender();
  171.  
  172. function fetchExternals() {
  173. let codeBlocks = $$(post, 'pre code');
  174. if (codeBlocks.length) {
  175. codeBlocks.forEach(e => e.parentElement.classList.add('prettyprint'));
  176. externalsReady.push(
  177. '<script> StackExchange = {}; </script>',
  178. '<script src="https://cdn.sstatic.net/Js/prettify-full.en.js"></script>'
  179. );
  180. afterBodyHtml += '<script> prettyPrint(); </script>';
  181. }
  182.  
  183. $$(doc, 'style, link[rel="stylesheet"]').forEach(e => {
  184. if (e.localName == 'style')
  185. externalsReady.push(e.outerHTML);
  186. else if (e.href in preview.CSScache)
  187. externalsReady.push(preview.CSScache[e.href]);
  188. else {
  189. externalsToGet.add(e.href);
  190. GM_xmlhttpRequest({
  191. method: 'GET',
  192. url: e.href,
  193. onload: data => {
  194. externalsReady.push(preview.CSScache[e.href] = '<style>' + data.responseText + '</style>');
  195. externalsToGet.delete(e.href);
  196. maybeRender();
  197. },
  198. });
  199. }
  200. });
  201.  
  202. }
  203.  
  204. function maybeRender() {
  205. if (externalsToGet.size)
  206. return;
  207. if (!preview.frame) {
  208. preview.frame = document.createElement('iframe');
  209. preview.frame.id = 'SEpreview';
  210. }
  211. preview.frame.classList.toggle('SEpreviewIsAnswer', !!answerIdMatch);
  212. document.body.appendChild(preview.frame);
  213.  
  214. const answers = $$(doc, '.answer');
  215. const answersShown = answers.length > (isQuestion ? 0 : 1);
  216. if (answersShown) {
  217. afterBodyHtml += '<div id="SEpreviewAnswers">Answers:&nbsp;' +
  218. answers.map((e, index) =>
  219. `<a href="${$(e, '.short-link').href.replace(/(\d+)\/\d+/, '$1')}"
  220. title="${
  221. $text(e, '.user-details a') + ' (' +
  222. $text(e, '.reputation-score') + ') ' +
  223. $text(e, '.user-action-time') +
  224. $text(e, '.vote-count-post').replace(/\d+/, s => !s ? '' : ', votes: ' + s)}"
  225. class="${e.matches(postId) ? 'SEpreviewed' : ''}"
  226. >${index + 1}</a>`
  227. ).join('') + '</div>';
  228. }
  229.  
  230. $$remove(doc, 'script');
  231.  
  232. let html = `<head>${externalsReady.join('')}</head>
  233. <body${answerIdMatch ? ' class="SEpreviewIsAnswer"' : ''}>
  234. <a id="SEpreviewTitle" href="${
  235. isQuestion ? data.finalUrl : data.finalUrl.replace(/\/\d+[^\/]*$/, '')
  236. }">${title}</a>
  237. <div id="SEpreviewBody">${
  238. [post.parentElement, comments, commentsShowLink, status]
  239. .map(e => e ? e.outerHTML : '').join('')
  240. }</div>
  241. ${afterBodyHtml}
  242. </body>`;
  243.  
  244. try {
  245. let pvDoc = preview.frame.contentDocument;
  246. pvDoc.open();
  247. pvDoc.write(html);
  248. pvDoc.close();
  249. } catch(e) {
  250. preview.frame.srcdoc = `<html>${html}</html>`;
  251. }
  252.  
  253. onFrameReady(preview.frame, function() {
  254. this.onload = null;
  255. this.style.opacity = 1;
  256. this.contentDocument.addEventListener('mouseover', retainMainScrollPos);
  257. this.contentDocument.addEventListener('click', interceptLinks);
  258. });
  259. }
  260.  
  261. function interceptLinks(e) {
  262. const link = e.target;
  263. if (link.localName != 'a')
  264. return;
  265. if (link.matches('.js-show-link.comments-link')) {
  266. hideAndRemove(link, 0.5);
  267. downloadComments();
  268. }
  269. else if (e.button || e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)
  270. return (link.target = '_blank');
  271. else if (link.matches('#SEpreviewAnswers a, a#SEpreviewTitle'))
  272. showPreview({
  273. finalUrl: link.href.includes('/questions/')
  274. ? link.href
  275. : data.finalUrl.replace(/(\/\d+[^\/]*|\?.*)?$/g, '') + '/' + link.pathname.match(/\d+/)[0],
  276. SEpreviewDoc: doc,
  277. });
  278. else if (!isLinkPreviewable(link))
  279. return (link.target = '_blank');
  280. else if (!link.matches('.SEpreviewed'))
  281. downloadPreview(link.href);
  282. e.preventDefault();
  283. }
  284.  
  285. function downloadComments() {
  286. GM_xmlhttpRequest({
  287. method: 'GET',
  288. url: new URL(data.finalUrl).origin + '/posts/' + comments.id.match(/\d+/)[0] + '/comments',
  289. onload: r => showComments(r.responseText),
  290. });
  291. }
  292.  
  293. function showComments(html) {
  294. let tbody = $(preview.frame.contentDocument, `#${comments.id} tbody`);
  295. let oldIds = new Set([...tbody.rows].map(e => e.id));
  296. tbody.innerHTML = html;
  297. for (let tr of tbody.rows)
  298. if (!oldIds.has(tr.id))
  299. tr.classList.add('new-comment-highlight');
  300. }
  301. }
  302.  
  303. function retainMainScrollPos(e) {
  304. let scrollPos = {x:scrollX, y:scrollY};
  305. document.addEventListener('scroll', preventScroll);
  306. document.addEventListener('mouseover', releaseScrollLock);
  307.  
  308. function preventScroll(e) {
  309. scrollTo(scrollPos.x, scrollPos.y);
  310. log('prevented main page scroll');
  311. }
  312. function releaseScrollLock(e) {
  313. document.removeEventListener('mouseout', releaseScrollLock);
  314. document.removeEventListener('scroll', preventScroll);
  315. }
  316. }
  317.  
  318. function getURLregexForMatchedSites() {
  319. return new RegExp('https?://(\\w*\\.)*(' + GM_info.script.matches.map(m =>
  320. m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')
  321. ).join('|') + ')/(questions|q|a)/\\d+');
  322. }
  323.  
  324. function getPageBaseUrls(url) {
  325. let base = httpsUrl((url.match(rxPreviewable) || [])[0]);
  326. return base ? {
  327. base,
  328. short: base.replace('/questions/', '/q/'),
  329. } : {};
  330. }
  331.  
  332. function isLinkPreviewable(link) {
  333. const inPreview = link.ownerDocument != document;
  334. if (!rxPreviewable.test(link.href) || link.matches('.short-link'))
  335. return false;
  336. const pageUrls = inPreview ? getPageBaseUrls(preview.link.href) : thisPageUrls;
  337. const url = httpsUrl(link.href);
  338. return !url.startsWith(pageUrls.base) &&
  339. !url.startsWith(pageUrls.short);
  340. }
  341.  
  342. function onFrameReady(frame, callback) {
  343. if (frame.contentDocument.readyState == 'complete')
  344. return callback.call(frame);
  345. else
  346. frame.onload = callback;
  347. }
  348.  
  349. function httpsUrl(url) {
  350. return (url || '').replace(/^http:/, 'https:');
  351. }
  352.  
  353. function $(node__optional, selector) {
  354. return (node__optional || document).querySelector(selector || node__optional);
  355. }
  356.  
  357. function $$(node__optional, selector) {
  358. return (node__optional || document).querySelectorAll(selector || node__optional);
  359. }
  360.  
  361. function $text(node__optional, selector) {
  362. let e = $(node__optional, selector);
  363. return e ? e.textContent.trim() : '';
  364. }
  365.  
  366. function $$remove(node__optional, selector) {
  367. (node__optional || document).querySelectorAll(selector || node__optional)
  368. .forEach(e => e.remove());
  369. }
  370.  
  371. function log(...args) {
  372. console.log(GM_info.script.name, ...args);
  373. }
  374.  
  375. function error(...args) {
  376. console.error(GM_info.script.name, ...args);
  377. }
  378.  
  379. function initPolyfills() {
  380. NodeList.prototype.forEach = NodeList.prototype.forEach || Array.prototype.forEach;
  381. NodeList.prototype.map = NodeList.prototype.map || Array.prototype.map;
  382. }
  383.  
  384. function initStyles() {
  385. GM_addStyle(`
  386. #SEpreview {
  387. all: unset;
  388. box-sizing: content-box;
  389. width: 720px; /* 660px + 30px + 30px */
  390. height: 33%;
  391. min-height: 200px;
  392. position: fixed;
  393. opacity: 0;
  394. transition: opacity .5s cubic-bezier(.88,.02,.92,.66);
  395. right: 0;
  396. bottom: 0;
  397. padding: 0;
  398. margin: 0;
  399. background: white;
  400. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  401. z-index: 999999;
  402. border: 8px solid rgb(${COLORS.question.backRGB});
  403. }
  404. #SEpreview.SEpreviewIsAnswer {
  405. border-color: rgb(${COLORS.answer.backRGB});
  406. }
  407. `);
  408.  
  409. preview.stylesOverride = `<style>
  410. body, html {
  411. min-width: unset!important;
  412. box-shadow: none!important;
  413. }
  414. html, body {
  415. background: unset!important;;
  416. }
  417. body {
  418. display: flex;
  419. flex-direction: column;
  420. height: 100vh;
  421. }
  422. #SEpreviewTitle {
  423. all: unset;
  424. display: block;
  425. padding: 20px 30px;
  426. font-weight: bold;
  427. font-size: 20px;
  428. line-height: 1.3;
  429. background-color: rgba(${COLORS.question.backRGB}, 0.37);
  430. color: ${COLORS.question.foreRGB};
  431. cursor: pointer;
  432. }
  433. #SEpreviewTitle:hover {
  434. text-decoration: underline;
  435. }
  436. #SEpreviewBody {
  437. padding: 30px!important;
  438. overflow: auto;
  439. flex-grow: 2;
  440. }
  441. #SEpreviewBody .post-menu {
  442. display: none!important;
  443. }
  444. #SEpreviewBody .question-status {
  445. margin: -25px -30px -30px;
  446. padding-left: 30px;
  447. }
  448. #SEpreviewBody .question-status h2 {
  449. font-weight: normal;
  450. }
  451.  
  452. #SEpreviewBody::-webkit-scrollbar {
  453. background-color: rgba(${COLORS.question.backRGB}, 0.1);
  454. }
  455. #SEpreviewBody::-webkit-scrollbar-thumb {
  456. background-color: rgba(${COLORS.question.backRGB}, 0.2);
  457. }
  458. #SEpreviewBody::-webkit-scrollbar-thumb:hover {
  459. background-color: rgba(${COLORS.question.backRGB}, 0.3);
  460. }
  461. #SEpreviewBody::-webkit-scrollbar-thumb:active {
  462. background-color: rgba(${COLORS.question.backRGB}, 0.75);
  463. }
  464.  
  465. body.SEpreviewIsAnswer #SEpreviewTitle {
  466. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  467. color: ${COLORS.answer.foreRGB};
  468. }
  469. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar {
  470. background-color: rgba(${COLORS.answer.backRGB}, 0.1);
  471. }
  472. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb {
  473. background-color: rgba(${COLORS.answer.backRGB}, 0.2);
  474. }
  475. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb:hover {
  476. background-color: rgba(${COLORS.answer.backRGB}, 0.3);
  477. }
  478. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb:active {
  479. background-color: rgba(${COLORS.answer.backRGB}, 0.75);
  480. }
  481.  
  482. #SEpreviewAnswers {
  483. all: unset;
  484. display: block;
  485. padding: 10px 30px;
  486. font-weight: bold;
  487. font-size: 20px;
  488. line-height: 1.3;
  489. border-top: 4px solid rgba(${COLORS.answer.backRGB}, 0.37);
  490. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  491. color: ${COLORS.answer.foreRGB};
  492. word-break: break-word;
  493. }
  494. #SEpreviewAnswers a {
  495. color: ${COLORS.answer.foreRGB};
  496. padding: .25ex .75ex;
  497. text-decoration: none;
  498. }
  499. #SEpreviewAnswers a:hover:not(.SEpreviewed) {
  500. text-decoration: underline;
  501. }
  502. #SEpreviewAnswers a.SEpreviewed {
  503. background-color: ${COLORS.answer.foreRGB};
  504. color: ${COLORS.answer.foreInv};
  505. }
  506.  
  507. .comments .new-comment-highlight {
  508. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  509. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  510. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  511. }
  512.  
  513. @-webkit-keyframes highlight {
  514. from {background-color: #ffcf78}
  515. to {background-color: none}
  516. }
  517. </style>`;
  518. }