SE Preview on hover

Shows preview of the linked questions/answers on hover

当前为 2020-11-14 提交的版本,查看 最新版本

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