43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
export type DraftStorageMode = 'local' | 'session'
|
|||
|
|
|
||
|
|
export interface DraftRecord<T> {
|
||
|
|
savedAt: number
|
||
|
|
payload: T
|
||
|
|
}
|
||
|
|
|
||
|
|
const getStorage = (mode: DraftStorageMode) => (mode === 'session' ? window.sessionStorage : window.localStorage)
|
||
|
|
|
||
|
|
export const buildDraftStorageKey = (...parts: Array<string | number | undefined | null>) => {
|
||
|
|
const normalizedParts = parts
|
||
|
|
.filter((part): part is string | number => part !== undefined && part !== null && String(part).trim().length > 0)
|
||
|
|
.map(part => String(part).trim())
|
||
|
|
return `yuminail:draft:${normalizedParts.join(':')}`
|
||
|
|
}
|
||
|
|
|
||
|
|
export const saveDraftRecord = <T>(key: string, payload: T, mode: DraftStorageMode = 'local') => {
|
||
|
|
const record: DraftRecord<T> = {
|
||
|
|
savedAt: Date.now(),
|
||
|
|
payload
|
||
|
|
}
|
||
|
|
getStorage(mode).setItem(key, JSON.stringify(record))
|
||
|
|
return record
|
||
|
|
}
|
||
|
|
|
||
|
|
export const loadDraftRecord = <T>(key: string, mode: DraftStorageMode = 'local') => {
|
||
|
|
const rawValue = getStorage(mode).getItem(key)
|
||
|
|
if (!rawValue) {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
return JSON.parse(rawValue) as DraftRecord<T>
|
||
|
|
} catch {
|
||
|
|
getStorage(mode).removeItem(key)
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export const clearDraftRecord = (key: string, mode: DraftStorageMode = 'local') => {
|
||
|
|
getStorage(mode).removeItem(key)
|
||
|
|
}
|