SE Preview on hover

Shows preview of the linked questions/answers on hover

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

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