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

QingJ © 2025

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