Comments Owl for Hacker News

Highlight new comments, mute users, and other tweaks for Hacker News

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

  1. // ==UserScript==
  2. // @name Comments Owl for Hacker News
  3. // @description Highlight new comments, mute users, and other tweaks for Hacker News
  4. // @namespace https://github.com/insin/comments-owl-for-hacker-news/
  5. // @match https://news.ycombinator.com/*
  6. // @version 46
  7. // ==/UserScript==
  8. let debug = false
  9. let isSafari = navigator.userAgent.includes('Safari/') && !/Chrom(e|ium)\//.test(navigator.userAgent)
  10.  
  11. const HIGHLIGHT_COLOR = '#ffffde'
  12. const TOGGLE_HIDE = '[–]'
  13. const TOGGLE_SHOW = '[+]'
  14. const MUTED_USERS_KEY = 'mutedUsers'
  15. const USER_NOTES_KEY = 'userNotes'
  16. const LOGGED_OUT_USER_PAGE = `<head>
  17. <meta name="referrer" content="origin">
  18. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  19. <link rel="stylesheet" type="text/css" href="news.css">
  20. <link rel="shortcut icon" href="favicon.ico">
  21. <title>Muted | Comments Owl for Hacker News</title>
  22. </head>
  23. <body>
  24. <center>
  25. <table id="hnmain" width="85%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f6f6ef">
  26. <tbody>
  27. <tr>
  28. <td bgcolor="#ff6600">
  29. <table style="padding: 2px" width="100%" cellspacing="0" cellpadding="0" border="0">
  30. <tbody>
  31. <tr>
  32. <td style="width: 18px; padding-right: 4px">
  33. <a href="https://news.ycombinator.com">
  34. <img src="y18.svg" style="border: 1px white solid; display: block" width="18" height="18">
  35. </a>
  36. </td>
  37. <td style="line-height: 12pt; height: 10px">
  38. <span class="pagetop"><b class="hnname"><a href="news">Hacker News</a></b>
  39. <a href="newest">new</a> | <a href="front">past</a> | <a href="newcomments">comments</a> | <a href="ask">ask</a> | <a href="show">show</a> | <a href="jobs">jobs</a>
  40. </span>
  41. </td>
  42. <td style="text-align: right; padding-right: 4px">
  43. <span class="pagetop">
  44. <a href="login?goto=news">login</a>
  45. </span>
  46. </td>
  47. </tr>
  48. </tbody>
  49. </table>
  50. </td>
  51. </tr>
  52. <tr id="pagespace" title="Muted" style="height: 10px"></tr>
  53. <tr>
  54. <td>
  55. <table border="0">
  56. <tbody>
  57. <tr class="athing">
  58. <td valign="top">user:</td>
  59. <td>
  60. <a class="hnuser">anonymous comments owl user</a>
  61. </td>
  62. </tr>
  63. </tbody>
  64. </table>
  65. <br><br>
  66. </td>
  67. </tr>
  68. </tbody>
  69. </table>
  70. </center>
  71. </body>`
  72.  
  73. //#region Config
  74. /** @type {import("./types").Config} */
  75. let config = {
  76. addUpvotedToHeader: true,
  77. autoCollapseNotNew: true,
  78. autoHighlightNew: true,
  79. hideCommentsNav: false,
  80. hideJobsNav: false,
  81. hidePastNav: false,
  82. hideReplyLinks: false,
  83. hideSubmitNav: false,
  84. listPageFlagging: 'enabled',
  85. }
  86. //#endregion
  87.  
  88. //#region Storage
  89. class Visit {
  90. constructor({commentCount, maxCommentId, time}) {
  91. /** @type {number} */
  92. this.commentCount = commentCount
  93. /** @type {number} */
  94. this.maxCommentId = maxCommentId
  95. /** @type {Date} */
  96. this.time = time
  97. }
  98.  
  99. toJSON() {
  100. return {
  101. c: this.commentCount,
  102. m: this.maxCommentId,
  103. t: this.time.getTime(),
  104. }
  105. }
  106. }
  107.  
  108. Visit.fromJSON = function(obj) {
  109. return new Visit({
  110. commentCount: obj.c,
  111. maxCommentId: obj.m,
  112. time: new Date(obj.t),
  113. })
  114. }
  115.  
  116. function getLastVisit(itemId) {
  117. let json = localStorage.getItem(itemId)
  118. if (json == null) return null
  119. return Visit.fromJSON(JSON.parse(json))
  120. }
  121.  
  122. function storeVisit(itemId, visit) {
  123. log('storing visit', visit)
  124. localStorage.setItem(itemId, JSON.stringify(visit))
  125. }
  126.  
  127. /** @returns {Set<string>} */
  128. function getMutedUsers(json = localStorage[MUTED_USERS_KEY]) {
  129. return new Set(JSON.parse(json || '[]'))
  130. }
  131.  
  132. /** @returns {Record<string, string>} */
  133. function getUserNotes(json = localStorage[USER_NOTES_KEY]) {
  134. return JSON.parse(json || '{}')
  135. }
  136.  
  137. function storeMutedUsers(mutedUsers) {
  138. localStorage[MUTED_USERS_KEY] = JSON.stringify(Array.from(mutedUsers))
  139. }
  140.  
  141. function storeUserNotes(userNotes) {
  142. localStorage[USER_NOTES_KEY] = JSON.stringify(userNotes)
  143. }
  144. //#endregion
  145.  
  146. //#region Utility functions
  147. /**
  148. * @param {string} role
  149. * @param {...string} css
  150. */
  151. function addStyle(role, ...css) {
  152. let $style = document.createElement('style')
  153. $style.dataset.insertedBy = 'comments-owl'
  154. $style.dataset.role = role
  155. if (css.length > 0) {
  156. $style.textContent = css.filter(Boolean).map(dedent).join('\n')
  157. }
  158. document.querySelector('head').appendChild($style)
  159. return $style
  160. }
  161.  
  162. const autosizeTextArea = (() => {
  163. /** @type {Number} */
  164. let textAreaPadding
  165.  
  166. return function autosizeTextarea($textArea) {
  167. if (textAreaPadding == null) {
  168. textAreaPadding = Number(getComputedStyle($textArea).paddingTop.replace('px', '')) * 2
  169. }
  170. $textArea.style.height = '0px'
  171. $textArea.style.height = $textArea.scrollHeight + textAreaPadding + 'px'
  172. }
  173. })()
  174.  
  175. function checkbox(attributes, label) {
  176. return h('label', null,
  177. h('input', {
  178. style: {verticalAlign: 'middle'},
  179. type: 'checkbox',
  180. ...attributes,
  181. }),
  182. ' ',
  183. label,
  184. )
  185. }
  186.  
  187. /**
  188. * @param {string} str
  189. * @return {string}
  190. */
  191. function dedent(str) {
  192. str = str.replace(/^[ \t]*\r?\n/, '')
  193. let indent = /^[ \t]+/m.exec(str)
  194. if (indent) str = str.replace(new RegExp('^' + indent[0], 'gm'), '')
  195. return str.replace(/(\r?\n)[ \t]+$/, '$1')
  196. }
  197.  
  198. /**
  199. * Create an element.
  200. * @param {string} tagName
  201. * @param {{[key: string]: any}} [attributes]
  202. * @param {...any} children
  203. * @returns {HTMLElement}
  204. */
  205. function h(tagName, attributes, ...children) {
  206. let $el = document.createElement(tagName)
  207.  
  208. if (attributes) {
  209. for (let [prop, value] of Object.entries(attributes)) {
  210. if (prop.indexOf('on') === 0) {
  211. $el.addEventListener(prop.slice(2).toLowerCase(), value)
  212. }
  213. else if (prop.toLowerCase() == 'style') {
  214. for (let [styleProp, styleValue] of Object.entries(value)) {
  215. $el.style[styleProp] = styleValue
  216. }
  217. }
  218. else {
  219. $el[prop] = value
  220. }
  221. }
  222. }
  223.  
  224. for (let child of children) {
  225. if (child == null || child === false) {
  226. continue
  227. }
  228. if (child instanceof Node) {
  229. $el.appendChild(child)
  230. }
  231. else {
  232. $el.insertAdjacentText('beforeend', String(child))
  233. }
  234. }
  235.  
  236. return $el
  237. }
  238.  
  239. function log(...args) {
  240. if (debug) {
  241. console.log('🦉', ...args)
  242. }
  243. }
  244.  
  245. function warn(...args) {
  246. if (debug) {
  247. console.log('❗', ...args)
  248. }
  249. }
  250.  
  251. /**
  252. * @param {number} count
  253. * @param {string} suffixes
  254. * @returns {string}
  255. */
  256. function s(count, suffixes = ',s') {
  257. if (!suffixes.includes(',')) {
  258. suffixes = `,${suffixes}`
  259. }
  260. return suffixes.split(',')[count === 1 ? 0 : 1]
  261. }
  262.  
  263. /**
  264. * @param {HTMLElement} $el
  265. * @param {boolean} hidden
  266. */
  267. function toggleDisplay($el, hidden) {
  268. $el.classList.toggle('noshow', hidden)
  269. // We need to enforce display setting as the page's own script expands all
  270. // comments on page load.
  271. $el.style.display = hidden ? 'none' : ''
  272. }
  273.  
  274. /**
  275. * @param {HTMLElement} $el
  276. * @param {boolean} hidden
  277. */
  278. function toggleVisibility($el, hidden) {
  279. $el.classList.toggle('nosee', hidden)
  280. // We need to enforce visibility setting as the page's own script expands
  281. // all comments on page load.
  282. $el.style.visibility = hidden ? 'hidden' : 'visible'
  283. }
  284. //#endregion
  285.  
  286. //#region Navigation
  287. function tweakNav() {
  288. let $pageTop = document.querySelector('span.pagetop')
  289. if (!$pageTop) {
  290. warn('pagetop not found')
  291. return
  292. }
  293.  
  294. //#region CSS
  295. addStyle('nav-static', `
  296. .desktopnav {
  297. display: inline;
  298. }
  299. .mobilenav {
  300. display: none;
  301. }
  302. @media only screen and (min-width : 300px) and (max-width : 750px) {
  303. .desktopnav {
  304. display: none;
  305. }
  306. .mobilenav {
  307. display: revert;
  308. }
  309. }
  310. `)
  311.  
  312. let $style = addStyle('nav-dynamic')
  313.  
  314. function configureCss() {
  315. let hideNavSelectors = [
  316. config.hidePastNav && 'span.past-sep, span.past-sep + a',
  317. config.hideCommentsNav && 'span.comments-sep, span.comments-sep + a',
  318. config.hideJobsNav && 'span.jobs-sep, span.jobs-sep + a',
  319. config.hideSubmitNav && 'span.submit-sep, span.submit-sep + a',
  320. !config.addUpvotedToHeader && 'span.upvoted-sep, span.upvoted-sep + a',
  321. ].filter(Boolean)
  322. $style.textContent = hideNavSelectors.length == 0 ? '' : dedent(`
  323. ${hideNavSelectors.join(',\n')} {
  324. display: none;
  325. }
  326. `)
  327. }
  328. //#endregion
  329.  
  330. //#region Main
  331. // Add a 'muted' link next to 'login' for logged-out users
  332. let $loginLink = document.querySelector('span.pagetop a[href^="login"]')
  333. if ($loginLink) {
  334. $loginLink.parentElement.append(
  335. h('a', {href: `muted`}, 'muted'),
  336. ' | ',
  337. $loginLink,
  338. )
  339. }
  340.  
  341. // Add /upvoted if we're not on it and the user is logged in
  342. if (!location.pathname.startsWith('/upvoted')) {
  343. let $userLink = document.querySelector('span.pagetop a[href^="user?id"]')
  344. if ($userLink) {
  345. let $submit = $pageTop.querySelector('a[href="submit"]')
  346. $submit.insertAdjacentElement('afterend', h('a', {href: `upvoted?id=${$userLink.textContent}`}, 'upvoted'))
  347. $submit.insertAdjacentElement('afterend', h('span', {className: 'upvoted-sep'}, ' | '))
  348. }
  349. }
  350.  
  351. // Wrap separators in elements so they can be used to hide items
  352. Array.from($pageTop.childNodes)
  353. .filter(n => n.nodeType == Node.TEXT_NODE && n.nodeValue == ' | ')
  354. .forEach(n => n.replaceWith(h('span', {className: `${n.nextSibling?.textContent}-sep`}, ' | ')))
  355.  
  356. // Create a new row for mobile nav
  357. let $mobileNav = /** @type {HTMLTableCellElement} */ ($pageTop.parentElement.cloneNode(true))
  358. $mobileNav.querySelector('b')?.remove()
  359. $mobileNav.colSpan = 3
  360. $pageTop.closest('tbody').append(h('tr', {className: 'mobilenav'}, $mobileNav))
  361.  
  362. // Move everything after b.hnname into a desktop nav wrapper
  363. $pageTop.appendChild(h('span', {className: 'desktopnav'}, ...Array.from($pageTop.childNodes).slice(1)))
  364.  
  365. configureCss()
  366.  
  367. chrome.storage.onChanged.addListener((changes) => {
  368. for (let [configProp, change] of Object.entries(changes)) {
  369. if (['hidePastNav', 'hideCommentsNav', 'hideJobsNav', 'hideSubmitNav', 'addUpvotedToHeader'].includes(configProp)) {
  370. config[configProp] = change.newValue
  371. configureCss()
  372. }
  373. }
  374. })
  375. //#endregion
  376. }
  377. //#endregion
  378.  
  379. //#region Comment page
  380. /**
  381. * Each comment on a comment page has the following structure:
  382. *
  383. * ```html
  384. * <tr class="athing"> (wrapper)
  385. * <td>
  386. * <table>
  387. * <tr>
  388. * <td class="ind">
  389. * <img src="s.gif" height="1" width="123"> (indentation)
  390. * </td>
  391. * <td class="votelinks">…</td> (vote up/down controls)
  392. * <td class="default">
  393. * <div style="margin-top:2px; margin-bottom:-10px;">
  394. * <div class="comhead"> (meta bar: user, age and folding control)
  395. * …
  396. * <div class="comment">
  397. * <span class="comtext"> (text and reply link)
  398. * ```
  399. *
  400. * We want to be able to collapse comment trees which don't contain new comments
  401. * and highlight new comments, so for each wrapper we'll create a `HNComment`
  402. * object to manage this.
  403. *
  404. * Comments are rendered as a flat list of table rows, so we'll use the width of
  405. * the indentation spacer to determine which comments are descendants of a given
  406. * comment.
  407. *
  408. * Since we have to reimplement our own comment folding, we'll hide the built-in
  409. * folding controls and create new ones in a better position (on the left), with
  410. * a larger hitbox (larger font and an en dash [–] instead of a hyphen [-]).
  411. *
  412. * On each comment page view, we store the current comment count, the max
  413. * comment id on the page and the current time as the last visit time.
  414. */
  415. function commentPage() {
  416. log('comment page')
  417.  
  418. //#region CSS
  419. addStyle('comments-static', `
  420. /* Hide default toggle and nav links */
  421. a.togg {
  422. display: none;
  423. }
  424. .toggle {
  425. cursor: pointer;
  426. margin-right: 3px;
  427. }
  428. /* Display the mute control on hover, unless the comment is collapsed */
  429. .mute {
  430. display: none;
  431. }
  432. /* Prevent :hover causing double-tap on comment functionality in iOS Safari */
  433. @media(hover: hover) and (pointer: fine) {
  434. tr.comtr:hover td.votelinks:not(.nosee) + td .mute {
  435. display: inline;
  436. }
  437. }
  438. /* Don't show notes on collapsed comments */
  439. td.votelinks.nosee + td .note {
  440. display: none;
  441. }
  442. #timeTravel {
  443. margin-top: 1em;
  444. vertical-align: middle;
  445. }
  446. #timeTravelRange {
  447. width: 100%;
  448. }
  449. #timeTravelButton {
  450. margin-right: 1em;
  451. }
  452.  
  453. @media only screen and (min-width: 300px) and (max-width: 750px) {
  454. td.votelinks:not(.nosee) + td .mute {
  455. display: inline;
  456. }
  457. /* Allow comments to go full-width */
  458. .comment {
  459. max-width: unset;
  460. }
  461. /* Increase distance between upvote and downvote */
  462. a[id^="down_"] {
  463. margin-top: 16px;
  464. }
  465. /* Increase hit-target */
  466. .toggle {
  467. font-size: 14px;
  468. }
  469. #highlightControls label {
  470. display: block;
  471. }
  472. #highlightControls label + label {
  473. margin-top: .5rem;
  474. }
  475. #timeTravelRange {
  476. width: calc(100% - 32px);
  477. }
  478. }
  479. `)
  480.  
  481. let $style = addStyle('comments-dynamic')
  482.  
  483. function configureCss() {
  484. $style.textContent = [
  485. config.hideReplyLinks && `
  486. div.reply {
  487. margin-top: 8px;
  488. }
  489. div.reply p {
  490. display: none;
  491. }
  492. `
  493. ].filter(Boolean).map(dedent).join('\n')
  494. }
  495. //#endregion
  496.  
  497. //#region Variables
  498. /** @type {boolean} */
  499. let autoCollapseNotNew = config.autoCollapseNotNew || location.search.includes('?shownew')
  500.  
  501. /** @type {boolean} */
  502. let autoHighlightNew = config.autoHighlightNew || location.search.includes('?shownew')
  503.  
  504. /** @type {HNComment[]} */
  505. let comments = []
  506.  
  507. /** @type {Record<string, HNComment>} */
  508. let commentsById = {}
  509.  
  510. /** @type {boolean} */
  511. let hasNewComments = false
  512.  
  513. /** @type {string} */
  514. let itemId = /id=(\d+)/.exec(location.search)[1]
  515.  
  516. /** @type {Visit} */
  517. let lastVisit
  518.  
  519. /** @type {number} */
  520. let maxCommentId
  521.  
  522. /** @type {Set<string>} */
  523. let mutedUsers = getMutedUsers()
  524.  
  525. /** @type {Record<string, string>} */
  526. let userNotes = getUserNotes()
  527.  
  528. // Comment counts
  529. let commentCount = 0
  530. let mutedCommentCount = 0
  531. let newCommentCount = 0
  532. let replyToMutedCommentCount = 0
  533. //#endregion
  534.  
  535. class HNComment {
  536. /**
  537. * returns {boolean}
  538. */
  539. get isMuted() {
  540. return mutedUsers.has(this.user)
  541. }
  542.  
  543. /**
  544. * @returns {HNComment[]}
  545. */
  546. get childComments() {
  547. if (this._childComments == null) {
  548. this._childComments = []
  549. for (let i = this.index + 1; i < comments.length; i++) {
  550. if (comments[i].indent <= this.indent) {
  551. break
  552. }
  553. this._childComments.push(comments[i])
  554. }
  555. }
  556. return this._childComments
  557. }
  558.  
  559. get collapsedChildrenText() {
  560. return this.childCommentCount == 0 ? '' : [
  561. this.isDeleted ? '(' : ' | (',
  562. this.childCommentCount,
  563. ` child${s(this.childCommentCount, 'ren')})`,
  564. ].join('')
  565. }
  566.  
  567. /**
  568. * @returns {HNComment[]}
  569. */
  570. get nonMutedChildComments() {
  571. if (this._nonMutedChildComments == null) {
  572. let muteIndent = null
  573. this._nonMutedChildComments = this.childComments.filter(comment => {
  574. if (muteIndent != null) {
  575. if (comment.indent > muteIndent) {
  576. return false
  577. }
  578. muteIndent = null
  579. }
  580.  
  581. if (comment.isMuted) {
  582. muteIndent = comment.indent
  583. return false
  584. }
  585.  
  586. return true
  587. })
  588. }
  589. return this._nonMutedChildComments
  590. }
  591.  
  592. /**
  593. * returns {number}
  594. */
  595. get childCommentCount() {
  596. return this.nonMutedChildComments.length
  597. }
  598.  
  599. /**
  600. * @param {HTMLElement} $wrapper
  601. * @param {number} index
  602. */
  603. constructor($wrapper, index) {
  604. /** @type {number} */
  605. this.indent = Number( /** @type {HTMLImageElement} */ ($wrapper.querySelector('img[src="s.gif"]')).width)
  606.  
  607. /** @type {number} */
  608. this.index = index
  609.  
  610. let $user = /** @type {HTMLElement} */ ($wrapper.querySelector('a.hnuser'))
  611. /** @type {string} */
  612. this.user = $user?.innerText
  613.  
  614. /** @type {HTMLElement} */
  615. this.$comment = $wrapper.querySelector('div.comment')
  616.  
  617. /** @type {HTMLElement} */
  618. this.$topBar = $wrapper.querySelector('td.default > div')
  619.  
  620. /** @type {HTMLElement} */
  621. this.$voteLinks = $wrapper.querySelector('td.votelinks')
  622.  
  623. /** @type {HTMLElement} */
  624. this.$wrapper = $wrapper
  625.  
  626. /** @private @type {HNComment[]} */
  627. this._childComments = null
  628.  
  629. /** @private @type {HNComment[]} */
  630. this._nonMutedChildComments = null
  631.  
  632. /**
  633. * The comment's id.
  634. * Will be `-1` for deleted comments.
  635. * @type {number}
  636. */
  637. this.id = -1
  638.  
  639. /**
  640. * Some flagged comments are collapsed by default.
  641. * @type {boolean}
  642. */
  643. this.isCollapsed = $wrapper.classList.contains('coll')
  644.  
  645. /**
  646. * Comments whose text has been removed but are still displayed may have
  647. * their text replaced with [flagged], [dead] or similar - we'll take any
  648. * word in square brackets as indication of this.
  649. * @type {boolean}
  650. */
  651. this.isDeleted = /^\s*\[\w+]\s*$/.test(this.$comment.firstChild.nodeValue)
  652.  
  653. /**
  654. * The displayed age of the comment; `${n} minutes/hours/days ago`, or
  655. * `on ${date}` for older comments.
  656. * Will be blank for deleted comments.
  657. * @type {string}
  658. */
  659. this.when = ''
  660.  
  661. /** @type {HTMLElement} */
  662. this.$childCount = null
  663.  
  664. /** @type {HTMLElement} */
  665. this.$comhead = this.$topBar.querySelector('span.comhead')
  666.  
  667. /** @type {HTMLElement} */
  668. this.$toggleControl = h('span', {
  669. className: 'toggle',
  670. onclick: () => this.toggleCollapsed(),
  671. }, this.isCollapsed ? TOGGLE_SHOW : TOGGLE_HIDE)
  672.  
  673. if (!this.isDeleted) {
  674. let $permalink = /** @type {HTMLAnchorElement} */ (this.$topBar.querySelector('a[href^=item]'))
  675. this.id = Number($permalink.href.split('=').pop())
  676. this.when = $permalink?.textContent.replace('minute', 'min')
  677. }
  678. }
  679.  
  680. addControls() {
  681. // We want to use the comment meta bar for the folding control, so put
  682. // it back above the deleted comment placeholder.
  683. if (this.isDeleted) {
  684. this.$topBar.style.marginBottom = '4px'
  685. }
  686. this.$topBar.insertAdjacentText('afterbegin', ' ')
  687. this.$topBar.insertAdjacentElement('afterbegin', this.$toggleControl)
  688. this.$comhead.append(...[
  689. // User note
  690. userNotes[this.user] && h('span', {className: 'note'},
  691. ` | nb: ${userNotes[this.user].split(/\r?\n/)[0]}`,
  692. ),
  693. // Mute control
  694. this.user && h('span', {className: 'mute'}, ' | ', h('a', {
  695. href: `mute?id=${this.user}`,
  696. onclick: (e) => {
  697. e.preventDefault()
  698. this.mute()
  699. }
  700. }, 'mute'))
  701. ].filter(Boolean))
  702. }
  703.  
  704. mute() {
  705. mutedUsers = getMutedUsers()
  706. mutedUsers.add(this.user)
  707. storeMutedUsers(mutedUsers)
  708.  
  709. // Invalidate non-muted child caches and update child counts on any
  710. // comments which have been collapsed.
  711. for (let i = 0; i < comments.length; i++) {
  712. let comment = comments[i]
  713.  
  714. if (comment.isMuted) {
  715. i += comment.childComments.length
  716. continue
  717. }
  718.  
  719. comment._nonMutedChildComments = null
  720. if (comment.$childCount) {
  721. comment.$childCount.textContent = comment.collapsedChildrenText
  722. }
  723. }
  724.  
  725. hideMutedUsers()
  726. }
  727.  
  728. /**
  729. * @param {boolean} updateChildren
  730. */
  731. updateDisplay(updateChildren = true) {
  732. // Show/hide this comment, preserving display of the meta bar
  733. toggleDisplay(this.$comment, this.isCollapsed)
  734. if (this.$voteLinks) {
  735. toggleVisibility(this.$voteLinks, this.isCollapsed)
  736. }
  737. this.$toggleControl.textContent = this.isCollapsed ? TOGGLE_SHOW : TOGGLE_HIDE
  738.  
  739. // Show/hide the number of child comments when collapsed
  740. if (this.childCommentCount > 0) {
  741. if (this.isCollapsed && this.$childCount == null) {
  742. this.$childCount = h('span', null, this.collapsedChildrenText)
  743. this.$comhead.appendChild(this.$childCount)
  744. }
  745. toggleDisplay(this.$childCount, !this.isCollapsed)
  746. }
  747.  
  748. if (updateChildren) {
  749. for (let i = 0; i < this.nonMutedChildComments.length; i++) {
  750. let child = this.nonMutedChildComments[i]
  751. toggleDisplay(child.$wrapper, this.isCollapsed)
  752. if (child.isCollapsed) {
  753. i += child.childComments.length
  754. }
  755. }
  756. }
  757. }
  758.  
  759. /**
  760. * Completely hides this comment and its replies.
  761. */
  762. hide() {
  763. toggleDisplay(this.$wrapper, true)
  764. this.childComments.forEach((child) => toggleDisplay(child.$wrapper, true))
  765. }
  766.  
  767. /**
  768. * @param {number} commentId
  769. * @returns {boolean}
  770. */
  771. hasChildCommentsNewerThan(commentId) {
  772. return this.nonMutedChildComments.some((comment) => comment.isNewerThan(commentId))
  773. }
  774.  
  775. /**
  776. * @param {number} commentId
  777. * @returns {boolean}
  778. */
  779. isNewerThan(commentId) {
  780. return this.id > commentId
  781. }
  782.  
  783. /**
  784. * @param {boolean} isCollapsed
  785. */
  786. toggleCollapsed(isCollapsed = !this.isCollapsed) {
  787. this.isCollapsed = isCollapsed
  788. this.updateDisplay()
  789. }
  790.  
  791. /**
  792. * @param {boolean} highlight
  793. */
  794. toggleHighlighted(highlight) {
  795. this.$wrapper.style.backgroundColor = highlight ? HIGHLIGHT_COLOR : 'transparent'
  796. }
  797. }
  798.  
  799. //#region Functions
  800. function addHighlightCommentsControl($container) {
  801. let $highlightComments = h('span', null, ' | ', h('a', {
  802. href: '#',
  803. onClick(e) {
  804. e.preventDefault()
  805. addTimeTravelCommentControls($container)
  806. $highlightComments.remove()
  807. },
  808. }, 'highlight comments'))
  809.  
  810. $container.querySelector('.subline')?.append($highlightComments)
  811. }
  812.  
  813. /**
  814. * Adds checkboxes to toggle folding and highlighting when there are new
  815. * comments on a comment page.
  816. * @param {HTMLElement} $container
  817. */
  818. function addNewCommentControls($container) {
  819. $container.appendChild(
  820. h('div', null,
  821. h('p', null,
  822. `${newCommentCount} new comment${s(newCommentCount)} since ${lastVisit.time.toLocaleString()}`
  823. ),
  824. h('div', {id: 'highlightControls'},
  825. checkbox({
  826. checked: autoHighlightNew,
  827. onclick: (e) => {
  828. highlightNewComments(e.target.checked, lastVisit.maxCommentId)
  829. },
  830. }, 'highlight new comments'),
  831. ' ',
  832. checkbox({
  833. checked: autoCollapseNotNew,
  834. onclick: (e) => {
  835. collapseThreadsWithoutNewComments(e.target.checked, lastVisit.maxCommentId)
  836. },
  837. }, 'collapse threads without new comments'),
  838. ),
  839. )
  840. )
  841. }
  842.  
  843. /**
  844. * Adds the appropriate page controls depending on whether or not there are
  845. * new comments or any comments at all.
  846. */
  847. function addPageControls() {
  848. let $container = /** @type {HTMLElement} */ (document.querySelector('td.subtext'))
  849. if (!$container) {
  850. warn('no container found for page controls')
  851. return
  852. }
  853.  
  854. if (hasNewComments) {
  855. addNewCommentControls($container)
  856. }
  857. else if (commentCount > 1) {
  858. addHighlightCommentsControl($container)
  859. }
  860. }
  861.  
  862. /**
  863. * Adds a range control and button to show the last X new comments.
  864. */
  865. function addTimeTravelCommentControls($container) {
  866. let sortedCommentIds = []
  867. for (let i = 0; i < comments.length; i++) {
  868. let comment = comments[i]
  869. if (comment.isMuted) {
  870. // Skip muted comments and their replies as they're always hidden
  871. i += comment.childComments.length
  872. continue
  873. }
  874. sortedCommentIds.push(comment.id)
  875. }
  876. sortedCommentIds.sort()
  877.  
  878. let showNewCommentsAfter = Math.max(0, sortedCommentIds.length - 1)
  879. let howMany = sortedCommentIds.length - showNewCommentsAfter
  880.  
  881. function getRangeDescription() {
  882. let fromWhen = commentsById[sortedCommentIds[showNewCommentsAfter]].when
  883. // Older comments display `on ${date}` instead of a relative time
  884. if (fromWhen.startsWith(' on')) {
  885. fromWhen = fromWhen.replace(' on', 'since')
  886. }
  887. else {
  888. fromWhen = `from ${fromWhen}`
  889. }
  890. return `${howMany} ${fromWhen}`
  891. }
  892.  
  893. let $description = h('span', null, getRangeDescription())
  894.  
  895. let $range = h('input', {
  896. id: 'timeTravelRange',
  897. max: sortedCommentIds.length - 1,
  898. min: 1,
  899. oninput(e) {
  900. showNewCommentsAfter = Number(e.target.value)
  901. howMany = sortedCommentIds.length - showNewCommentsAfter
  902. $description.textContent = getRangeDescription()
  903. },
  904. type: 'range',
  905. value: sortedCommentIds.length - 1,
  906. })
  907.  
  908. let $button = /** @type {HTMLInputElement} */ (h('input', {
  909. id: 'timeTravelButton',
  910. onclick() {
  911. let referenceCommentId = sortedCommentIds[showNewCommentsAfter - 1]
  912. log(`manually highlighting ${howMany} comments since ${referenceCommentId}`)
  913. highlightNewComments(true, referenceCommentId)
  914. collapseThreadsWithoutNewComments(true, referenceCommentId)
  915. $timeTravelControl.remove()
  916. },
  917. type: 'button',
  918. value: 'highlight comments',
  919. }))
  920.  
  921. let $timeTravelControl = h('div', {
  922. id: 'timeTravel',
  923. }, h('div', null, $range), $button, $description)
  924.  
  925. $container.appendChild($timeTravelControl)
  926. }
  927.  
  928. /**
  929. * Collapses threads which don't have any comments newer than the given
  930. * comment id.
  931. * @param {boolean} collapse
  932. * @param {number} referenceCommentId
  933. */
  934. function collapseThreadsWithoutNewComments(collapse, referenceCommentId) {
  935. for (let i = 0; i < comments.length; i++) {
  936. let comment = comments[i]
  937. if (comment.isMuted) {
  938. // Skip muted comments and their replies as they're always hidden
  939. i += comment.childComments.length
  940. continue
  941. }
  942. if (!comment.isNewerThan(referenceCommentId) &&
  943. !comment.hasChildCommentsNewerThan(referenceCommentId)) {
  944. comment.toggleCollapsed(collapse)
  945. // Skip replies as we've already checked them
  946. i += comment.childComments.length
  947. }
  948. }
  949. }
  950.  
  951. function hideMutedUsers() {
  952. for (let i = 0; i < comments.length; i++) {
  953. let comment = comments[i]
  954. if (comment.isMuted) {
  955. comment.hide()
  956. // Skip replies as hide() already hid them
  957. i += comment.childComments.length
  958. }
  959. }
  960. }
  961.  
  962. /**
  963. * Highlights comments newer than the given comment id.
  964. * @param {boolean} highlight
  965. * @param {number} referenceCommentId
  966. */
  967. function highlightNewComments(highlight, referenceCommentId) {
  968. comments.forEach((comment) => {
  969. if (!comment.isMuted && comment.isNewerThan(referenceCommentId)) {
  970. comment.toggleHighlighted(highlight)
  971. }
  972. })
  973. }
  974.  
  975. function initComments() {
  976. let commentWrappers = /** @type {NodeListOf<HTMLTableRowElement>} */ (document.querySelectorAll('table.comment-tree tr.athing'))
  977. log('number of comment wrappers', commentWrappers.length)
  978.  
  979. let commentIndex = 0
  980. for (let $wrapper of commentWrappers) {
  981. let comment = new HNComment($wrapper, commentIndex++)
  982. comments.push(comment)
  983. if (!comment.isMuted && !comment.isDeleted) {
  984. commentsById[comment.id] = comment
  985. }
  986. }
  987.  
  988. let lastVisitMaxCommentId = lastVisit?.maxCommentId ?? -1
  989. for (let i = 0; i < comments.length; i++) {
  990. let comment = comments[i]
  991.  
  992. if (comment.isMuted) {
  993. mutedCommentCount++
  994. for (let j = i + 1; j <= i + comment.childComments.length; j++) {
  995. if (comments[j].isMuted) {
  996. mutedCommentCount++
  997. } else {
  998. replyToMutedCommentCount++
  999. }
  1000. }
  1001. // Skip child comments as we've already accounted for them
  1002. i += comment.childComments.length
  1003. // Don't consider muted comments or their replies when counting new
  1004. // comments, or add controls to them, as they'll all be hidden.
  1005. continue
  1006. }
  1007.  
  1008. if (!comment.isDeleted && comment.isNewerThan(lastVisitMaxCommentId)) {
  1009. newCommentCount++
  1010. }
  1011.  
  1012. comment.addControls()
  1013. }
  1014.  
  1015. maxCommentId = comments.map(comment => comment.id).sort().pop()
  1016. hasNewComments = lastVisit != null && newCommentCount > 0
  1017. }
  1018.  
  1019. // TODO Only store visit data when the item header is present (i.e. not a comment permalink)
  1020. // TODO Only store visit data for commentable items (a reply box / reply links are visible)
  1021. // TODO Clear any existing stored visit if the item is no longer commentable
  1022. function storePageViewData() {
  1023. storeVisit(itemId, new Visit({
  1024. commentCount,
  1025. maxCommentId,
  1026. time: new Date(),
  1027. }))
  1028. }
  1029. //#endregion
  1030.  
  1031. //#region Main
  1032. lastVisit = getLastVisit(itemId)
  1033.  
  1034. let $commentsLink = document.querySelector('span.subline > a[href^=item]')
  1035. if ($commentsLink && /^\d+/.test($commentsLink.textContent)) {
  1036. commentCount = Number($commentsLink.textContent.split(/\s/).shift())
  1037. } else {
  1038. warn('number of comments link not found')
  1039. }
  1040.  
  1041. configureCss()
  1042. initComments()
  1043. // Update display of any comments which were already collapsed by HN's own
  1044. // functionality, e.g. deleted comments
  1045. comments.filter(comment => comment.isCollapsed).forEach(comment => comment.updateDisplay(false))
  1046. hideMutedUsers()
  1047. if (hasNewComments && (autoHighlightNew || autoCollapseNotNew)) {
  1048. if (autoHighlightNew) {
  1049. highlightNewComments(true, lastVisit.maxCommentId)
  1050. }
  1051. if (autoCollapseNotNew) {
  1052. collapseThreadsWithoutNewComments(true, lastVisit.maxCommentId)
  1053. }
  1054. }
  1055. addPageControls()
  1056. storePageViewData()
  1057.  
  1058. log('page view data', {
  1059. autoHighlightNew,
  1060. commentCount,
  1061. mutedCommentCount,
  1062. replyToMutedCommentCount,
  1063. hasNewComments,
  1064. itemId,
  1065. lastVisit,
  1066. maxCommentId,
  1067. newCommentCount,
  1068. })
  1069.  
  1070. chrome.storage.onChanged.addListener((changes) => {
  1071. if ('hideReplyLinks' in changes) {
  1072. config.hideReplyLinks = changes['hideReplyLinks'].newValue
  1073. configureCss()
  1074. }
  1075. })
  1076. //#endregion
  1077. }
  1078. //#endregion
  1079.  
  1080. //#region Item list page
  1081. /**
  1082. * Each item on an item list page has the following structure:
  1083. *
  1084. * ```html
  1085. * <tr class="athing">…</td> (rank, upvote control, title/link and domain)
  1086. * <tr>
  1087. * <td>…</td> (spacer)
  1088. * <td class="subtext">
  1089. * <span class="subline">…</span> (item meta info)
  1090. * </td>
  1091. * </tr>
  1092. * <tr class="spacer">…</tr>
  1093. * ```
  1094. *
  1095. * Using the comment count stored when you visit a comment page, we'll display
  1096. * the number of new comments in the subtext section and provide a link which
  1097. * will automatically highlight new comments and collapse comment trees without
  1098. * new comments.
  1099. *
  1100. * For regular stories, the subtext element contains points, user, age (in
  1101. * a link to the comments page), flag/hide controls and finally the number of
  1102. * comments (in another link to the comments page). We'll look for the latter
  1103. * to detemine the current number of comments and the item id.
  1104. *
  1105. * For job postings, the subtext element only contains age (in
  1106. * a link to the comments page) and a hide control, so we'll try to ignore
  1107. * those.
  1108. */
  1109. function itemListPage() {
  1110. log('item list page')
  1111.  
  1112. //#region CSS
  1113. let $style = addStyle('list-dynamic')
  1114.  
  1115. function configureCss() {
  1116. $style.textContent = [
  1117. // Hide flag links
  1118. config.listPageFlagging == 'disabled' && `
  1119. .flag-sep, .flag-sep + a {
  1120. display: none;
  1121. }
  1122. `
  1123. ].filter(Boolean).map(dedent).join('\n')
  1124. }
  1125. //#endregion
  1126.  
  1127. //#region Functions
  1128. function confirmFlag(e) {
  1129. if (config.listPageFlagging != 'confirm') return
  1130. let title = e.target.closest('tr').previousElementSibling.querySelector('.titleline a')?.textContent || 'this item'
  1131. if (!confirm(`Are you sure you want to flag "${title}"?`)) {
  1132. e.preventDefault()
  1133. }
  1134. }
  1135. //#endregion
  1136.  
  1137. //#region Main
  1138. if (location.pathname != '/flagged') {
  1139. for (let $flagLink of document.querySelectorAll('span.subline > a[href^="flag"]')) {
  1140. // Wrap the '|' before flag links in an element so they can be hidden
  1141. $flagLink.previousSibling.replaceWith(h('span', {className: 'flag-sep'}, ' | '))
  1142. $flagLink.addEventListener('click', confirmFlag)
  1143. }
  1144. }
  1145.  
  1146. let commentLinks = /** @type {NodeListOf<HTMLAnchorElement>} */ (document.querySelectorAll('span.subline > a[href^="item?id="]:last-child'))
  1147. log('number of comments/discuss links', commentLinks.length)
  1148.  
  1149. let noCommentsCount = 0
  1150. let noLastVisitCount = 0
  1151.  
  1152. for (let $commentLink of commentLinks) {
  1153. let id = $commentLink.href.split('=').pop()
  1154.  
  1155. let commentCountMatch = /^(\d+)/.exec($commentLink.textContent)
  1156. if (commentCountMatch == null) {
  1157. noCommentsCount++
  1158. continue
  1159. }
  1160.  
  1161. let lastVisit = getLastVisit(id)
  1162. if (lastVisit == null) {
  1163. noLastVisitCount++
  1164. continue
  1165. }
  1166.  
  1167. let commentCount = Number(commentCountMatch[1])
  1168. if (commentCount <= lastVisit.commentCount) {
  1169. log(`${id} doesn't have any new comments`, lastVisit)
  1170. continue
  1171. }
  1172.  
  1173. $commentLink.insertAdjacentElement('afterend',
  1174. h('span', null,
  1175. ' (',
  1176. h('a', {
  1177. href: `item?shownew&id=${id}`,
  1178. style: {fontWeight: 'bold'},
  1179. },
  1180. commentCount - lastVisit.commentCount,
  1181. ' new'
  1182. ),
  1183. ')',
  1184. )
  1185. )
  1186. }
  1187.  
  1188. if (noCommentsCount > 0) {
  1189. log(`${noCommentsCount} item${s(noCommentsCount, " doesn't,s don't")} have any comments`)
  1190. }
  1191. if (noLastVisitCount > 0) {
  1192. log(`${noLastVisitCount} item${s(noLastVisitCount, " doesn't,s don't")} have a last visit stored`)
  1193. }
  1194.  
  1195. configureCss()
  1196.  
  1197. chrome.storage.onChanged.addListener((changes) => {
  1198. if ('listPageFlagging' in changes) {
  1199. config.listPageFlagging = changes['listPageFlagging'].newValue
  1200. configureCss()
  1201. }
  1202. })
  1203. //#endregion
  1204. }
  1205. //#endregion
  1206.  
  1207. //#region Profile page
  1208. function userProfilePage() {
  1209. log('user profile page')
  1210.  
  1211. let $userLink = /** @type {HTMLAnchorElement} */ (document.querySelector('a.hnuser'))
  1212. if ($userLink == null) {
  1213. warn('not a valid user')
  1214. return
  1215. }
  1216.  
  1217. let userId = $userLink.innerText
  1218. let $currentUserLink = /** @type {HTMLAnchorElement} */ (document.querySelector('a#me'))
  1219. let currentUser = $currentUserLink?.innerText ?? ''
  1220. let mutedUsers = getMutedUsers()
  1221. let userNotes = getUserNotes()
  1222. let $table = $userLink.closest('table')
  1223.  
  1224. if (userId == currentUser || location.pathname.startsWith('/muted')) {
  1225. //#region Logged-in user's profile
  1226. let $mutedUsers = createMutedUsers()
  1227.  
  1228. function createMutedUsers() {
  1229. if (mutedUsers.size == 0) {
  1230. return h('tbody', null,
  1231. h('tr', null,
  1232. h('td', {valign: 'top'}, 'muted:'),
  1233. h('td', null, 'No muted users.')
  1234. )
  1235. )
  1236. }
  1237.  
  1238. let first = 0
  1239. return h('tbody', null,
  1240. ...Array.from(mutedUsers).map((mutedUserId) => h('tr', null,
  1241. h('td', {valign: 'top'}, first++ == 0 ? 'muted:' : ''),
  1242. h('td', null,
  1243. h('a', {href: `user?id=${mutedUserId}`}, mutedUserId),
  1244. h('a', {
  1245. href: '#',
  1246. onClick: function(e) {
  1247. e.preventDefault()
  1248. mutedUsers = getMutedUsers()
  1249. mutedUsers.delete(mutedUserId)
  1250. storeMutedUsers(mutedUsers)
  1251. replaceMutedUsers()
  1252. }
  1253. },
  1254. ' (', h('u', null, 'unmute'), ')'
  1255. ),
  1256. userNotes[mutedUserId] ? ` - ${userNotes[mutedUserId].split(/\r?\n/)[0]}` : null,
  1257. ),
  1258. ))
  1259. )
  1260. }
  1261.  
  1262. function replaceMutedUsers() {
  1263. let $newMutedUsers = createMutedUsers()
  1264. $mutedUsers.replaceWith($newMutedUsers)
  1265. $mutedUsers = $newMutedUsers
  1266. }
  1267.  
  1268. $table.append($mutedUsers)
  1269.  
  1270. window.addEventListener('storage', (e) => {
  1271. if (e.storageArea !== localStorage ||
  1272. e.newValue == null ||
  1273. e.key != MUTED_USERS_KEY && e.key != USER_NOTES_KEY) {
  1274. return
  1275. }
  1276.  
  1277. if (e.key == MUTED_USERS_KEY) {
  1278. mutedUsers = getMutedUsers(e.newValue)
  1279. }
  1280. else if (e.key == USER_NOTES_KEY) {
  1281. userNotes = getUserNotes(e.newValue)
  1282. }
  1283.  
  1284. replaceMutedUsers()
  1285. })
  1286. //#endregion
  1287. }
  1288. else {
  1289. //#region Other user profile
  1290. addStyle('profile-static', `
  1291. .saved {
  1292. color: #000;
  1293. opacity: 0;
  1294. }
  1295. .saved.show {
  1296. animation: flash 2s forwards;
  1297. }
  1298. @keyframes flash {
  1299. from {
  1300. opacity: 0;
  1301. }
  1302. 15% {
  1303. opacity: 1;
  1304. animation-timing-function: ease-in;
  1305. }
  1306. 75% {
  1307. opacity: 1;
  1308. }
  1309. to {
  1310. opacity: 0;
  1311. animation-timing-function: ease-out;
  1312. }
  1313. }
  1314. .notes {
  1315. display: flex;
  1316. flex-direction: column;
  1317. align-items: flex-start;
  1318. gap: 3px;
  1319. }
  1320. `)
  1321.  
  1322. function getMutedStatusText() {
  1323. return mutedUsers.has(userId) ? 'unmute' : 'mute'
  1324. }
  1325.  
  1326. function getUserNote() {
  1327. return userNotes[userId] || ''
  1328. }
  1329.  
  1330. function userHasNote() {
  1331. return userNotes.hasOwnProperty(userId)
  1332. }
  1333.  
  1334. function saveNotes() {
  1335. userNotes = getUserNotes()
  1336. let note = $textArea.value.trim()
  1337.  
  1338. // Don't save initial blanks or duplicates
  1339. if (userNotes[userId] == note || note == '' && !userHasNote()) return
  1340.  
  1341. userNotes[userId] = $textArea.value.trim()
  1342. storeUserNotes(userNotes)
  1343.  
  1344. if ($saved.classList.contains('show')) {
  1345. $saved.classList.remove('show')
  1346. $saved.offsetHeight
  1347. }
  1348. $saved.classList.add('show')
  1349. }
  1350.  
  1351. let $textArea = /** @type {HTMLTextAreaElement} */ (h('textarea', {
  1352. cols: 60,
  1353. value: userNotes[userId] || '',
  1354. className: 'notes',
  1355. style: {resize: 'none'},
  1356. onInput() {
  1357. autosizeTextArea(this)
  1358. },
  1359. onKeydown(e) {
  1360. // Save on Use Ctrl+Enter / Cmd+Return
  1361. if (e.key == 'Enter' && (e.ctrlKey || e.metaKey)) {
  1362. e.preventDefault()
  1363. saveNotes()
  1364. }
  1365. },
  1366. onBlur() {
  1367. saveNotes()
  1368. }
  1369. }))
  1370.  
  1371. let $muted = h('u', null, getMutedStatusText())
  1372. let $saved = h('span', {className: 'saved'}, 'saved')
  1373.  
  1374. $table.querySelector('tbody').append(
  1375. h('tr', null,
  1376. h('td'),
  1377. h('td', null,
  1378. h('a', {
  1379. href: '#',
  1380. onClick: function(e) {
  1381. e.preventDefault()
  1382. if (mutedUsers.has(userId)) {
  1383. mutedUsers = getMutedUsers()
  1384. mutedUsers.delete(userId)
  1385. this.firstElementChild.innerText = 'mute'
  1386. }
  1387. else {
  1388. mutedUsers = getMutedUsers()
  1389. mutedUsers.add(userId)
  1390. this.firstElementChild.innerText = 'unmute'
  1391. }
  1392. storeMutedUsers(mutedUsers)
  1393. }
  1394. },
  1395. $muted
  1396. )
  1397. )
  1398. ),
  1399. h('tr', null,
  1400. h('td', {vAlign: 'top'}, 'notes:'),
  1401. h('td', {className: 'notes'}, $textArea, $saved),
  1402. ),
  1403. )
  1404.  
  1405. autosizeTextArea($textArea)
  1406.  
  1407. window.addEventListener('storage', (e) => {
  1408. if (e.storageArea !== localStorage || e.newValue == null) return
  1409.  
  1410. if (e.key == MUTED_USERS_KEY) {
  1411. mutedUsers = getMutedUsers(e.newValue)
  1412. if ($muted.textContent != getMutedStatusText()) {
  1413. $muted.textContent = getMutedStatusText()
  1414. }
  1415. }
  1416. else if (e.key == USER_NOTES_KEY) {
  1417. userNotes = getUserNotes(e.newValue)
  1418. if (userHasNote() && $textArea.value.trim() != getUserNote()) {
  1419. $textArea.value = getUserNote()
  1420. }
  1421. }
  1422. })
  1423. //#endregion
  1424. }
  1425. }
  1426. //#endregion
  1427.  
  1428. //#region Main
  1429. function main() {
  1430. log('config', config)
  1431.  
  1432. if (location.pathname.startsWith('/login')) {
  1433. log('login screen')
  1434. if (isSafari) {
  1435. log('trying to prevent Safari zooming in on the autofocused input')
  1436. addStyle('login-safari', `input[type="text"], input[type="password"] { font-size: 16px; }`)
  1437. setTimeout(() => {
  1438. document.querySelector('input[type="password"]').focus()
  1439. document.querySelector('input[type="text"]').focus()
  1440. })
  1441. }
  1442. return
  1443. }
  1444.  
  1445. if (location.pathname.startsWith('/muted')) {
  1446. document.documentElement.innerHTML = LOGGED_OUT_USER_PAGE
  1447. // Safari on macOS has a default dark background in dark mode
  1448. if (isSafari) {
  1449. addStyle('muted-safari', 'html { background-color: #fff; }')
  1450. }
  1451. }
  1452.  
  1453. tweakNav()
  1454.  
  1455. let path = location.pathname.slice(1)
  1456.  
  1457. if (/^($|active|ask|best($|\?)|flagged|front|hidden|invited|launches|news|newest|noobstories|pool|show|submitted|upvoted)/.test(path) ||
  1458. /^favorites/.test(path) && !location.search.includes('&comments=t')) {
  1459. itemListPage()
  1460. }
  1461. else if (/^item/.test(path)) {
  1462. commentPage()
  1463. }
  1464. else if (/^(user|muted)/.test(path)) {
  1465. userProfilePage()
  1466. }
  1467. }
  1468.  
  1469. if (
  1470. typeof GM == 'undefined' &&
  1471. typeof chrome != 'undefined' &&
  1472. typeof chrome.storage != 'undefined'
  1473. ) {
  1474. chrome.storage.local.get((storedConfig) => {
  1475. Object.assign(config, storedConfig)
  1476. main()
  1477. })
  1478. }
  1479. else {
  1480. main()
  1481. }
  1482. //#endregion