feat(island): add listener on navigator.connection is available for IsOnline

This commit is contained in:
Julien Oculi 2024-07-19 14:35:28 +02:00
parent 356014ec46
commit 3c35dcbf8e

View file

@ -2,6 +2,13 @@ import { type Signal, useComputed, useSignal } from '@preact/signals'
import { useEffect } from 'preact/hooks'
import { IS_BROWSER } from '$fresh/runtime.ts'
type NetworkConnection = {
addEventListener: (
type: 'change',
listener: (event: Event) => void | Promise<void>,
) => void
}
export default function IsOnline(
{ online, offline }: { online?: string; offline: string },
) {
@ -19,7 +26,17 @@ export default function IsOnline(
}
return <span class={'island__is_online'}>{offline}</span>
})
useEffect(() => openSocket(status, { id: undefined }), [])
const connection = 'connection' in navigator
? navigator.connection as NetworkConnection
: null
useEffect(() => {
openSocket(status, { id: undefined })
connection?.addEventListener('change', () => {
fetch('/api/serviceworker/is-online')
.then(() => status.value = true)
.catch(() => status.value = false)
})
}, [])
return <>{displayed}</>
}