Comments Owl for Hacker News

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

当前为 2023-10-19 提交的版本,查看 最新版本

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