51 lines
1.4 KiB
TypeScript
51 lines
1.4 KiB
TypeScript
|
|
// Saving to the browser and to JSON files.
|
||
|
|
|
||
|
|
import type { Project } from './types'
|
||
|
|
|
||
|
|
const KEY = 'logigate:project:v1'
|
||
|
|
|
||
|
|
/** Parses and checks a project file. Throws with a readable message. */
|
||
|
|
export function parseProject(json: string): Project {
|
||
|
|
let data: unknown
|
||
|
|
try {
|
||
|
|
data = JSON.parse(json)
|
||
|
|
} catch {
|
||
|
|
throw new Error('Not a valid JSON file')
|
||
|
|
}
|
||
|
|
const p = data as Partial<Project>
|
||
|
|
if (!p || typeof p !== 'object' || !Array.isArray(p.components) || p.components.length === 0) {
|
||
|
|
throw new Error('Not a Logigate project (no components)')
|
||
|
|
}
|
||
|
|
for (const d of p.components) {
|
||
|
|
if (typeof d?.id !== 'string' || typeof d.name !== 'string' || !Array.isArray(d.nodes) || !Array.isArray(d.wires)) {
|
||
|
|
throw new Error('Not a Logigate project (broken component)')
|
||
|
|
}
|
||
|
|
d.symbol ??= 'box'
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
version: 1,
|
||
|
|
components: p.components,
|
||
|
|
openId: p.components.some(d => d.id === p.openId) ? p.openId! : p.components[0]!.id,
|
||
|
|
settings: { symbols: p.settings?.symbols === 'ansi' ? 'ansi' : 'iec', flow: p.settings?.flow ?? true },
|
||
|
|
solved: Array.isArray(p.solved) ? p.solved : [],
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function loadLocal(): Project | null {
|
||
|
|
try {
|
||
|
|
const raw = localStorage.getItem(KEY)
|
||
|
|
return raw ? parseProject(raw) : null
|
||
|
|
} catch {
|
||
|
|
return null
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function saveLocal(project: Project): boolean {
|
||
|
|
try {
|
||
|
|
localStorage.setItem(KEY, JSON.stringify(project))
|
||
|
|
return true
|
||
|
|
} catch {
|
||
|
|
return false
|
||
|
|
}
|
||
|
|
}
|