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