SE Preview on hover

Shows preview of the linked questions/answers on hover

当前为 2017-03-09 提交的版本,查看 最新版本

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