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.2
  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. userMenu.onmouseover = e => e.target == userMenu && (userMenu.style.opacity = 1);
  470. fadeIn(userMenu);
  471. },
  472. });
  473. }
  474. }
  475.  
  476. function getCacheableUrl(url) {
  477. // strips querys and hashes and anything after the main part https://site/questions/####/title/
  478. return url
  479. .replace(/(\/q(?:uestions)?\/\d+\/[^\/]+).*/, '$1')
  480. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  481. .replace(/[?#].*$/, '');
  482. }
  483.  
  484. function readCache(url) {
  485. keyUrl = getCacheableUrl(url);
  486. const meta = (localStorage[keyUrl] || '').split('\t');
  487. const expired = +meta[0] < Date.now();
  488. const finalUrl = meta[1] || url;
  489. const keyFinalUrl = meta[1] ? getCacheableUrl(finalUrl) : keyUrl;
  490. return !expired && {
  491. finalUrl,
  492. html: LZString.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  493. };
  494. }
  495.  
  496. function writeCache({url, finalUrl, html, cacheDuration = CACHE_DURATION, cleanupRetry}) {
  497. // keyUrl=expires
  498. // redirected keyUrl=expires+finalUrl, and an additional entry keyFinalUrl=expires is created
  499. // keyFinalUrl\thtml=html
  500. cacheDuration = Math.max(CACHE_DURATION, Math.min(0xDEADBEEF, Math.floor(cacheDuration)));
  501. finalUrl = finalUrl.replace(/[?#].*/, '');
  502. const keyUrl = getCacheableUrl(url);
  503. const keyFinalUrl = getCacheableUrl(finalUrl);
  504. const expires = Date.now() + cacheDuration;
  505. if (!tryCatch(() => localStorage[keyFinalUrl + '\thtml'] = LZString.compressToUTF16(html))) {
  506. if (cleanupRetry)
  507. return error('localStorage write error');
  508. cleanupCache({aggressive: true});
  509. setIimeout(writeCache, 0, {url, finalUrl, html, cacheDuration, cleanupRetry: true});
  510. }
  511. localStorage[keyFinalUrl] = expires;
  512. if (keyUrl != keyFinalUrl)
  513. localStorage[keyUrl] = expires + '\t' + finalUrl;
  514. setTimeout(() => {
  515. [keyUrl, keyFinalUrl, keyFinalUrl + '\thtml'].forEach(e => localStorage.removeItem(e));
  516. }, cacheDuration + 1000);
  517. }
  518.  
  519. function cleanupCache({aggressive = false} = {}) {
  520. Object.keys(localStorage).forEach(k => {
  521. if (k.match(/^https?:\/\/[^\t]+$/)) {
  522. let meta = (localStorage[k] || '').split('\t');
  523. if (+meta[0] > Date.now() && !aggressive)
  524. return;
  525. if (meta[1])
  526. localStorage.removeItem(meta[1]);
  527. localStorage.removeItem(`${meta[1] || k}\thtml`);
  528. localStorage.removeItem(k);
  529. }
  530. });
  531. }
  532.  
  533. function onFrameReady(frame) {
  534. if (frame.contentDocument.readyState == 'complete')
  535. return Promise.resolve();
  536. else
  537. return new Promise(resolve => {
  538. $on('load', frame, function onLoad() {
  539. $off('load', frame, onLoad);
  540. resolve();
  541. });
  542. });
  543. }
  544.  
  545. function onStyleSheetsReady(linkElements) {
  546. let retryCount = 0;
  547. return new Promise(function retry(resolve) {
  548. if (linkElements.every(e => e.sheet && e.sheet.href == e.href))
  549. resolve();
  550. else if (retryCount++ > 10)
  551. resolve();
  552. else
  553. setTimeout(retry, 0, resolve);
  554. });
  555. }
  556.  
  557. function getURLregexForMatchedSites() {
  558. return new RegExp('https?://(\\w*\\.)*(' + GM_info.script.matches.map(m =>
  559. m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.')
  560. ).join('|') + ')/(questions|q|a|posts\/comments)/\\d+');
  561. }
  562.  
  563. function isLinkPreviewable(link) {
  564. const inPreview = link.ownerDocument != document;
  565. if (!rxPreviewable.test(link.href) || link.matches('.short-link'))
  566. return false;
  567. const pageUrls = inPreview ? getPageBaseUrls(preview.link.href) : thisPageUrls;
  568. const url = httpsUrl(link.href);
  569. return !url.startsWith(pageUrls.base) &&
  570. !url.startsWith(pageUrls.short);
  571. }
  572.  
  573. function getPageBaseUrls(url) {
  574. const base = httpsUrl((url.match(rxPreviewable) || [])[0]);
  575. return base ? {
  576. base,
  577. short: base.replace('/questions/', '/q/'),
  578. } : {};
  579. }
  580.  
  581. function httpsUrl(url) {
  582. return (url || '').replace(/^http:/, 'https:');
  583. }
  584.  
  585. function $(selector, node = document) {
  586. return node.querySelector(selector);
  587. }
  588.  
  589. function $$(selector, node = document) {
  590. return node.querySelectorAll(selector);
  591. }
  592.  
  593. function $text(selector, node = document) {
  594. const e = typeof selector == 'string' ? node.querySelector(selector) : selector;
  595. return e ? e.textContent.trim() : '';
  596. }
  597.  
  598. function $$remove(selector, node = document) {
  599. node.querySelectorAll(selector).forEach(e => e.remove());
  600. }
  601.  
  602. function $appendChildren(newParent, elements) {
  603. const doc = newParent.ownerDocument;
  604. for (let e of elements)
  605. if (e)
  606. newParent.appendChild(e.ownerDocument == doc ? e : doc.importNode(e, true));
  607. }
  608.  
  609. function $removeChildren(el) {
  610. if (!el.children.length)
  611. return;
  612. const range = new Range();
  613. range.selectNodeContents(el);
  614. range.deleteContents();
  615. }
  616.  
  617. function $replaceOrCreate(options) {
  618. if (typeof options.map == 'function')
  619. return options.map($replaceOrCreate);
  620. const doc = (options.parent || options.before).ownerDocument;
  621. const el = doc.getElementById(options.id) || doc.createElement(options.tag || 'div');
  622. for (let key of Object.keys(options)) {
  623. const value = options[key];
  624. switch (key) {
  625. case 'tag':
  626. case 'parent':
  627. case 'before':
  628. break;
  629. case 'dataset':
  630. for (let dataAttr of Object.keys(value))
  631. if (el.dataset[dataAttr] != value[dataAttr])
  632. el.dataset[dataAttr] = value[dataAttr];
  633. break;
  634. case 'children':
  635. $removeChildren(el);
  636. $appendChildren(el, options[key]);
  637. break;
  638. default:
  639. if (key in el && el[key] != value)
  640. el[key] = value;
  641. }
  642. }
  643. if (!el.parentElement)
  644. (options.parent || options.before.parentElement).insertBefore(el, options.before);
  645. return el;
  646. }
  647.  
  648. function $scriptIn(element) {
  649. return element.appendChild(element.ownerDocument.createElement('script'));
  650. }
  651.  
  652. function $on(eventName, ...args) {
  653. // eventName, selector, node, callback, options
  654. // eventName, selector, callback, options
  655. // eventName, node, callback, options
  656. // eventName, callback, options
  657. const selector = typeof args[0] == 'string' ? args[0] : null;
  658. const node = args[0].nodeType ? args[0] : args[1].nodeType ? args[1] : document;
  659. const callback = args[typeof args[0] == 'function' ? 0 : typeof args[1] == 'function' ? 1 : 2];
  660. const options = args[args.length - 1] != callback ? args[args.length - 1] : undefined;
  661. const method = this == 'removeEventListener' ? this : 'addEventListener';
  662. (selector ? node.querySelector(selector) : node)[method](eventName, callback, options);
  663. }
  664.  
  665. function $off(eventName, ...args) {
  666. $on.apply('removeEventListener', arguments);
  667. }
  668.  
  669. function log(...args) {
  670. console.log(GM_info.script.name, ...args);
  671. }
  672.  
  673. function error(...args) {
  674. console.error(GM_info.script.name, ...args);
  675. }
  676.  
  677. function tryCatch(fn) {
  678. try { return fn() }
  679. catch(e) {}
  680. }
  681.  
  682. function initPolyfills(context = window) {
  683. for (let method of ['forEach', 'filter', 'map', 'every', context.Symbol.iterator])
  684. if (!context.NodeList.prototype[method])
  685. context.NodeList.prototype[method] = context.Array.prototype[method];
  686. }
  687.  
  688. function initStyles() {
  689. GM_addStyle(`
  690. #SEpreview {
  691. all: unset;
  692. box-sizing: content-box;
  693. width: 720px; /* 660px + 30px + 30px */
  694. height: 33%;
  695. min-height: 400px;
  696. position: fixed;
  697. opacity: 0;
  698. transition: opacity .25s cubic-bezier(.88,.02,.92,.66);
  699. right: 0;
  700. bottom: 0;
  701. padding: 0;
  702. margin: 0;
  703. background: white;
  704. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  705. z-index: 999999;
  706. border-width: 8px;
  707. border-style: solid;
  708. }
  709. `
  710. + Object.keys(COLORS).map(s => `
  711. #SEpreview[SEpreview-type="${s}"] {
  712. border-color: rgb(${COLORS[s].backRGB});
  713. }
  714. `).join('')
  715. );
  716.  
  717. preview.stylesOverride = `
  718. body, html {
  719. min-width: unset!important;
  720. box-shadow: none!important;
  721. padding: 0!important;
  722. margin: 0!important;
  723. }
  724. html, body {
  725. background: unset!important;;
  726. }
  727. body {
  728. display: flex;
  729. flex-direction: column;
  730. height: 100vh;
  731. }
  732. #SEpreview-body a.SEpreviewable {
  733. text-decoration: underline !important;
  734. }
  735. #SEpreview-title {
  736. all: unset;
  737. display: block;
  738. padding: 20px 30px;
  739. font-weight: bold;
  740. font-size: 18px;
  741. line-height: 1.2;
  742. cursor: pointer;
  743. }
  744. #SEpreview-title:hover {
  745. text-decoration: underline;
  746. }
  747. #SEpreview-meta {
  748. position: absolute;
  749. top: .5ex;
  750. left: 30px;
  751. opacity: 0.5;
  752. }
  753. #SEpreview-title:hover + #SEpreview-meta {
  754. opacity: 1.0;
  755. }
  756.  
  757. #SEpreview-close {
  758. position: absolute;
  759. top: 0;
  760. right: 0;
  761. flex: none;
  762. cursor: pointer;
  763. padding: .5ex 1ex;
  764. }
  765. #SEpreview-close:after {
  766. content: "x"; }
  767. #SEpreview-close:active {
  768. background-color: rgba(0,0,0,.1); }
  769. #SEpreview-close:hover {
  770. background-color: rgba(0,0,0,.05); }
  771.  
  772. #SEpreview-body {
  773. padding: 30px!important;
  774. overflow: auto;
  775. flex-grow: 2;
  776. }
  777. #SEpreview-body .post-menu {
  778. display: none!important;
  779. }
  780. #SEpreview-body > .question-status {
  781. margin: -30px -30px 30px;
  782. padding-left: 30px;
  783. }
  784. #SEpreview-body .question-originals-of-duplicate {
  785. margin: -30px -30px 30px;
  786. padding: 15px 30px;
  787. }
  788. #SEpreview-body > .question-status h2 {
  789. font-weight: normal;
  790. }
  791.  
  792. #SEpreview-answers {
  793. all: unset;
  794. display: block;
  795. padding: 10px 10px 10px 30px;
  796. font-weight: bold;
  797. line-height: 1.0;
  798. border-top: 4px solid rgba(${COLORS.answer.backRGB}, 0.37);
  799. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  800. color: ${COLORS.answer.fore};
  801. word-break: break-word;
  802. }
  803. #SEpreview-answers:before {
  804. content: "Answers:";
  805. margin-right: 1ex;
  806. font-size: 20px;
  807. line-height: 48px;
  808. }
  809. #SEpreview-answers a {
  810. color: ${COLORS.answer.fore};
  811. text-decoration: none;
  812. font-size: 11px;
  813. font-family: monospace;
  814. width: 32px;
  815. display: inline-block;
  816. vertical-align: top;
  817. margin: 0 1ex 1ex 0;
  818. }
  819. #SEpreview-answers img {
  820. width: 32px;
  821. height: 32px;
  822. }
  823. .SEpreview-accepted {
  824. position: relative;
  825. }
  826. .SEpreview-accepted:after {
  827. content: "✔";
  828. position: absolute;
  829. display: block;
  830. top: 1.3ex;
  831. right: -0.7ex;
  832. font-size: 32px;
  833. color: #4bff2c;
  834. text-shadow: 1px 2px 2px rgba(0,0,0,0.5);
  835. }
  836. #SEpreview-answers a.deleted-answer {
  837. color: ${COLORS.deleted.fore};
  838. background: transparent;
  839. opacity: 0.25;
  840. }
  841. #SEpreview-answers a.deleted-answer:hover {
  842. opacity: 1.0;
  843. }
  844. #SEpreview-answers a:hover:not(.SEpreviewed) {
  845. text-decoration: underline;
  846. }
  847. #SEpreview-answers a.SEpreviewed {
  848. background-color: ${COLORS.answer.fore};
  849. color: ${COLORS.answer.foreInv};
  850. position: relative;
  851. }
  852. #SEpreview-answers a.SEpreviewed:after {
  853. display: block;
  854. content: " ";
  855. position: absolute;
  856. left: -4px;
  857. top: -4px;
  858. right: -4px;
  859. bottom: -4px;
  860. border: 4px solid ${COLORS.answer.fore};
  861. }
  862.  
  863. .delete-tag,
  864. .comment-actions td:last-child {
  865. display: none;
  866. }
  867. .comments {
  868. border-top: none;
  869. }
  870. .comments tr:last-child td {
  871. border-bottom: none;
  872. }
  873. .comments .new-comment-highlight {
  874. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  875. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  876. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  877. }
  878.  
  879. .user-info {
  880. position: relative;
  881. }
  882. #user-menu {
  883. position: absolute;
  884. }
  885. .SEpreview-user {
  886. position: absolute;
  887. right: -1em;
  888. top: -2em;
  889. transition: opacity .25s ease-in-out;
  890. opacity: 0;
  891. display: none;
  892. }
  893.  
  894. @-webkit-keyframes highlight {
  895. from {background-color: #ffcf78}
  896. to {background-color: none}
  897. }
  898. `
  899. + Object.keys(COLORS).map(s => `
  900. body[SEpreview-type="${s}"] #SEpreview-title {
  901. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  902. color: ${COLORS[s].fore};
  903. }
  904. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar {
  905. background-color: rgba(${COLORS[s].backRGB}, 0.1); }
  906. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb {
  907. background-color: rgba(${COLORS[s].backRGB}, 0.2); }
  908. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:hover {
  909. background-color: rgba(${COLORS[s].backRGB}, 0.3); }
  910. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:active {
  911. background-color: rgba(${COLORS[s].backRGB}, 0.75); }
  912. `).join('')
  913. + ['deleted', 'closed'].map(s => `
  914. body[SEpreview-type="${s}"] #SEpreview-answers {
  915. border-top-color: rgba(${COLORS[s].backRGB}, 0.37);
  916. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  917. color: ${COLORS[s].fore};
  918. }
  919. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed {
  920. background-color: ${COLORS[s].fore};
  921. color: ${COLORS[s].foreInv};
  922. }
  923. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed:after {
  924. border-color: ${COLORS[s].fore};
  925. }
  926. `).join('');
  927. }