mirror of
https://github.com/ourongxing/newsnow.git
synced 2025-01-19 03:09:14 +08:00
feat(ui): disable relative time sync when window is not visible
This commit is contained in:
parent
6268dad4db
commit
f8303382ef
@ -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
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user