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