forked from FlowwStar/FlowStar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddress-book.ts
More file actions
68 lines (60 loc) · 2.21 KB
/
Copy pathaddress-book.ts
File metadata and controls
68 lines (60 loc) · 2.21 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
export interface AddressBookEntry {
id: string
label: string
address: string
lastUsed: number
}
const STORAGE_KEY = 'flowstar:address-book'
function readEntries(): AddressBookEntry[] {
if (typeof window === 'undefined') return []
try {
const stored = window.localStorage.getItem(STORAGE_KEY)
if (!stored) return []
const parsed = JSON.parse(stored) as AddressBookEntry[]
return Array.isArray(parsed) ? parsed : []
} catch {
return []
}
}
function writeEntries(entries: AddressBookEntry[]) {
if (typeof window === 'undefined') return
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(entries.slice(0, 50)))
}
export function getAddressBookEntries(): AddressBookEntry[] {
return readEntries().sort((a, b) => b.lastUsed - a.lastUsed)
}
export function addAddressBookEntry(entry: Omit<AddressBookEntry, 'id' | 'lastUsed'>) {
const entries = readEntries()
const normalized = {
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
label: entry.label.trim(),
address: entry.address.trim(),
lastUsed: Date.now(),
}
const next = [normalized, ...entries.filter((item) => item.address !== normalized.address)].slice(0, 50)
writeEntries(next)
return normalized
}
export function updateAddressBookEntry(id: string, patch: Partial<Omit<AddressBookEntry, 'id'>>) {
const entries = readEntries()
const next = entries.map((entry) => (entry.id === id ? { ...entry, ...patch } : entry))
writeEntries(next)
return next.find((entry) => entry.id === id) ?? null
}
export function deleteAddressBookEntry(id: string) {
const entries = readEntries().filter((entry) => entry.id !== id)
writeEntries(entries)
}
export function touchAddressBookEntry(address: string, label?: string) {
const entries = readEntries()
const existing = entries.find((entry) => entry.address === address)
if (existing) {
const next = entries.map((entry) =>
entry.address === address ? { ...entry, label: label?.trim() || entry.label, lastUsed: Date.now() } : entry,
)
writeEntries(next)
return next.find((entry) => entry.address === address) ?? null
}
if (!address.trim()) return null
return addAddressBookEntry({ label: label?.trim() || 'Saved recipient', address })
}