logigate/app/lib/logic/storage.ts

187 lines
5.1 KiB
TypeScript
Raw Permalink Normal View History

// 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
/** Set once the project is stored in an account: whose, and which revision this browser has. */
cloud?: { owner: string; rev: number }
/** Changed here since the last upload to the account. */
dirty?: boolean
/** The example project a new browser starts with, never touched yet. */
starter?: boolean
/** Ask the server to keep the state before the next upload as a savegame (after restoring an old version). */
snapshot?: boolean
/** The project's mode (campaign, challenges), so the main menu can find them without loading every project. */
mode?: 'campaign' | 'challenges'
}
export interface AccountUser {
id: string
email: string
}
const INDEX = 'logigate:projects'
const CURRENT = 'logigate:current'
const LEGACY = 'logigate:project:v1'
const ACCOUNT = 'logigate:account'
const PENDING_DELETES = 'logigate:pending-deletes'
const LIBRARY_KEYS = 'logigate:library-keys'
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 {}
}
/** The account this browser was last signed in to, so the UI knows before the server answers. */
export function cachedAccount(): AccountUser | null {
try {
const a = JSON.parse(read(ACCOUNT) ?? 'null') as AccountUser | null
return a && typeof a.id === 'string' ? a : null
} catch {
return null
}
}
export function setCachedAccount(user: AccountUser | null) {
if (user) write(ACCOUNT, JSON.stringify(user))
else
try {
localStorage.removeItem(ACCOUNT)
} catch {}
}
/** Account projects deleted while offline, to delete on the server at the next sync. */
export function pendingDeletes(): { owner: string; id: string }[] {
try {
const list = JSON.parse(read(PENDING_DELETES) ?? '[]')
return Array.isArray(list) ? list : []
} catch {
return []
}
}
export function setPendingDeletes(list: { owner: string; id: string }[]) {
write(PENDING_DELETES, JSON.stringify(list))
}
/** A library entry published from this browser. */
export interface LibraryKey {
/** Edit key: updates or removes the entry. */
key: string
/** The project and component it was published from. */
project: string
def: string
}
/** Library entries published from this browser, by entry id. Never part of a project, so whoever gets a copy of it can't change them. */
export function libraryKeys(): Record<string, LibraryKey> {
try {
const keys = JSON.parse(read(LIBRARY_KEYS) ?? '{}')
return keys && typeof keys === 'object' && !Array.isArray(keys) ? keys : {}
} catch {
return {}
}
}
export function setLibraryKey(id: string, own: LibraryKey | null) {
const keys = libraryKeys()
if (own) keys[id] = own
else delete keys[id]
write(LIBRARY_KEYS, JSON.stringify(keys))
}