SE Preview on hover

Shows preview of the linked questions/answers on hover

当前为 2018-03-18 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 0.6.2
  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. // @include /https?:\/\/www\.?google(\.com?)?(\.\w\w)?\/(webhp|q|.*?[?#]q=|search).*/
  16. // @match *://*.bing.com/*
  17. // @match *://*.yahoo.com/*
  18. // @match *://*.yahoo.co.jp/*
  19. // @match *://*.yahoo.cn/*
  20. // @include /https?:\/\/(\w+\.)*yahoo.(com|\w\w(\.\w\w)?)\/.*/
  21. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  22. // @require https://greasyfork.org/scripts/27531/code/LZString-2xspeedup.js
  23. // @grant GM_addStyle
  24. // @grant GM_xmlhttpRequest
  25. // @grant GM_getValue
  26. // @grant GM_setValue
  27. // @connect stackoverflow.com
  28. // @connect superuser.com
  29. // @connect serverfault.com
  30. // @connect askubuntu.com
  31. // @connect stackapps.com
  32. // @connect mathoverflow.net
  33. // @connect stackexchange.com
  34. // @connect cdn.sstatic.net
  35. // @run-at document-end
  36. // @noframes
  37. // ==/UserScript==
  38.  
  39. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  40.  
  41. const PREVIEW_DELAY = 200;
  42. const BUSY_CURSOR_DELAY = 1000;
  43. const CACHE_DURATION = 1 * 60 * 1000; // 1 minute for the recently active posts, scales up logarithmically
  44. const MIN_HEIGHT = 400; // px
  45. const COLORS = {
  46. question: {
  47. backRGB: '80, 133, 195',
  48. fore: '#265184',
  49. },
  50. answer: {
  51. backRGB: '112, 195, 80',
  52. fore: '#3f7722',
  53. foreInv: 'white',
  54. },
  55. deleted: {
  56. backRGB: '181, 103, 103',
  57. fore: 'rgb(181, 103, 103)',
  58. foreInv: 'white',
  59. },
  60. closed: {
  61. backRGB: '255, 206, 93',
  62. fore: 'rgb(194, 136, 0)',
  63. foreInv: 'white',
  64. },
  65. };
  66.  
  67. let xhr;
  68. const xhrNoSSL = new Set();
  69. const preview = {
  70. frame: null,
  71. link: null,
  72. hover: {x:0, y:0},
  73. timer: 0,
  74. timerCursor: 0,
  75. stylesOverride: '',
  76. };
  77. const lockScroll = {};
  78.  
  79. const {full: rxPreviewable, siteOnly: rxPreviewableSite} = getURLregexForMatchedSites();
  80. const thisPageUrls = getPageBaseUrls(location.href);
  81.  
  82. initStyles();
  83. initPolyfills();
  84. setMutationHandler('a, .question-summary .answered, .question-summary .answered-accepted', onLinkAdded, {processExisting: true});
  85. setTimeout(cleanupCache, 10000);
  86.  
  87. /**************************************************************/
  88.  
  89. function onLinkAdded(links) {
  90. for (let i = 0, link; (link = links[i++]); ) {
  91. if (link.localName != 'a' || isLinkPreviewable(link)) {
  92. link.removeAttribute('title');
  93. $on('mouseover', link, onLinkHovered);
  94. }
  95. }
  96. }
  97.  
  98. function onLinkHovered(e) {
  99. if (hasKeyModifiers(e))
  100. return;
  101. preview.link = this;
  102. $on('mousemove', this, onLinkMouseMove);
  103. $on('mouseout', this, abortPreview);
  104. $on('mousedown', this, abortPreview);
  105. restartPreviewTimer(this);
  106. }
  107.  
  108. function onLinkMouseMove(e) {
  109. let stoppedMoving = Math.abs(preview.hover.x - e.clientX) < 2 &&
  110. Math.abs(preview.hover.y - e.clientY) < 2;
  111. if (!stoppedMoving)
  112. return;
  113. preview.hover.x = e.clientX;
  114. preview.hover.y = e.clientY;
  115. restartPreviewTimer(this);
  116. }
  117.  
  118. function restartPreviewTimer(link) {
  119. clearTimeout(preview.timer);
  120. preview.timer = setTimeout(() => {
  121. preview.timer = 0;
  122. if (!link.matches(':hover'))
  123. return releaseLinkListeners(link);
  124. $off('mousemove', link, onLinkMouseMove);
  125. if (link.localName != 'a')
  126. link.href = $('a', link.closest('.question-summary')).href;
  127. downloadPreview(link);
  128. }, PREVIEW_DELAY);
  129. }
  130.  
  131. function abortPreview(e) {
  132. releaseLinkListeners(this);
  133. preview.timer = setTimeout(link => {
  134. if (link == preview.link && preview.frame && !preview.frame.matches(':hover'))
  135. preview.frame.contentWindow.postMessage('SEpreview-hidden', '*');
  136. }, PREVIEW_DELAY * 3, this);
  137. if (xhr)
  138. xhr.abort();
  139. if (this.style.cursor == 'wait')
  140. this.style.cursor = '';
  141. }
  142.  
  143. function releaseLinkListeners(link = preview.link) {
  144. $off('mousemove', link, onLinkMouseMove);
  145. $off('mouseout', link, abortPreview);
  146. $off('mousedown', link, abortPreview);
  147. stopTimers();
  148. }
  149.  
  150. function stopTimers(names) {
  151. for (let k in preview) {
  152. if (k.startsWith('timer') && preview[k]) {
  153. clearTimeout(preview[k]);
  154. preview[k] = 0;
  155. }
  156. }
  157. }
  158.  
  159. function fadeOut(element, transition) {
  160. return new Promise(resolve => {
  161. if (transition) {
  162. element.style.transition = typeof transition == 'number' ? `opacity ${transition}s ease-in-out` : transition;
  163. setTimeout(doFadeOut);
  164. } else
  165. doFadeOut();
  166.  
  167. function doFadeOut() {
  168. element.style.opacity = '0';
  169. $on('transitionend', element, done);
  170. $on('visibilitychange', done);
  171. function done(e) {
  172. $off('transitionend', element, done);
  173. $off('visibilitychange', done);
  174. if (element.style.opacity == '0')
  175. element.style.display = 'none';
  176. resolve();
  177. }
  178. }
  179. });
  180. }
  181.  
  182. function fadeIn(element) {
  183. element.style.opacity = '0';
  184. element.style.display = 'block';
  185. setTimeout(() => element.style.opacity = '1');
  186. }
  187.  
  188. function downloadPreview(link) {
  189. const showAnswers = link.localName != 'a';
  190. const cached = readCache(link.href);
  191. if (cached)
  192. return showPreview(Object.assign(cached, {showAnswers}));
  193.  
  194. preview.timerCursor = setTimeout(() => {
  195. preview.timerCursor = 0;
  196. link.style.cursor = 'wait';
  197. }, BUSY_CURSOR_DELAY);
  198.  
  199. doXHR(link.href).then(r => {
  200. const html = r.responseText;
  201. const finalUrl = r.finalUrl;
  202. if (link.matches(':hover') || preview.frame && preview.frame.matches(':hover'))
  203. return {
  204. html,
  205. finalUrl,
  206. lastActivity: showPreview({finalUrl, html, showAnswers}),
  207. };
  208. }).then(({html, finalUrl, lastActivity} = {}) => {
  209. if (preview.timerCursor)
  210. clearTimeout(preview.timerCursor), preview.timerCursor = 0;
  211. if (link.style.cursor == 'wait')
  212. link.style.cursor = '';
  213. if (lastActivity) {
  214. const inactiveDays = Math.max(0, (Date.now() - lastActivity) / (24 * 3600 * 1000));
  215. const cacheDuration = CACHE_DURATION * Math.pow(Math.log(inactiveDays + 1) + 1, 2);
  216. setTimeout(writeCache, 1000, {url: link.href, finalUrl, html, cacheDuration});
  217. }
  218. });
  219. }
  220.  
  221. function initPreview() {
  222. preview.frame = document.createElement('iframe');
  223. preview.frame.id = 'SEpreview';
  224. document.body.appendChild(preview.frame);
  225. makeResizable();
  226.  
  227. lockScroll.attach = e => {
  228. if (lockScroll.pos)
  229. return;
  230. lockScroll.pos = {x: scrollX, y: scrollY};
  231. $on('scroll', document, lockScroll.run);
  232. $on('mouseover', document, lockScroll.detach);
  233. };
  234. lockScroll.run = e => scrollTo(lockScroll.pos.x, lockScroll.pos.y);
  235. lockScroll.detach = e => {
  236. if (!lockScroll.pos)
  237. return;
  238. lockScroll.pos = null;
  239. $off('mouseover', document, lockScroll.detach);
  240. $off('scroll', document, lockScroll.run);
  241. };
  242.  
  243. const killer = mutations => mutations.forEach(m => [...m.addedNodes].forEach(n => n.remove()));
  244. const killerMO = {
  245. head: new MutationObserver(killer),
  246. documentElement: new MutationObserver(killer),
  247. };
  248. preview.killInvaders = {
  249. start: () => Object.keys(killerMO).forEach(k => killerMO[k].observe(preview.frame.contentDocument[k], {childList: true})),
  250. stop: () => Object.keys(killerMO).forEach(k => killerMO[k].disconnect()),
  251. };
  252. }
  253.  
  254. function showPreview({finalUrl, html, doc, showAnswers}) {
  255. doc = doc || new DOMParser().parseFromString(html, 'text/html');
  256. if (!doc || !doc.head)
  257. return error('no HEAD in the document received for', finalUrl);
  258.  
  259. if (!$('base', doc))
  260. doc.head.insertAdjacentHTML('afterbegin', `<base href="${finalUrl}">`);
  261.  
  262. const answerIdMatch = !showAnswers
  263. ? finalUrl.match(/questions\/\d+\/[^\/]+\/(\d+)/)
  264. : [0, ($('[id^="answer-"]', doc) || {id:''}).id.replace(/^answer-/, '')];
  265. const isQuestion = !answerIdMatch;
  266. const postNumber = isQuestion ? finalUrl.match(/\d+/)[0] : answerIdMatch[1];
  267. const postId = answerIdMatch ? '#answer-' + answerIdMatch[1] : '#question';
  268. const post = $(postId + ' .post-text', doc);
  269. if (!post)
  270. return error('No parsable post found', doc);
  271. const isDeleted = !!post.closest('.deleted-answer');
  272. const title = $('meta[property="og:title"]', doc).content;
  273. const status = isQuestion && !$('.question-status', post) ? $('.question-status', doc) : null;
  274. const isClosed = $('.question-originals-of-duplicate, .close-as-off-topic-status-list, .close-status-suffix', doc);
  275. const comments = $(`${postId} .comments`, doc);
  276. const commentsHidden = +$('[data-remaining-comments-count]', comments).dataset.remainingCommentsCount;
  277. const commentsShowLink = commentsHidden && $(`${postId} .js-show-link.comments-link`, doc);
  278. const finalUrlOfQuestion = getCacheableUrl(finalUrl);
  279. const lastActivity = tryCatch(() => new Date($('.lastactivity-link', doc).title).getTime()) || Date.now();
  280. const answers = $$('.answer', doc);
  281. const hasAnswers = answers.length > (isQuestion ? 0 : 1);
  282.  
  283. markPreviewableLinks(doc);
  284. $$remove('script', doc);
  285.  
  286. if (!preview.frame)
  287. initPreview();
  288.  
  289. let pvDoc, pvWin;
  290. preview.frame.style.display = '';
  291. preview.frame.setAttribute('SEpreview-type',
  292. isDeleted ? 'deleted' : isQuestion ? (isClosed ? 'closed' : 'question') : 'answer');
  293. preview.frame.classList.toggle('SEpreview-hasAnswers', hasAnswers);
  294.  
  295. return onFrameReady(preview.frame).then(
  296. () => {
  297. pvDoc = preview.frame.contentDocument;
  298. pvWin = preview.frame.contentWindow;
  299. initPolyfills(pvWin);
  300. preview.killInvaders.stop();
  301. })
  302. .then(addStyles)
  303. .then(render)
  304. .then(show)
  305. .then(() => lastActivity);
  306.  
  307. function markPreviewableLinks(container) {
  308. for (let link of $$('a:not(.SEpreviewable)', container)) {
  309. if (rxPreviewable.test(link.href)) {
  310. link.removeAttribute('title');
  311. link.classList.add('SEpreviewable');
  312. }
  313. }
  314. }
  315.  
  316. function markHoverableUsers(container) {
  317. for (let link of $$('a[href*="/users/"]', container)) {
  318. if (rxPreviewableSite.test(link.href) && link.pathname.match(/^\/users\/\d+/)) {
  319. link.onmouseover = loadUserCard;
  320. link.classList.add('SEpreview-userLink');
  321. }
  322. }
  323. }
  324.  
  325. function addStyles() {
  326. const SEpreviewStyles = $replaceOrCreate({
  327. id: 'SEpreviewStyles',
  328. tag: 'style', parent: pvDoc.head, className: 'SEpreview-reuse',
  329. innerHTML: preview.stylesOverride,
  330. });
  331. $replaceOrCreate($$('style', doc).map(e => ({
  332. id: 'SEpreview' + e.innerHTML.replace(/\W+/g, '').length,
  333. tag: 'style', before: SEpreviewStyles, className: 'SEpreview-reuse',
  334. innerHTML: e.innerHTML,
  335. })));
  336. return onStyleSheetsReady({
  337. doc: pvDoc,
  338. urls: $$('link[rel="stylesheet"]', doc).map(e => e.href),
  339. onBeforeRequest: preview.frame.style.opacity != '1' ? null : () => {
  340. preview.frame.style.transition = 'border-color .5s ease-in-out';
  341. $on('transitionend', preview.frame, () => preview.frame.style.transition = '', {once: true});
  342. },
  343. }).then(els => {
  344. els.forEach(e => e && (e.className = 'SEpreview-reuse'));
  345. });
  346. }
  347.  
  348. function render() {
  349. pvDoc.body.setAttribute('SEpreview-type', preview.frame.getAttribute('SEpreview-type'));
  350.  
  351. $replaceOrCreate([{
  352. // base
  353. id: 'SEpreview-base', tag: 'base',
  354. parent: pvDoc.head,
  355. href: $('base', doc).href,
  356. }, {
  357. // title
  358. id: 'SEpreview-title', tag: 'a',
  359. parent: pvDoc.body, className: 'SEpreviewable',
  360. href: finalUrlOfQuestion,
  361. textContent: title,
  362. }, {
  363. // close button
  364. id: 'SEpreview-close',
  365. parent: pvDoc.body,
  366. title: 'Or press Esc key while the preview is focused (also when just shown)',
  367. }, {
  368. // vote count, date, views#
  369. id: 'SEpreview-meta',
  370. parent: pvDoc.body,
  371. innerHTML: [
  372. $text('.vote-count-post', post.closest('.post-layout')).replace(/(-?)(\d+)/,
  373. (s, sign, v) => s == '0' ? '' : `<b>${s}</b> vote${+v > 1 ? 's' : ''}, `),
  374. isQuestion
  375. ? $$('#qinfo tr', doc)
  376. .map(row => $$('.label-key', row).map($text).join(' '))
  377. .join(', ').replace(/^((.+?) (.+?), .+?), .+? \3$/, '$1')
  378. : [...$$('.user-action-time', post.closest('.answer'))]
  379. .reverse().map($text).join(', ')
  380. ].join('')
  381. }, {
  382. // content wrapper
  383. id: 'SEpreview-body',
  384. parent: pvDoc.body,
  385. className: isDeleted ? 'deleted-answer' : '',
  386. children: [status, post.parentElement, comments, commentsShowLink],
  387. }]);
  388.  
  389. // delinkify/remove non-functional items in post-menu
  390. $$remove('.short-link, .flag-post-link', pvDoc);
  391. $$('.post-menu a:not(.edit-post)', pvDoc).forEach(a => {
  392. if (a.children.length)
  393. a.outerHTML = `<span>${a.innerHTML}</span>`;
  394. else
  395. a.remove();
  396. });
  397.  
  398. // add a timeline link
  399. $('.post-menu', pvDoc).insertAdjacentHTML('beforeend',
  400. '<span class="lsep">|</span>' +
  401. `<a href="/posts/${postNumber}/timeline">timeline</a>`);
  402.  
  403. // prettify code blocks
  404. const codeBlocks = $$('pre code', pvDoc);
  405. if (codeBlocks.length) {
  406. codeBlocks.forEach(e => e.parentElement.classList.add('prettyprint'));
  407. if (!pvWin.StackExchange) {
  408. pvWin.StackExchange = {};
  409. let script = $scriptIn(pvDoc.head);
  410. script.text = 'StackExchange = {}';
  411. script = $scriptIn(pvDoc.head);
  412. script.src = 'https://cdn.sstatic.net/Js/prettify-full.en.js';
  413. script.setAttribute('onload', 'prettyPrint()');
  414. } else
  415. $scriptIn(pvDoc.body).text = 'prettyPrint()';
  416. }
  417.  
  418. // render bottom shelf
  419. if (hasAnswers) {
  420. $replaceOrCreate({
  421. id: 'SEpreview-answers',
  422. parent: pvDoc.body,
  423. innerHTML: answers.map(renderShelfAnswer).join(' '),
  424. });
  425. } else
  426. $$remove('#SEpreview-answers', pvDoc);
  427.  
  428. // cleanup leftovers from previously displayed post and foreign elements not injected by us
  429. $$('style, link, body script, html > *:not(head):not(body), .post-menu .lsep + .lsep', pvDoc).forEach(e => {
  430. if (e.classList.contains('SEpreview-reuse'))
  431. e.classList.remove('SEpreview-reuse');
  432. else
  433. e.remove();
  434. });
  435. }
  436.  
  437. function renderShelfAnswer(e) {
  438. const shortUrl = $('.short-link', e).href.replace(/(\d+)\/\d+/, '$1');
  439. const extraClasses = (e.matches(postId) ? ' SEpreviewed' : '') +
  440. (e.matches('.deleted-answer') ? ' deleted-answer' : '') +
  441. ($('.vote-accepted-on', e) ? ' SEpreview-accepted' : '');
  442. const author = $('.post-signature:last-child', e);
  443. const title = $text('.user-details a', author) + ' (rep ' +
  444. $text('.reputation-score', author) + ')\n' +
  445. $text('.user-action-time', author);
  446. const gravatar = $('img, .anonymous-gravatar, .community-wiki', author);
  447. return (
  448. `<a href="${shortUrl}" title="${title}" class="SEpreviewable${extraClasses}">` +
  449. $text('.vote-count-post', e).replace(/^0$/, '&nbsp;') + ' ' +
  450. (!gravatar ? '' : gravatar.src ? `<img src="${gravatar.src}">` : gravatar.outerHTML) +
  451. '</a>');
  452. }
  453.  
  454. function show() {
  455. pvDoc.onmouseover = lockScroll.attach;
  456. pvDoc.onclick = onClick;
  457. pvDoc.onkeydown = e => { if (!hasKeyModifiers(e) && e.keyCode == 27) hide() };
  458. pvWin.onmessage = e => { if (e.data == 'SEpreview-hidden') hide({fade: true}) };
  459.  
  460. markHoverableUsers(pvDoc);
  461. preview.killInvaders.start();
  462.  
  463. $('#SEpreview-body', pvDoc).scrollTop = 0;
  464. preview.frame.style.opacity = '1';
  465. preview.frame.focus();
  466. }
  467.  
  468. function hide({fade = false} = {}) {
  469. releaseLinkListeners();
  470. releasePreviewListeners();
  471. const cleanup = () => preview.frame.style.opacity == '0' && $removeChildren(pvDoc.body);
  472. if (fade)
  473. fadeOut(preview.frame).then(cleanup);
  474. else {
  475. preview.frame.style.opacity = '0';
  476. preview.frame.style.display = 'none';
  477. cleanup();
  478. }
  479. }
  480.  
  481. function releasePreviewListeners(e) {
  482. pvWin.onmessage = null;
  483. pvDoc.onmouseover = null;
  484. pvDoc.onclick = null;
  485. pvDoc.onkeydown = null;
  486. }
  487.  
  488. function onClick(e) {
  489. if (e.target.id == 'SEpreview-close')
  490. return hide();
  491.  
  492. const link = e.target.closest('a');
  493. if (!link)
  494. return;
  495.  
  496. if (link.matches('.js-show-link.comments-link')) {
  497. fadeOut(link, 0.5);
  498. loadComments();
  499. return e.preventDefault();
  500. }
  501.  
  502. if (e.button || hasKeyModifiers(e) || !link.matches('.SEpreviewable'))
  503. return (link.target = '_blank');
  504.  
  505. e.preventDefault();
  506.  
  507. if (link.id == 'SEpreview-title')
  508. showPreview({doc, finalUrl: finalUrlOfQuestion});
  509. else if (link.matches('#SEpreview-answers a'))
  510. showPreview({doc, finalUrl: finalUrlOfQuestion + '/' + link.pathname.match(/\/(\d+)/)[1]});
  511. else
  512. downloadPreview(link);
  513. }
  514.  
  515. function loadComments() {
  516. const url = new URL(finalUrl).origin + '/posts/' + comments.id.match(/\d+/)[0] + '/comments';
  517. doXHR(url).then(r => {
  518. const list = $(`#${comments.id} .comments-list`, pvDoc);
  519. const oldIds = new Set([...list.children].map(e => e.id));
  520. list.innerHTML = r.responseText;
  521. list.closest('.comments').style.display = 'block';
  522. for (const cmt of list.children)
  523. if (!oldIds.has(cmt.id))
  524. cmt.classList.add('new-comment-highlight');
  525. markPreviewableLinks(list);
  526. markHoverableUsers(list);
  527. });
  528. }
  529.  
  530. function loadUserCard(e, ready) {
  531. if (ready !== true)
  532. return setTimeout(loadUserCard, PREVIEW_DELAY * 2, e, true);
  533. const link = e.target.closest('a');
  534. if (!link.matches(':hover'))
  535. return;
  536. let timer;
  537. let userCard = link.nextElementSibling;
  538. if (userCard && userCard.matches('.SEpreview-userCard'))
  539. return fadeInUserCard();
  540. const url = link.origin + '/users/user-info/' + link.pathname.match(/\d+/)[0];
  541.  
  542. Promise.resolve(
  543. readCache(url) ||
  544. doXHR(url).then(r => {
  545. writeCache({url, html: r.responseText, cacheDuration: CACHE_DURATION * 100});
  546. return {html: r.responseText};
  547. })
  548. ).then(renderUserCard);
  549.  
  550. function renderUserCard({html}) {
  551. const linkBounds = link.getBoundingClientRect();
  552. const wrapperBounds = $('#SEpreview-body', pvDoc).getBoundingClientRect();
  553. userCard = $replaceOrCreate({id: 'user-menu-tmp', className: 'SEpreview-userCard', innerHTML: html, after: link});
  554. userCard.style.left = Math.min(linkBounds.left - 20, pvWin.innerWidth - 350) + 'px';
  555. if (linkBounds.bottom + 100 > wrapperBounds.bottom)
  556. userCard.style.marginTop = '-5rem';
  557. userCard.onmouseout = e => {
  558. if (e.target != userCard || userCard.contains(e.relatedTarget))
  559. if (e.relatedTarget) // null if mouse is outside the preview
  560. return;
  561. fadeOut(userCard);
  562. clearTimeout(timer);
  563. timer = 0;
  564. };
  565. fadeInUserCard();
  566. }
  567.  
  568. function fadeInUserCard() {
  569. if (userCard.id != 'user-menu') {
  570. $$('#user-menu', pvDoc).forEach(e => e.id = e.style.display = '' );
  571. userCard.id = 'user-menu';
  572. }
  573. userCard.style.opacity = '0';
  574. userCard.style.display = 'block';
  575. timer = setTimeout(() => timer && (userCard.style.opacity = '1'));
  576. }
  577. }
  578. }
  579.  
  580. function getCacheableUrl(url) {
  581. // strips queries and hashes and anything after the main part https://site/questions/####/title/
  582. return url
  583. .replace(/(\/q(?:uestions)?\/\d+\/[^\/]+).*/, '$1')
  584. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  585. .replace(/[?#].*$/, '');
  586. }
  587.  
  588. function readCache(url) {
  589. const keyUrl = getCacheableUrl(url);
  590. const meta = (localStorage[keyUrl] || '').split('\t');
  591. const expired = +meta[0] < Date.now();
  592. const finalUrl = meta[1] || url;
  593. const keyFinalUrl = meta[1] ? getCacheableUrl(finalUrl) : keyUrl;
  594. return !expired && {
  595. finalUrl,
  596. html: LZString.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  597. };
  598. }
  599.  
  600. function writeCache({url, finalUrl, html, cacheDuration = CACHE_DURATION, cleanupRetry}) {
  601. // keyUrl=expires
  602. // redirected keyUrl=expires+finalUrl, and an additional entry keyFinalUrl=expires is created
  603. // keyFinalUrl\thtml=html
  604. cacheDuration = Math.max(CACHE_DURATION, Math.min(0xDEADBEEF, Math.floor(cacheDuration)));
  605. finalUrl = (finalUrl || url).replace(/[?#].*/, '');
  606. const keyUrl = getCacheableUrl(url);
  607. const keyFinalUrl = getCacheableUrl(finalUrl);
  608. const expires = Date.now() + cacheDuration;
  609. const lz = LZString.compressToUTF16(html);
  610. if (!tryCatch(() => localStorage[keyFinalUrl + '\thtml'] = lz)) {
  611. if (cleanupRetry)
  612. return error('localStorage write error');
  613. cleanupCache({aggressive: true});
  614. setIimeout(writeCache, 0, {url, finalUrl, html, cacheDuration, cleanupRetry: true});
  615. }
  616. localStorage[keyFinalUrl] = expires;
  617. if (keyUrl != keyFinalUrl)
  618. localStorage[keyUrl] = expires + '\t' + finalUrl;
  619. setTimeout(() => {
  620. [keyUrl, keyFinalUrl, keyFinalUrl + '\thtml'].forEach(e => localStorage.removeItem(e));
  621. }, cacheDuration + 1000);
  622. }
  623.  
  624. function cleanupCache({aggressive = false} = {}) {
  625. Object.keys(localStorage).forEach(k => {
  626. if (k.match(/^https?:\/\/[^\t]+$/)) {
  627. let meta = (localStorage[k] || '').split('\t');
  628. if (+meta[0] > Date.now() && !aggressive)
  629. return;
  630. if (meta[1])
  631. localStorage.removeItem(meta[1]);
  632. localStorage.removeItem(`${meta[1] || k}\thtml`);
  633. localStorage.removeItem(k);
  634. }
  635. });
  636. }
  637.  
  638. function onFrameReady(frame) {
  639. if (frame.contentDocument.readyState == 'complete')
  640. return Promise.resolve();
  641. else
  642. return new Promise(resolve => {
  643. $on('load', frame, function onLoad() {
  644. $off('load', frame, onLoad);
  645. resolve();
  646. });
  647. });
  648. }
  649.  
  650. function onStyleSheetsReady({urls, doc = document, onBeforeRequest = null}) {
  651. return Promise.all(
  652. urls.map(url => $(`link[href="${url}"]`, doc) || new Promise(resolve => {
  653. if (typeof onBeforeRequest == 'function')
  654. onBeforeRequest(url);
  655. doXHR(url).then(() => {
  656. const sheetElement = $replaceOrCreate({tag: 'link', href: url, rel: 'stylesheet', parent: doc.head});
  657. const timeout = setTimeout(doResolve, 100);
  658. sheetElement.onload = doResolve;
  659. function doResolve() {
  660. sheetElement.onload = null;
  661. clearTimeout(timeout);
  662. resolve(sheetElement);
  663. }
  664. }).catch(() => resolve());
  665. }))
  666. );
  667. }
  668.  
  669. function getURLregexForMatchedSites() {
  670. const sites = 'https?://(\\w*\\.)*(' + GM_info.script.matches.map(
  671. m => m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')).join('|') + ')/';
  672. return {
  673. full: new RegExp(sites + '(questions|q|a|posts\/comments)/\\d+'),
  674. siteOnly: new RegExp(sites),
  675. };
  676. }
  677.  
  678. function isLinkPreviewable(link) {
  679. if (!rxPreviewable.test(link.href) || link.matches('.short-link'))
  680. return false;
  681. const inPreview = preview.frame && link.ownerDocument == preview.frame.contentDocument;
  682. const pageUrls = inPreview ? getPageBaseUrls(preview.link.href) : thisPageUrls;
  683. const url = httpsUrl(link.href);
  684. return url.indexOf(pageUrls.base) &&
  685. url.indexOf(pageUrls.short);
  686. }
  687.  
  688. function getPageBaseUrls(url) {
  689. const base = httpsUrl((url.match(rxPreviewable) || [])[0]);
  690. return base ? {
  691. base,
  692. short: base.replace('/questions/', '/q/'),
  693. } : {};
  694. }
  695.  
  696. function httpsUrl(url) {
  697. return (url || '').replace(/^http:/, 'https:');
  698. }
  699.  
  700. function doXHR(options) {
  701. options = typeof options == 'string' ? {url: options} : options;
  702. options = Object.assign({method: 'GET'}, options);
  703. const useHttpUrl = () => options.url = options.url.replace(/^https/, 'http');
  704. const hostname = new URL(options.url).hostname;
  705. if (xhrNoSSL.has(hostname))
  706. useHttpUrl();
  707. else {
  708. options.url = options.url.replace(/^http:/, 'https:');
  709. options.onerror = e => {
  710. useHttpUrl();
  711. xhrNoSSL.add(hostname);
  712. xhr = GM_xmlhttpRequest(options);
  713. };
  714. }
  715. if (options.onload)
  716. return (xhr = GM_xmlhttpRequest(options));
  717. else
  718. return new Promise(resolve => {
  719. xhr = GM_xmlhttpRequest(Object.assign(options, {onload: resolve}));
  720. });
  721. }
  722.  
  723. function makeResizable() {
  724. let heightOnClick;
  725. const pvDoc = preview.frame.contentDocument;
  726. const topBorderHeight = (preview.frame.offsetHeight - preview.frame.clientHeight) / 2;
  727. setHeight(GM_getValue('height', innerHeight / 3) |0);
  728.  
  729. // mouseover in the main page is fired only on the border of the iframe
  730. $on('mouseover', preview.frame, onOverAttach);
  731. $on('message', preview.frame.contentWindow, e => {
  732. if (e.data != 'SEpreview-hidden')
  733. return;
  734. if (heightOnClick) {
  735. releaseResizeListeners();
  736. setHeight(heightOnClick);
  737. }
  738. if (preview.frame.style.cursor)
  739. onOutDetach();
  740. });
  741.  
  742. function setCursorStyle(e) {
  743. return (preview.frame.style.cursor = e.offsetY <= 0 ? 's-resize' : '');
  744. }
  745.  
  746. function onOverAttach(e) {
  747. setCursorStyle(e);
  748. $on('mouseout', preview.frame, onOutDetach);
  749. $on('mousemove', preview.frame, setCursorStyle);
  750. $on('mousedown', onDownStartResize);
  751. }
  752.  
  753. function onOutDetach(e) {
  754. if (!e || !e.relatedTarget || !pvDoc.contains(e.relatedTarget)) {
  755. $off('mouseout', preview.frame, onOutDetach);
  756. $off('mousemove', preview.frame, setCursorStyle);
  757. $off('mousedown', onDownStartResize);
  758. preview.frame.style.cursor = '';
  759. }
  760. }
  761.  
  762. function onDownStartResize(e) {
  763. if (!preview.frame.style.cursor)
  764. return;
  765. heightOnClick = preview.frame.clientHeight;
  766.  
  767. $off('mouseover', preview.frame, onOverAttach);
  768. $off('mousemove', preview.frame, setCursorStyle);
  769. $off('mouseout', preview.frame, onOutDetach);
  770.  
  771. document.documentElement.style.cursor = 's-resize';
  772. document.body.style.cssText += ';pointer-events: none!important';
  773. $on('mousemove', onMoveResize);
  774. $on('mouseup', onUpConfirm);
  775. }
  776.  
  777. function onMoveResize(e) {
  778. setHeight(innerHeight - topBorderHeight - e.clientY);
  779. getSelection().removeAllRanges();
  780. preview.frame.contentWindow.getSelection().removeAllRanges();
  781. }
  782.  
  783. function onUpConfirm(e) {
  784. GM_setValue('height', pvDoc.body.clientHeight);
  785. releaseResizeListeners(e);
  786. }
  787.  
  788. function releaseResizeListeners() {
  789. $off('mouseup', releaseResizeListeners);
  790. $off('mousemove', onMoveResize);
  791.  
  792. $on('mouseover', preview.frame, onOverAttach);
  793. onOverAttach({});
  794.  
  795. document.body.style.pointerEvents = '';
  796. document.documentElement.style.cursor = '';
  797. heightOnClick = 0;
  798. }
  799. }
  800.  
  801. function setHeight(height) {
  802. const currentHeight = preview.frame.clientHeight;
  803. const borderHeight = preview.frame.offsetHeight - currentHeight;
  804. const newHeight = Math.max(MIN_HEIGHT, Math.min(innerHeight - borderHeight, height));
  805. if (newHeight != currentHeight)
  806. preview.frame.style.height = newHeight + 'px';
  807. }
  808.  
  809. function $(selector, node = document) {
  810. return node.querySelector(selector);
  811. }
  812.  
  813. function $$(selector, node = document) {
  814. return node.querySelectorAll(selector);
  815. }
  816.  
  817. function $text(selector, node = document) {
  818. const e = typeof selector == 'string' ? node.querySelector(selector) : selector;
  819. return e ? e.textContent.trim() : '';
  820. }
  821.  
  822. function $$remove(selector, node = document) {
  823. node.querySelectorAll(selector).forEach(e => e.remove());
  824. }
  825.  
  826. function $appendChildren(newParent, elements) {
  827. const doc = newParent.ownerDocument;
  828. const fragment = doc.createDocumentFragment();
  829. for (let e of elements)
  830. if (e)
  831. fragment.appendChild(e.ownerDocument == doc ? e : doc.importNode(e, true));
  832. newParent.appendChild(fragment);
  833. }
  834.  
  835. function $removeChildren(el) {
  836. if (el.children.length)
  837. el.innerHTML = ''; // the fastest as per https://jsperf.com/innerhtml-vs-removechild/256
  838. }
  839.  
  840. function $replaceOrCreate(options) {
  841. if (typeof options.map == 'function')
  842. return options.map($replaceOrCreate);
  843. const doc = (options.parent || options.before || options.after).ownerDocument;
  844. const el = doc.getElementById(options.id) || doc.createElement(options.tag || 'div');
  845. for (let key of Object.keys(options)) {
  846. const value = options[key];
  847. switch (key) {
  848. case 'tag':
  849. case 'parent':
  850. case 'before':
  851. case 'after':
  852. break;
  853. case 'dataset':
  854. for (let dataAttr of Object.keys(value))
  855. if (el.dataset[dataAttr] != value[dataAttr])
  856. el.dataset[dataAttr] = value[dataAttr];
  857. break;
  858. case 'children':
  859. $removeChildren(el);
  860. $appendChildren(el, options[key]);
  861. break;
  862. default:
  863. if (key in el && el[key] != value)
  864. el[key] = value;
  865. }
  866. }
  867. if (!el.parentElement)
  868. (options.parent || (options.before || options.after).parentElement)
  869. .insertBefore(el, options.before || (options.after && options.after.nextElementSibling));
  870. return el;
  871. }
  872.  
  873. function $scriptIn(element) {
  874. return element.appendChild(element.ownerDocument.createElement('script'));
  875. }
  876.  
  877. function $on(eventName, ...args) {
  878. // eventName, selector, node, callback, options
  879. // eventName, selector, callback, options
  880. // eventName, node, callback, options
  881. // eventName, callback, options
  882. let i = 0;
  883. const selector = typeof args[i] == 'string' ? args[i++] : null;
  884. const node = args[i].nodeType ? args[i++] : document;
  885. const callback = args[i++];
  886. const options = args[i];
  887.  
  888. const actualNode = selector ? node.querySelector(selector) : node;
  889. const method = this == 'removeEventListener' ? this : 'addEventListener';
  890. actualNode[method](eventName, callback, options);
  891. }
  892.  
  893. function $off() {
  894. $on.apply('removeEventListener', arguments);
  895. }
  896.  
  897. function hasKeyModifiers(e) {
  898. return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey;
  899. }
  900.  
  901. function log(...args) {
  902. console.log(GM_info.script.name, ...args);
  903. }
  904.  
  905. function error(...args) {
  906. console.error(GM_info.script.name, ...args);
  907. console.trace();
  908. }
  909.  
  910. function tryCatch(fn) {
  911. try { return fn() }
  912. catch(e) {}
  913. }
  914.  
  915. function initPolyfills(context = window) {
  916. for (let method of ['forEach', 'filter', 'map', 'every', 'some', context.Symbol.iterator])
  917. if (!context.NodeList.prototype[method])
  918. context.NodeList.prototype[method] = context.Array.prototype[method];
  919. }
  920.  
  921. function initStyles() {
  922. GM_addStyle(`
  923. #SEpreview {
  924. all: unset;
  925. box-sizing: content-box;
  926. width: 720px; /* 660px + 30px + 30px */
  927. height: 33%;
  928. min-height: ${MIN_HEIGHT}px;
  929. position: fixed;
  930. transition: opacity .25s cubic-bezier(.88,.02,.92,.66);
  931. right: 0;
  932. bottom: 0;
  933. padding: 0;
  934. margin: 0;
  935. background: white;
  936. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  937. z-index: 999999;
  938. border-width: 8px;
  939. border-style: solid;
  940. border-color: transparent;
  941. }
  942. #SEpreview:not([style*="opacity: 1"]) {
  943. pointer-events: none;
  944. }
  945. #SEpreview[SEpreview-type="question"].SEpreview-hasAnswers {
  946. border-image: linear-gradient(rgb(${COLORS.question.backRGB}) 66%, rgb(${COLORS.answer.backRGB})) 1 1;
  947. }
  948. `
  949. + Object.keys(COLORS).map(s => `
  950. #SEpreview[SEpreview-type="${s}"] {
  951. border-color: rgb(${COLORS[s].backRGB});
  952. }
  953. `).join('')
  954. );
  955.  
  956. preview.stylesOverride = `
  957. html, body {
  958. min-width: unset!important;
  959. box-shadow: none!important;
  960. padding: 0!important;
  961. margin: 0!important;
  962. background: unset!important;;
  963. }
  964. body {
  965. display: flex;
  966. flex-direction: column;
  967. height: 100vh;
  968. }
  969. #SEpreview-body a.SEpreviewable {
  970. text-decoration: underline !important;
  971. text-decoration-skip: ink;
  972. }
  973. #SEpreview-title {
  974. all: unset;
  975. display: block;
  976. padding: 20px 30px;
  977. font-weight: bold;
  978. font-size: 18px;
  979. line-height: 1.2;
  980. cursor: pointer;
  981. }
  982. #SEpreview-title:hover {
  983. text-decoration: underline;
  984. text-decoration-skip: ink;
  985. }
  986. #SEpreview-meta {
  987. position: absolute;
  988. top: .5ex;
  989. left: 30px;
  990. opacity: 0.5;
  991. }
  992. #SEpreview-title:hover + #SEpreview-meta {
  993. opacity: 1.0;
  994. }
  995.  
  996. #SEpreview-close {
  997. position: absolute;
  998. top: 0;
  999. right: 0;
  1000. flex: none;
  1001. cursor: pointer;
  1002. padding: .5ex 1ex;
  1003. }
  1004. #SEpreview-close:after {
  1005. content: "x"; }
  1006. #SEpreview-close:active {
  1007. background-color: rgba(0,0,0,.1); }
  1008. #SEpreview-close:hover {
  1009. background-color: rgba(0,0,0,.05); }
  1010.  
  1011. #SEpreview-body {
  1012. position: relative;
  1013. padding: 30px!important;
  1014. overflow: auto;
  1015. flex-grow: 2;
  1016. }
  1017. #SEpreview-body > .question-status {
  1018. margin: -30px -30px 30px;
  1019. padding-left: 30px;
  1020. }
  1021. #SEpreview-body .question-originals-of-duplicate {
  1022. margin: -30px -30px 30px;
  1023. padding: 15px 30px;
  1024. }
  1025. #SEpreview-body > .question-status h2 {
  1026. font-weight: normal;
  1027. }
  1028.  
  1029. #SEpreview-answers {
  1030. all: unset;
  1031. display: block;
  1032. padding: 10px 10px 10px 30px;
  1033. font-weight: bold;
  1034. line-height: 1.0;
  1035. border-top: 4px solid rgba(${COLORS.answer.backRGB}, 0.37);
  1036. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  1037. color: ${COLORS.answer.fore};
  1038. word-break: break-word;
  1039. }
  1040. #SEpreview-answers:before {
  1041. content: "Answers:";
  1042. margin-right: 1ex;
  1043. font-size: 20px;
  1044. line-height: 48px;
  1045. }
  1046. #SEpreview-answers a {
  1047. color: ${COLORS.answer.fore};
  1048. text-decoration: none;
  1049. font-size: 11px;
  1050. font-family: monospace;
  1051. width: 32px;
  1052. display: inline-block;
  1053. vertical-align: top;
  1054. margin: 0 1ex 1ex 0;
  1055. }
  1056. #SEpreview-answers img {
  1057. width: 32px;
  1058. height: 32px;
  1059. }
  1060. .SEpreview-accepted {
  1061. position: relative;
  1062. }
  1063. .SEpreview-accepted:after {
  1064. content: "✔";
  1065. position: absolute;
  1066. display: block;
  1067. top: 1.3ex;
  1068. right: -0.7ex;
  1069. font-size: 32px;
  1070. color: #4bff2c;
  1071. text-shadow: 1px 2px 2px rgba(0,0,0,0.5);
  1072. }
  1073. #SEpreview-answers a.deleted-answer {
  1074. color: ${COLORS.deleted.fore};
  1075. background: transparent;
  1076. opacity: 0.25;
  1077. }
  1078. #SEpreview-answers a.deleted-answer:hover {
  1079. opacity: 1.0;
  1080. }
  1081. #SEpreview-answers a:hover:not(.SEpreviewed) {
  1082. text-decoration: underline;
  1083. text-decoration-skip: ink;
  1084. }
  1085. #SEpreview-answers a.SEpreviewed {
  1086. background-color: ${COLORS.answer.fore};
  1087. color: ${COLORS.answer.foreInv};
  1088. position: relative;
  1089. }
  1090. #SEpreview-answers a.SEpreviewed:before {
  1091. display: block;
  1092. content: " ";
  1093. position: absolute;
  1094. left: -4px;
  1095. top: -4px;
  1096. right: -4px;
  1097. bottom: -4px;
  1098. border: 4px solid ${COLORS.answer.fore};
  1099. }
  1100.  
  1101. #SEpreview-body .comment-edit,
  1102. #SEpreview-body .delete-tag,
  1103. #SEpreview-body .comment-actions td:last-child {
  1104. display: none;
  1105. }
  1106. #SEpreview-body .comments {
  1107. border-top: none;
  1108. }
  1109. #SEpreview-body .comments tr:last-child td {
  1110. border-bottom: none;
  1111. }
  1112. #SEpreview-body .comments .new-comment-highlight .comment-text {
  1113. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1114. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1115. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1116. }
  1117.  
  1118. #SEpreview-body .post-menu > span {
  1119. opacity: .35;
  1120. }
  1121. #SEpreview-body #user-menu {
  1122. position: absolute;
  1123. }
  1124. .SEpreview-userCard {
  1125. position: absolute;
  1126. display: none;
  1127. transition: opacity .25s cubic-bezier(.88,.02,.92,.66) .5s;
  1128. margin-top: -3rem;
  1129. }
  1130.  
  1131. #SEpreview-body .wmd-preview a:not(.post-tag),
  1132. #SEpreview-body .post-text a:not(.post-tag),
  1133. #SEpreview-body .comment-copy a:not(.post-tag) {
  1134. border-bottom: none;
  1135. }
  1136.  
  1137. @-webkit-keyframes highlight {
  1138. from {background-color: #ffcf78}
  1139. to {background-color: none}
  1140. }
  1141. `
  1142. + Object.keys(COLORS).map(s => `
  1143. body[SEpreview-type="${s}"] #SEpreview-title {
  1144. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  1145. color: ${COLORS[s].fore};
  1146. }
  1147. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar {
  1148. background-color: rgba(${COLORS[s].backRGB}, 0.1); }
  1149. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb {
  1150. background-color: rgba(${COLORS[s].backRGB}, 0.2); }
  1151. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:hover {
  1152. background-color: rgba(${COLORS[s].backRGB}, 0.3); }
  1153. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:active {
  1154. background-color: rgba(${COLORS[s].backRGB}, 0.75); }
  1155. `).join('')
  1156. + ['deleted', 'closed'].map(s => `
  1157. body[SEpreview-type="${s}"] #SEpreview-answers {
  1158. border-top-color: rgba(${COLORS[s].backRGB}, 0.37);
  1159. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  1160. color: ${COLORS[s].fore};
  1161. }
  1162. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed {
  1163. background-color: ${COLORS[s].fore};
  1164. color: ${COLORS[s].foreInv};
  1165. }
  1166. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed:after {
  1167. border-color: ${COLORS[s].fore};
  1168. }
  1169. `).join('');
  1170. }