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.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. // @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.style.pointerEvents = '';
  466. preview.frame.focus();
  467. }
  468.  
  469. function hide({fade = false} = {}) {
  470. releaseLinkListeners();
  471. releasePreviewListeners();
  472. const cleanup = () => preview.frame.style.opacity == '0' && $removeChildren(pvDoc.body);
  473. if (fade)
  474. fadeOut(preview.frame).then(cleanup);
  475. else {
  476. preview.frame.style.opacity = '0';
  477. preview.frame.style.display = 'none';
  478. cleanup();
  479. }
  480. }
  481.  
  482. function releasePreviewListeners(e) {
  483. pvWin.onmessage = null;
  484. pvDoc.onmouseover = null;
  485. pvDoc.onclick = null;
  486. pvDoc.onkeydown = null;
  487. }
  488.  
  489. function onClick(e) {
  490. if (e.target.id == 'SEpreview-close')
  491. return hide();
  492.  
  493. const link = e.target.closest('a');
  494. if (!link)
  495. return;
  496.  
  497. if (link.matches('.js-show-link.comments-link')) {
  498. fadeOut(link, 0.5);
  499. loadComments();
  500. return e.preventDefault();
  501. }
  502.  
  503. if (e.button || hasKeyModifiers(e) || !link.matches('.SEpreviewable'))
  504. return (link.target = '_blank');
  505.  
  506. e.preventDefault();
  507.  
  508. if (link.id == 'SEpreview-title')
  509. showPreview({doc, finalUrl: finalUrlOfQuestion});
  510. else if (link.matches('#SEpreview-answers a'))
  511. showPreview({doc, finalUrl: finalUrlOfQuestion + '/' + link.pathname.match(/\/(\d+)/)[1]});
  512. else
  513. downloadPreview(link);
  514. }
  515.  
  516. function loadComments() {
  517. const url = new URL(finalUrl).origin + '/posts/' + comments.id.match(/\d+/)[0] + '/comments';
  518. doXHR(url).then(r => {
  519. const list = $(`#${comments.id} .comments-list`, pvDoc);
  520. const oldIds = new Set([...list.children].map(e => e.id));
  521. list.innerHTML = r.responseText;
  522. list.closest('.comments').style.display = 'block';
  523. for (const cmt of list.children)
  524. if (!oldIds.has(cmt.id))
  525. cmt.classList.add('new-comment-highlight');
  526. markPreviewableLinks(list);
  527. markHoverableUsers(list);
  528. });
  529. }
  530.  
  531. function loadUserCard(e, ready) {
  532. if (ready !== true)
  533. return setTimeout(loadUserCard, PREVIEW_DELAY * 2, e, true);
  534. const link = e.target.closest('a');
  535. if (!link.matches(':hover'))
  536. return;
  537. let timer;
  538. let userCard = link.nextElementSibling;
  539. if (userCard && userCard.matches('.SEpreview-userCard'))
  540. return fadeInUserCard();
  541. const url = link.origin + '/users/user-info/' + link.pathname.match(/\d+/)[0];
  542.  
  543. Promise.resolve(
  544. readCache(url) ||
  545. doXHR(url).then(r => {
  546. writeCache({url, html: r.responseText, cacheDuration: CACHE_DURATION * 100});
  547. return {html: r.responseText};
  548. })
  549. ).then(renderUserCard);
  550.  
  551. function renderUserCard({html}) {
  552. const linkBounds = link.getBoundingClientRect();
  553. const wrapperBounds = $('#SEpreview-body', pvDoc).getBoundingClientRect();
  554. userCard = $replaceOrCreate({id: 'user-menu-tmp', className: 'SEpreview-userCard', innerHTML: html, after: link});
  555. userCard.style.left = Math.min(linkBounds.left - 20, pvWin.innerWidth - 350) + 'px';
  556. if (linkBounds.bottom + 100 > wrapperBounds.bottom)
  557. userCard.style.marginTop = '-5rem';
  558. userCard.onmouseout = e => {
  559. if (e.target != userCard || userCard.contains(e.relatedTarget))
  560. if (e.relatedTarget) // null if mouse is outside the preview
  561. return;
  562. fadeOut(userCard);
  563. clearTimeout(timer);
  564. timer = 0;
  565. };
  566. fadeInUserCard();
  567. }
  568.  
  569. function fadeInUserCard() {
  570. if (userCard.id != 'user-menu') {
  571. $$('#user-menu', pvDoc).forEach(e => e.id = e.style.display = '' );
  572. userCard.id = 'user-menu';
  573. }
  574. userCard.style.opacity = '0';
  575. userCard.style.display = 'block';
  576. timer = setTimeout(() => timer && (userCard.style.opacity = '1'));
  577. }
  578. }
  579. }
  580.  
  581. function getCacheableUrl(url) {
  582. // strips queries and hashes and anything after the main part https://site/questions/####/title/
  583. return url
  584. .replace(/(\/q(?:uestions)?\/\d+\/[^\/]+).*/, '$1')
  585. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  586. .replace(/[?#].*$/, '');
  587. }
  588.  
  589. function readCache(url) {
  590. const keyUrl = getCacheableUrl(url);
  591. const meta = (localStorage[keyUrl] || '').split('\t');
  592. const expired = +meta[0] < Date.now();
  593. const finalUrl = meta[1] || url;
  594. const keyFinalUrl = meta[1] ? getCacheableUrl(finalUrl) : keyUrl;
  595. return !expired && {
  596. finalUrl,
  597. html: LZString.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  598. };
  599. }
  600.  
  601. function writeCache({url, finalUrl, html, cacheDuration = CACHE_DURATION, cleanupRetry}) {
  602. // keyUrl=expires
  603. // redirected keyUrl=expires+finalUrl, and an additional entry keyFinalUrl=expires is created
  604. // keyFinalUrl\thtml=html
  605. cacheDuration = Math.max(CACHE_DURATION, Math.min(0xDEADBEEF, Math.floor(cacheDuration)));
  606. finalUrl = (finalUrl || url).replace(/[?#].*/, '');
  607. const keyUrl = getCacheableUrl(url);
  608. const keyFinalUrl = getCacheableUrl(finalUrl);
  609. const expires = Date.now() + cacheDuration;
  610. const lz = LZString.compressToUTF16(html);
  611. if (!tryCatch(() => localStorage[keyFinalUrl + '\thtml'] = lz)) {
  612. if (cleanupRetry)
  613. return error('localStorage write error');
  614. cleanupCache({aggressive: true});
  615. setIimeout(writeCache, 0, {url, finalUrl, html, cacheDuration, cleanupRetry: true});
  616. }
  617. localStorage[keyFinalUrl] = expires;
  618. if (keyUrl != keyFinalUrl)
  619. localStorage[keyUrl] = expires + '\t' + finalUrl;
  620. setTimeout(() => {
  621. [keyUrl, keyFinalUrl, keyFinalUrl + '\thtml'].forEach(e => localStorage.removeItem(e));
  622. }, cacheDuration + 1000);
  623. }
  624.  
  625. function cleanupCache({aggressive = false} = {}) {
  626. Object.keys(localStorage).forEach(k => {
  627. if (k.match(/^https?:\/\/[^\t]+$/)) {
  628. let meta = (localStorage[k] || '').split('\t');
  629. if (+meta[0] > Date.now() && !aggressive)
  630. return;
  631. if (meta[1])
  632. localStorage.removeItem(meta[1]);
  633. localStorage.removeItem(`${meta[1] || k}\thtml`);
  634. localStorage.removeItem(k);
  635. }
  636. });
  637. }
  638.  
  639. function onFrameReady(frame) {
  640. if (frame.contentDocument.readyState == 'complete')
  641. return Promise.resolve();
  642. else
  643. return new Promise(resolve => {
  644. $on('load', frame, function onLoad() {
  645. $off('load', frame, onLoad);
  646. resolve();
  647. });
  648. });
  649. }
  650.  
  651. function onStyleSheetsReady({urls, doc = document, onBeforeRequest = null}) {
  652. return Promise.all(
  653. urls.map(url => $(`link[href="${url}"]`, doc) || new Promise(resolve => {
  654. if (typeof onBeforeRequest == 'function')
  655. onBeforeRequest(url);
  656. doXHR(url).then(() => {
  657. const sheetElement = $replaceOrCreate({tag: 'link', href: url, rel: 'stylesheet', parent: doc.head});
  658. const timeout = setTimeout(doResolve, 100);
  659. sheetElement.onload = doResolve;
  660. function doResolve() {
  661. sheetElement.onload = null;
  662. clearTimeout(timeout);
  663. resolve(sheetElement);
  664. }
  665. }).catch(() => resolve());
  666. }))
  667. );
  668. }
  669.  
  670. function getURLregexForMatchedSites() {
  671. const sites = 'https?://(\\w*\\.)*(' + GM_info.script.matches.map(
  672. m => m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')).join('|') + ')/';
  673. return {
  674. full: new RegExp(sites + '(questions|q|a|posts\/comments)/\\d+'),
  675. siteOnly: new RegExp(sites),
  676. };
  677. }
  678.  
  679. function isLinkPreviewable(link) {
  680. if (!rxPreviewable.test(link.href) || link.matches('.short-link'))
  681. return false;
  682. const inPreview = preview.frame && link.ownerDocument == preview.frame.contentDocument;
  683. const pageUrls = inPreview ? getPageBaseUrls(preview.link.href) : thisPageUrls;
  684. const url = httpsUrl(link.href);
  685. return url.indexOf(pageUrls.base) &&
  686. url.indexOf(pageUrls.short);
  687. }
  688.  
  689. function getPageBaseUrls(url) {
  690. const base = httpsUrl((url.match(rxPreviewable) || [])[0]);
  691. return base ? {
  692. base,
  693. short: base.replace('/questions/', '/q/'),
  694. } : {};
  695. }
  696.  
  697. function httpsUrl(url) {
  698. return (url || '').replace(/^http:/, 'https:');
  699. }
  700.  
  701. function doXHR(options) {
  702. options = typeof options == 'string' ? {url: options} : options;
  703. options = Object.assign({method: 'GET'}, options);
  704. const useHttpUrl = () => options.url = options.url.replace(/^https/, 'http');
  705. const hostname = new URL(options.url).hostname;
  706. if (xhrNoSSL.has(hostname))
  707. useHttpUrl();
  708. else {
  709. options.url = options.url.replace(/^http:/, 'https:');
  710. options.onerror = e => {
  711. useHttpUrl();
  712. xhrNoSSL.add(hostname);
  713. xhr = GM_xmlhttpRequest(options);
  714. };
  715. }
  716. if (options.onload)
  717. return (xhr = GM_xmlhttpRequest(options));
  718. else
  719. return new Promise(resolve => {
  720. xhr = GM_xmlhttpRequest(Object.assign(options, {onload: resolve}));
  721. });
  722. }
  723.  
  724. function makeResizable() {
  725. let heightOnClick;
  726. const pvDoc = preview.frame.contentDocument;
  727. const topBorderHeight = (preview.frame.offsetHeight - preview.frame.clientHeight) / 2;
  728. setHeight(GM_getValue('height', innerHeight / 3) |0);
  729.  
  730. // mouseover in the main page is fired only on the border of the iframe
  731. $on('mouseover', preview.frame, onOverAttach);
  732. $on('message', preview.frame.contentWindow, e => {
  733. if (e.data != 'SEpreview-hidden')
  734. return;
  735. if (heightOnClick) {
  736. releaseResizeListeners();
  737. setHeight(heightOnClick);
  738. }
  739. if (preview.frame.style.cursor)
  740. onOutDetach();
  741. });
  742.  
  743. function setCursorStyle(e) {
  744. return (preview.frame.style.cursor = e.offsetY <= 0 ? 's-resize' : '');
  745. }
  746.  
  747. function onOverAttach(e) {
  748. setCursorStyle(e);
  749. $on('mouseout', preview.frame, onOutDetach);
  750. $on('mousemove', preview.frame, setCursorStyle);
  751. $on('mousedown', onDownStartResize);
  752. }
  753.  
  754. function onOutDetach(e) {
  755. if (!e || !e.relatedTarget || !pvDoc.contains(e.relatedTarget)) {
  756. $off('mouseout', preview.frame, onOutDetach);
  757. $off('mousemove', preview.frame, setCursorStyle);
  758. $off('mousedown', onDownStartResize);
  759. preview.frame.style.cursor = '';
  760. }
  761. }
  762.  
  763. function onDownStartResize(e) {
  764. if (!preview.frame.style.cursor)
  765. return;
  766. heightOnClick = preview.frame.clientHeight;
  767.  
  768. $off('mouseover', preview.frame, onOverAttach);
  769. $off('mousemove', preview.frame, setCursorStyle);
  770. $off('mouseout', preview.frame, onOutDetach);
  771.  
  772. document.documentElement.style.cursor = 's-resize';
  773. document.body.style.cssText += ';pointer-events: none!important';
  774. $on('mousemove', onMoveResize);
  775. $on('mouseup', onUpConfirm);
  776. }
  777.  
  778. function onMoveResize(e) {
  779. setHeight(innerHeight - topBorderHeight - e.clientY);
  780. getSelection().removeAllRanges();
  781. preview.frame.contentWindow.getSelection().removeAllRanges();
  782. }
  783.  
  784. function onUpConfirm(e) {
  785. GM_setValue('height', pvDoc.body.clientHeight);
  786. releaseResizeListeners(e);
  787. }
  788.  
  789. function releaseResizeListeners() {
  790. $off('mouseup', releaseResizeListeners);
  791. $off('mousemove', onMoveResize);
  792.  
  793. $on('mouseover', preview.frame, onOverAttach);
  794. onOverAttach({});
  795.  
  796. document.body.style.pointerEvents = '';
  797. document.documentElement.style.cursor = '';
  798. heightOnClick = 0;
  799. }
  800. }
  801.  
  802. function setHeight(height) {
  803. const currentHeight = preview.frame.clientHeight;
  804. const borderHeight = preview.frame.offsetHeight - currentHeight;
  805. const newHeight = Math.max(MIN_HEIGHT, Math.min(innerHeight - borderHeight, height));
  806. if (newHeight != currentHeight)
  807. preview.frame.style.height = newHeight + 'px';
  808. }
  809.  
  810. function $(selector, node = document) {
  811. return node.querySelector(selector);
  812. }
  813.  
  814. function $$(selector, node = document) {
  815. return node.querySelectorAll(selector);
  816. }
  817.  
  818. function $text(selector, node = document) {
  819. const e = typeof selector == 'string' ? node.querySelector(selector) : selector;
  820. return e ? e.textContent.trim() : '';
  821. }
  822.  
  823. function $$remove(selector, node = document) {
  824. node.querySelectorAll(selector).forEach(e => e.remove());
  825. }
  826.  
  827. function $appendChildren(newParent, elements) {
  828. const doc = newParent.ownerDocument;
  829. const fragment = doc.createDocumentFragment();
  830. for (let e of elements)
  831. if (e)
  832. fragment.appendChild(e.ownerDocument == doc ? e : doc.importNode(e, true));
  833. newParent.appendChild(fragment);
  834. }
  835.  
  836. function $removeChildren(el) {
  837. if (el.children.length)
  838. el.innerHTML = ''; // the fastest as per https://jsperf.com/innerhtml-vs-removechild/256
  839. }
  840.  
  841. function $replaceOrCreate(options) {
  842. if (typeof options.map == 'function')
  843. return options.map($replaceOrCreate);
  844. const doc = (options.parent || options.before || options.after).ownerDocument;
  845. const el = doc.getElementById(options.id) || doc.createElement(options.tag || 'div');
  846. for (let key of Object.keys(options)) {
  847. const value = options[key];
  848. switch (key) {
  849. case 'tag':
  850. case 'parent':
  851. case 'before':
  852. case 'after':
  853. break;
  854. case 'dataset':
  855. for (let dataAttr of Object.keys(value))
  856. if (el.dataset[dataAttr] != value[dataAttr])
  857. el.dataset[dataAttr] = value[dataAttr];
  858. break;
  859. case 'children':
  860. $removeChildren(el);
  861. $appendChildren(el, options[key]);
  862. break;
  863. default:
  864. if (key in el && el[key] != value)
  865. el[key] = value;
  866. }
  867. }
  868. if (!el.parentElement)
  869. (options.parent || (options.before || options.after).parentElement)
  870. .insertBefore(el, options.before || (options.after && options.after.nextElementSibling));
  871. return el;
  872. }
  873.  
  874. function $scriptIn(element) {
  875. return element.appendChild(element.ownerDocument.createElement('script'));
  876. }
  877.  
  878. function $on(eventName, ...args) {
  879. // eventName, selector, node, callback, options
  880. // eventName, selector, callback, options
  881. // eventName, node, callback, options
  882. // eventName, callback, options
  883. let i = 0;
  884. const selector = typeof args[i] == 'string' ? args[i++] : null;
  885. const node = args[i].nodeType ? args[i++] : document;
  886. const callback = args[i++];
  887. const options = args[i];
  888.  
  889. const actualNode = selector ? node.querySelector(selector) : node;
  890. const method = this == 'removeEventListener' ? this : 'addEventListener';
  891. actualNode[method](eventName, callback, options);
  892. }
  893.  
  894. function $off() {
  895. $on.apply('removeEventListener', arguments);
  896. }
  897.  
  898. function hasKeyModifiers(e) {
  899. return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey;
  900. }
  901.  
  902. function log(...args) {
  903. console.log(GM_info.script.name, ...args);
  904. }
  905.  
  906. function error(...args) {
  907. console.error(GM_info.script.name, ...args);
  908. console.trace();
  909. }
  910.  
  911. function tryCatch(fn) {
  912. try { return fn() }
  913. catch(e) {}
  914. }
  915.  
  916. function initPolyfills(context = window) {
  917. for (let method of ['forEach', 'filter', 'map', 'every', 'some', context.Symbol.iterator])
  918. if (!context.NodeList.prototype[method])
  919. context.NodeList.prototype[method] = context.Array.prototype[method];
  920. }
  921.  
  922. function initStyles() {
  923. GM_addStyle(`
  924. #SEpreview {
  925. all: unset;
  926. box-sizing: content-box;
  927. width: 720px; /* 660px + 30px + 30px */
  928. height: 33%;
  929. min-height: ${MIN_HEIGHT}px;
  930. position: fixed;
  931. opacity: 0;
  932. pointer-events: none;
  933. transition: opacity .25s cubic-bezier(.88,.02,.92,.66);
  934. right: 0;
  935. bottom: 0;
  936. padding: 0;
  937. margin: 0;
  938. background: white;
  939. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  940. z-index: 999999;
  941. border-width: 8px;
  942. border-style: solid;
  943. border-color: transparent;
  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. }