feat(ui): disable relative time sync when window is not visible

This commit is contained in:
Ou 2024-10-20 13:50:19 +08:00
parent 6268dad4db
commit f8303382ef

View File

@ -1,9 +1,10 @@
import { relativeTime } from "@shared/utils"
import { atom, useAtomValue } from "jotai"
import { useEffect, useState } from "react"
import { useMount } from "react-use"
/**
* change every minute
* changed every minute
*/
const timerAtom = atom(0)
@ -14,16 +15,33 @@ timerAtom.onMount = (set) => {
return () => clearInterval(timer)
}
function useVisibility() {
const [visible, setVisible] = useState(true)
useMount(() => {
const handleVisibilityChange = () => {
setVisible(document.visibilityState === "visible")
}
document.addEventListener("visibilitychange", handleVisibilityChange)
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange)
}
})
return visible
}
export function useRelativeTime(timestamp: string | number) {
const [time, setTime] = useState<string>()
const timer = useAtomValue(timerAtom)
const visible = useVisibility()
useEffect(() => {
const t = relativeTime(timestamp)
if (t) {
setTime(t)
if (visible) {
const t = relativeTime(timestamp)
if (t) {
setTime(t)
}
}
}, [timestamp, timer])
}, [timestamp, timer, visible])
return time
}