mirror of
https://github.com/ourongxing/newsnow.git
synced 2025-01-31 10:58:04 +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 { relativeTime } from "@shared/utils"
|
||||||
import { atom, useAtomValue } from "jotai"
|
import { atom, useAtomValue } from "jotai"
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
|
import { useMount } from "react-use"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* change every minute
|
* changed every minute
|
||||||
*/
|
*/
|
||||||
const timerAtom = atom(0)
|
const timerAtom = atom(0)
|
||||||
|
|
||||||
@ -14,16 +15,33 @@ timerAtom.onMount = (set) => {
|
|||||||
return () => clearInterval(timer)
|
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) {
|
export function useRelativeTime(timestamp: string | number) {
|
||||||
const [time, setTime] = useState<string>()
|
const [time, setTime] = useState<string>()
|
||||||
const timer = useAtomValue(timerAtom)
|
const timer = useAtomValue(timerAtom)
|
||||||
|
const visible = useVisibility()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const t = relativeTime(timestamp)
|
if (visible) {
|
||||||
if (t) {
|
const t = relativeTime(timestamp)
|
||||||
setTime(t)
|
if (t) {
|
||||||
|
setTime(t)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [timestamp, timer])
|
}, [timestamp, timer, visible])
|
||||||
|
|
||||||
return time
|
return time
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user