SE Preview on hover

Shows preview of the linked questions/answers on hover

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

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