SE Preview on hover

Shows preview of the linked questions/answers on hover

  1. // ==UserScript==
  2. // @name SE Preview on hover
  3. // @description Shows preview of the linked questions/answers on hover
  4. // @version 1.1.9
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. //
  9. // please use only matches for the previewable targets and make sure the domain
  10. // is extractable via [-.\w] so that it starts with . like .stackoverflow.com
  11. // @match *://*.stackoverflow.com/*
  12. // @match *://*.superuser.com/*
  13. // @match *://*.serverfault.com/*
  14. // @match *://*.askubuntu.com/*
  15. // @match *://*.stackapps.com/*
  16. // @match *://*.mathoverflow.net/*
  17. // @match *://*.stackexchange.com/*
  18. // stackexchange.com must be the last main site
  19. //
  20. // @include /https?:\/\/(www\.)?google(\.com?)?(\.\w\w)?\/(webhp|q|.*?[?#]q=|search).*/
  21. // @match *://www.google.com/search*
  22. // @match *://*.bing.com/*
  23. // @match *://*.yahoo.com/*
  24. // @include /https?:\/\/(\w+\.)*yahoo.(com|\w\w(\.\w\w)?)\/.*/
  25. //
  26. // @require https://cdn.jsdelivr.net/gh/openstyles/lz-string-unsafe@22af192175b5e1707f49c57de7ce942d4d4ad480/lz-string-unsafe.min.js
  27. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/highlight.min.js
  28. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/autohotkey.min.js
  29. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/autoit.min.js
  30. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/dart.min.js
  31. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/delphi.min.js
  32. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/haskell.min.js
  33. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/moonscript.min.js
  34. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/nsis.min.js
  35. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/powershell.min.js
  36. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/r.min.js
  37. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/vbnet.min.js
  38. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/vbscript-html.min.js
  39. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/vbscript.min.js
  40. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/x86asm.min.js
  41. // @resource HL-style https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/default.min.css
  42. // @resource HL-style-dark https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/atom-one-dark-reasonable.min.css
  43. //
  44. // @grant GM_addStyle
  45. // @grant GM_xmlhttpRequest
  46. // @grant GM_getValue
  47. // @grant GM_setValue
  48. // @grant GM_getResourceText
  49. //
  50. // @connect stackoverflow.com
  51. // @connect superuser.com
  52. // @connect serverfault.com
  53. // @connect askubuntu.com
  54. // @connect stackapps.com
  55. // @connect mathoverflow.net
  56. // @connect stackexchange.com
  57. // @connect sstatic.net
  58. // @connect gravatar.com
  59. // @connect imgur.com
  60. // @connect self
  61. //
  62. // @noframes
  63. // @run-at document-idle
  64. // ==/UserScript==
  65.  
  66. /* global hljs LZStringUnsafe */
  67. 'use strict';
  68.  
  69. Promise.resolve().then(() => {
  70. Detector.init();
  71. Security.init();
  72. Urler.init();
  73. Cache.init();
  74. });
  75.  
  76. const PREVIEW_DELAY = 200;
  77. const AUTOHIDE_DELAY = 1000;
  78. const BUSY_CURSOR_DELAY = 300;
  79. // 1 minute for the recently active posts, scales up logarithmically
  80. const CACHE_DURATION = 60e3;
  81.  
  82. const PADDING = 24;
  83. const PROSE_WIDTH = 660; // .s-prose selector
  84. const PROSE_MARGIN = 16; // .s-prose margin-right
  85. const WIDTH = PROSE_WIDTH + PADDING * 2;
  86. const BORDER = 8;
  87. const TOP_BORDER = 24;
  88. const MIN_HEIGHT = 200;
  89. let colors;
  90. const COLORS_LIGHT = {
  91. body: {
  92. back: '#ffffff',
  93. fore: '#000000',
  94. },
  95. question: {
  96. back: '#5894d8',
  97. fore: '#265184',
  98. foreInv: '#fff',
  99. },
  100. answer: {
  101. back: '#70c350',
  102. fore: '#3f7722',
  103. foreInv: '#fff',
  104. },
  105. deleted: {
  106. back: '#cd9898',
  107. fore: '#b56767',
  108. foreInv: '#fff',
  109. },
  110. closed: {
  111. back: '#ffce5d',
  112. fore: '#c28800',
  113. foreInv: '#fff',
  114. },
  115. };
  116. const COLORS_DARK = {
  117. body: {
  118. back: '#222222',
  119. fore: '#cccccc',
  120. },
  121. question: {
  122. back: '#004696',
  123. fore: '#6abaff',
  124. foreInv: '#004696',
  125. },
  126. answer: {
  127. back: '#004c1b',
  128. fore: '#39c466',
  129. foreInv: '#004c1b',
  130. },
  131. deleted: {
  132. back: '#4d0a0b',
  133. fore: '#b56767',
  134. foreInv: '#fff',
  135. },
  136. closed: {
  137. back: '#4b360a',
  138. fore: '#c28800',
  139. foreInv: '#fff',
  140. },
  141. };
  142. const ID = 'SEpreview';
  143. const EXPANDO = Symbol(ID);
  144. const SEL_COMMENTS = '.js-follow-ups, .comments-list';
  145. const SEL_MORE = '.js-show-more-button, .js-show-link.comments-link';
  146.  
  147. const pv = {
  148. /** @type {Target} */
  149. target: null,
  150. /** @type {Element} */
  151. _frame: null,
  152. /** @type {Element} */
  153. get frame() {
  154. if (!this._frame)
  155. Preview.init();
  156. if (!document.contains(this._frame))
  157. document.body.appendChild(this._frame);
  158. return this._frame;
  159. },
  160. set frame(element) {
  161. this._frame = element;
  162. return element;
  163. },
  164. /** @type {Post} */
  165. post: {},
  166. hover: {x: 0, y: 0},
  167. stylesOverride: '',
  168. };
  169.  
  170. class Detector {
  171.  
  172. static init() {
  173. const {matches} = GM_info.script;
  174. const sites = matches
  175. .slice(0, matches.findIndex(m => m.includes('stackexchange.com')) + 1)
  176. .map(m => m.match(/[-.\w]+/)[0]);
  177. const rxsSites = 'https?://(\\w*\\.)*(' +
  178. matches
  179. .map(m => m.match(/^.*?\/\/\W*(\w.*?)\//)[1].replace(/\./g, '\\.'))
  180. .join('|') +
  181. ')/';
  182. Detector.rxPreviewableSite = new RegExp(rxsSites);
  183. Detector.rxPreviewablePost = new RegExp(rxsSites + '(questions|q|a|posts/comments)/\\d+');
  184. Detector.pageUrls = getBaseUrls(location, Detector.rxPreviewablePost);
  185. Detector.isStackExchangePage = Detector.rxPreviewableSite.test(location);
  186.  
  187. const {
  188. rxPreviewablePost,
  189. isStackExchangePage: isSE,
  190. pageUrls: {base, baseShort},
  191. } = Detector;
  192.  
  193. // array of target elements accumulated in mutation observer
  194. // cleared in attachHoverListener
  195. const moQueue = [];
  196.  
  197. onMutation([{
  198. addedNodes: [document.body],
  199. }]);
  200.  
  201. new MutationObserver(onMutation)
  202. .observe(document.body, {
  203. childList: true,
  204. subtree: true,
  205. });
  206.  
  207. Detector.init = true;
  208.  
  209. function onMutation(mutations) {
  210. const alreadyScheduled = moQueue.length > 0;
  211. for (const {addedNodes} of mutations) {
  212. for (const n of addedNodes) {
  213. if (!n.localName)
  214. continue;
  215. if (n.localName === 'a') {
  216. moQueue.push(n);
  217. continue;
  218. }
  219. // not using ..spreading since there could be 100k links for all we know
  220. // and that might exceed JS engine stack limit which can be pretty low
  221. const targets = n.getElementsByTagName('a');
  222. for (let k = 0, len = targets.length; k < len; k++)
  223. moQueue.push(targets[k]);
  224. if (!isSE)
  225. continue;
  226. if (n.classList.contains('question-summary')) {
  227. moQueue.push(...n.getElementsByClassName('answered'));
  228. moQueue.push(...n.getElementsByClassName('answered-accepted'));
  229. continue;
  230. }
  231. for (const el of n.getElementsByClassName('question-summary')) {
  232. moQueue.push(...el.getElementsByClassName('answered'));
  233. moQueue.push(...el.getElementsByClassName('answered-accepted'));
  234. }
  235. }
  236. }
  237. if (!alreadyScheduled && moQueue.length)
  238. setTimeout(hoverize);
  239. }
  240.  
  241. function hoverize() {
  242. for (const el of moQueue) {
  243. if (el[EXPANDO] instanceof Target)
  244. continue;
  245. if (el.localName === 'a') {
  246. if (isSE && el.classList.contains('js-share-link'))
  247. continue;
  248. const previewable = isPreviewable(el) || !isSE && isEmbeddedUrlPreviewable(el);
  249. if (!previewable)
  250. continue;
  251. const url = Urler.makeHttps(el.href);
  252. if (url.startsWith(base) || url.startsWith(baseShort))
  253. continue;
  254. }
  255. Target.createHoverable(el);
  256. }
  257. moQueue.length = 0;
  258. }
  259.  
  260. function isPreviewable(a) {
  261. let href = false;
  262. const host = '.' + a.hostname;
  263. const hostLen = host.length;
  264. for (const stackSite of sites) {
  265. if (host[hostLen - stackSite.length] === '.' &&
  266. host.endsWith(stackSite) &&
  267. rxPreviewablePost.test(href || (href = a.href)))
  268. return true;
  269. }
  270. }
  271.  
  272. function isEmbeddedUrlPreviewable(a) {
  273. const url = a.href;
  274. let i = url.indexOf('http', 1);
  275. if (i < 0)
  276. return false;
  277. i = (
  278. url.indexOf('http://', i) + 1 ||
  279. url.indexOf('https://', i) + 1 ||
  280. url.indexOf('http%3A%2F%2F', i) + 1 ||
  281. url.indexOf('https%3A%2F%2F', i) + 1
  282. ) - 1;
  283. if (i < 0)
  284. return false;
  285. const j = url.indexOf('&', i);
  286. const embeddedUrl = url.slice(i, j > 0 ? j : undefined);
  287. return rxPreviewablePost.test(embeddedUrl);
  288. }
  289.  
  290. function getBaseUrls(url, rx) {
  291. if (!rx.test(url))
  292. return {};
  293. const base = Urler.makeHttps(RegExp.lastMatch);
  294. return {
  295. base,
  296. baseShort: base.replace('/questions/', '/q/'),
  297. };
  298. }
  299. }
  300. }
  301.  
  302. /**
  303. * @property {Element} element
  304. * @property {Boolean} isLink
  305. * @property {String} url
  306. * @property {Number} timer
  307. * @property {Number} timerCursor
  308. * @property {String} savedCursor
  309. */
  310. class Target {
  311.  
  312. /** @param {Element} el */
  313. static createHoverable(el) {
  314. const target = new Target(el);
  315. Object.defineProperty(el, EXPANDO, {value: target});
  316. el.removeAttribute('title');
  317. el.addEventListener('mouseover', Target._onMouseOver);
  318. return target;
  319. }
  320.  
  321. /** @param {Element} el */
  322. constructor(el) {
  323. this.element = el;
  324. this.isLink = el.localName === 'a';
  325. }
  326.  
  327. release() {
  328. $.off('mousemove', this.element, Target._onMove);
  329. $.off('mouseout', this.element, Target._onHoverEnd);
  330. $.off('mousedown', this.element, Target._onHoverEnd);
  331.  
  332. for (const k in this) {
  333. if (k.startsWith('timer') && this[k] >= 1) {
  334. clearTimeout(this[k]);
  335. this[k] = 0;
  336. }
  337. }
  338. BusyCursor.hide(this);
  339. pv.target = null;
  340. }
  341.  
  342. get url() {
  343. const el = this.element;
  344. if (this.isLink)
  345. return el.href;
  346. const a = $('a', el.closest('.question-summary'));
  347. if (a)
  348. return a.href;
  349. }
  350.  
  351. /** @param {MouseEvent} e */
  352. static _onMouseOver(e) {
  353. if (Util.hasKeyModifiers(e))
  354. return;
  355. const self = /** @type {Target} */ this[EXPANDO];
  356. if (self === Preview.target && Preview.shown() ||
  357. self === pv.target)
  358. return;
  359.  
  360. if (pv.target)
  361. pv.target.release();
  362. pv.target = self;
  363.  
  364. pv.hover.x = e.pageX;
  365. pv.hover.y = e.pageY;
  366.  
  367. $.on('mousemove', this, Target._onMove);
  368. $.on('mouseout', this, Target._onHoverEnd);
  369. $.on('mousedown', this, Target._onHoverEnd);
  370.  
  371. Target._restartTimer(self);
  372. }
  373.  
  374. /** @param {MouseEvent} e */
  375. static _onHoverEnd(e) {
  376. if (e.type === 'mouseout' && e.target !== this)
  377. return;
  378. const self = /** @type {Target} */ this[EXPANDO];
  379. if (pv.xhr && pv.target === self) {
  380. pv.xhr.abort();
  381. pv.xhr = null;
  382. }
  383. self.release();
  384. self.timer = setTimeout(Target._onAbortTimer, AUTOHIDE_DELAY, self);
  385. }
  386.  
  387. /** @param {MouseEvent} e */
  388. static _onMove(e) {
  389. const stoppedMoving =
  390. Math.abs(pv.hover.x - e.pageX) < 2 &&
  391. Math.abs(pv.hover.y - e.pageY) < 2;
  392. if (stoppedMoving) {
  393. pv.hover.x = e.pageX;
  394. pv.hover.y = e.pageY;
  395. Target._restartTimer(this[EXPANDO]);
  396. }
  397. }
  398.  
  399. /** @param {Target} self */
  400. static _restartTimer(self) {
  401. if (self.timer)
  402. clearTimeout(self.timer);
  403. self.timer = setTimeout(Target._onTimer, PREVIEW_DELAY, self);
  404. }
  405.  
  406. /** @param {Target} self */
  407. static _onTimer(self) {
  408. self.timer = 0;
  409. const el = self.element;
  410. if (!el.matches(':hover')) {
  411. self.release();
  412. return;
  413. }
  414. $.off('mousemove', el, Target._onMove);
  415.  
  416. if (self.url)
  417. Preview.start(self);
  418. }
  419.  
  420. /** @param {Target} self */
  421. static _onAbortTimer(self) {
  422. if ((self === pv.target || self === Preview.target) &&
  423. pv.frame && !pv.frame.matches(':hover')) {
  424. pv.target = null;
  425. Preview.hide({fade: true});
  426. }
  427. }
  428. }
  429.  
  430.  
  431. class BusyCursor {
  432.  
  433. /** @param {Target} target */
  434. static schedule(target) {
  435. target.timerCursor = setTimeout(BusyCursor._onTimer, BUSY_CURSOR_DELAY, target);
  436. }
  437.  
  438. /** @param {Target} target */
  439. static hide(target) {
  440. if (target.timerCursor) {
  441. clearTimeout(target.timerCursor);
  442. target.timerCursor = 0;
  443. }
  444. const style = target.element.style;
  445. if (style.cursor === 'wait')
  446. style.cursor = target.savedCursor;
  447. }
  448.  
  449. /** @param {Target} target */
  450. static _onTimer(target) {
  451. target.timerCursor = 0;
  452. target.savedCursor = target.element.style.cursor;
  453. $.setStyle(target.element, ['cursor', 'wait']);
  454. }
  455. }
  456.  
  457.  
  458. class Preview {
  459.  
  460. static init() {
  461. pv.frame = $.create(`#${ID}`, {parent: document.body});
  462. pv.shadow = pv.frame.attachShadow({mode: 'open'});
  463. pv.body = $.create(`body#${ID}-body`, {parent: pv.shadow});
  464.  
  465. const WRAP_AROUND = '(or wrap around to the question)';
  466. const TITLE_PREV = 'Previous answer\n' + WRAP_AROUND;
  467. const TITLE_NEXT = 'Next answer\n' + WRAP_AROUND;
  468. const TITLE_ENTER = 'Return to the question\n(Enter was Return initially)';
  469.  
  470. pv.answersTitle =
  471. $.create(`#${ID}-answers-title`, [
  472. 'Answers:',
  473. $.create('p', [
  474. 'Use ',
  475. $.create('b', {title: TITLE_PREV}),
  476. $.create('b', {title: TITLE_NEXT, attributes: {mirrored: ''}}),
  477. $.create('label', {title: TITLE_ENTER}, 'Enter'),
  478. ' to switch entries',
  479. ]),
  480. ]);
  481.  
  482. $.on('keydown', pv.frame, Preview.onKey);
  483. $.on('keyup', pv.frame, Util.consumeEsc);
  484.  
  485. $.on('mouseover', pv.body, ScrollLock.enable);
  486. $.on('click', pv.body, Preview.onClick);
  487.  
  488. Sizer.init();
  489. Styles.init();
  490. Preview.init = true;
  491. }
  492.  
  493. /** @param {Target} target */
  494. static async start(target) {
  495. Preview.target = target;
  496.  
  497. if (!Security.checked)
  498. Security.check();
  499.  
  500. const {url} = target;
  501.  
  502. let data = Cache.read(url);
  503. if (data) {
  504. const r = await Urler.get(url, {method: 'HEAD'});
  505. const postTime = Util.getResponseDate(r.responseHeaders);
  506. if (postTime >= data.time)
  507. data = null;
  508. }
  509.  
  510. if (!data) {
  511. BusyCursor.schedule(target);
  512. const {finalUrl, responseText: html} = await Urler.get(target.url);
  513. data = {finalUrl, html, unsaved: true};
  514. BusyCursor.hide(target);
  515. }
  516.  
  517. data.url = url;
  518. data.showAnswer = !target.isLink;
  519.  
  520. if (!Preview.prepare(data))
  521. Preview.target = null;
  522. else if (data.unsaved && data.lastActivity >= 1)
  523. Preview.save(data);
  524. }
  525.  
  526. static save({url, finalUrl, html, lastActivity}) {
  527. const inactiveDays = Math.max(0, (Date.now() - lastActivity) / (24 * 3600e3));
  528. const cacheDuration = CACHE_DURATION * Math.pow(Math.log(inactiveDays + 1) + 1, 2);
  529. setTimeout(Cache.write, 1000, {url, finalUrl, html, cacheDuration});
  530. }
  531.  
  532. // data is mutated: its lastActivity property is assigned!
  533. static prepare(data) {
  534. const {finalUrl, html, showAnswer, doc = Util.parseHtml(html)} = data;
  535.  
  536. if (!doc || !doc.head)
  537. return Util.error('no HEAD in the document received for', finalUrl);
  538.  
  539. let answerId;
  540. if (showAnswer) {
  541. const el = $('[id^="answer-"]', doc);
  542. answerId = el && el.id.match(/\d+/)[0];
  543. } else {
  544. answerId = finalUrl.match(/questions\/\d+\/[^/]+\/(\d+)|$/)[1];
  545. }
  546. const selector = answerId ? '#answer-' + answerId : '#question';
  547. const thing = $(selector, doc);
  548. const core = $(`.${answerId ? 'answer' : 'post'}cell`, thing);
  549. if (!core)
  550. return Util.error('No parsable post found', doc);
  551.  
  552. const isQuestion = !answerId;
  553. const status = isQuestion && $('[role="status"]', core);
  554. const isClosed = status && $('[href*="closed"]', status);
  555. const isDeleted = Boolean(core.closest('.deleted-answer'));
  556. const type = [
  557. isQuestion && 'question' || 'answer',
  558. isDeleted && 'deleted',
  559. isClosed && 'closed',
  560. ].filter(Boolean).join(' ');
  561. const answers = $.all('.answer', doc);
  562. const comments = $(SEL_COMMENTS, thing);
  563. const more = $(SEL_MORE, thing);
  564. const lastActivity = Util.tryCatch(Util.extractTime, $('a[href*="?lastactivity"]', core)) ||
  565. Date.now();
  566. Object.assign(pv, {
  567. finalUrl,
  568. finalUrlOfQuestion: Urler.makeCacheable(finalUrl),
  569. });
  570. /** @typedef Post
  571. * @property {Document} doc
  572. * @property {String} html
  573. * @property {String} selector
  574. * @property {String} type
  575. * @property {String} id
  576. * @property {String} title
  577. * @property {Boolean} isQuestion
  578. * @property {Boolean} isDeleted
  579. * @property {Number} lastActivity
  580. * @property {Number} numAnswers
  581. * @property {Element} core
  582. * @property {Element} comments
  583. * @property {Element[]} answers
  584. * @property {Element[]} renderParts
  585. */
  586. Object.assign(pv.post, {
  587. doc,
  588. html,
  589. core,
  590. selector,
  591. answers,
  592. comments,
  593. type,
  594. isQuestion,
  595. isDeleted,
  596. lastActivity,
  597. id: isQuestion ? Urler.getFirstNumber(finalUrl) : answerId,
  598. title: $('meta[property="og:title"]', doc).content,
  599. numAnswers: answers.length,
  600. renderParts: [
  601. // including the parent so the right CSS kicks in
  602. core.cloneNode(true),
  603. comments,
  604. ],
  605. });
  606.  
  607. $.remove('script', doc);
  608. if (comments) {
  609. Render._comments(comments);
  610. if (more)
  611. comments.appendChild($.create('a', {className: more.className}, more.innerText));
  612. }
  613. // Expanding relative URLs manually since <base> may be restricted via CSP
  614. for (const a of $.all('a[href]:not([href*=":"])', doc))
  615. a.href = new URL(a.getAttribute('href'), finalUrl);
  616.  
  617. Promise.all([
  618. pv.frame,
  619. Preview.addStyles(),
  620. Security.ready(),
  621. ]).then(Preview.show);
  622.  
  623. data.lastActivity = lastActivity;
  624. return true;
  625. }
  626.  
  627. static show() {
  628. Render.all();
  629.  
  630. const style = getComputedStyle(pv.frame);
  631. if (style.opacity !== '1' || style.display !== 'block') {
  632. $.setStyle(pv.frame, ['display', 'block']);
  633. setTimeout($.setStyle, 0, pv.frame, ['opacity', '1']);
  634. }
  635.  
  636. pv.parts.focus();
  637. }
  638.  
  639. static hide({fade = false} = {}) {
  640. if (Preview.target) {
  641. Preview.target.release();
  642. Preview.target = null;
  643. }
  644.  
  645. pv.body.onmouseover = null;
  646. pv.body.onclick = null;
  647. pv.body.onkeydown = null;
  648.  
  649. if (fade) {
  650. Util.fadeOut(pv.frame)
  651. .then(Preview.eraseBoxIfHidden);
  652. } else {
  653. $.setStyle(pv.frame,
  654. ['opacity', '0'],
  655. ['display', 'none']);
  656. Preview.eraseBoxIfHidden();
  657. }
  658. }
  659.  
  660. static shown() {
  661. return pv.frame.style.opacity === '1';
  662. }
  663.  
  664. /** @param {KeyboardEvent} e */
  665. static onKey(e) {
  666. switch (e.key) {
  667. case 'Escape':
  668. Preview.hide({fade: true});
  669. break;
  670. case 'ArrowUp':
  671. case 'PageUp':
  672. if (pv.parts.scrollTop)
  673. return;
  674. break;
  675. case 'ArrowDown':
  676. case 'PageDown': {
  677. const {scrollTop: t, clientHeight: h, scrollHeight} = pv.parts;
  678. if (t + h < scrollHeight)
  679. return;
  680. break;
  681. }
  682. case 'ArrowLeft':
  683. case 'ArrowRight': {
  684. if (!pv.post.numAnswers)
  685. return;
  686. // current is 0 if isQuestion, 1 is the first answer
  687. const answers = $.all(`#${ID}-answers a`);
  688. const current = pv.post.numAnswers ?
  689. answers.indexOf($('.SEpreviewed')) + 1 :
  690. pv.post.isQuestion ? 0 : 1;
  691. const num = pv.post.numAnswers + 1;
  692. const dir = e.key === 'ArrowLeft' ? -1 : 1;
  693. const toShow = (current + dir + num) % num;
  694. const a = toShow ? answers[toShow - 1] : $(`#${ID}-title`);
  695. a.click();
  696. break;
  697. }
  698. case 'Enter':
  699. if (pv.post.isQuestion)
  700. return;
  701. $(`#${ID}-title`).click();
  702. break;
  703. default:
  704. return;
  705. }
  706. e.preventDefault();
  707. }
  708.  
  709. /** @param {MouseEvent} e */
  710. static onClick(e) {
  711. if (e.target.id === `${ID}-close`) {
  712. Preview.hide();
  713. return;
  714. }
  715.  
  716. const link = e.target.closest('a');
  717. if (!link)
  718. return;
  719.  
  720. if (link.matches(SEL_MORE)) {
  721. Util.fadeOut(link, 0.5);
  722. Preview.loadComments();
  723. e.preventDefault();
  724. return;
  725. }
  726.  
  727. if (e.button ||
  728. Util.hasKeyModifiers(e) ||
  729. !link.matches('.SEpreviewable')) {
  730. link.target = '_blank';
  731. return;
  732. }
  733.  
  734. e.preventDefault();
  735.  
  736. const {doc} = pv.post;
  737. if (link.id === `${ID}-title`)
  738. Preview.prepare({doc, finalUrl: pv.finalUrlOfQuestion});
  739. else if (link.matches(`#${ID}-answers a`))
  740. Preview.prepare({doc, finalUrl: pv.finalUrlOfQuestion + '/' + Urler.getFirstNumber(link)});
  741. else
  742. Preview.start(new Target(link));
  743. }
  744.  
  745. static eraseBoxIfHidden() {
  746. if (!Preview.shown())
  747. pv.body.textContent = '';
  748. }
  749.  
  750. static setHeight(height) {
  751. const currentHeight = pv.frame.clientHeight;
  752. const borderHeight = pv.frame.offsetHeight - currentHeight;
  753. const newHeight = Math.max(MIN_HEIGHT, Math.min(innerHeight - borderHeight, height));
  754. if (newHeight !== currentHeight)
  755. $.setStyle(pv.frame, ['height', newHeight + 'px']);
  756. }
  757.  
  758. static async addStyles() {
  759. const isDark = matchMedia('(prefers-color-scheme: dark)').matches;
  760. colors = isDark ? COLORS_DARK : COLORS_LIGHT;
  761. pv.body.className = isDark ? 'theme-dark' : '';
  762. Styles.init(isDark);
  763.  
  764. let last = $.create(`style#${ID}-styles.${Styles.REUSABLE}`, {
  765. textContent: pv.stylesOverride,
  766. before: pv.shadow.firstChild,
  767. });
  768.  
  769. if (!pv.styles) {
  770. pv.styles = new Map();
  771. pv.stylesScaled = new Set();
  772. }
  773.  
  774. const toDownload = [];
  775. const sourceElements = $.all('link[rel="stylesheet"], style', pv.post.doc);
  776.  
  777. for (const {href, textContent, localName} of sourceElements) {
  778. const isLink = localName === 'link';
  779. const id = ID + '-style-' + (isLink ? href : await Util.sha256(textContent));
  780. const el = pv.styles.get(id);
  781. if (!el && isLink)
  782. toDownload.push(Urler.get({url: href, context: id}));
  783. last = $.create('style', {
  784. id,
  785. className: Styles.REUSABLE,
  786. textContent: isLink ? $.text(el) : textContent,
  787. after: last,
  788. });
  789. pv.styles.set(id, last);
  790. }
  791.  
  792. const downloaded = await Promise.all(toDownload);
  793.  
  794. for (const {responseText, context: id} of downloaded)
  795. Styles.applyRemScale(id, responseText);
  796.  
  797. if (!pv.remScale) {
  798. pv.remScale = parseFloat(getComputedStyle(pv.body).fontSize) /
  799. parseFloat(getComputedStyle(document.documentElement).fontSize);
  800. if (pv.remScale !== 1)
  801. for (const id of pv.styles.keys())
  802. Styles.applyRemScale(id);
  803. }
  804. }
  805.  
  806. static async loadComments() {
  807. const list = pv.post.comments;
  808. const url = new URL(pv.finalUrl).origin + '/posts/' + pv.post.id.match(/\d+/)[0] + '/comments';
  809. const doc = Util.parseHtml((await Urler.get(url)).responseText);
  810. const oldIds = new Set([...list.children].map(e => e.id));
  811.  
  812. Render._comments(doc);
  813. list.textContent = '';
  814. list.append(...doc.body.children);
  815. for (const cmt of list.children) {
  816. if (!oldIds.has(cmt.id))
  817. cmt.classList.add('new-comment-highlight');
  818. }
  819.  
  820. Render.previewableLinks(list);
  821. Render.hoverableUsers(list);
  822. }
  823. }
  824.  
  825.  
  826. class Render {
  827.  
  828. static all() {
  829. pv.frame.classList.toggle(`${ID}-hasAnswerShelf`, pv.post.numAnswers > 0);
  830. pv.frame.setAttribute(`${ID}-type`, pv.post.type);
  831. pv.body.setAttribute(`${ID}-type`, pv.post.type);
  832.  
  833. $.create(`a#${ID}-title.SEpreviewable`, {
  834. href: pv.finalUrlOfQuestion,
  835. textContent: pv.post.title,
  836. parent: pv.body,
  837. });
  838.  
  839. $.create(`#${ID}-close`, {
  840. title: 'Or press Esc key while the preview is focused (also when just shown)',
  841. parent: pv.body,
  842. });
  843.  
  844. $.create(`#${ID}-meta`, {
  845. parent: pv.body,
  846. onmousedown: Sizer.onMouseDown,
  847. children: [
  848. Render._votes(),
  849. pv.post.isQuestion
  850. ? Render._questionMeta()
  851. : Render._answerMeta(),
  852. ],
  853. });
  854.  
  855. Render.previewableLinks(pv.post.doc);
  856.  
  857. // rendering answers should happen before pv.body is processed
  858. const shelf = pv.post.numAnswers &&
  859. pv.post.answers.reduce(Render._answer, [pv.answersTitle]);
  860.  
  861. if (Security.noImages)
  862. Security.embedImages(...pv.post.renderParts);
  863.  
  864. pv.parts = $.create(`#${ID}-parts`, {
  865. className: pv.post.isDeleted ? 'deleted-answer' : '',
  866. tabIndex: 0,
  867. scrollTop: 0,
  868. parent: pv.body,
  869. children: pv.post.renderParts,
  870. });
  871. Render.hoverableUsers(pv.parts);
  872.  
  873. if (shelf) {
  874. $.create(`#${ID}-answers`, {parent: pv.body}, shelf);
  875. } else {
  876. $.remove(`#${ID}-answers`, pv.body);
  877. }
  878.  
  879. const ACTIONS_SEL = '.js-post-menu > div';
  880. const elActions = $(ACTIONS_SEL);
  881.  
  882. // delinkify/remove non-functional items in post-menu
  883. $.remove('.js-share-link, .flag-post-link', pv.body);
  884. for (const el of $.all(`${ACTIONS_SEL} button`)) {
  885. const elWrapper = el.closest(`${ACTIONS_SEL} > div`);
  886. if (elWrapper) elWrapper.remove();
  887. }
  888.  
  889. // add a timeline link
  890. elActions.append(
  891. $.create('div.' + elActions.firstElementChild.className, [
  892. $.create('a', {href: `/posts/${pv.post.id}/timeline`}, 'Timeline'),
  893. ])
  894. );
  895.  
  896. // prettify code blocks
  897. hljs.configure({
  898. languages: [
  899. ...$.all('.post-taglist .post-tag', pv.post.doc).map($.text),
  900. 'javascript',
  901. 'html',
  902. ],
  903. });
  904. $.all('pre > code').forEach(el => {
  905. el = el.parentElement;
  906. el.className = el.className.replace(/((?:^|\s)lang-)bsh(?=\s|$)/, '$1powershell');
  907. hljs.highlightBlock(el);
  908. });
  909.  
  910. const leftovers = $.all('style, link, script');
  911. for (const el of leftovers) {
  912. if (el.classList.contains(Styles.REUSABLE))
  913. el.classList.remove(Styles.REUSABLE);
  914. else
  915. el.remove();
  916. }
  917.  
  918. pv.post.html = null;
  919. pv.post.core = null;
  920. pv.post.renderParts = null;
  921. pv.post.answers = null;
  922. }
  923.  
  924. /** @param {Element} container */
  925. static previewableLinks(container) {
  926. for (const a of $.all('a:not(.SEpreviewable)', container)) {
  927. let href = a.getAttribute('href');
  928. if (!href)
  929. continue;
  930. if (!href.includes('://')) {
  931. href = a.href;
  932. a.setAttribute('href', href);
  933. }
  934. if (Detector.rxPreviewablePost.test(href)) {
  935. a.removeAttribute('title');
  936. a.classList.add('SEpreviewable');
  937. }
  938. }
  939. }
  940.  
  941. /** @param {Element} container */
  942. static hoverableUsers(container) {
  943. for (const a of $.all('a[href*="/users/"]', container)) {
  944. if (Detector.rxPreviewableSite.test(a.href) &&
  945. a.pathname.match(/^\/users\/\d+/)) {
  946. a.onmouseover = UserCard.onUserLinkHovered;
  947. a.classList.add(`${ID}-userLink`);
  948. }
  949. }
  950. }
  951.  
  952. static _answer(res, el) {
  953. const shortUrl = $('.js-share-link', el).href.replace(/(\d+)\/\d+/, '$1');
  954. const extraClasses =
  955. (el.matches(pv.post.selector) ? ' SEpreviewed' : '') +
  956. (el.matches('.deleted-answer') ? ' deleted-answer' : '') +
  957. (el.matches('.accepted-answer') ? ` ${ID}-accepted` : '');
  958. const author = $('.post-signature:last-child', el);
  959. const title =
  960. $.text('.user-details a', author) +
  961. ' (rep ' +
  962. $.text('.reputation-score', author) +
  963. ')\n' +
  964. $.text('.user-action-time', author);
  965. let gravatar = $('img, .anonymous-gravatar, .community-wiki', author);
  966. if (gravatar && Security.noImages)
  967. Security.embedImages(gravatar);
  968. if (gravatar && gravatar.src)
  969. gravatar = $.create('img', {src: gravatar.src});
  970. const a = $.create('a', {
  971. href: shortUrl,
  972. title: title,
  973. className: 'SEpreviewable' + extraClasses,
  974. textContent: $.text('.js-vote-count', el).replace(/^0$/, '\xA0') + ' ',
  975. children: gravatar,
  976. });
  977. res.push(a, ' ');
  978. return res;
  979. }
  980.  
  981. static _comments(list) {
  982. for (let el of $.all('.js-comment-body + div', list)) {
  983. el.textContent = +$('.js-vote-button', el).textContent.trim() || '\xA0';
  984. if ((el = el.nextElementSibling)) el.remove();
  985. }
  986. $.remove('.edit-comment-form', list);
  987. for (const el of $.all('.comment-actions', list))
  988. el.textContent = +el.innerText || '\xA0';
  989. list.className = '';
  990. }
  991.  
  992. static _votes() {
  993. const votes = $.text('.js-vote-count', pv.post.core.closest('.post-layout'));
  994. if (Number(votes))
  995. return $.create('b', `${votes} vote${Math.abs(votes) >= 2 ? 's' : ''}`);
  996. }
  997.  
  998. static _questionMeta() {
  999. try {
  1000. return [...$('time', pv.post.doc).closest('.grid').children]
  1001. .map(el => el.textContent.trim())
  1002. .map((s, i) => (i ? s.toLowerCase() : s))
  1003. .join(', ');
  1004. } catch (e) {
  1005. return '';
  1006. }
  1007. }
  1008.  
  1009. static _answerMeta() {
  1010. return $.all('.user-action-time', pv.post.core.closest('.answer'))
  1011. .reverse()
  1012. .map($.text)
  1013. .join(', ');
  1014. }
  1015. }
  1016.  
  1017.  
  1018. class UserCard {
  1019.  
  1020. _fadeIn() {
  1021. this._retakeId(this);
  1022. $.setStyle(this.element,
  1023. ['opacity', '0'],
  1024. ['display', 'block']);
  1025. this.timer = setTimeout(() => {
  1026. if (this.timer)
  1027. $.setStyle(this.element, ['opacity', '1']);
  1028. });
  1029. }
  1030.  
  1031. _retakeId() {
  1032. if (this.element.id !== 'user-menu') {
  1033. const oldCard = $('#user-menu');
  1034. if (oldCard)
  1035. oldCard.id = oldCard.style.display = '';
  1036. this.element.id = 'user-menu';
  1037. }
  1038. }
  1039.  
  1040. // 'this' is the hoverable link enclosing the user's name/avatar
  1041. static onUserLinkHovered() {
  1042. clearTimeout(this[EXPANDO]);
  1043. this[EXPANDO] = setTimeout(UserCard._show, PREVIEW_DELAY * 2, this);
  1044. }
  1045.  
  1046. /** @param {HTMLAnchorElement} a */
  1047. static async _show(a) {
  1048. if (!a.matches(':hover'))
  1049. return;
  1050. const el = a.nextElementSibling;
  1051. const card = el && el.matches(`.${ID}-userCard`) && el[EXPANDO] ||
  1052. await UserCard._create(a);
  1053. card._fadeIn();
  1054. }
  1055.  
  1056. /** @param {HTMLAnchorElement} a */
  1057. static async _create(a) {
  1058. const url = a.origin + '/users/user-info/' + Urler.getFirstNumber(a);
  1059. let {html} = Cache.read(url) || {};
  1060. if (!html) {
  1061. html = (await Urler.get(url)).responseText;
  1062. Cache.write({url, html, cacheDuration: CACHE_DURATION * 100});
  1063. }
  1064.  
  1065. const dom = Util.parseHtml(html);
  1066. if (Security.noImages)
  1067. Security.embedImages(dom);
  1068.  
  1069. const b = a.getBoundingClientRect();
  1070. const pb = pv.parts.getBoundingClientRect();
  1071. const left = Math.min(b.left - 20, pb.right - 350) - pb.left + 'px';
  1072. const isClipped = b.bottom + 100 > pb.bottom;
  1073.  
  1074. const el = $.create(`#user-menu-tmp.${ID}-userCard`, {
  1075. attributes: {
  1076. style: `left: ${left} !important;` +
  1077. (isClipped ? 'margin-top: -5rem !important;' : ''),
  1078. },
  1079. onmouseout: UserCard._onMouseOut,
  1080. children: dom.body.children,
  1081. after: a,
  1082. });
  1083.  
  1084. const card = new UserCard(el);
  1085. Object.defineProperty(el, EXPANDO, {value: card});
  1086. card.element = el;
  1087. return card;
  1088. }
  1089.  
  1090. /** @param {MouseEvent} e */
  1091. static _onMouseOut(e) {
  1092. if (this.matches(':hover') ||
  1093. this.style.opacity === '0' /* fading out already */)
  1094. return;
  1095.  
  1096. const self = /** @type {UserCard} */ this[EXPANDO];
  1097. clearTimeout(self.timer);
  1098. self.timer = 0;
  1099.  
  1100. Util.fadeOut(this);
  1101. }
  1102. }
  1103.  
  1104.  
  1105. class Sizer {
  1106.  
  1107. static init() {
  1108. Preview.setHeight(GM_getValue('height', innerHeight / 3) >> 0);
  1109. }
  1110.  
  1111. /** @param {MouseEvent} e */
  1112. static onMouseDown(e) {
  1113. if (e.button !== 0 || Util.hasKeyModifiers(e))
  1114. return;
  1115. Sizer._heightDelta = innerHeight - e.clientY - pv.frame.clientHeight;
  1116. $.on('mousemove', document, Sizer._onMouseMove);
  1117. $.on('mouseup', document, Sizer._onMouseUp);
  1118. }
  1119.  
  1120. /** @param {MouseEvent} e */
  1121. static _onMouseMove(e) {
  1122. Preview.setHeight(innerHeight - e.clientY - Sizer._heightDelta);
  1123. getSelection().removeAllRanges();
  1124. }
  1125.  
  1126. /** @param {MouseEvent} e */
  1127. static _onMouseUp(e) {
  1128. GM_setValue('height', pv.frame.clientHeight);
  1129. $.off('mouseup', document, Sizer._onMouseUp);
  1130. $.off('mousemove', document, Sizer._onMouseMove);
  1131. }
  1132. }
  1133.  
  1134.  
  1135. class ScrollLock {
  1136.  
  1137. static enable() {
  1138. if (ScrollLock.active)
  1139. return;
  1140. ScrollLock.active = true;
  1141. ScrollLock.x = scrollX;
  1142. ScrollLock.y = scrollY;
  1143. $.on('mouseover', document.body, ScrollLock._onMouseOver);
  1144. $.on('scroll', document, ScrollLock._onScroll);
  1145. }
  1146.  
  1147. static disable() {
  1148. ScrollLock.active = false;
  1149. $.off('mouseover', document.body, ScrollLock._onMouseOver);
  1150. $.off('scroll', document, ScrollLock._onScroll);
  1151. }
  1152.  
  1153. static _onMouseOver() {
  1154. if (ScrollLock.active)
  1155. ScrollLock.disable();
  1156. }
  1157.  
  1158. static _onScroll() {
  1159. scrollTo(ScrollLock.x, ScrollLock.y);
  1160. }
  1161. }
  1162.  
  1163.  
  1164. class Security {
  1165.  
  1166. static init() {
  1167. if (Detector.isStackExchangePage) {
  1168. Security.checked = true;
  1169. Security.check = null;
  1170. }
  1171. Security.init = true;
  1172. }
  1173.  
  1174. static async check() {
  1175. Security.noImages = false;
  1176. Security._resolveOnReady = [];
  1177. Security._imageCache = new Map();
  1178.  
  1179. const {headers} = await fetch(location.href, {
  1180. method: 'HEAD',
  1181. cache: 'force-cache',
  1182. mode: 'same-origin',
  1183. credentials: 'same-origin',
  1184. });
  1185. const csp = headers.get('Content-Security-Policy');
  1186. const imgSrc = /(?:^|[\s;])img-src\s+([^;]+)/i.test(csp) && RegExp.$1.trim();
  1187. if (imgSrc)
  1188. Security.noImages = !/(^\s)(\*|https?:)(\s|$)/.test(imgSrc);
  1189.  
  1190. Security._resolveOnReady.forEach(fn => fn());
  1191. Security._resolveOnReady = null;
  1192. Security.checked = true;
  1193. Security.check = null;
  1194. }
  1195.  
  1196. /** @return Promise<void> */
  1197. static ready() {
  1198. return Security.checked ?
  1199. Promise.resolve() :
  1200. new Promise(done => Security._resolveOnReady.push(done));
  1201. }
  1202.  
  1203. static embedImages(...containers) {
  1204. for (const container of containers) {
  1205. if (!container)
  1206. continue;
  1207. if (Util.isIterable(container)) {
  1208. Security.embedImages(...container);
  1209. continue;
  1210. }
  1211. if (container.localName === 'img') {
  1212. Security._embedImage(container);
  1213. continue;
  1214. }
  1215. for (const img of container.getElementsByTagName('img'))
  1216. Security._embedImage(img);
  1217. }
  1218. }
  1219.  
  1220. static _embedImage(img) {
  1221. const src = img.src;
  1222. if (!src || src.startsWith('data:'))
  1223. return;
  1224. const data = Security._imageCache.get(src);
  1225. const alreadyFetching = Array.isArray(data);
  1226. if (alreadyFetching) {
  1227. data.push(img);
  1228. } else if (data) {
  1229. img.src = data;
  1230. return;
  1231. } else {
  1232. Security._imageCache.set(src, [img]);
  1233. Security._fetchImage(src);
  1234. }
  1235. $.setStyle(img, ['visibility', 'hidden']);
  1236. img.dataset.src = src;
  1237. img.removeAttribute('src');
  1238. }
  1239.  
  1240. static async _fetchImage(src) {
  1241. const r = await Urler.get({url: src, responseType: 'blob'});
  1242. const type = Util.getResponseMimeType(r.responseHeaders);
  1243. const blob = r.response;
  1244. const blobType = blob.type;
  1245. let dataUri = await Util.blobToBase64(blob);
  1246. if (blobType !== type)
  1247. dataUri = 'data:' + type + dataUri.slice(dataUri.indexOf(';'));
  1248.  
  1249. const images = Security._imageCache.get(src);
  1250. Security._imageCache.set(src, dataUri);
  1251.  
  1252. let detached = false;
  1253. for (const el of images) {
  1254. el.src = dataUri;
  1255. el.style.removeProperty('visibility');
  1256. if (!detached && el.ownerDocument !== document)
  1257. detached = true;
  1258. }
  1259.  
  1260. if (detached) {
  1261. for (const el of $.all(`img[data-src="${src}"]`)) {
  1262. el.src = dataUri;
  1263. el.style.removeProperty('visibility');
  1264. }
  1265. }
  1266. }
  1267. }
  1268.  
  1269.  
  1270. // eslint-disable-next-line no-redeclare
  1271. class Cache {
  1272.  
  1273. static init() {
  1274. Cache.timers = new Map();
  1275. setTimeout(Cache._cleanup, 10e3);
  1276. }
  1277.  
  1278. static read(url) {
  1279. const keyUrl = Urler.makeCacheable(url);
  1280. const [time, expires, finalUrl = url] = (localStorage[keyUrl] || '').split('\t');
  1281. const keyFinalUrl = Urler.makeCacheable(finalUrl);
  1282. return expires > Date.now() && {
  1283. time,
  1284. finalUrl,
  1285. html: LZStringUnsafe.decompressFromUTF16(localStorage[keyFinalUrl + '\thtml']),
  1286. };
  1287. }
  1288.  
  1289. // standard keyUrl = time,expiry
  1290. // keyUrl\thtml = html
  1291. // redirected keyUrl = time,expiry,finalUrl
  1292. // keyFinalUrl = time,expiry
  1293. // keyFinalUrl\thtml = html
  1294. static write({url, finalUrl, html, cacheDuration = CACHE_DURATION}) {
  1295.  
  1296. cacheDuration = Math.max(CACHE_DURATION, Math.min(0x7FFF0000, cacheDuration >> 0));
  1297. finalUrl = (finalUrl || url).replace(/[?#].*/, '');
  1298.  
  1299. const keyUrl = Urler.makeCacheable(url);
  1300. const keyFinalUrl = Urler.makeCacheable(finalUrl);
  1301. const lz = LZStringUnsafe.compressToUTF16(html);
  1302.  
  1303. if (!Util.tryCatch(Cache._writeRaw, keyFinalUrl + '\thtml', lz)) {
  1304. Cache._cleanup({aggressive: true});
  1305. if (!Util.tryCatch(Cache._writeRaw, keyFinalUrl + '\thtml', lz))
  1306. return Util.error('localStorage write error');
  1307. }
  1308.  
  1309. const time = Date.now();
  1310. const expiry = time + cacheDuration;
  1311. localStorage[keyFinalUrl] = time + '\t' + expiry;
  1312. if (keyUrl !== keyFinalUrl)
  1313. localStorage[keyUrl] = time + '\t' + expiry + '\t' + finalUrl;
  1314.  
  1315. const t = setTimeout(Cache._delete, cacheDuration + 1000,
  1316. keyUrl,
  1317. keyFinalUrl,
  1318. keyFinalUrl + '\thtml');
  1319.  
  1320. for (const url of [keyUrl, keyFinalUrl]) {
  1321. clearTimeout(Cache.timers.get(url));
  1322. Cache.timers.set(url, t);
  1323. }
  1324. }
  1325.  
  1326. static _writeRaw(k, v) {
  1327. localStorage[k] = v;
  1328. return true;
  1329. }
  1330.  
  1331. static _delete(...keys) {
  1332. for (const k of keys) {
  1333. delete localStorage[k];
  1334. Cache.timers.delete(k);
  1335. }
  1336. }
  1337.  
  1338. static _cleanup({aggressive = false} = {}) {
  1339. for (const k in localStorage) {
  1340. if ((k.startsWith('http://') || k.startsWith('https://')) &&
  1341. !k.includes('\t')) {
  1342. const [, expires, url] = (localStorage[k] || '').split('\t');
  1343. if (Number(expires) > Date.now() && !aggressive)
  1344. break;
  1345. if (url) {
  1346. delete localStorage[url];
  1347. Cache.timers.delete(url);
  1348. }
  1349. delete localStorage[(url || k) + '\thtml'];
  1350. delete localStorage[k];
  1351. Cache.timers.delete(k);
  1352. }
  1353. }
  1354. }
  1355. }
  1356.  
  1357.  
  1358. class Urler {
  1359.  
  1360. static init() {
  1361. Urler.xhr = null;
  1362. Urler.xhrNoSSL = new Set();
  1363. Urler.init = true;
  1364. }
  1365.  
  1366. static getFirstNumber(url) {
  1367. if (typeof url === 'string')
  1368. url = new URL(url);
  1369. return url.pathname.match(/\/(\d+)/)[1];
  1370. }
  1371.  
  1372. static makeHttps(url) {
  1373. if (!url)
  1374. return '';
  1375. if (url.startsWith('http:'))
  1376. return 'https:' + url.slice(5);
  1377. return url;
  1378. }
  1379.  
  1380. // strips queries and hashes and anything after the main part
  1381. // https://site/questions/NNNNNN/title/
  1382. static makeCacheable(url) {
  1383. return url
  1384. .replace(/(\/q(?:uestions)?\/\d+\/[^/]+).*/, '$1')
  1385. .replace(/(\/a(?:nswers)?\/\d+).*/, '$1')
  1386. .replace(/[?#].*$/, '');
  1387. }
  1388.  
  1389. static get(options) {
  1390. if (!options.url)
  1391. options = {url: options, method: 'GET'};
  1392. if (!options.method)
  1393. options = Object.assign({method: 'GET'}, options);
  1394.  
  1395. let url = options.url;
  1396. const hostname = new URL(url).hostname;
  1397.  
  1398. if (Urler.xhrNoSSL.has(hostname)) {
  1399. url = url.replace(/^https/, 'http');
  1400. } else {
  1401. url = Urler.makeHttps(url);
  1402. const _onerror = options.onerror;
  1403. options.onerror = () => {
  1404. options.onerror = _onerror;
  1405. options.url = url.replace(/^https/, 'http');
  1406. Urler.xhrNoSSL.add(hostname);
  1407. return Urler.get(options);
  1408. };
  1409. }
  1410.  
  1411. return new Promise(resolve => {
  1412. let xhr;
  1413. options.onload = r => {
  1414. if (pv.xhr === xhr)
  1415. pv.xhr = null;
  1416. resolve(r);
  1417. };
  1418. options.url = url;
  1419. xhr = pv.xhr = GM_xmlhttpRequest(options);
  1420. });
  1421. }
  1422. }
  1423.  
  1424.  
  1425. class Util {
  1426.  
  1427. static tryCatch(fn, ...args) {
  1428. try {
  1429. return fn(...args);
  1430. } catch (e) {}
  1431. }
  1432.  
  1433. static isIterable(o) {
  1434. return typeof o === 'object' && Symbol.iterator in o;
  1435. }
  1436.  
  1437. static parseHtml(html) {
  1438. if (!Util.parser)
  1439. Util.parser = new DOMParser();
  1440. return Util.parser.parseFromString(html, 'text/html');
  1441. }
  1442.  
  1443. static extractTime(element) {
  1444. return new Date(element.title).getTime();
  1445. }
  1446.  
  1447. static getResponseMimeType(headers) {
  1448. return headers.match(/^\s*content-type:\s*(.*)|$/mi)[1] ||
  1449. 'image/png';
  1450. }
  1451.  
  1452. static getResponseDate(headers) {
  1453. try {
  1454. return new Date(headers.match(/^\s*date:\s*(.*)/mi)[1]);
  1455. } catch (e) {}
  1456. }
  1457.  
  1458. static blobToBase64(blob) {
  1459. return new Promise((resolve, reject) => {
  1460. const reader = new FileReader();
  1461. reader.onerror = reject;
  1462. reader.onload = e => resolve(e.target.result);
  1463. reader.readAsDataURL(blob);
  1464. });
  1465. }
  1466.  
  1467. static async sha256(str) {
  1468. if (!pv.utf8encoder)
  1469. pv.utf8encoder = new TextEncoder('utf-8');
  1470. const buf = await crypto.subtle.digest('SHA-256', pv.utf8encoder.encode(str));
  1471. const blob = new Blob([buf]);
  1472. const url = await Util.blobToBase64(blob);
  1473. return url.slice(url.indexOf(',') + 1);
  1474. }
  1475.  
  1476. /** @param {KeyboardEvent} e */
  1477. static hasKeyModifiers(e) {
  1478. return e.ctrlKey || e.altKey || e.shiftKey || e.metaKey;
  1479. }
  1480.  
  1481. static fadeOut(el, transition) {
  1482. return new Promise(resolve => {
  1483. if (transition) {
  1484. if (typeof transition === 'number')
  1485. transition = `opacity ${transition}s ease-in-out`;
  1486. $.setStyle(el, ['transition', transition]);
  1487. setTimeout(doFadeOut);
  1488. } else {
  1489. doFadeOut();
  1490. }
  1491. function doFadeOut() {
  1492. $.setStyle(el, ['opacity', '0']);
  1493. $.on('transitionend', el, done);
  1494. $.on('visibilitychange', el, done);
  1495. }
  1496. function done() {
  1497. $.off('transitionend', el, done);
  1498. $.off('visibilitychange', el, done);
  1499. if (el.style.opacity === '0')
  1500. $.setStyle(el, ['display', 'none']);
  1501. resolve();
  1502. }
  1503. });
  1504. }
  1505.  
  1506. /** @param {KeyboardEvent} e */
  1507. static consumeEsc(e) {
  1508. if (e.key === 'Escape')
  1509. e.preventDefault();
  1510. }
  1511.  
  1512. static error(...args) {
  1513. console.error(GM_info.script.name, ...args);
  1514. }
  1515. }
  1516.  
  1517.  
  1518. class Styles {
  1519.  
  1520. static init(isDark) {
  1521. if (Styles.isDark === isDark)
  1522. return;
  1523.  
  1524. Styles.isDark = isDark;
  1525. Styles.REUSABLE = `${ID}-reusable`;
  1526.  
  1527. const KBD_COLOR = '#0008';
  1528.  
  1529. // language=HTML
  1530. const SVG_ARROW = btoa(`
  1531. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
  1532. <path stroke="${KBD_COLOR}" stroke-width="3" fill="none"
  1533. d="M2.5,8.5H15 M9,2L2.5,8.5L9,15"/>
  1534. </svg>`
  1535. .replace(/>\s+</g, '><')
  1536. .replace(/[\r\n]/g, ' ')
  1537. .replace(/\s\s+/g, ' ')
  1538. .trim()
  1539. );
  1540.  
  1541. const IMPORTANT = '!important;';
  1542.  
  1543. // language=CSS
  1544. pv.stylesOverride = [
  1545. `
  1546. :host {
  1547. all: initial;
  1548. border-color: transparent;
  1549. display: none;
  1550. opacity: 0;
  1551. height: 33%;
  1552. transition: opacity .25s cubic-bezier(.88,.02,.92,.66),
  1553. border-color .25s ease-in-out;
  1554. }
  1555. `,
  1556.  
  1557. `
  1558. :host {
  1559. box-sizing: content-box;
  1560. width: ${WIDTH}px;
  1561. min-height: ${MIN_HEIGHT}px;
  1562. position: fixed;
  1563. right: 0;
  1564. bottom: 0;
  1565. padding: 0;
  1566. margin: 0;
  1567. background: white;
  1568. box-shadow: 0 0 100px rgba(0,0,0,0.5);
  1569. z-index: 999999;
  1570. border-width: ${TOP_BORDER}px ${BORDER}px ${BORDER}px;
  1571. border-style: solid;
  1572. }
  1573. :host(:not([style*="opacity: 1"])) {
  1574. pointer-events: none;
  1575. }
  1576. :host([\\type$="question"].\\hasAnswerShelf) {
  1577. border-image: linear-gradient(
  1578. ${colors.question.back} 66%,
  1579. ${colors.answer.back}) 1 1;
  1580. }
  1581. `.replace(/;/g, IMPORTANT),
  1582.  
  1583. ...Object.entries(colors).map(([type, colors]) => `
  1584. :host([\\type$="${type}"]) {
  1585. border-color: ${colors.back} !important;
  1586. }
  1587. `),
  1588.  
  1589. `
  1590. #\\body {
  1591. min-width: unset!important;
  1592. box-shadow: none!important;
  1593. padding: 0!important;
  1594. margin: 0!important;
  1595. background: ${colors.body.back}!important;
  1596. color: ${colors.body.fore}!important;
  1597. display: flex;
  1598. flex-direction: column;
  1599. height: 100%;
  1600. }
  1601.  
  1602. #\\title {
  1603. all: unset;
  1604. display: block;
  1605. padding: 12px ${PADDING}px;
  1606. font-weight: bold;
  1607. font-size: 18px;
  1608. line-height: 1.2;
  1609. cursor: pointer;
  1610. }
  1611. #\\title:hover {
  1612. text-decoration: underline;
  1613. text-decoration-skip: ink;
  1614. }
  1615. #\\title:hover + #\\meta {
  1616. opacity: 1.0;
  1617. }
  1618.  
  1619. #\\meta {
  1620. position: absolute;
  1621. font: bold 14px/${TOP_BORDER}px sans-serif;
  1622. height: ${TOP_BORDER}px;
  1623. top: -${TOP_BORDER}px;
  1624. left: -${BORDER}px;
  1625. right: ${BORDER * 2}px;
  1626. padding: 0 0 0 ${BORDER + PADDING}px;
  1627. display: flex;
  1628. align-items: center;
  1629. cursor: s-resize;
  1630. }
  1631. #\\meta b {
  1632. height: ${TOP_BORDER}px;
  1633. display: inline-block;
  1634. padding: 0 6px;
  1635. margin-left: -6px;
  1636. margin-right: 3px;
  1637. }
  1638.  
  1639. #\\close {
  1640. position: absolute;
  1641. top: -${TOP_BORDER}px;
  1642. right: -${BORDER}px;
  1643. width: ${BORDER * 3}px;
  1644. flex: none;
  1645. cursor: pointer;
  1646. padding: .5ex 1ex;
  1647. font: normal 15px/1.0 sans-serif;
  1648. color: #fff8;
  1649. }
  1650. #\\close:after {
  1651. content: "x";
  1652. }
  1653. #\\close:active {
  1654. background-color: rgba(0,0,0,.2);
  1655. }
  1656. #\\close:hover {
  1657. background-color: rgba(0,0,0,.1);
  1658. }
  1659.  
  1660. #\\parts {
  1661. position: relative;
  1662. overflow-y: overlay; /* will replace with scrollbar-gutter once it's implemented */
  1663. overflow-x: hidden;
  1664. flex-grow: 2;
  1665. outline: none;
  1666. margin: 0;
  1667. padding: ${PADDING}px ${PADDING - PROSE_MARGIN}px ${PADDING}px ${PADDING}px !important;
  1668. }
  1669. #\\parts > .question-status {
  1670. margin: -${PADDING}px -${PADDING}px ${PADDING}px;
  1671. padding-left: ${PADDING}px;
  1672. }
  1673. #\\parts .question-originals-of-duplicate {
  1674. margin: -${PADDING}px -${PADDING}px ${PADDING}px;
  1675. padding: ${PADDING / 2 >> 0}px ${PADDING}px;
  1676. }
  1677. #\\parts > .question-status h2 {
  1678. font-weight: normal;
  1679. }
  1680. #\\parts a.SEpreviewable {
  1681. text-decoration: underline !important;
  1682. text-decoration-skip: ink;
  1683. }
  1684.  
  1685. #\\parts .js-follow-up .fd-column {
  1686. flex-flow: row-reverse !important;
  1687. justify-content: flex-end;
  1688. }
  1689. #\\parts li.comment > :first-child,
  1690. #\\parts .js-follow-up .fd-column > :last-child {
  1691. font-weight: bold;
  1692. flex: 0 0 2em;
  1693. }
  1694. #\\parts li.comment {
  1695. display: flex;
  1696. }
  1697. #\\parts li.comment:nth-last-child(n + 2) {
  1698. margin-bottom: 1em;
  1699. }
  1700. #\\parts .delete-tag {
  1701. display: none;
  1702. }
  1703. #\\parts .new-comment-highlight .comment-text {
  1704. -webkit-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1705. -moz-animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1706. animation: highlight 9s cubic-bezier(0,.8,.37,.88);
  1707. }
  1708. #\\parts .post-menu > span {
  1709. opacity: .35;
  1710. }
  1711.  
  1712. #\\parts #user-menu {
  1713. position: absolute;
  1714. }
  1715. .\\userCard {
  1716. position: absolute;
  1717. display: none;
  1718. transition: opacity .25s cubic-bezier(.88,.02,.92,.66) .5s;
  1719. margin-top: -3rem;
  1720. }
  1721. #\\parts .wmd-preview a:not(.post-tag),
  1722. #\\parts .postcell a:not(.post-tag),
  1723. #\\parts .comment-copy a:not(.post-tag) {
  1724. border-bottom: none;
  1725. }
  1726.  
  1727. #\\answers-title {
  1728. margin: .5ex 1ex 0 0;
  1729. font-size: 18px;
  1730. line-height: 1.0;
  1731. float: left;
  1732. }
  1733. #\\answers-title p {
  1734. font-size: 11px;
  1735. font-weight: normal;
  1736. max-width: 8em;
  1737. line-height: 1.0;
  1738. margin: 1ex 0 0 0;
  1739. padding: 0;
  1740. }
  1741. #\\answers-title b,
  1742. #\\answers-title label {
  1743. background: linear-gradient(#fff8 30%, #fff);
  1744. width: 10px;
  1745. height: 10px;
  1746. padding: 2px;
  1747. margin-right: 2px;
  1748. box-shadow: 0 1px 3px #0008;
  1749. border-radius: 3px;
  1750. font-weight: normal;
  1751. display: inline-block;
  1752. vertical-align: middle;
  1753. }
  1754. #\\answers-title b::after {
  1755. content: "";
  1756. display: block;
  1757. width: 100%;
  1758. height: 100%;
  1759. background: url('data:image/svg+xml;base64,${SVG_ARROW}') no-repeat center;
  1760. }
  1761. #\\answers-title b[mirrored]::after {
  1762. transform: scaleX(-1);
  1763. }
  1764. #\\answers-title label {
  1765. width: auto;
  1766. color: ${KBD_COLOR};
  1767. }
  1768.  
  1769. #\\answers {
  1770. all: unset;
  1771. display: block;
  1772. padding: 10px 10px 10px ${PADDING}px;
  1773. font-weight: bold;
  1774. line-height: 1.0;
  1775. border-top: 4px solid ${colors.answer.back}5e;
  1776. background-color: ${colors.answer.back}5e;
  1777. color: ${colors.answer.fore};
  1778. word-break: break-word;
  1779. }
  1780. #\\answers a {
  1781. color: ${colors.answer.fore};
  1782. text-decoration: none;
  1783. font-size: 11px;
  1784. font-family: monospace;
  1785. width: 32px !important;
  1786. display: inline-block;
  1787. position: relative;
  1788. vertical-align: top;
  1789. margin: 0 1ex 1ex 0;
  1790. padding: 0 0 1.1ex 0;
  1791. }
  1792. [\\type*="deleted"] #\\answers a {
  1793. color: ${colors.deleted.fore};
  1794. }
  1795. #\\answers img {
  1796. width: 32px;
  1797. height: 32px;
  1798. }
  1799. #\\answers a.deleted-answer {
  1800. color: ${colors.deleted.fore};
  1801. background: transparent;
  1802. opacity: 0.25;
  1803. }
  1804. #\\answers a.deleted-answer:hover {
  1805. opacity: 1.0;
  1806. }
  1807. #\\answers a:hover:not(.SEpreviewed) {
  1808. text-decoration: underline;
  1809. text-decoration-skip: ink;
  1810. }
  1811. #\\answers a.SEpreviewed {
  1812. background-color: ${colors.answer.fore};
  1813. color: ${colors.answer.foreInv};
  1814. outline: 4px solid ${colors.answer.fore};
  1815. }
  1816. #\\answers a::after {
  1817. white-space: nowrap;
  1818. overflow: hidden;
  1819. text-overflow: ellipsis;
  1820. max-width: 40px;
  1821. position: absolute;
  1822. content: attr(title);
  1823. top: 44px;
  1824. left: 0;
  1825. font: normal .75rem/1.0 sans-serif;
  1826. opacity: .7;
  1827. }
  1828. #\\answers a:only-child::after {
  1829. max-width: calc(${WIDTH}px - 10em);
  1830. }
  1831. #\\answers a:hover::after {
  1832. opacity: 1;
  1833. }
  1834. .\\accepted::before {
  1835. content: "✔";
  1836. position: absolute;
  1837. display: block;
  1838. top: 1.3ex;
  1839. right: -0.7ex;
  1840. font-size: 32px;
  1841. color: #4bff2c;
  1842. text-shadow: 1px 2px 2px rgba(0,0,0,0.5);
  1843. }
  1844.  
  1845. @-webkit-keyframes highlight {
  1846. from {background: #ffcf78}
  1847. to {background: none}
  1848. }
  1849. `,
  1850.  
  1851. ...Object.keys(colors).map(s => `
  1852. #\\title {
  1853. background-color: ${colors[s].back}5e;
  1854. color: ${colors[s].fore};
  1855. }
  1856. #\\meta {
  1857. color: ${colors[s].fore};
  1858. }
  1859. #\\meta b {
  1860. color: ${colors[s].foreInv};
  1861. background: ${colors[s].fore};
  1862. }
  1863. #\\close {
  1864. color: ${colors[s].fore};
  1865. }
  1866. #\\parts::-webkit-scrollbar {
  1867. background-color: ${colors[s].back}19;
  1868. }
  1869. #\\parts::-webkit-scrollbar-thumb {
  1870. background-color: ${colors[s].back}32;
  1871. }
  1872. #\\parts::-webkit-scrollbar-thumb:hover {
  1873. background-color: ${colors[s].back}4b;
  1874. }
  1875. #\\parts::-webkit-scrollbar-thumb:active {
  1876. background-color: ${colors[s].back}c0;
  1877. }
  1878. `
  1879. // language=JS
  1880. .replace(/#\\/g, `[\\type$="${s}"] $&`)
  1881. ),
  1882.  
  1883. ...['deleted', 'closed'].map(s => /* language=CSS */ `
  1884. #\\answers {
  1885. border-top-color: ${colors[s].back}5e;
  1886. background-color: ${colors[s].back}5e;
  1887. color: ${colors[s].fore};
  1888. }
  1889. #\\answers a.SEpreviewed {
  1890. background-color: ${colors[s].fore};
  1891. color: ${colors[s].foreInv};
  1892. }
  1893. #\\answers a.SEpreviewed:after {
  1894. border-color: ${colors[s].fore};
  1895. }
  1896. `
  1897. // language=JS
  1898. .replace(/#\\/g, `[\\type$="${s}"] $&`)
  1899. ),
  1900.  
  1901. GM_getResourceText(`HL-style${isDark ? '-dark' : ''}`),
  1902. ].join('\n').replace(/\\/g, `${ID}-`);
  1903. }
  1904.  
  1905. static applyRemScale(id, css) {
  1906. const el = pv.styles.get(id);
  1907. if (pv.remScale && pv.remScale !== 1 && !pv.stylesScaled.has(id)) {
  1908. css = (css || el.textContent).replace(/([:\s])((?:\d*\.?)?\d+)(?=rem([;}\s]|\/\*))/gi,
  1909. (_, prev, size) => prev + (pv.remScale * size));
  1910. pv.stylesScaled.add(id);
  1911. }
  1912. el.textContent = css;
  1913. }
  1914. }
  1915.  
  1916. function $(selector, node = pv.shadow) {
  1917. return node && node.querySelector(selector);
  1918. }
  1919.  
  1920. Object.assign($, {
  1921.  
  1922. all(selector, node = pv.shadow) {
  1923. return node ? [...node.querySelectorAll(selector)] : [];
  1924. },
  1925.  
  1926. on(eventName, node, fn, options) {
  1927. return node.addEventListener(eventName, fn, options);
  1928. },
  1929.  
  1930. off(eventName, node, fn, options) {
  1931. return node.removeEventListener(eventName, fn, options);
  1932. },
  1933.  
  1934. remove(selector, node = pv.shadow) {
  1935. for (const el of node.querySelectorAll(selector))
  1936. el.remove();
  1937. },
  1938.  
  1939. text(selector, node = pv.shadow) {
  1940. const el = typeof selector === 'string' ?
  1941. node && node.querySelector(selector) :
  1942. selector;
  1943. return el ? el.textContent.trim() : '';
  1944. },
  1945.  
  1946. create(
  1947. selector,
  1948. opts = {},
  1949. children = opts.children ||
  1950. (typeof opts !== 'object' || Util.isIterable(opts)) && opts
  1951. ) {
  1952. const EOL = selector.length;
  1953. const idStart = (selector.indexOf('#') + 1 || EOL + 1) - 1;
  1954. const clsStart = (selector.indexOf('.', idStart < EOL ? idStart : 0) + 1 || EOL + 1) - 1;
  1955. const tagEnd = Math.min(idStart, clsStart);
  1956. const tag = (tagEnd < EOL ? selector.slice(0, tagEnd) : selector) || opts.tag || 'div';
  1957. const id = idStart < EOL && selector.slice(idStart + 1, clsStart) || opts.id || '';
  1958. const cls = clsStart < EOL && selector.slice(clsStart + 1).replace(/\./g, ' ') ||
  1959. opts.className ||
  1960. '';
  1961. const el = id && pv.shadow && pv.shadow.getElementById(id) ||
  1962. document.createElement(tag);
  1963. if (el.id !== id)
  1964. el.id = id;
  1965. if (el.className !== cls)
  1966. el.className = cls;
  1967. const hasOwnProperty = Object.hasOwnProperty;
  1968. for (const key in opts) {
  1969. if (!hasOwnProperty.call(opts, key))
  1970. continue;
  1971. const value = opts[key];
  1972. switch (key) {
  1973. case 'tag':
  1974. case 'id':
  1975. case 'className':
  1976. case 'children':
  1977. break;
  1978. case 'dataset': {
  1979. const dataset = el.dataset;
  1980. for (const k in value) {
  1981. if (hasOwnProperty.call(value, k)) {
  1982. const v = value[k];
  1983. if (dataset[k] !== v)
  1984. dataset[k] = v;
  1985. }
  1986. }
  1987. break;
  1988. }
  1989. case 'attributes': {
  1990. for (const k in value) {
  1991. if (hasOwnProperty.call(value, k)) {
  1992. const v = value[k];
  1993. if (el.getAttribute(k) !== v)
  1994. el.setAttribute(k, v);
  1995. }
  1996. }
  1997. break;
  1998. }
  1999. default:
  2000. if (el[key] !== value)
  2001. el[key] = value;
  2002. }
  2003. }
  2004. if (children) {
  2005. if (!hasOwnProperty.call(opts, 'textContent'))
  2006. el.textContent = '';
  2007. el.append(...Array.isArray(children) ? children.filter(Boolean)
  2008. : Util.isIterable(children) ? children
  2009. : [children]);
  2010. }
  2011. let before, after, parent;
  2012. if ((before = opts.before) && before !== el.nextSibling && before !== el)
  2013. before.insertAdjacentElement('beforebegin', el);
  2014. else if ((after = opts.after) && after !== el.previousSibling && after !== el)
  2015. after.insertAdjacentElement('afterend', el);
  2016. else if ((parent = opts.parent) && parent !== el.parentNode)
  2017. parent.appendChild(el);
  2018. return el;
  2019. },
  2020.  
  2021. setStyle(el, ...props) {
  2022. const style = el.style;
  2023. const s0 = style.cssText;
  2024. let s = s0;
  2025.  
  2026. for (const p of props) {
  2027. if (!p)
  2028. continue;
  2029.  
  2030. const [name, value, important = true] = p;
  2031. const rValue = value + (important && value ? ' !important' : '');
  2032. const rx = new RegExp(`(^|[\\s;])${name}(\\s*:\\s*)([^;]*?)(\\s*(?:;|$))`, 'i');
  2033. const m = rx.exec(s);
  2034.  
  2035. if (!m && value) {
  2036. const rule = name + ': ' + rValue;
  2037. s += !s || s.endsWith(';') ? rule : '; ' + rule;
  2038. continue;
  2039. }
  2040.  
  2041. if (!m && !value)
  2042. continue;
  2043.  
  2044. const [, sep1, sep2, oldValue, sep3] = m;
  2045. if (value !== oldValue) {
  2046. s = s.slice(0, m.index) +
  2047. sep1 + (rValue ? name + sep2 + rValue + sep3 : '') +
  2048. s.slice(m.index + m[0].length);
  2049. }
  2050. }
  2051.  
  2052. if (s !== s0)
  2053. style.cssText = s;
  2054. },
  2055. });

QingJ © 2025

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