logigate/app/lib/logic/storage.ts

111 lines
2.7 KiB
TypeScript

// The browser's project library: several projects in localStorage, each
// with its own entry, plus an index with names and share links.
import { parseProject } from './project'
import type { Project } from './types'
export interface ShareLink {
id: string
/** Edit key; only the person who created the link has it. */
key?: string
}
export interface ProjectMeta {
id: string
name: string
updated: number
link?: ShareLink
}
const INDEX = 'logigate:projects'
const CURRENT = 'logigate:current'
const LEGACY = 'logigate:project:v1'
const entry = (id: string) => `logigate:p:${id}`
function read(key: string): string | null {
try {
return localStorage.getItem(key)
} catch {
return null
}
}
function write(key: string, value: string): boolean {
try {
localStorage.setItem(key, value)
return true
} catch {
return false
}
}
export function newLocalId(): string {
return Math.random().toString(36).slice(2, 10)
}
export function listProjects(): ProjectMeta[] {
try {
const list = JSON.parse(read(INDEX) ?? '[]') as ProjectMeta[]
return Array.isArray(list) ? list.filter(m => m && typeof m.id === 'string') : []
} catch {
return []
}
}
function writeIndex(list: ProjectMeta[]) {
write(INDEX, JSON.stringify(list))
}
export function loadProject(id: string): Project | null {
const raw = read(entry(id))
if (!raw) return null
try {
return parseProject(raw)
} catch {
return null
}
}
/** Saves a project and its index entry. Returns false when storage is full or blocked. */
export function saveProject(meta: ProjectMeta, project: Project): boolean {
const ok = write(entry(meta.id), JSON.stringify(project))
const list = listProjects().filter(m => m.id !== meta.id)
list.unshift(meta)
writeIndex(list)
return ok
}
export function saveMeta(meta: ProjectMeta) {
writeIndex(listProjects().map(m => (m.id === meta.id ? meta : m)))
}
export function removeProject(id: string) {
try {
localStorage.removeItem(entry(id))
} catch {}
writeIndex(listProjects().filter(m => m.id !== id))
}
export function currentId(): string | null {
return read(CURRENT)
}
export function setCurrentId(id: string) {
write(CURRENT, id)
}
/** Moves the single project of the first version into the library. */
export function migrateLegacy(): void {
const raw = read(LEGACY)
if (!raw || listProjects().length) return
try {
const project = parseProject(raw)
if (project.name === 'Untitled') project.name = 'My first project'
const meta: ProjectMeta = { id: newLocalId(), name: project.name, updated: Date.now() }
if (saveProject(meta, project)) {
setCurrentId(meta.id)
localStorage.removeItem(LEGACY)
}
} catch {}
}