Greasy Fork 还支持 简体中文。

SE Preview on hover

Shows preview of the linked questions/answers on hover

目前為 2017-02-19 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 0.3.7
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @match *://*.stackoverflow.com/*
  9. // @match *://*.superuser.com/*
  10. // @match *://*.serverfault.com/*
  11. // @match *://*.askubuntu.com/*
  12. // @match *://*.stackapps.com/*
  13. // @match *://*.mathoverflow.net/*
  14. // @match *://*.stackexchange.com/*
  15. // @include /https?:\/\/www\.?google(\.com?)?(\.\w\w)?\/(webhp|q|.*?[?#]q=|#q|search).*/
  16. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/lz-string/1.4.4/lz-string.min.js
  18. // @grant GM_addStyle
  19. // @grant GM_xmlhttpRequest
  20. // @connect stackoverflow.com
  21. // @connect superuser.com
  22. // @connect serverfault.com
  23. // @connect askubuntu.com
  24. // @connect stackapps.com
  25. // @connect mathoverflow.net
  26. // @connect stackexchange.com
  27. // @connect cdn.sstatic.net
  28. // @run-at document-end
  29. // @noframes
  30. // ==/UserScript==
  31.  
  32. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  33.  
  34. const PREVIEW_DELAY = 200;
  35. const CACHE_DURATION = 1 * 60 * 1000; // 1 minute for the recently active posts, scales up logarithmically
  36. const COLORS = {
  37. question: {
  38. backRGB: '80, 133, 195',
  39. fore: '#265184',
  40. },
  41. answer: {
  42. backRGB: '112, 195, 80',
  43. fore: '#3f7722',
  44. foreInv: 'white',
  45. },
  46. deleted: {
  47. backRGB: '181, 103, 103',
  48. fore: 'rgb(181, 103, 103)',
  49. foreInv: 'white',
  50. },
  51. closed: {
  52. backRGB: '255, 206, 93',
  53. fore: 'rgb(194, 136, 0)',
  54. foreInv: 'white',
  55. },
  56. };
  57.  
  58. let xhr;
  59. let preview = {
  60. frame: null,
  61. link: null,
  62. hover: {x:0, y:0},
  63. timer: 0,
  64. stylesOverride: '',
  65. };
  66. const lockScroll = {};
  67.  
  68. const rxPreviewable = getURLregexForMatchedSites();
  69. const thisPageUrls = getPageBaseUrls(location.href);
  70.  
  71. initStyles();
  72. initPolyfills();
  73. setMutationHandler('a', onLinkAdded, {processExisting: true});
  74. setTimeout(cleanupCache, 10000);
  75.  
  76. /**************************************************************/
  77.  
  78. function onLinkAdded(links) {
  79. for (let i = 0, link; (link = links[i++]); ) {
  80. if (isLinkPreviewable(link)) {
  81. link.removeAttribute('title');
  82. $on('mouseover', link, onLinkHovered);
  83. }
  84. }
  85. }
  86.  
  87. function onLinkHovered(e) {
  88. if (hasKeyModifier(e))
  89. return;
  90. preview.link = this;
  91. $on('mousemove', this, onLinkMouseMove);
  92. $on('mouseout', this, abortPreview);
  93. $on('mousedown', this, abortPreview);
  94. restartPreviewTimer(this);
  95. }
  96.  
  97. function onLinkMouseMove(e) {
  98. let stoppedMoving = Math.abs(preview.hover.x - e.clientX) < 2 &&
  99. Math.abs(preview.hover.y - e.clientY) < 2;
  100. if (!stoppedMoving)
  101. return;
  102. preview.hover.x = e.clientX;
  103. preview.hover.y = e.clientY;
  104. restartPreviewTimer(this);
  105. }
  106.  
  107. function restartPreviewTimer(link) {
  108. clearTimeout(preview.timer);
  109. preview.timer = setTimeout(() => {
  110. preview.timer = 0;
  111. $off('mousemove', link, onLinkMouseMove);
  112. if (link.matches(':hover'))
  113. downloadPreview(link.href);
  114. }, PREVIEW_DELAY);
  115. }
  116.  
  117. function abortPreview(e) {
  118. releaseLinkListeners(this);
  119. preview.timer = setTimeout(link => {
  120. if (link == preview.link && preview.frame && !preview.frame.matches(':hover'))
  121. preview.frame.contentWindow.postMessage('SEpreview-hidden', '*');
  122. }, PREVIEW_DELAY * 3, this);
  123. if (xhr)
  124. xhr.abort();
  125. }
  126.  
  127. function releaseLinkListeners(link = preview.link) {
  128. $off('mousemove', link, onLinkMouseMove);
  129. $off('mouseout', link, abortPreview);
  130. $off('mousedown', link, abortPreview);
  131. clearTimeout(preview.timer);
  132. }
  133.  
  134. function fadeOut(element, transition) {
  135. return new Promise(resolve => {
  136. if (transition) {
  137. element.style.transition = typeof transition == 'number' ? `opacity ${transition}s ease-in-out` : transition;
  138. setTimeout(doFadeOut);
  139. } else
  140. doFadeOut();
  141.  
  142. function doFadeOut() {
  143. element.style.opacity = '0';
  144. $on('transitionend', element, function done() {
  145. $off('transitionend', element, done);
  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. if (!lastActivity)
  176. return;
  177. const inactiveDays = Math.max(0, (Date.now() - lastActivity) / (24 * 3600 * 1000));
  178. const cacheDuration = CACHE_DURATION * Math.pow(Math.log(inactiveDays + 1) + 1, 2);
  179. setTimeout(writeCache, 1000, {url, finalUrl: r.finalUrl, html, cacheDuration});
  180. },
  181. });
  182. }
  183. }
  184.  
  185. function initPreview() {
  186. preview.frame = document.createElement('iframe');
  187. preview.frame.id = 'SEpreview';
  188. document.body.appendChild(preview.frame);
  189.  
  190. lockScroll.attach = e => {
  191. if (lockScroll.pos)
  192. return;
  193. lockScroll.pos = {x: scrollX, y: scrollY};
  194. $on('scroll', document, lockScroll.run);
  195. $on('mouseover', document, lockScroll.detach);
  196. };
  197. lockScroll.run = e => scrollTo(lockScroll.pos.x, lockScroll.pos.y);
  198. lockScroll.detach = e => {
  199. if (!lockScroll.pos)
  200. return;
  201. lockScroll.pos = null;
  202. $off('mouseout', document, lockScroll.detach);
  203. $off('scroll', document, lockScroll.run);
  204. };
  205. }
  206.  
  207. function showPreview({finalUrl, html, doc}) {
  208. doc = doc || new DOMParser().parseFromString(html, 'text/html');
  209. if (!doc || !doc.head)
  210. return error('no HEAD in the document received for', finalUrl);
  211.  
  212. if (!$('base', doc))
  213. doc.head.insertAdjacentHTML('afterbegin', `<base href="${finalUrl}">`);
  214.  
  215. const answerIdMatch = finalUrl.match(/questions\/\d+\/[^\/]+\/(\d+)/);
  216. const isQuestion = !answerIdMatch;
  217. const postId = answerIdMatch ? '#answer-' + answerIdMatch[1] : '#question';
  218. const post = $(postId + ' .post-text', doc);
  219. if (!post)
  220. return error('No parsable post found', doc);
  221. const isDeleted = !!post.closest('.deleted-answer');
  222. const title = $('meta[property="og:title"]', doc).content;
  223. const status = isQuestion && !$('.question-status', post) ? $('.question-status', doc) : null;
  224. const isClosed = $('.question-originals-of-duplicate, .close-as-off-topic-status-list, .close-status-suffix', doc);
  225. const comments = $(`${postId} .comments`, doc);
  226. const commentsHidden = +$('tbody', comments).dataset.remainingCommentsCount;
  227. const commentsShowLink = commentsHidden && $(`${postId} .js-show-link.comments-link`, doc);
  228. const finalUrlOfQuestion = getCacheableUrl(finalUrl);
  229. const lastActivity = tryCatch(() => new Date($('.lastactivity-link', doc).title).getTime()) || Date.now();
  230.  
  231. markPreviewableLinks(doc);
  232. $$remove('script', doc);
  233.  
  234. if (!preview.frame)
  235. initPreview();
  236.  
  237. let pvDoc, pvWin;
  238. preview.frame.style.display = '';
  239. preview.frame.setAttribute('SEpreview-type',
  240. isDeleted ? 'deleted' : isQuestion ? (isClosed ? 'closed' : 'question') : 'answer');
  241. onFrameReady(preview.frame).then(
  242. () => {
  243. pvDoc = preview.frame.contentDocument;
  244. pvWin = preview.frame.contentWindow;
  245. initPolyfills(pvWin);
  246. })
  247. .then(addStyles)
  248. .then(render)
  249. .then(show);
  250. return lastActivity;
  251.  
  252. function markPreviewableLinks(container) {
  253. for (let link of $$('a:not(.SEpreviewable)', container)) {
  254. if (rxPreviewable.test(link.href)) {
  255. link.removeAttribute('title');
  256. link.classList.add('SEpreviewable');
  257. }
  258. }
  259. }
  260.  
  261. function addStyles() {
  262. const SEpreviewStyles = $replaceOrCreate({
  263. id: 'SEpreviewStyles',
  264. tag: 'style', parent: pvDoc.head, className: 'SEpreview-reuse',
  265. innerHTML: preview.stylesOverride,
  266. });
  267. $replaceOrCreate($$('style', doc).map(e => ({
  268. id: 'SEpreview' + e.innerHTML.replace(/\W+/g, '').length,
  269. tag: 'style', before: SEpreviewStyles, className: 'SEpreview-reuse',
  270. innerHTML: e.innerHTML,
  271. })));
  272. return onStyleSheetsReady(
  273. $replaceOrCreate($$('link[rel="stylesheet"]', doc).map(e => ({
  274. id: e.href.replace(/\W+/g, ''),
  275. tag: 'link', before: SEpreviewStyles, className: 'SEpreview-reuse',
  276. href: e.href, rel: 'stylesheet',
  277. })))
  278. );
  279. }
  280.  
  281. function render() {
  282. pvDoc.body.setAttribute('SEpreview-type', preview.frame.getAttribute('SEpreview-type'));
  283.  
  284. $replaceOrCreate([{
  285. // title
  286. id: 'SEpreview-title', tag: 'a',
  287. parent: pvDoc.body, className: 'SEpreviewable',
  288. href: finalUrlOfQuestion,
  289. textContent: title,
  290. }, {
  291. // close button
  292. id: 'SEpreview-close',
  293. parent: pvDoc.body,
  294. title: 'Or press Esc key while the preview is focused (also when just shown)',
  295. }, {
  296. // vote count, date, views#
  297. id: 'SEpreview-meta',
  298. parent: pvDoc.body,
  299. innerHTML: [
  300. $text('.vote-count-post', post.closest('table')).replace(/(-?)(\d+)/,
  301. (s, sign, v) => s == '0' ? '' : `<b>${s}</b> vote${+v > 1 ? 's' : ''}, `),
  302. isQuestion
  303. ? $$('#qinfo tr', doc)
  304. .map(row => $$('.label-key', row).map($text).join(' '))
  305. .join(', ').replace(/^((.+?) (.+?), .+?), .+? \3$/, '$1')
  306. : [...$$('.user-action-time', post.closest('.answer'))]
  307. .reverse().map($text).join(', ')
  308. ].join('')
  309. }, {
  310. // content wrapper
  311. id: 'SEpreview-body',
  312. parent: pvDoc.body,
  313. className: isDeleted ? 'deleted-answer' : '',
  314. children: [status, post.parentElement, comments, commentsShowLink],
  315. }]);
  316.  
  317. // prettify code blocks
  318. const codeBlocks = $$('pre code', pvDoc);
  319. if (codeBlocks.length) {
  320. codeBlocks.forEach(e => e.parentElement.classList.add('prettyprint'));
  321. if (!pvWin.StackExchange) {
  322. pvWin.StackExchange = {};
  323. let script = $scriptIn(pvDoc.head);
  324. script.text = 'StackExchange = {}';
  325. script = $scriptIn(pvDoc.head);
  326. script.src = 'https://cdn.sstatic.net/Js/prettify-full.en.js';
  327. script.setAttribute('onload', 'prettyPrint()');
  328. } else
  329. $scriptIn(pvDoc.body).text = 'prettyPrint()';
  330. }
  331.  
  332. // render bottom shelf
  333. const answers = $$('.answer', doc);
  334. if (answers.length > (isQuestion ? 0 : 1)) {
  335. $replaceOrCreate({
  336. id: 'SEpreview-answers',
  337. parent: pvDoc.body,
  338. innerHTML: answers.map(renderShelfAnswer).join(' '),
  339. });
  340. } else
  341. $$remove('#SEpreview-answers', pvDoc);
  342.  
  343. // cleanup leftovers from previously displayed post and foreign elements not injected by us
  344. $$('style, link, body script, html > *:not(head):not(body)', pvDoc).forEach(e => {
  345. if (e.classList.contains('SEpreview-reuse'))
  346. e.classList.remove('SEpreview-reuse');
  347. else
  348. e.remove();
  349. });
  350. }
  351.  
  352. function renderShelfAnswer(e) {
  353. const shortUrl = $('.short-link', e).href.replace(/(\d+)\/\d+/, '$1');
  354. const extraClasses = (e.matches(postId) ? ' SEpreviewed' : '') +
  355. (e.matches('.deleted-answer') ? ' deleted-answer' : '') +
  356. ($('.vote-accepted-on', e) ? ' SEpreview-accepted' : '');
  357. const author = $('.post-signature:last-child', e);
  358. const title = $text('.user-details a', author) + ' (rep ' +
  359. $text('.reputation-score', author) + ')\n' +
  360. $text('.user-action-time', author);
  361. const gravatar = $('img, .anonymous-gravatar, .community-wiki', author);
  362. return (
  363. `<a href="${shortUrl}" title="${title}" class="SEpreviewable${extraClasses}">` +
  364. $text('.vote-count-post', e).replace(/^0$/, '&nbsp;') + ' ' +
  365. (!gravatar ? '' : gravatar.src ? `<img src="${gravatar.src}">` : gravatar.outerHTML) +
  366. '</a>');
  367. }
  368.  
  369. function show() {
  370. pvDoc.onmouseover = lockScroll.attach;
  371. pvDoc.onclick = onClick;
  372. pvDoc.onkeydown = e => !hasKeyModifier(e) && e.keyCode == 27 ? hide() : null;
  373. pvWin.onmessage = e => e.data == 'SEpreview-hidden' ? hide({fade: true}) : null;
  374. $$('.user-info a img', pvDoc).forEach(e => e.onmouseover = loadUserDetails);
  375. $('#SEpreview-body', pvDoc).scrollTop = 0;
  376. preview.frame.style.opacity = '1';
  377. preview.frame.focus();
  378. }
  379.  
  380. function hide({fade = false} = {}) {
  381. releaseLinkListeners();
  382. releasePreviewListeners();
  383. const maybeZap = () => preview.frame.style.opacity == '0' && $removeChildren(pvDoc.body);
  384. if (fade)
  385. fadeOut(preview.frame).then(maybeZap);
  386. else {
  387. preview.frame.style.opacity = '0';
  388. preview.frame.style.display = 'none';
  389. maybeZap();
  390. }
  391. }
  392.  
  393. function releasePreviewListeners(e) {
  394. pvWin.onmessage = null;
  395. pvDoc.onmouseover = null;
  396. pvDoc.onclick = null;
  397. pvDoc.onkeydown = null;
  398. }
  399.  
  400. function onClick(e) {
  401. if (e.target.id == 'SEpreview-close')
  402. return hide();
  403.  
  404. const link = e.target.closest('a');
  405. if (!link)
  406. return;
  407.  
  408. if (link.matches('.js-show-link.comments-link')) {
  409. fadeOut(link, 0.5);
  410. loadComments();
  411. return e.preventDefault();
  412. }
  413.  
  414. if (e.button || hasKeyModifier(e) || !link.matches('.SEpreviewable'))
  415. return (link.target = '_blank');
  416.  
  417. e.preventDefault();
  418.  
  419. if (link.id == 'SEpreview-title')
  420. showPreview({doc, finalUrl: finalUrlOfQuestion});
  421. else if (link.matches('#SEpreview-answers a'))
  422. showPreview({doc, finalUrl: finalUrlOfQuestion + '/' + link.pathname.match(/\/(\d+)/)[1]});
  423. else
  424. downloadPreview(link.href);
  425. }
  426.  
  427. function loadComments() {
  428. GM_xmlhttpRequest({
  429. method: 'GET',
  430. url: new URL(finalUrl).origin + '/posts/' + comments.id.match(/\d+/)[0] + '/comments',
  431. onload: r => {
  432. let tbody = $(`#${comments.id} tbody`, pvDoc);
  433. let oldIds = new Set([...tbody.rows].map(e => e.id));
  434. tbody.innerHTML = r.responseText;
  435. tbody.closest('.comments').style.display = 'block';
  436. for (let tr of tbody.rows)
  437. if (!oldIds.has(tr.id))
  438. tr.classList.add('new-comment-highlight');
  439. markPreviewableLinks(tbody);
  440. },
  441. });
  442. }
  443.  
  444. function loadUserDetails(e, ready) {
  445. if (ready !== true)
  446. return setTimeout(loadUserDetails, PREVIEW_DELAY, e, true);
  447. $$('#user-menu', pvDoc).forEach(e => e.id = '');
  448. const userId = e.target.closest('a').pathname.match(/\d+/)[0];
  449. const existing = $(`.SEpreview-user[data-id="${userId}"]`, pvDoc);
  450. if (existing) {
  451. existing.id = 'user-menu';
  452. fadeIn(existing);
  453. return;
  454. }
  455. GM_xmlhttpRequest({
  456. method: 'GET',
  457. url: new URL(finalUrl).origin + '/users/user-info/' + userId,
  458. onload: r => {
  459. let userMenu = $replaceOrCreate({
  460. id: 'user-menu',
  461. dataset: {id: userId},
  462. parent: e.target.closest('.user-info'),
  463. className: 'SEpreview-user',
  464. innerHTML: r.responseText,
  465. });
  466. userMenu.onmouseout = e => e.target == userMenu ? fadeOut(userMenu) : null;
  467. userMenu.onmouseover = e => e.target == userMenu ? (userMenu.style.opacity = '1') : null;
  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 = preview.frame && link.ownerDocument == preview.frame.contentDocument;
  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.indexOf(pageUrls.base) &&
  568. url.indexOf(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. const fragment = doc.createDocumentFragment();
  603. for (let e of elements)
  604. if (e)
  605. fragment.appendChild(e.ownerDocument == doc ? e : doc.importNode(e, true));
  606. newParent.appendChild(fragment);
  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 hasKeyModifier(e) {
  670. return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey;
  671. }
  672.  
  673. function log(...args) {
  674. console.log(GM_info.script.name, ...args);
  675. }
  676.  
  677. function error(...args) {
  678. console.error(GM_info.script.name, ...args);
  679. }
  680.  
  681. function tryCatch(fn) {
  682. try { return fn() }
  683. catch(e) {}
  684. }
  685.  
  686. function initPolyfills(context = window) {
  687. for (let method of ['forEach', 'filter', 'map', 'every', context.Symbol.iterator])
  688. if (!context.NodeList.prototype[method])
  689. context.NodeList.prototype[method] = context.Array.prototype[method];
  690. }
  691.  
  692. function initStyles() {
  693. GM_addStyle(`
  694. #SEpreview {
  695. all: unset;
  696. box-sizing: content-box;
  697. width: 720px; /* 660px + 30px + 30px */
  698. height: 33%;
  699. min-height: 400px;
  700. position: fixed;
  701. opacity: 0;
  702. transition: opacity .25s cubic-bezier(.88,.02,.92,.66);
  703. right: 0;
  704. bottom: 0;
  705. padding: 0;
  706. margin: 0;
  707. background: white;
  708. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  709. z-index: 999999;
  710. border-width: 8px;
  711. border-style: solid;
  712. }
  713. `
  714. + Object.keys(COLORS).map(s => `
  715. #SEpreview[SEpreview-type="${s}"] {
  716. border-color: rgb(${COLORS[s].backRGB});
  717. }
  718. `).join('')
  719. );
  720.  
  721. preview.stylesOverride = `
  722. body, html {
  723. min-width: unset!important;
  724. box-shadow: none!important;
  725. padding: 0!important;
  726. margin: 0!important;
  727. }
  728. html, body {
  729. background: unset!important;;
  730. }
  731. body {
  732. display: flex;
  733. flex-direction: column;
  734. height: 100vh;
  735. }
  736. #SEpreview-body a.SEpreviewable {
  737. text-decoration: underline !important;
  738. }
  739. #SEpreview-title {
  740. all: unset;
  741. display: block;
  742. padding: 20px 30px;
  743. font-weight: bold;
  744. font-size: 18px;
  745. line-height: 1.2;
  746. cursor: pointer;
  747. }
  748. #SEpreview-title:hover {
  749. text-decoration: underline;
  750. }
  751. #SEpreview-meta {
  752. position: absolute;
  753. top: .5ex;
  754. left: 30px;
  755. opacity: 0.5;
  756. }
  757. #SEpreview-title:hover + #SEpreview-meta {
  758. opacity: 1.0;
  759. }
  760.  
  761. #SEpreview-close {
  762. position: absolute;
  763. top: 0;
  764. right: 0;
  765. flex: none;
  766. cursor: pointer;
  767. padding: .5ex 1ex;
  768. }
  769. #SEpreview-close:after {
  770. content: "x"; }
  771. #SEpreview-close:active {
  772. background-color: rgba(0,0,0,.1); }
  773. #SEpreview-close:hover {
  774. background-color: rgba(0,0,0,.05); }
  775.  
  776. #SEpreview-body {
  777. padding: 30px!important;
  778. overflow: auto;
  779. flex-grow: 2;
  780. }
  781. #SEpreview-body .post-menu {
  782. display: none!important;
  783. }
  784. #SEpreview-body > .question-status {
  785. margin: -30px -30px 30px;
  786. padding-left: 30px;
  787. }
  788. #SEpreview-body .question-originals-of-duplicate {
  789. margin: -30px -30px 30px;
  790. padding: 15px 30px;
  791. }
  792. #SEpreview-body > .question-status h2 {
  793. font-weight: normal;
  794. }
  795.  
  796. #SEpreview-answers {
  797. all: unset;
  798. display: block;
  799. padding: 10px 10px 10px 30px;
  800. font-weight: bold;
  801. line-height: 1.0;
  802. border-top: 4px solid rgba(${COLORS.answer.backRGB}, 0.37);
  803. background-color: rgba(${COLORS.answer.backRGB}, 0.37);
  804. color: ${COLORS.answer.fore};
  805. word-break: break-word;
  806. }
  807. #SEpreview-answers:before {
  808. content: "Answers:";
  809. margin-right: 1ex;
  810. font-size: 20px;
  811. line-height: 48px;
  812. }
  813. #SEpreview-answers a {
  814. color: ${COLORS.answer.fore};
  815. text-decoration: none;
  816. font-size: 11px;
  817. font-family: monospace;
  818. width: 32px;
  819. display: inline-block;
  820. vertical-align: top;
  821. margin: 0 1ex 1ex 0;
  822. }
  823. #SEpreview-answers img {
  824. width: 32px;
  825. height: 32px;
  826. }
  827. .SEpreview-accepted {
  828. position: relative;
  829. }
  830. .SEpreview-accepted:after {
  831. content: "✔";
  832. position: absolute;
  833. display: block;
  834. top: 1.3ex;
  835. right: -0.7ex;
  836. font-size: 32px;
  837. color: #4bff2c;
  838. text-shadow: 1px 2px 2px rgba(0,0,0,0.5);
  839. }
  840. #SEpreview-answers a.deleted-answer {
  841. color: ${COLORS.deleted.fore};
  842. background: transparent;
  843. opacity: 0.25;
  844. }
  845. #SEpreview-answers a.deleted-answer:hover {
  846. opacity: 1.0;
  847. }
  848. #SEpreview-answers a:hover:not(.SEpreviewed) {
  849. text-decoration: underline;
  850. }
  851. #SEpreview-answers a.SEpreviewed {
  852. background-color: ${COLORS.answer.fore};
  853. color: ${COLORS.answer.foreInv};
  854. position: relative;
  855. }
  856. #SEpreview-answers a.SEpreviewed:after {
  857. display: block;
  858. content: " ";
  859. position: absolute;
  860. left: -4px;
  861. top: -4px;
  862. right: -4px;
  863. bottom: -4px;
  864. border: 4px solid ${COLORS.answer.fore};
  865. }
  866.  
  867. .comment-edit,
  868. .delete-tag,
  869. .comment-actions td:last-child {
  870. display: none;
  871. }
  872. .comments {
  873. border-top: none;
  874. }
  875. .comments tr:last-child td {
  876. border-bottom: none;
  877. }
  878. .comments .new-comment-highlight {
  879. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  880. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  881. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  882. }
  883.  
  884. .user-info {
  885. position: relative;
  886. }
  887. #user-menu {
  888. position: absolute;
  889. }
  890. .SEpreview-user {
  891. position: absolute;
  892. right: -1em;
  893. top: -2em;
  894. transition: opacity .25s ease-in-out;
  895. opacity: 0;
  896. display: none;
  897. }
  898.  
  899. @-webkit-keyframes highlight {
  900. from {background-color: #ffcf78}
  901. to {background-color: none}
  902. }
  903. `
  904. + Object.keys(COLORS).map(s => `
  905. body[SEpreview-type="${s}"] #SEpreview-title {
  906. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  907. color: ${COLORS[s].fore};
  908. }
  909. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar {
  910. background-color: rgba(${COLORS[s].backRGB}, 0.1); }
  911. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb {
  912. background-color: rgba(${COLORS[s].backRGB}, 0.2); }
  913. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:hover {
  914. background-color: rgba(${COLORS[s].backRGB}, 0.3); }
  915. body[SEpreview-type="${s}"] #SEpreview-body::-webkit-scrollbar-thumb:active {
  916. background-color: rgba(${COLORS[s].backRGB}, 0.75); }
  917. `).join('')
  918. + ['deleted', 'closed'].map(s => `
  919. body[SEpreview-type="${s}"] #SEpreview-answers {
  920. border-top-color: rgba(${COLORS[s].backRGB}, 0.37);
  921. background-color: rgba(${COLORS[s].backRGB}, 0.37);
  922. color: ${COLORS[s].fore};
  923. }
  924. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed {
  925. background-color: ${COLORS[s].fore};
  926. color: ${COLORS[s].foreInv};
  927. }
  928. body[SEpreview-type="${s}"] #SEpreview-answers a.SEpreviewed:after {
  929. border-color: ${COLORS[s].fore};
  930. }
  931. `).join('');
  932. }