Files
challenge-pl/src/utils/drafts.ts
T

33 lines
927 B
TypeScript

const STORAGE_PREFIX = 'challenge_draft_'
const isBrowser = () => typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'
export function saveDraft(taskId: string, result: string) {
if (!isBrowser()) return
window.localStorage.setItem(`${STORAGE_PREFIX}${taskId}`, result)
}
export function loadDraft(taskId: string): string | null {
if (!isBrowser()) return null
return window.localStorage.getItem(`${STORAGE_PREFIX}${taskId}`)
}
export function clearDraft(taskId: string) {
if (!isBrowser()) return
window.localStorage.removeItem(`${STORAGE_PREFIX}${taskId}`)
}
export function listDrafts() {
if (!isBrowser()) return [] as string[]
const keys = [] as string[]
for (let i = 0; i < window.localStorage.length; i += 1) {
const key = window.localStorage.key(i)
if (key?.startsWith(STORAGE_PREFIX)) {
keys.push(key.replace(STORAGE_PREFIX, ''))
}
}
return keys
}