SE Preview on hover

Shows preview of the linked questions/answers on hover

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址