logigate/app/composables/useEditor.ts

510 lines
14 KiB
TypeScript

// Editor state: the project, selection, undo history and the running
// simulation of the open circuit. One shared instance for the whole page.
import { runSteps, stats, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile } from '~/lib/logic/compile'
import { shapeOf } from '~/lib/logic/geometry'
import {
addExamples,
containsDef,
copySelection,
createProject,
deleteComponent,
duplicateComponent,
lookup,
newComponent,
packageSelection,
pasteClip,
pruneWires,
startChallenge,
uid,
type Clip,
} from '~/lib/logic/ops'
import { Simulator } from '~/lib/logic/sim'
import { loadLocal, parseProject, saveLocal } from '~/lib/logic/storage'
import type { CircuitNode, NodeKind, PinRef, Project } from '~/lib/logic/types'
export interface Placing {
kind: NodeKind
chip?: string
keep?: boolean
}
export interface View {
x: number
y: number
zoom: number
}
const BUDGET = 300_000
function create() {
const project = ref<Project>(loadLocal() ?? createProject({ examples: true }))
const getDef = computed(() => lookup(project.value))
const def = computed(() => getDef.value(project.value.openId) ?? project.value.components[0]!)
const selection = ref<string[]>([])
const selectedWire = ref<string | null>(null)
const placing = ref<Placing | null>(null)
const nav = ref<string[]>([])
const views = reactive<Record<string, View>>({})
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
let noticeTimer: ReturnType<typeof setTimeout> | undefined
function notify(text: string, kind: 'ok' | 'error' = 'ok') {
notice.value = { text, kind }
clearTimeout(noticeTimer)
noticeTimer = setTimeout(() => (notice.value = null), 3500)
}
// ── History ───────────────────────────────────────────────────────
const snap = () => JSON.stringify({ components: project.value.components, solved: project.value.solved })
let last = snap()
const undoStack: string[] = []
const redoStack: string[] = []
const canUndo = ref(false)
const canRedo = ref(false)
let saveTimer: ReturnType<typeof setTimeout> | undefined
function persist() {
clearTimeout(saveTimer)
saveTimer = setTimeout(() => saveLocal(toRaw(project.value)), 300)
}
/** Record a change. Structural changes (parts, wires) rebuild the simulation. */
function commit(structural = true) {
if (structural) pruneWires(project.value)
const s = snap()
if (s === last) return
undoStack.push(last)
if (undoStack.length > 200) undoStack.shift()
redoStack.length = 0
last = s
canUndo.value = true
canRedo.value = false
persist()
if (structural) scheduleRebuild()
}
function restore(s: string) {
const data = JSON.parse(s) as Pick<Project, 'components' | 'solved'>
project.value.components = data.components
project.value.solved = data.solved
if (!project.value.components.some(d => d.id === project.value.openId)) project.value.openId = project.value.components[0]!.id
last = s
selection.value = selection.value.filter(id => def.value.nodes.some(n => n.id === id))
selectedWire.value = null
canUndo.value = undoStack.length > 0
canRedo.value = redoStack.length > 0
persist()
scheduleRebuild()
}
function undo() {
const s = undoStack.pop()
if (s === undefined) return
redoStack.push(last)
restore(s)
}
function redo() {
const s = redoStack.pop()
if (s === undefined) return
undoStack.push(last)
restore(s)
}
// ── Simulation ────────────────────────────────────────────────────
const sim = shallowRef<Simulator | null>(null)
let simRoot = ''
const tick = ref(0)
const status = ref<'stable' | 'busy' | 'oscillating'>('stable')
const running = ref(true)
const hz = ref(2)
const cycles = ref(0)
const errors = ref<string[]>([])
const circuitStats = ref<Stats>({ nands: 0, sequential: false, delay: 0 })
const pressed = new Set<string>()
function rebuild() {
const d = def.value
const nl = compile(getDef.value, d.id)
const carry = sim.value && simRoot === d.id ? sim.value.carry() : undefined
const s = new Simulator(nl, carry)
for (const n of d.nodes) {
if (n.kind === 'input') s.setSource(n.id, !!n.on)
else if (n.kind === 'button') s.setSource(n.id, pressed.has(n.id))
}
s.run(BUDGET)
if (simRoot !== d.id) cycles.value = 0
sim.value = s
simRoot = d.id
errors.value = nl.errors
circuitStats.value = stats(nl)
tick.value++
}
let rebuildQueued = false
function scheduleRebuild() {
if (rebuildQueued) return
rebuildQueued = true
queueMicrotask(() => {
rebuildQueued = false
rebuild()
})
}
/** Value at a pin of the open circuit. Reactive through `tick`. */
function val(nodeId: string, pin: string): number {
void tick.value
return sim.value?.pin(nodeId, pin) ?? 0
}
let raf = 0
function startLoop() {
let lastT = performance.now()
let acc = 0
let unsettled = 0
let lastChanges = -1
const frame = (t: number) => {
const dt = Math.min(100, t - lastT)
lastT = t
const s = sim.value
if (s) {
let rises = 0
if (running.value && s.nl.clocks.length) {
if (hz.value > 0) {
acc += dt
const half = 500 / hz.value
for (let n = 0; acc >= half && n < 16; n++) {
acc -= half
s.run(BUDGET)
s.setClock(s.clock ^ 1)
if (s.clock) rises++
}
if (acc > half) acc = 0
} else {
const end = performance.now() + 10
while (performance.now() < end) {
if (!s.run(BUDGET)) break
s.setClock(s.clock ^ 1)
if (s.clock) rises++
}
}
}
if (rises) cycles.value += rises
const settled = s.run(BUDGET)
unsettled = settled ? 0 : unsettled + 1
status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy'
if (s.changes !== lastChanges) {
lastChanges = s.changes
tick.value++
}
}
raf = requestAnimationFrame(frame)
}
raf = requestAnimationFrame(frame)
return () => cancelAnimationFrame(raf)
}
/** One full clock cycle (rise and fall), each half settled. */
function step() {
const s = sim.value
if (!s) return
s.run(BUDGET)
if (s.clock) {
s.setClock(0)
s.run(BUDGET)
}
s.setClock(1)
s.run(BUDGET)
cycles.value++
s.setClock(0)
s.run(BUDGET)
tick.value++
}
// ── Navigation ────────────────────────────────────────────────────
function open(id: string, push = true) {
if (id === def.value.id || !getDef.value(id)) return
if (push) nav.value.push(def.value.id)
project.value.openId = id
selection.value = []
selectedWire.value = null
placing.value = null
persist()
rebuild()
}
function back() {
const id = nav.value.pop()
if (id) open(id, false)
}
// ── Editing ───────────────────────────────────────────────────────
function nextLabel(kind: 'input' | 'output'): string {
const used = new Set(def.value.nodes.filter(n => n.kind === kind).map(n => n.label))
if (kind === 'input') {
for (const c of 'ABCDEFGHIJKLMNOPRSTUVWXYZ') if (!used.has(c)) return c
return `I${used.size + 1}`
}
if (!used.has('Q')) return 'Q'
for (let i = 1; ; i++) if (!used.has(`Q${i}`)) return `Q${i}`
}
function addNode(p: Placing, x: number, y: number): CircuitNode {
const node: CircuitNode = { id: uid('n'), kind: p.kind, x, y }
if (p.chip) node.chip = p.chip
if (p.kind === 'input' || p.kind === 'output') node.label = nextLabel(p.kind)
if (p.kind === 'note') node.label = 'Note'
def.value.nodes.push(node)
selection.value = [node.id]
selectedWire.value = null
commit()
return node
}
function canPlace(chipId: string) {
return !containsDef(project.value, chipId, def.value.id)
}
function connect(from: PinRef, to: PinRef) {
const d = def.value
d.wires = d.wires.filter(w => !(w.to.node === to.node && w.to.pin === to.pin))
d.wires.push({ id: uid('w'), from, to })
commit()
}
function deleteSelected() {
const d = def.value
if (selection.value.length) {
const ids = new Set(selection.value)
d.nodes = d.nodes.filter(n => !ids.has(n.id))
d.wires = d.wires.filter(w => !ids.has(w.from.node) && !ids.has(w.to.node))
selection.value = []
commit()
} else if (selectedWire.value) {
d.wires = d.wires.filter(w => w.id !== selectedWire.value)
selectedWire.value = null
commit()
}
}
function toggleInput(node: CircuitNode) {
node.on = !node.on
sim.value?.setSource(node.id, node.on)
persist()
}
function press(node: CircuitNode, down: boolean) {
if (down) pressed.add(node.id)
else pressed.delete(node.id)
sim.value?.setSource(node.id, down)
}
let clip: Clip | null = null
let pasteCount = 0
function copy() {
if (!selection.value.length) return
clip = copySelection(def.value, new Set(selection.value))
pasteCount = 0
notify(`Copied ${clip.nodes.length} part${clip.nodes.length === 1 ? '' : 's'}`)
}
function paste() {
if (!clip) return
pasteCount++
const blocked = clip.nodes.filter(n => n.kind === 'chip' && n.chip && !canPlace(n.chip))
const usable: Clip = blocked.length
? { nodes: clip.nodes.filter(n => !blocked.includes(n)), wires: clip.wires }
: clip
if (blocked.length) notify('Skipped parts that would contain this circuit itself', 'error')
selection.value = pasteClip(def.value, usable, 2 * pasteCount, 2 * pasteCount)
selectedWire.value = null
commit()
}
function duplicate() {
copy()
paste()
}
function selectAll() {
selection.value = def.value.nodes.map(n => n.id)
selectedWire.value = null
}
function packageSelected(name: string) {
const res = packageSelection(project.value, def.value.id, new Set(selection.value), name)
if (!res.ok) {
notify(res.error, 'error')
return
}
selection.value = [res.chipNode]
commit()
notify(`Created component "${res.def.name}"`)
}
// ── Components ────────────────────────────────────────────────────
function createComponent(name = 'New part') {
const d = newComponent(project.value, name)
commit()
open(d.id)
labelFocus.value++
}
function removeComponent(id: string) {
const err = deleteComponent(project.value, id)
if (err) return notify(err, 'error')
nav.value = nav.value.filter(n => n !== id)
commit()
rebuild()
}
function copyComponent(id: string) {
const d = duplicateComponent(project.value, id)
if (!d) return
commit()
open(d.id)
}
function beginChallenge(c: Challenge) {
const existing = project.value.components.find(d => d.challenge === c.id)
if (existing) return open(existing.id)
const d = startChallenge(project.value, c)
commit()
open(d.id)
}
function checkChallenge(): TestResult | null {
const c = CHALLENGES.find(c => c.id === def.value.challenge)
if (!c) return null
const res = runSteps(getDef.value, def.value.id, challengeSteps(c))
if (res.pass && !project.value.solved.includes(c.id)) {
project.value.solved.push(c.id)
commit(false)
}
return res
}
function table(): TruthTable | { error: string } {
return truthTable(getDef.value, def.value.id)
}
// ── Project ───────────────────────────────────────────────────────
function replaceProject(p: Project) {
project.value = p
undoStack.length = 0
redoStack.length = 0
last = snap()
canUndo.value = false
canRedo.value = false
nav.value = []
selection.value = []
selectedWire.value = null
simRoot = ''
persist()
rebuild()
}
function newProject(examples: boolean) {
replaceProject(createProject({ examples }))
}
function loadExamples() {
const n = addExamples(project.value)
commit()
notify(n ? `Added ${n} example parts` : 'All examples are already here')
}
function exportJson() {
const blob = new Blob([JSON.stringify(project.value, null, 1)], { type: 'application/json' })
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = `logigate-${new Date().toISOString().slice(0, 10)}.json`
a.click()
URL.revokeObjectURL(a.href)
}
async function importJson(file: File) {
try {
replaceProject(parseProject(await file.text()))
notify(`Loaded ${file.name}`)
} catch (e) {
notify((e as Error).message, 'error')
}
}
function shape(node: CircuitNode) {
return shapeOf(node, getDef.value)
}
rebuild()
return {
project,
getDef,
def,
selection,
selectedWire,
placing,
nav,
views,
notice,
labelFocus,
showHelp,
notify,
commit,
undo,
redo,
canUndo,
canRedo,
sim,
tick,
status,
running,
hz,
cycles,
errors,
circuitStats,
val,
startLoop,
step,
rebuild,
open,
back,
addNode,
canPlace,
connect,
deleteSelected,
toggleInput,
press,
copy,
paste,
duplicate,
selectAll,
packageSelected,
createComponent,
removeComponent,
copyComponent,
beginChallenge,
checkChallenge,
table,
newProject,
loadExamples,
exportJson,
importJson,
shape,
}
}
let editor: ReturnType<typeof create> | undefined
export function useEditor() {
editor ??= create()
return editor
}