mirror of
https://github.com/johndoe6345789/low-code-react-app-b.git
synced 2026-04-24 13:44:54 +00:00
Merge pull request #67 from johndoe6345789/codex/add-timeago-and-isrecent-properties
Add useSaveIndicator hook and refactor SaveIndicator to use it
This commit is contained in:
@@ -1,31 +1,14 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import { StatusIcon } from '@/components/atoms'
|
||||
import { useSaveIndicator } from '@/hooks/use-save-indicator'
|
||||
|
||||
interface SaveIndicatorProps {
|
||||
lastSaved: number | null
|
||||
}
|
||||
|
||||
export function SaveIndicator({ lastSaved }: SaveIndicatorProps) {
|
||||
const [timeAgo, setTimeAgo] = useState<string>('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastSaved) return
|
||||
|
||||
const updateTimeAgo = () => {
|
||||
const distance = formatDistanceToNow(lastSaved, { addSuffix: true })
|
||||
setTimeAgo(distance)
|
||||
}
|
||||
|
||||
updateTimeAgo()
|
||||
const interval = setInterval(updateTimeAgo, 10000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [lastSaved])
|
||||
|
||||
if (!lastSaved) return null
|
||||
|
||||
const isRecent = Date.now() - lastSaved < 3000
|
||||
const { timeAgo, isRecent } = useSaveIndicator(lastSaved)
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
|
||||
39
src/hooks/use-save-indicator.ts
Normal file
39
src/hooks/use-save-indicator.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 10000
|
||||
const DEFAULT_RECENT_THRESHOLD_MS = 3000
|
||||
|
||||
export function useSaveIndicator(
|
||||
lastSaved: number | null,
|
||||
{
|
||||
intervalMs = DEFAULT_INTERVAL_MS,
|
||||
recentThresholdMs = DEFAULT_RECENT_THRESHOLD_MS,
|
||||
}: {
|
||||
intervalMs?: number
|
||||
recentThresholdMs?: number
|
||||
} = {},
|
||||
) {
|
||||
const [timeAgo, setTimeAgo] = useState<string>('')
|
||||
const [isRecent, setIsRecent] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!lastSaved) {
|
||||
setTimeAgo('')
|
||||
setIsRecent(false)
|
||||
return
|
||||
}
|
||||
|
||||
const updateIndicator = () => {
|
||||
setTimeAgo(formatDistanceToNow(lastSaved, { addSuffix: true }))
|
||||
setIsRecent(Date.now() - lastSaved < recentThresholdMs)
|
||||
}
|
||||
|
||||
updateIndicator()
|
||||
const interval = setInterval(updateIndicator, intervalMs)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [intervalMs, lastSaved, recentThresholdMs])
|
||||
|
||||
return { timeAgo, isRecent }
|
||||
}
|
||||
Reference in New Issue
Block a user