forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-form-draft.ts
More file actions
98 lines (86 loc) · 2.51 KB
/
Copy pathuse-form-draft.ts
File metadata and controls
98 lines (86 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use client'
import { useEffect, useRef, useCallback } from 'react'
const DRAFT_TTL_MS = 24 * 60 * 60 * 1000
interface DraftEntry<T> {
data: T
savedAt: number
}
export function useFormDraft<T>(
key: string,
value: T,
onChange: (draft: T) => void,
enabled = true,
) {
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const isRestoringRef = useRef(false)
const storageKey = `flowstar_draft_${key}`
const save = useCallback(
(data: T) => {
try {
const entry: DraftEntry<T> = { data, savedAt: Date.now() }
localStorage.setItem(storageKey, JSON.stringify(entry))
} catch {
// storage quota exceeded or unavailable — silently skip
}
},
[storageKey],
)
const discard = useCallback(() => {
localStorage.removeItem(storageKey)
}, [storageKey])
const loadDraft = useCallback((): { data: T; savedAt: number } | null => {
try {
const raw = localStorage.getItem(storageKey)
if (!raw) return null
const entry: DraftEntry<T> = JSON.parse(raw)
if (Date.now() - entry.savedAt > DRAFT_TTL_MS) {
localStorage.removeItem(storageKey)
return null
}
return entry
} catch {
return null
}
}, [storageKey])
const restore = useCallback(() => {
const entry = loadDraft()
if (!entry) return
isRestoringRef.current = true
onChange(entry.data)
setTimeout(() => {
isRestoringRef.current = false
}, 0)
}, [loadDraft, onChange])
// Debounced auto-save on value changes
useEffect(() => {
if (!enabled || isRestoringRef.current) return
if (debounceRef.current) clearTimeout(debounceRef.current)
debounceRef.current = setTimeout(() => save(value), 500)
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current)
}
}, [value, enabled, save])
return { loadDraft, restore, discard }
}
export function clearExpiredDrafts(prefix = 'flowstar_draft_') {
try {
const keysToRemove: string[] = []
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i)
if (!k?.startsWith(prefix)) continue
try {
const raw = localStorage.getItem(k)
if (!raw) continue
const entry: DraftEntry<unknown> = JSON.parse(raw)
if (Date.now() - entry.savedAt > DRAFT_TTL_MS) {
keysToRemove.push(k)
}
} catch {
keysToRemove.push(k!)
}
}
keysToRemove.forEach((k) => localStorage.removeItem(k))
} catch {
// localStorage unavailable
}
}