SE Preview on hover

Shows preview of the linked questions/answers on hover

当前为 2017-02-21 提交的版本,查看 最新版本

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