anbot

root / feed-live.js

1225 bytes

import { startComposer } from './feed-composer.mjs'

const entries = document.getElementById('feed-entries')
let refreshing = false

async function refreshFeed() {
  if (document.hidden || refreshing) return
  refreshing = true
  try {
    const response = await fetch(window.location.href, {
      cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(10000)
    })
    if (!response.ok) return
    const nextPage = new DOMParser().parseFromString(await response.text(), 'text/html')
    const nextEntries = nextPage.getElementById('feed-entries')
    if (!nextEntries || nextEntries.innerHTML === entries.innerHTML) return

    const focusedLink = entries.contains(document.activeElement) ? document.activeElement.href : null
    entries.replaceChildren(...nextEntries.childNodes)
    if (focusedLink) {
      const link = Array.from(entries.querySelectorAll('a')).find(item => item.href === focusedLink)
      link?.focus({ preventScroll: true })
    }
  } catch {
    // Keep the current entries during a connection failure. The next poll retries.
  } finally {
    refreshing = false
  }
}

setInterval(refreshFeed, 3000)
document.addEventListener('visibilitychange', refreshFeed)
startComposer(refreshFeed)

Git ยท Social feed