Greasy Fork 支持简体中文。

SE Preview on hover

Shows preview of the linked questions/answers on hover while Ctrl key is held

目前為 2017-02-13 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover while Ctrl key is held
  4. // @version 0.0.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. // @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. back: '80, 133, 195',
  36. fore: '#265184',
  37. },
  38. answer: {
  39. back: '112, 195, 80',
  40. fore: '#3f7722',
  41. },
  42. };
  43.  
  44. var xhr;
  45. var preview;
  46. var previewLink;
  47. var previewTimer;
  48. var previewCSScache = {};
  49. var hovering = {stoppedAt: {x:0, y:0}};
  50.  
  51. const rx = getURLregexForMatchedSites();
  52. const thisPageBaseUrl = (location.href.match(rx) || [])[0];
  53. const thisPageBaseUrlShort = thisPageBaseUrl ? thisPageBaseUrl.replace('/questions/', '/q/') : undefined;
  54.  
  55. const stylesOverride = `<style>
  56. body, html {
  57. min-width: unset!important;
  58. box-shadow: none!important;
  59. }
  60. html, body {
  61. background: unset!important;;
  62. }
  63. body {
  64. display: flex;
  65. flex-direction: column;
  66. height: 100%;
  67. }
  68. #SEpreviewTitle {
  69. all: unset;
  70. display: block;
  71. padding: 20px 30px;
  72. font-weight: bold;
  73. font-size: 20px;
  74. line-height: 1.3;
  75. background-color: rgba(${COLORS.question.back}, 0.37);
  76. color: ${COLORS.question.fore};
  77. }
  78. #SEpreviewTitle:hover {
  79. text-decoration: underline;
  80. }
  81. #SEpreviewBody {
  82. padding: 30px!important;
  83. overflow: auto;
  84. }
  85. #SEpreviewBody::-webkit-scrollbar {
  86. background-color: rgba(${COLORS.question.back}, 0.1);
  87. }
  88. #SEpreviewBody::-webkit-scrollbar-thumb {
  89. background-color: rgba(${COLORS.question.back}, 0.2);
  90. }
  91. #SEpreviewBody::-webkit-scrollbar-thumb:hover {
  92. background-color: rgba(${COLORS.question.back}, 0.3);
  93. }
  94. #SEpreviewBody::-webkit-scrollbar-thumb:active {
  95. background-color: rgba(${COLORS.question.back}, 0.75);
  96. }
  97.  
  98. body.SEpreviewIsAnswer #SEpreviewTitle {
  99. background-color: rgba(${COLORS.answer.back}, 0.37);
  100. color: ${COLORS.answer.fore};
  101. }
  102. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar {
  103. background-color: rgba(${COLORS.answer.back}, 0.1);
  104. }
  105. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb {
  106. background-color: rgba(${COLORS.answer.back}, 0.2);
  107. }
  108. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb:hover {
  109. background-color: rgba(${COLORS.answer.back}, 0.3);
  110. }
  111. body.SEpreviewIsAnswer #SEpreviewBody::-webkit-scrollbar-thumb:active {
  112. background-color: rgba(${COLORS.answer.back}, 0.75);
  113. }
  114.  
  115. #SEpreviewAnswers {
  116. all: unset;
  117. display: block;
  118. padding: 10px 30px;
  119. font-weight: bold;
  120. font-size: 20px;
  121. line-height: 1.3;
  122. border-top: 4px solid rgba(${COLORS.answer.back}, 0.37);
  123. background-color: rgba(${COLORS.answer.back}, 0.37);
  124. color: ${COLORS.answer.fore};
  125. }
  126. </style>`;
  127.  
  128. GM_addStyle(`
  129. #SEpreview {
  130. all: unset;
  131. box-sizing: content-box;
  132. width: 720px; /* 660px + 30px + 30px */
  133. height: 33%;
  134. min-height: 200px;
  135. position: fixed;
  136. transition: opacity .25s ease-in-out;
  137. right: 0;
  138. bottom: 0;
  139. padding: 0;
  140. margin: 0;
  141. background: white;
  142. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  143. z-index: 999999;
  144. border: 8px solid rgb(${COLORS.question.back});
  145. }
  146. #SEpreview.SEpreviewIsAnswer {
  147. border-color: rgb(${COLORS.answer.back});
  148. }
  149. `);
  150.  
  151. processExistingAndSetMutationHandler('a', onLinkAdded);
  152.  
  153. /**************************************************************/
  154.  
  155. function onLinkAdded(links) {
  156. for (var i = 0, link; (link = links[i++]); ) {
  157. if (rx.test(link.href) &&
  158. !link.matches('.short-link') &&
  159. !link.href.startsWith(thisPageBaseUrl) &&
  160. !link.href.startsWith(thisPageBaseUrlShort)
  161. ) {
  162. link.removeAttribute('title');
  163. link.addEventListener('mouseover', onLinkHovered);
  164. }
  165. }
  166. }
  167.  
  168. function onLinkHovered(e) {
  169. if (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)
  170. return;
  171. previewLink = this;
  172. previewLink.addEventListener('mousemove', onLinkMouseMove);
  173. previewLink.addEventListener('mouseout', abortPreview);
  174. previewLink.addEventListener('mousedown', abortPreview);
  175. restartPreviewTimer();
  176. }
  177.  
  178. function onLinkMouseMove(e) {
  179. if (Math.abs(hovering.stoppedAt.x - e.clientX) < 2 && Math.abs(hovering.stoppedAt.y - e.clientY) < 2)
  180. return;
  181. hovering.stoppedAt.x = e.clientX;
  182. hovering.stoppedAt.y = e.clientY;
  183. restartPreviewTimer();
  184. }
  185.  
  186. function restartPreviewTimer() {
  187. clearTimeout(previewTimer);
  188. previewTimer = setTimeout(() => {
  189. previewTimer = 0;
  190. if (!previewLink.matches(':hover'))
  191. return;
  192. downloadPage();
  193. }, PREVIEW_DELAY);
  194. }
  195.  
  196. function abortPreview() {
  197. previewLink.removeEventListener('mousemove', onLinkMouseMove);
  198. previewLink.removeEventListener('mouseout', abortPreview);
  199. previewLink.removeEventListener('mousedown', abortPreview);
  200. clearTimeout(previewTimer);
  201. previewTimer = setTimeout(() => {
  202. previewTimer = 0;
  203. if (preview && !preview.matches(':hover'))
  204. hidePreview();
  205. }, 500);
  206. if (xhr)
  207. xhr.abort();
  208. }
  209.  
  210. function downloadPage() {
  211. xhr = GM_xmlhttpRequest({
  212. method: 'GET',
  213. url: previewLink.href,
  214. onload: showPreview,
  215. });
  216. }
  217.  
  218. function showPreview(data) {
  219. var doc = new DOMParser().parseFromString(data.responseText, 'text/html');
  220. if (!doc || !doc.head) {
  221. console.error(GM_info.script.name, 'empty document received:', data);
  222. return;
  223. }
  224.  
  225. if (!$(doc, 'base'))
  226. doc.head.insertAdjacentHTML('afterbegin', `<base href="${data.finalUrl}">`);
  227.  
  228. var answerIdMatch = data.finalUrl.match(/questions\/.+?\/(\d+)/);
  229. var postId = answerIdMatch ? '#answer-' + answerIdMatch[1] : '#question';
  230. var post = $(doc, postId + ' .post-text');
  231. if (!post)
  232. return;
  233. var title = $(doc, 'meta[property="og:title"]').content;
  234. var comments = $(doc, postId + ' .comments');
  235. var answers; // = answerIdMatch ? null : $$(doc, '.answer');
  236.  
  237. $$remove(doc, 'script, .post-menu');
  238.  
  239. var externalsReady = [stylesOverride];
  240. var stylesToGet = new Set();
  241. var afterBodyHtml = '';
  242.  
  243. fetchExternals();
  244. maybeRender();
  245.  
  246. function fetchExternals() {
  247. var codeBlocks = $$(post, 'pre code');
  248. if (codeBlocks.length) {
  249. codeBlocks.forEach(e => e.parentElement.classList.add('prettyprint'));
  250. externalsReady.push(
  251. '<script> StackExchange = {}; </script>',
  252. '<script src="https://cdn.sstatic.net/Js/prettify-full.en.js"></script>'
  253. );
  254. afterBodyHtml = '<script> prettyPrint(); </script>';
  255. }
  256.  
  257. $$(doc, 'style, link[rel="stylesheet"]').forEach(e => {
  258. if (e.localName == 'style')
  259. externalsReady.push(e.outerHTML);
  260. else if (e.href in previewCSScache)
  261. externalsReady.push(previewCSScache[e.href]);
  262. else {
  263. stylesToGet.add(e.href);
  264. GM_xmlhttpRequest({
  265. method: 'GET',
  266. url: e.href,
  267. onload: data => {
  268. externalsReady.push(previewCSScache[e.href] = '<style>' + data.responseText + '</style>');
  269. stylesToGet.delete(e.href);
  270. maybeRender();
  271. },
  272. });
  273. }
  274. });
  275.  
  276. }
  277.  
  278. function maybeRender() {
  279. if (stylesToGet.size)
  280. return;
  281. if (!preview) {
  282. preview = document.createElement('iframe');
  283. preview.id = 'SEpreview';
  284. preview.sandbox = 'allow-same-origin allow-scripts';
  285. }
  286. preview.classList.toggle('SEpreviewIsAnswer', !!answerIdMatch);
  287. document.body.appendChild(preview);
  288.  
  289. var headHtml = externalsReady.join('');
  290. var bodyHtml = [post.parentElement, comments].map(e => e ? e.outerHTML || e : '').join('');
  291. var pvDoc = preview.contentDocument;
  292. pvDoc.open();
  293. pvDoc.write(`
  294. <head>${headHtml}</head>
  295. <body${answerIdMatch ? ' class="SEpreviewIsAnswer"' : ''}>
  296. <a id="SEpreviewTitle" href="${data.finalUrl}">${title}</a>
  297. <div id="SEpreviewBody">${bodyHtml}</div>
  298. ${!answers ? '' : '<div id="SEpreviewAnswers">' + answers.length + ' answer' + (answers.length > 1 ? 's' : '') + '</div>'}
  299. ${afterBodyHtml}
  300. </body>`);
  301. pvDoc.close();
  302.  
  303. pvDoc.addEventListener('mouseover', retainMainScrollPos);
  304. if (answers)
  305. $(pvDoc, '#SEpreviewAnswers').addEventListener('click', revealAnswers);
  306. }
  307. }
  308.  
  309. function retainMainScrollPos(e) {
  310. var scrollPos = {x:scrollX, y:scrollY};
  311. document.addEventListener('scroll', preventScroll);
  312. document.addEventListener('mouseover', releaseScrollLock);
  313.  
  314. function preventScroll(e) {
  315. scrollTo(scrollPos.x, scrollPos.y);
  316. }
  317. function releaseScrollLock(e) {
  318. document.removeEventListener('mouseout', releaseScrollLock);
  319. document.removeEventListener('scroll', preventScroll);
  320. }
  321. }
  322.  
  323. function hidePreview() {
  324. preview.remove();
  325. }
  326.  
  327. function getURLregexForMatchedSites() {
  328. return new RegExp('https?://(\\w*\\.)*(' + GM_info.script.matches.map(m =>
  329. m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')
  330. ).join('|') + ')/(questions|q|a)/\\d+');
  331. }
  332.  
  333. function $(node__optional, selector) {
  334. // or $(selector) {
  335. return (node__optional || document).querySelector(selector || node__optional);
  336. }
  337.  
  338. function $$(node__optional, selector) {
  339. // or $$(selector) {
  340. return (node__optional || document).querySelectorAll(selector || node__optional);
  341. }
  342.  
  343. function $$remove(node__optional, selector) {
  344. // or $$remove(selector) {
  345. (node__optional || document).querySelectorAll(selector || node__optional)
  346. .forEach(e => e.remove());
  347. }