A logigate: NAND-only logic editor and simulator with components, challenges and examples

Draw circuits from NAND gates, package them as components and reuse them.
Event-driven simulation runs live while drawing. IEC/ANSI symbols, truth
tables, 17 challenges, example library up to a 4-bit counter. Deploys to
edgerealm like autismus-spektrum (logicate.blax.at).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-17 12:49:38 +02:00
commit 03a4d55834
38 changed files with 12109 additions and 0 deletions

19
.dockerignore Normal file
View File

@ -0,0 +1,19 @@
.git
.gitignore
.env
.env.*
node_modules
docker-data
.nuxt
.output
.nitro
.data
.cache
dist
_*
localhost.pem
localhost-key.pem
*.pem
*.key
*.map
*.log

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
[*]
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2
[*.yml]
indent_style = space
indent_size = 2
[*.xml]
indent_style = space
indent_size = 4
[*.gradle]
indent_style = space
indent_size = 4

2
.env.example Normal file
View File

@ -0,0 +1,2 @@
# Canonical origin, used for absolute links in meta tags.
NUXT_PUBLIC_SITE_URL=https://logicate.blax.at

35
.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# Nuxt build output
.nuxt
.output
.data
.nitro
.cache
dist
# Node
node_modules
*.log
*.tsbuildinfo
# Env (commit only the example)
.env
.env.*
!.env.example
# IDE
.vscode
.idea
*.swp
# OS
.DS_Store
# Throwaway artefacts
_*
# Docker volumes
docker-data/
# Playwright artefacts
test-results/
playwright-report/

13
Dockerfile.build Normal file
View File

@ -0,0 +1,13 @@
# Reusable build environment. The source is bind-mounted, not copied.
FROM node:current-slim
WORKDIR /app
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0
# Lets pnpm purge a stale bind-mounted node_modules without a TTY prompt.
ENV CI=true
RUN npm install -g --force corepack && corepack enable
CMD ["sh", "-c", "pnpm install --frozen-lockfile && pnpm run build && find .output -type f -name '*.map' -delete && find .output -type f \\( -name '*.js' -o -name '*.mjs' -o -name '*.css' \\) -exec sed -i -e '/^[[:space:]]*\\/\\/# sourceMappingURL=.*$/d' -e '/^[[:space:]]*\\/\\*# sourceMappingURL=.*\\*\\/[[:space:]]*$/d' {} +"]

12
Dockerfile.serve Normal file
View File

@ -0,0 +1,12 @@
# Lightweight server — .output is bind-mounted from the host.
FROM node:current-slim
WORKDIR /app
ENV HOST=0.0.0.0
ENV PORT=3000
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", ".output/server/index.mjs"]

41
README.md Normal file
View File

@ -0,0 +1,41 @@
# Logigate
Logic circuit editor and simulator at <https://logicate.blax.at>, in the spirit of the game "Turing Complete". NAND is the only gate. You draw circuits with it, package them as components, and reuse those in bigger circuits, up to a CPU. Everything runs live while you draw: green wires carry a 1, grey wires a 0.
Nuxt 4 (client-only, `ssr: false`), Tailwind CSS v4, Lucide icons via `@nuxt/icon`, Inter and JetBrains Mono self-hosted via `@nuxt/fonts`. No backend, no tracking: projects live in the browser's localStorage and can be exported as JSON.
## What it does
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, note.
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
- Select parts and press "Make component" to turn them into a new component; wires crossing the selection become pins.
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
- Truth table, NAND count, gate delay, and loop detection for the open circuit.
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
- Example library, all built from NAND: NOT, AND, OR, NOR, XOR, XNOR, Mux, Half/Full Adder, SR Latch, D Latch, D Flip-Flop, Register 4, Increment 4, Adder 4, Counter 4, and a counter demo with a hex display.
## How the simulation works
All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency:
- `compile.ts` flattens the component tree into a list of NAND gates over numbered nets. Chip boundaries and pins are aliases, merged with union-find. Net 0 is constant 0, net 1 constant 1.
- `sim.ts` is event-driven: a net change queues the gates that read it, and gates run in FIFO order on the newest values. NAND latches settle deterministically; a loop with an odd number of inversions never settles and the top bar shows "Oscillating".
- Gate outputs are keyed by their path ("chipNode/chipNode/nand"), so latch state survives editing.
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
The editor UI is in [app/components/editor/](app/components/editor/) with state in [app/composables/useEditor.ts](app/composables/useEditor.ts).
## Develop
```bash
pnpm install
pnpm dev # http://localhost:3000
pnpm test # engine tests (vitest)
pnpm typecheck
pnpm build # .output/
```
## Deploy
Same pattern as autismus-spektrum. On edgerealm the repo lives in `/mnt/HC_Volume_102040804/srv/logigate`; run `./deploy.sh` there. It pulls, builds in a one-shot container and recreates the `logigate` container. Host nginx terminates TLS with the `*.blax.at` wildcard cert and forwards to Traefik, which routes `logicate.blax.at` and `logigate.blax.at` by the labels in [docker-compose.yml](docker-compose.yml).

3
app/app.vue Normal file
View File

@ -0,0 +1,3 @@
<template>
<NuxtPage />
</template>

1147
app/assets/css/main.css Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,564 @@
<script setup lang="ts">
import { GRID as G, pinPos, routeWire, simplify, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, Wire } from '~/lib/logic/types'
const ed = useEditor()
const root = ref<HTMLDivElement>()
const size = reactive({ w: 800, h: 600 })
const def = ed.def
const view = computed(() => ed.views[def.value.id] ?? { x: 40, y: 40, zoom: 1 })
const nodeMap = computed(() => new Map(def.value.nodes.map(n => [n.id, n])))
const shapes = computed(() => new Map<string, Shape>(def.value.nodes.map(n => [n.id, ed.shape(n)])))
const selected = computed(() => new Set(ed.selection.value))
// ── Wires ───────────────────────────────────────────────────────────
interface Route {
wire: Wire
pts: Pt[]
d: string
src: string
}
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
const routes = computed<Route[]>(() => {
const out: Route[] = []
for (const w of def.value.wires) {
const fn = nodeMap.value.get(w.from.node)
const tn = nodeMap.value.get(w.to.node)
if (!fn || !tn) continue
const a = pinPos(fn, shapes.value.get(fn.id)!, w.from.pin, 'out')
const b = pinPos(tn, shapes.value.get(tn.id)!, w.to.pin, 'in')
if (!a || !b) continue
const pts = routeWire([a.x, a.y], [b.x, b.y], w.pts)
out.push({ wire: w, pts, d: toPath(pts), src: `${w.from.node}:${w.from.pin}` })
}
return out
})
/** Dots where a net branches, so crossings without a dot read as "not connected". */
const junctions = computed(() => {
const groups = new Map<string, Pt[][]>()
for (const r of routes.value) {
const g = groups.get(r.src)
if (g) g.push(r.pts)
else groups.set(r.src, [r.pts])
}
const dots: { x: number; y: number; src: string }[] = []
for (const [src, list] of groups) {
if (list.length < 2) continue
const candidates = new Map<string, Pt>()
for (const r of list) for (let i = 0; i < r.length - 1; i++) candidates.set(`${r[i]![0]},${r[i]![1]}`, r[i]!)
for (const [x, y] of candidates.values()) {
const dirs = new Set<string>()
for (const r of list) {
for (let i = 0; i < r.length - 1; i++) {
const [ax, ay] = r[i]!
const [bx, by] = r[i + 1]!
const onV = ax === bx && x === ax && y >= Math.min(ay, by) && y <= Math.max(ay, by)
const onH = ay === by && y === ay && x >= Math.min(ax, bx) && x <= Math.max(ax, bx)
if (!onV && !onH) continue
for (const [px, py] of [[ax, ay], [bx, by]] as Pt[]) {
if (px === x && py === y) continue
dirs.add(px < x ? 'L' : px > x ? 'R' : py < y ? 'U' : 'D')
}
}
}
if (dirs.size >= 3) dots.push({ x, y, src })
}
}
return dots
})
const srcVal = (src: string) => {
const [node, pin] = src.split(':')
return ed.val(node!, pin!)
}
// ── View ────────────────────────────────────────────────────────────
function bounds(nodes: CircuitNode[]) {
let x0 = Infinity
let y0 = Infinity
let x1 = -Infinity
let y1 = -Infinity
for (const n of nodes) {
const b = (shapes.value.get(n.id) ?? ed.shape(n)).body
x0 = Math.min(x0, n.x + b.x - (n.kind === 'input' || n.kind === 'button' ? 2 : 0))
y0 = Math.min(y0, n.y + b.y)
x1 = Math.max(x1, n.x + b.x + b.w + (n.kind === 'output' || n.kind === 'lamp' ? 2 : 0))
y1 = Math.max(y1, n.y + b.y + b.h)
}
return { x0, y0, x1, y1 }
}
function fit() {
const nodes = def.value.nodes
if (!nodes.length) {
ed.views[def.value.id] = { x: size.w / 2, y: size.h / 2, zoom: 1.25 }
return
}
const { x0, y0, x1, y1 } = bounds(nodes)
const pad = 2
const zoom = Math.min(2.2, Math.max(0.25, Math.min(size.w / ((x1 - x0 + 2 * pad) * G), size.h / ((y1 - y0 + 2 * pad) * G))))
ed.views[def.value.id] = {
zoom,
x: size.w / 2 - ((x0 + x1) / 2) * G * zoom,
y: size.h / 2 - ((y0 + y1) / 2) * G * zoom,
}
}
function zoomAt(factor: number, sx = size.w / 2, sy = size.h / 2) {
const v = view.value
const zoom = Math.min(4, Math.max(0.15, v.zoom * factor))
const k = zoom / v.zoom
ed.views[def.value.id] = { zoom, x: sx - (sx - v.x) * k, y: sy - (sy - v.y) * k }
}
function toWorld(e: { clientX: number; clientY: number }): Pt {
const r = root.value!.getBoundingClientRect()
const v = view.value
return [(e.clientX - r.left - v.x) / (G * v.zoom), (e.clientY - r.top - v.y) / (G * v.zoom)]
}
watch(
() => def.value.id,
id => {
if (!ed.views[id]) nextTick(fit)
},
)
let resize: ResizeObserver | undefined
onMounted(() => {
resize = new ResizeObserver(([entry]) => {
size.w = entry!.contentRect.width
size.h = entry!.contentRect.height
if (!ed.views[def.value.id]) fit()
})
resize.observe(root.value!)
window.addEventListener('keydown', onKey)
window.addEventListener('keyup', onKeyUp)
})
onBeforeUnmount(() => {
resize?.disconnect()
window.removeEventListener('keydown', onKey)
window.removeEventListener('keyup', onKeyUp)
})
// ── Placing ─────────────────────────────────────────────────────────
const cursor = ref<Pt | null>(null)
function originFor(p: { kind: CircuitNode['kind']; chip?: string }, at: Pt): Pt {
const b = ed.shape({ id: 'ghost', kind: p.kind, chip: p.chip, x: 0, y: 0 }).body
return [Math.round(at[0] - (b.x + b.w / 2)), Math.round(at[1] - (b.y + b.h / 2))]
}
const ghost = computed<CircuitNode | null>(() => {
const p = ed.placing.value
if (!p || !cursor.value) return null
const [x, y] = originFor(p, cursor.value)
return { id: 'ghost', kind: p.kind, chip: p.chip, x, y, label: p.kind === 'note' ? 'Note' : p.kind === 'input' ? '?' : undefined }
})
function onDrop(e: DragEvent) {
const raw = e.dataTransfer?.getData('application/x-logigate')
if (!raw) return
const p = JSON.parse(raw) as { kind: CircuitNode['kind']; chip?: string }
if (p.chip && !ed.canPlace(p.chip)) return ed.notify('A component cannot contain itself', 'error')
const [x, y] = originFor(p, toWorld(e))
ed.addNode(p, x, y)
}
// ── Pointer interaction ─────────────────────────────────────────────
type Drag =
| { kind: 'pan'; sx: number; sy: number; vx: number; vy: number }
| { kind: 'move'; start: Pt; orig: Map<string, Pt>; wires: Map<Wire, Pt[]>; moved: boolean; node: CircuitNode; toggle: boolean }
| { kind: 'wire'; node: string; pin: string; dir: 'in' | 'out'; cur: Pt }
| { kind: 'box'; start: Pt; cur: Pt; base: string[] }
| { kind: 'segment'; wire: Wire; index: number; axis: 0 | 1; base: Pt[]; start: number }
| { kind: 'press'; node: CircuitNode }
const drag = ref<Drag | null>(null)
const spaceDown = ref(false)
let lastClick = { id: '', t: 0 }
function onPointerDown(e: PointerEvent) {
const w = toWorld(e)
const v = view.value
if (e.button === 1 || e.button === 2 || (e.button === 0 && spaceDown.value)) {
drag.value = { kind: 'pan', sx: e.clientX, sy: e.clientY, vx: v.x, vy: v.y }
root.value!.setPointerCapture(e.pointerId)
return
}
if (e.button !== 0) return
root.value!.setPointerCapture(e.pointerId)
const placing = ed.placing.value
if (placing) {
if (placing.chip && !ed.canPlace(placing.chip)) {
ed.placing.value = null
return ed.notify('A component cannot contain itself', 'error')
}
const [x, y] = originFor(placing, w)
ed.addNode(placing, x, y)
if (!e.shiftKey && !placing.keep) ed.placing.value = null
return
}
const target = e.target as Element
const pinEl = target.closest('[data-pin]')
if (pinEl) {
drag.value = {
kind: 'wire',
node: pinEl.getAttribute('data-node')!,
pin: pinEl.getAttribute('data-pin')!,
dir: pinEl.getAttribute('data-dir') as 'in' | 'out',
cur: w,
}
return
}
const nodeEl = target.closest('[data-node]')
if (nodeEl) {
const id = nodeEl.getAttribute('data-node')!
const node = nodeMap.value.get(id)
if (!node) return
const multi = e.shiftKey || e.ctrlKey || e.metaKey
if (multi) {
ed.selection.value = selected.value.has(id) ? ed.selection.value.filter(s => s !== id) : [...ed.selection.value, id]
} else if (!selected.value.has(id)) {
ed.selection.value = [id]
}
ed.selectedWire.value = null
const now = performance.now()
if (lastClick.id === id && now - lastClick.t < 350) {
lastClick = { id: '', t: 0 }
onDoubleClick(node)
return
}
lastClick = { id, t: now }
if (node.kind === 'button') ed.press(node, true)
const ids = selected.value.has(id) ? ed.selection.value : [id]
const set = new Set(ids)
const orig = new Map<string, Pt>()
for (const sid of ids) {
const n = nodeMap.value.get(sid)
if (n) orig.set(sid, [n.x, n.y])
}
const wires = new Map<Wire, Pt[]>()
for (const wire of def.value.wires) {
if (wire.pts && set.has(wire.from.node) && set.has(wire.to.node)) wires.set(wire, wire.pts.map(p => [...p] as Pt))
}
drag.value = { kind: 'move', start: w, orig, wires, moved: false, node, toggle: node.kind === 'input' && !multi }
return
}
const wireEl = target.closest('[data-wire]')
if (wireEl) {
const wire = def.value.wires.find(x => x.id === wireEl.getAttribute('data-wire'))
if (!wire) return
ed.selectedWire.value = wire.id
ed.selection.value = []
const route = routes.value.find(r => r.wire === wire)
const index = Number(wireEl.getAttribute('data-seg'))
if (route && index >= 1 && index + 1 <= route.pts.length - 2) {
const [a, b] = [route.pts[index]!, route.pts[index + 1]!]
const axis = a[0] === b[0] ? 0 : 1
drag.value = { kind: 'segment', wire, index, axis, base: route.pts.map(p => [...p] as Pt), start: w[axis] }
}
return
}
if (!e.shiftKey) {
ed.selection.value = []
ed.selectedWire.value = null
}
drag.value = { kind: 'box', start: w, cur: w, base: [...ed.selection.value] }
}
function onPointerMove(e: PointerEvent) {
const w = toWorld(e)
cursor.value = w
const d = drag.value
if (!d) return
switch (d.kind) {
case 'pan':
ed.views[def.value.id] = { ...view.value, x: d.vx + e.clientX - d.sx, y: d.vy + e.clientY - d.sy }
break
case 'move': {
const dx = Math.round(w[0] - d.start[0])
const dy = Math.round(w[1] - d.start[1])
if (!d.moved && (dx || dy)) {
d.moved = true
if (d.node.kind === 'button') ed.press(d.node, false)
}
for (const [id, [x, y]] of d.orig) {
const n = nodeMap.value.get(id)
if (n) {
n.x = x + dx
n.y = y + dy
}
}
for (const [wire, pts] of d.wires) wire.pts = pts.map(([x, y]) => [x + dx, y + dy])
break
}
case 'wire':
d.cur = w
break
case 'box': {
d.cur = w
const x0 = Math.min(d.start[0], w[0])
const x1 = Math.max(d.start[0], w[0])
const y0 = Math.min(d.start[1], w[1])
const y1 = Math.max(d.start[1], w[1])
const hits = def.value.nodes
.filter(n => {
const b = shapes.value.get(n.id)!.body
return n.x + b.x < x1 && n.x + b.x + b.w > x0 && n.y + b.y < y1 && n.y + b.y + b.h > y0
})
.map(n => n.id)
ed.selection.value = [...new Set([...d.base, ...hits])]
break
}
case 'segment': {
const delta = Math.round(w[d.axis] - d.start)
const pts = d.base.map(p => [...p] as Pt)
pts[d.index]![d.axis] += delta
pts[d.index + 1]![d.axis] += delta
d.wire.pts = simplify(pts).slice(1, -1)
break
}
}
}
function nearestPin(at: Pt, dir: 'in' | 'out'): { node: string; pin: string } | null {
let best: { node: string; pin: string } | null = null
let bestD = 0.8 * 0.8
for (const n of def.value.nodes) {
const s = shapes.value.get(n.id)!
for (const p of dir === 'in' ? s.inputs : s.outputs) {
const dx = n.x + p.dx - at[0]
const dy = n.y + p.dy - at[1]
const dd = dx * dx + dy * dy
if (dd < bestD) {
bestD = dd
best = { node: n.id, pin: p.key }
}
}
}
return best
}
function onPointerUp() {
const d = drag.value
drag.value = null
if (!d) return
switch (d.kind) {
case 'move':
if (d.node.kind === 'button') ed.press(d.node, false)
if (d.moved) ed.commit(false)
else if (d.toggle) ed.toggleInput(d.node)
break
case 'wire': {
const target = nearestPin(d.cur, d.dir === 'out' ? 'in' : 'out')
if (!target) break
const here = { node: d.node, pin: d.pin }
if (d.dir === 'out') ed.connect(here, target)
else ed.connect(target, here)
break
}
case 'segment':
ed.commit(false)
break
}
}
function onDoubleClick(node: CircuitNode) {
if (node.kind === 'chip' && node.chip) ed.open(node.chip)
else if (['input', 'output', 'lamp', 'button', 'note'].includes(node.kind)) {
ed.selection.value = [node.id]
ed.labelFocus.value++
}
}
function onWheel(e: WheelEvent) {
const r = root.value!.getBoundingClientRect()
const k = e.ctrlKey ? 0.01 : 0.0015
zoomAt(Math.exp(-e.deltaY * k), e.clientX - r.left, e.clientY - r.top)
}
// ── Keyboard ────────────────────────────────────────────────────────
const QUICK: Record<string, CircuitNode['kind']> = { n: 'nand', i: 'input', o: 'output', l: 'lamp', c: 'clock', b: 'button', h: 'hex', t: 'note' }
function onKey(e: KeyboardEvent) {
const el = e.target as HTMLElement
if (el.closest('input, textarea, select, [contenteditable]')) return
const mod = e.ctrlKey || e.metaKey
const key = e.key.toLowerCase()
if (mod && key === 'z') {
e.preventDefault()
if (e.shiftKey) ed.redo()
else ed.undo()
} else if (mod && key === 'y') {
e.preventDefault()
ed.redo()
} else if (mod && key === 'c') ed.copy()
else if (mod && key === 'v') ed.paste()
else if (mod && key === 'd') {
e.preventDefault()
ed.duplicate()
} else if (mod && key === 'a') {
e.preventDefault()
ed.selectAll()
} else if (e.key === 'Delete' || e.key === 'Backspace') {
e.preventDefault()
ed.deleteSelected()
} else if (e.key === 'Escape') {
ed.placing.value = null
ed.selection.value = []
ed.selectedWire.value = null
ed.showHelp.value = false
} else if (e.key === ' ') {
e.preventDefault()
spaceDown.value = true
} else if (e.key === 'Enter' && ed.selection.value.length === 1) {
const n = nodeMap.value.get(ed.selection.value[0]!)
if (n?.kind === 'chip' && n.chip) ed.open(n.chip)
} else if (!mod && !e.altKey && key === 'f') fit()
else if (!mod && !e.altKey && e.key === '?') ed.showHelp.value = !ed.showHelp.value
else if (!mod && !e.altKey && QUICK[key]) ed.placing.value = { kind: QUICK[key]! }
}
function onKeyUp(e: KeyboardEvent) {
if (e.key === ' ') spaceDown.value = false
}
// ── Overlays ────────────────────────────────────────────────────────
const tempWire = computed(() => {
const d = drag.value
if (d?.kind !== 'wire') return null
const n = nodeMap.value.get(d.node)
if (!n) return null
const p = pinPos(n, shapes.value.get(n.id)!, d.pin, d.dir)!
const target = nearestPin(d.cur, d.dir === 'out' ? 'in' : 'out')
let end: Pt = [Math.round(d.cur[0]), Math.round(d.cur[1])]
if (target) {
const tn = nodeMap.value.get(target.node)!
const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, d.dir === 'out' ? 'in' : 'out')!
end = [tp.x, tp.y]
}
const pts = d.dir === 'out' ? routeWire([p.x, p.y], end) : routeWire(end, [p.x, p.y])
return { d: toPath(pts), snapped: !!target }
})
const boxRect = computed(() => {
const d = drag.value
if (d?.kind !== 'box') return null
return {
x: Math.min(d.start[0], d.cur[0]) * G,
y: Math.min(d.start[1], d.cur[1]) * G,
width: Math.abs(d.cur[0] - d.start[0]) * G,
height: Math.abs(d.cur[1] - d.start[1]) * G,
}
})
const gridSize = computed(() => G * view.value.zoom)
const flow = computed(() => ed.project.value.settings.flow)
const cursorStyle = computed(() => {
if (drag.value?.kind === 'pan') return 'grabbing'
if (spaceDown.value) return 'grab'
if (ed.placing.value) return 'copy'
return 'default'
})
defineExpose({ fit, zoomAt })
</script>
<template>
<div
ref="root"
class="canvas"
:style="{ cursor: cursorStyle }"
@pointerdown="onPointerDown"
@pointermove="onPointerMove"
@pointerup="onPointerUp"
@pointercancel="onPointerUp"
@pointerleave="cursor = null"
@wheel.prevent="onWheel"
@contextmenu.prevent
@dragover.prevent
@drop.prevent="onDrop"
>
<svg width="100%" height="100%">
<defs>
<pattern id="grid-dots" :width="gridSize" :height="gridSize" patternUnits="userSpaceOnUse" :x="view.x" :y="view.y">
<circle :cx="0.75" :cy="0.75" :r="view.zoom > 0.5 ? 0.9 : 0.6" class="grid-dot" />
</pattern>
<pattern id="grid-major" :width="gridSize * 8" :height="gridSize * 8" patternUnits="userSpaceOnUse" :x="view.x" :y="view.y">
<circle :cx="0.75" :cy="0.75" r="1.4" class="grid-major" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid-dots)" />
<rect width="100%" height="100%" fill="url(#grid-major)" />
<g :transform="`translate(${view.x} ${view.y}) scale(${view.zoom})`">
<g class="wires">
<g
v-for="r in routes"
:key="r.wire.id"
class="wire"
:class="{ on: srcVal(r.src) === 1, selected: ed.selectedWire.value === r.wire.id }"
>
<path :d="r.d" class="wire-line" />
<path v-if="flow && srcVal(r.src) === 1" :d="r.d" class="wire-flow" />
<path
v-for="(p, i) in r.pts.slice(0, -1)"
:key="i"
:d="`M${p[0] * G} ${p[1] * G}L${r.pts[i + 1]![0] * G} ${r.pts[i + 1]![1] * G}`"
class="wire-hit"
:class="{ draggable: i >= 1 && i + 1 <= r.pts.length - 2, vertical: p[0] === r.pts[i + 1]![0] }"
:data-wire="r.wire.id"
:data-seg="i"
/>
</g>
<circle
v-for="(j, i) in junctions"
:key="`j${i}`"
:cx="j.x * G"
:cy="j.y * G"
r="3.2"
class="junction"
:class="{ on: srcVal(j.src) === 1 }"
/>
</g>
<EditorNodeView
v-for="n in def.nodes"
:key="n.id"
:node="n"
:shape="shapes.get(n.id)!"
:selected="selected.has(n.id)"
/>
<path v-if="tempWire" :d="tempWire.d" class="temp-wire" :class="{ snapped: tempWire.snapped }" />
<EditorNodeView v-if="ghost" :node="ghost" :shape="ed.shape(ghost)" :selected="false" ghost />
<rect v-if="boxRect" v-bind="boxRect" class="box-select" />
</g>
</svg>
<div v-if="!def.nodes.length" class="empty-hint">
<p class="font-semibold">Empty circuit</p>
<p>Drag parts in from the left, or press <kbd>N</kbd> for a NAND gate.</p>
</div>
<div class="zoom-controls" @pointerdown.stop>
<button title="Zoom out" @click="zoomAt(1 / 1.25)"><Icon name="lucide:minus" /></button>
<span class="tabular-nums">{{ Math.round(view.zoom * 100) }}%</span>
<button title="Zoom in" @click="zoomAt(1.25)"><Icon name="lucide:plus" /></button>
<button title="Fit to screen (F)" @click="fit"><Icon name="lucide:scan" /></button>
</div>
</div>
</template>

View File

@ -0,0 +1,64 @@
<script setup lang="ts">
const ed = useEditor()
const SHORTCUTS: [string, string][] = [
['Click switch', 'Flip an input between 0 and 1'],
['Drag from a pin', 'Draw a wire to another pin'],
['Drag a wire segment', 'Reroute the wire'],
['Double-click a component', 'Open it and see inside'],
['Drag on empty space', 'Select several parts'],
['Right or middle drag, Space + drag', 'Move the view'],
['Mouse wheel', 'Zoom'],
['N, I, O, L, B, C, H, T', 'Place NAND, input, output, lamp, button, clock, hex display, note'],
['Shift + click on canvas', 'Keep placing the same part'],
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate'],
['Delete', 'Remove the selection'],
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
['F', 'Fit the circuit to the screen'],
['Enter', 'Open the selected component'],
]
function close() {
ed.showHelp.value = false
try {
localStorage.setItem('logigate:help-seen', '1')
} catch {}
}
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal" role="dialog" aria-labelledby="help-title">
<div class="flex items-start justify-between gap-4">
<h2 id="help-title">From one NAND gate to a computer</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<ol class="steps">
<li>
<strong>NAND is the only gate.</strong> Its output is 0 only when both inputs are 1. Everything else (NOT, AND, OR, adders, memory) can be built from it.
</li>
<li>
<strong>Every circuit is a component.</strong> Inputs and outputs you place inside a circuit become its pins. Place it in another circuit and it shows up as one block; double-click to look inside.
</li>
<li>
<strong>It runs while you draw.</strong> Green wires carry a 1, grey wires a 0. Flip switches, press buttons, or start the clock in the top bar.
</li>
<li>
<strong>Try the challenges</strong> on the left, or open the examples (NOT up to a 4-bit counter) to see how each step is made of the previous one.
</li>
<li>
<strong>Select parts and press "Make component"</strong> on the right to turn a piece of your drawing into a reusable block.
</li>
</ol>
<h3>Controls</h3>
<dl class="shortcuts">
<template v-for="[k, v] in SHORTCUTS" :key="k">
<dt>{{ k }}</dt>
<dd>{{ v }}</dd>
</template>
</dl>
<p class="hint">Your work is saved in this browser. Use Project → Export to keep a copy or move it to another computer.</p>
<button class="btn btn-primary mt-4" @click="close">Start building</button>
</div>
</div>
</template>

View File

@ -0,0 +1,247 @@
<script setup lang="ts">
import type { TestResult, TruthTable } from '~/lib/logic/analyze'
import { stats } from '~/lib/logic/analyze'
import { CHALLENGES } from '~/lib/logic/challenges'
import { compile } from '~/lib/logic/compile'
import { chipPins } from '~/lib/logic/geometry'
import { usages } from '~/lib/logic/ops'
import type { SymbolKind } from '~/lib/logic/types'
const ed = useEditor()
const def = ed.def
const KIND_NAMES: Record<string, string> = {
nand: 'NAND gate',
input: 'Input',
output: 'Output',
lamp: 'Lamp',
button: 'Push button',
clock: 'Clock',
high: 'Constant 1',
low: 'Ground (0)',
hex: 'Hex display',
note: 'Note',
}
const SYMBOLS: { value: SymbolKind; label: string }[] = [
{ value: 'box', label: 'Box with name' },
{ value: 'and', label: 'AND gate' },
{ value: 'or', label: 'OR gate' },
{ value: 'xor', label: 'XOR gate' },
{ value: 'not', label: 'NOT gate' },
{ value: 'buf', label: 'Buffer' },
{ value: 'nand', label: 'NAND gate' },
{ value: 'nor', label: 'NOR gate' },
{ value: 'xnor', label: 'XNOR gate' },
]
const single = computed(() => (ed.selection.value.length === 1 ? def.value.nodes.find(n => n.id === ed.selection.value[0]) : undefined))
const wire = computed(() => def.value.wires.find(w => w.id === ed.selectedWire.value))
const chipDef = computed(() => (single.value?.chip ? ed.getDef.value(single.value.chip) : undefined))
const chipStats = computed(() => (chipDef.value ? stats(compile(ed.getDef.value, chipDef.value.id)) : null))
const hasLabel = computed(() => !!single.value && ['input', 'output', 'lamp', 'button', 'note'].includes(single.value.kind))
const labelInput = ref<HTMLInputElement | HTMLTextAreaElement>()
const nameInput = ref<HTMLInputElement>()
watch(
() => ed.labelFocus.value,
() =>
nextTick(() => {
const el = labelInput.value ?? nameInput.value
el?.focus()
el?.select()
}),
)
const pins = computed(() => chipPins(def.value))
const users = computed(() => usages(ed.project.value, def.value.id))
const groupNames = computed(() => [...new Set(ed.project.value.components.map(d => d.group).filter(Boolean))])
const challenge = computed(() => CHALLENGES.find(c => c.id === def.value.challenge))
const solved = computed(() => !!challenge.value && ed.project.value.solved.includes(challenge.value.id))
const packName = ref('')
function pack() {
ed.packageSelected(packName.value || 'Part')
packName.value = ''
}
const showTable = ref(false)
const table = ref<TruthTable | { error: string } | null>(null)
function refreshTable() {
table.value = showTable.value ? ed.table() : null
}
watch([showTable, () => ed.sim.value, () => def.value.id], refreshTable)
const check = ref<TestResult | null>(null)
watch(() => def.value.id, () => (check.value = null))
watch(() => ed.sim.value, () => (check.value = null))
function runCheck() {
check.value = ed.checkChallenge()
}
const resetRoute = () => {
if (!wire.value) return
delete wire.value.pts
ed.commit(false)
}
const confirmDelete = ref(false)
watch(() => def.value.id, () => (confirmDelete.value = false))
</script>
<template>
<aside class="inspector">
<div class="scroll">
<!-- Selection -->
<section v-if="single">
<h3>{{ single.kind === 'chip' ? chipDef?.name ?? 'Missing component' : KIND_NAMES[single.kind] }}</h3>
<label v-if="hasLabel" class="field">
<span>{{ single.kind === 'note' ? 'Text' : 'Label' }}</span>
<textarea
v-if="single.kind === 'note'"
ref="labelInput"
v-model="single.label"
rows="3"
@change="ed.commit(false)"
/>
<input v-else ref="labelInput" v-model="single.label" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
</label>
<p v-if="single.kind === 'input'" class="hint">
Click the switch on the canvas to flip it. When this circuit is used as a component, this becomes one of its input pins (pins are ordered top to bottom).
</p>
<p v-else-if="single.kind === 'output'" class="hint">
When this circuit is used as a component, this becomes one of its output pins.
</p>
<p v-else-if="single.kind === 'nand'" class="hint">
Output is 0 only when both inputs are 1. Every other part can be built from this one.
</p>
<template v-else-if="single.kind === 'chip' && chipDef">
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
<dl v-if="chipStats" class="stats">
<dt>NAND gates</dt>
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
</dl>
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
</template>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
<section v-else-if="ed.selection.value.length > 1">
<h3>{{ ed.selection.value.length }} parts selected</h3>
<p class="hint">Turn them into a reusable component. Wires that cross the selection border become its pins.</p>
<label class="field">
<span>Component name</span>
<input v-model="packName" placeholder="e.g. Half Adder" @keydown.enter="pack" />
</label>
<button class="btn btn-primary w-full" @click="pack"><Icon name="lucide:package" class="size-4" /> Make component</button>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
<section v-else-if="wire">
<h3>Wire</h3>
<p class="hint">Drag a middle segment to reroute it.</p>
<button v-if="wire.pts" class="btn w-full" @click="resetRoute"><Icon name="lucide:undo-2" class="size-4" /> Automatic route</button>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
<!-- Challenge -->
<section v-if="challenge" class="challenge" :class="{ solved }">
<h3>
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
Challenge: {{ challenge.name }}
</h3>
<p>{{ challenge.goal }}</p>
<p class="pins">Pins: {{ challenge.inputs.join(', ') }} → {{ challenge.outputs.join(', ') }}</p>
<button class="btn btn-primary w-full" @click="runCheck"><Icon name="lucide:play" class="size-4" /> Check</button>
<p v-if="check" class="result" :class="check.pass ? 'pass' : 'fail'">
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
{{ check.message }}
</p>
</section>
<!-- Circuit -->
<section>
<h3>This circuit</h3>
<label class="field">
<span>Name</span>
<input ref="nameInput" v-model="def.name" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
</label>
<label class="field">
<span>Description</span>
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
</label>
<div class="grid grid-cols-2 gap-2">
<label class="field">
<span>Drawn as</span>
<select v-model="def.symbol" @change="ed.commit(false)">
<option v-for="s in SYMBOLS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select>
</label>
<label class="field">
<span>Group</span>
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
<datalist id="groups">
<option v-for="g in groupNames" :key="g" :value="g" />
</datalist>
</label>
</div>
<dl class="stats">
<dt>Pins</dt>
<dd>{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</dd>
<dt>NAND gates</dt>
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
</dl>
<p v-for="err in ed.errors.value" :key="err" class="result fail">
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
</p>
<p v-if="users.length" class="hint">
Used in
<template v-for="(u, i) in users" :key="u.id">
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
</template>
</p>
</section>
<section>
<button class="section-toggle" @click="showTable = !showTable">
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
Truth table
</button>
<template v-if="showTable && table">
<p v-if="'error' in table" class="hint">{{ table.error }}</p>
<template v-else>
<p v-if="ed.circuitStats.value.sequential" class="hint">This circuit stores state, so the table depends on the order the rows are tried in.</p>
<div class="truth">
<table>
<thead>
<tr>
<th v-for="l in table.inputs" :key="`i${l}`">{{ l }}</th>
<th class="sep" />
<th v-for="l in table.outputs" :key="`o${l}`" class="out">{{ l }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(r, i) in table.rows" :key="i" :class="{ unstable: !r.settled }">
<td v-for="(v, k) in r.ins" :key="`i${k}`" :class="{ one: v }">{{ v }}</td>
<td class="sep" />
<td v-for="(v, k) in r.outs" :key="`o${k}`" class="out" :class="{ one: v }">{{ r.settled ? v : '~' }}</td>
</tr>
</tbody>
</table>
</div>
</template>
</template>
</section>
<section class="actions">
<button class="btn btn-ghost" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
<button v-if="!confirmDelete" class="btn btn-ghost" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
<button v-else class="btn btn-danger" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
</section>
</div>
</aside>
</template>

View File

@ -0,0 +1,140 @@
<script setup lang="ts">
import { gateDrawing, sevenSegment } from '~/lib/draw'
import { GRID as G, noteLines, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode } from '~/lib/logic/types'
const props = defineProps<{
node: CircuitNode
shape: Shape
selected: boolean
ghost?: boolean
}>()
const ed = useEditor()
const style = computed(() => ed.project.value.settings.symbols)
const gate = computed(() => (props.shape.gate ? gateDrawing(props.shape, style.value) : null))
const chipDef = computed(() => (props.node.chip ? ed.getDef.value(props.node.chip) : undefined))
const b = computed(() => props.shape.body)
const v = (pin: string) => (props.ghost ? 0 : ed.val(props.node.id, pin))
const hexValue = computed(() => [0, 1, 2, 3].reduce((n, i) => n + (v(`b${i}`) << i), 0))
const segments = computed(() => sevenSegment(hexValue.value))
const lit = computed(() => v(props.node.kind === 'input' || props.node.kind === 'button' || props.node.kind === 'clock' ? 'q' : 'a') === 1)
const title = computed(() => {
if (props.node.kind === 'chip') return chipDef.value ? `${chipDef.value.name}${chipDef.value.description ? `: ${chipDef.value.description}` : ''}\nDouble-click to open` : 'Missing component'
return undefined
})
</script>
<template>
<g
:transform="`translate(${node.x * G} ${node.y * G})`"
:data-node="node.id"
class="node"
:class="{ selected, ghost, [`kind-${node.kind}`]: true }"
>
<title v-if="title">{{ title }}</title>
<!-- Logic gate symbol (NAND, or a component drawn as a gate) -->
<template v-if="gate">
<path :d="gate.stubs" class="stub" />
<path :d="gate.body" class="body" :class="{ prim: node.kind === 'nand' }" />
<path v-if="gate.extra" :d="gate.extra" class="stroke-only" />
<circle v-if="gate.bubble" v-bind="gate.bubble" class="body" />
<text v-if="gate.label" :x="gate.label.x" :y="gate.label.y" class="gate-label" text-anchor="middle">{{ gate.label.text }}</text>
</template>
<!-- Component box -->
<template v-else-if="node.kind === 'chip'">
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
<text :x="(b.w * G) / 2" :y="(b.y + b.h / 2) * G + 4" text-anchor="middle" class="chip-name">{{ chipDef?.name ?? 'Missing' }}</text>
<text v-for="p in shape.inputs" :key="p.key" :x="5" :y="p.dy * G + 3.5" class="pin-label">{{ p.label }}</text>
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 5" :y="p.dy * G + 3.5" text-anchor="end" class="pin-label">{{ p.label }}</text>
</template>
<!-- Switch (input pin) -->
<template v-else-if="node.kind === 'input'">
<text :x="-6" :y="4" text-anchor="end" class="io-label">{{ node.label }}</text>
<rect x="0" :y="-0.6 * G" :width="2 * G" :height="1.2 * G" :rx="0.6 * G" class="switch" :class="{ on: lit }" />
<circle :cx="lit ? 1.4 * G : 0.6 * G" cy="0" :r="0.42 * G" class="knob" />
</template>
<!-- Output pin -->
<template v-else-if="node.kind === 'output'">
<path :d="`M0 0H${0.4 * G}`" class="stub" />
<path :d="`M${0.4 * G} ${-0.6 * G}H${1.5 * G}L${2 * G} 0L${1.5 * G} ${0.6 * G}H${0.4 * G}Z`" class="terminal" :class="{ on: lit }" />
<text :x="2 * G + 6" :y="4" class="io-label">{{ node.label }}</text>
</template>
<!-- Lamp: IEC symbol, circle with a cross -->
<template v-else-if="node.kind === 'lamp'">
<path :d="`M0 0H${0.35 * G}`" class="stub" />
<circle :cx="G" cy="0" :r="0.65 * G" class="lamp" :class="{ on: lit }" />
<path :d="`M${G - 0.46 * G} ${-0.46 * G}L${G + 0.46 * G} ${0.46 * G}M${G + 0.46 * G} ${-0.46 * G}L${G - 0.46 * G} ${0.46 * G}`" class="lamp-cross" :class="{ on: lit }" />
<text v-if="node.label" :x="2 * G + 4" :y="4" class="io-label">{{ node.label }}</text>
</template>
<!-- Constant 1 -->
<template v-else-if="node.kind === 'high'">
<rect x="0" :y="-0.6 * G" :width="1.5 * G" :height="1.2 * G" rx="2" class="body" />
<text :x="0.75 * G" y="4" text-anchor="middle" class="const on">1</text>
<path :d="`M${1.5 * G} 0H${2 * G}`" class="stub" />
</template>
<!-- Constant 0: ground symbol -->
<template v-else-if="node.kind === 'low'">
<path :d="`M${2 * G} 0H${1.1 * G}M${1.1 * G} ${-0.6 * G}V${0.6 * G}M${0.75 * G} ${-0.4 * G}V${0.4 * G}M${0.4 * G} ${-0.2 * G}V${0.2 * G}`" class="ground" />
<rect x="0" :y="-0.7 * G" :width="2 * G" :height="1.4 * G" fill="transparent" />
</template>
<!-- Clock -->
<template v-else-if="node.kind === 'clock'">
<rect x="0" :y="-0.7 * G" :width="2.5 * G" :height="1.4 * G" rx="2" class="body" />
<path :d="`M${0.35 * G} ${0.35 * G}H${0.8 * G}V${-0.35 * G}H${1.3 * G}V${0.35 * G}H${1.8 * G}V${-0.35 * G}H${2.15 * G}`" class="wave" :class="{ on: lit }" />
<path :d="`M${2.5 * G} 0H${3 * G}`" class="stub" />
</template>
<!-- Push button -->
<template v-else-if="node.kind === 'button'">
<text v-if="node.label" :x="-6" :y="4" text-anchor="end" class="io-label">{{ node.label }}</text>
<rect x="0" :y="-0.7 * G" :width="1.6 * G" :height="1.4 * G" rx="3" class="body" />
<circle :cx="0.8 * G" cy="0" :r="0.45 * G" class="button" :class="{ on: lit }" />
<path :d="`M${1.6 * G} 0H${2 * G}`" class="stub" />
</template>
<!-- Hex display -->
<template v-else-if="node.kind === 'hex'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body display" />
<path v-for="(s, i) in segments" :key="i" :d="s.d" class="seg" :class="{ on: s.on }" />
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
</template>
<!-- Note -->
<template v-else-if="node.kind === 'note'">
<rect :x="-4" :y="b.y * G" :width="b.w * G + 8" :height="b.h * G" rx="3" class="note-bg" />
<text v-for="(line, i) in noteLines(node)" :key="i" x="0" :y="i * G + 4" class="note">{{ line }}</text>
</template>
<rect
v-if="selected"
:x="b.x * G - 4"
:y="b.y * G - 4"
:width="b.w * G + 8"
:height="b.h * G + 8"
rx="5"
class="sel-outline"
/>
<template v-if="!ghost">
<g v-for="p in shape.inputs" :key="`i-${p.key}`">
<circle :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="in" />
<circle :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
</g>
<g v-for="p in shape.outputs" :key="`o-${p.key}`">
<circle :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="out" />
<circle :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
</g>
</template>
</g>
</template>

View File

@ -0,0 +1,140 @@
<script setup lang="ts">
import { CHALLENGES } from '~/lib/logic/challenges'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
const ed = useEditor()
const tab = ref<'parts' | 'challenges'>('parts')
const query = ref('')
const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint: string }[] = [
{ kind: 'nand', name: 'NAND', icon: 'lucide:square-function', key: 'N', hint: 'The one logic gate. Output is 0 only when both inputs are 1.' },
{ kind: 'input', name: 'Input', icon: 'lucide:toggle-left', key: 'I', hint: 'A switch. Inside a component it becomes an input pin.' },
{ kind: 'output', name: 'Output', icon: 'lucide:log-out', key: 'O', hint: 'Shows a value. Inside a component it becomes an output pin.' },
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.' },
{ kind: 'button', name: 'Push button', icon: 'lucide:circle-dot', key: 'B', hint: '1 while held down.' },
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.' },
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.' },
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.' },
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F.' },
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
]
const GROUP_ORDER = ['', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Demos']
const groups = computed(() => {
const q = query.value.trim().toLowerCase()
const map = new Map<string, ComponentDef[]>()
for (const d of ed.project.value.components) {
if (q && !d.name.toLowerCase().includes(q)) continue
const g = d.group?.trim() ?? ''
if (!map.has(g)) map.set(g, [])
map.get(g)!.push(d)
}
const rank = (g: string) => (GROUP_ORDER.includes(g) ? GROUP_ORDER.indexOf(g) : GROUP_ORDER.length)
return [...map.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([name, defs]) => ({ name: name || 'My components', defs }))
})
function pick(kind: NodeKind, chip?: string) {
if (chip && !ed.canPlace(chip)) return
ed.placing.value = { kind, chip }
}
function onDragStart(e: DragEvent, kind: NodeKind, chip?: string) {
if (chip && !ed.canPlace(chip)) {
e.preventDefault()
return
}
e.dataTransfer?.setData('application/x-logigate', JSON.stringify({ kind, chip }))
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'copy'
}
const solved = computed(() => new Set(ed.project.value.solved))
const started = computed(() => new Map(ed.project.value.components.filter(d => d.challenge).map(d => [d.challenge!, d])))
</script>
<template>
<aside class="palette">
<div class="tabs">
<button :class="{ active: tab === 'parts' }" @click="tab = 'parts'">Parts</button>
<button :class="{ active: tab === 'challenges' }" @click="tab = 'challenges'">
Challenges
<span class="count">{{ solved.size }}/{{ CHALLENGES.length }}</span>
</button>
</div>
<div v-if="tab === 'parts'" class="scroll">
<h3>Basics</h3>
<ul class="items">
<li v-for="item in BASICS" :key="item.kind">
<button
class="item"
:class="{ active: ed.placing.value?.kind === item.kind && !ed.placing.value?.chip }"
:title="item.hint"
draggable="true"
@click="pick(item.kind)"
@dragstart="onDragStart($event, item.kind)"
>
<span v-if="item.kind === 'nand'" class="nand-badge">&amp;</span>
<Icon v-else :name="item.icon" class="size-4 shrink-0 text-(--muted)" />
<span class="grow truncate">{{ item.name }}</span>
<kbd v-if="item.key">{{ item.key }}</kbd>
</button>
</li>
</ul>
<div class="search">
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
<input v-model="query" placeholder="Find component" />
</div>
<template v-for="g in groups" :key="g.name">
<h3>{{ g.name }}</h3>
<ul class="items">
<li v-for="d in g.defs" :key="d.id" class="comp-row">
<button
class="item"
:class="{ active: ed.placing.value?.chip === d.id, current: d.id === ed.def.value.id, blocked: !ed.canPlace(d.id) }"
:title="d.id === ed.def.value.id ? 'You are editing this one' : !ed.canPlace(d.id) ? 'Contains the circuit you are editing' : d.description || 'Click, then click on the canvas to place'"
:draggable="ed.canPlace(d.id)"
@click="pick('chip', d.id)"
@dragstart="onDragStart($event, 'chip', d.id)"
>
<Icon :name="d.challenge && solved.has(d.challenge) ? 'lucide:badge-check' : 'lucide:box'" class="size-4 shrink-0" :class="d.challenge && solved.has(d.challenge) ? 'text-(--on)' : 'text-(--muted)'" />
<span class="grow truncate">{{ d.name }}</span>
<span v-if="d.id === ed.def.value.id" class="editing">editing</span>
</button>
<button v-if="d.id !== ed.def.value.id" class="open" title="Open and edit" @click="ed.open(d.id)">
<Icon name="lucide:pencil" class="size-3.5" />
</button>
</li>
</ul>
</template>
<div class="px-3 pt-2 pb-4">
<button class="btn w-full" @click="ed.createComponent()">
<Icon name="lucide:plus" class="size-4" /> New component
</button>
</div>
</div>
<div v-else class="scroll">
<p class="intro">
Build each part from NAND and the parts you already made. Start a challenge, wire it up, then press
<strong>Check</strong> on the right.
</p>
<ul class="challenges">
<li v-for="c in CHALLENGES" :key="c.id" :class="{ solved: solved.has(c.id) }">
<div class="flex items-center gap-2">
<Icon :name="solved.has(c.id) ? 'lucide:circle-check' : 'lucide:circle'" class="size-4 shrink-0" :class="solved.has(c.id) ? 'text-(--on)' : 'text-(--muted)'" />
<span class="grow font-medium">{{ c.name }}</span>
<button class="btn-sm" @click="ed.beginChallenge(c)">{{ started.has(c.id) ? 'Open' : 'Start' }}</button>
</div>
<p>{{ c.goal }}</p>
<p class="pins">{{ c.inputs.join(', ') }} → {{ c.outputs.join(', ') }}</p>
</li>
</ul>
</div>
</aside>
</template>

View File

@ -0,0 +1,122 @@
<script setup lang="ts">
const ed = useEditor()
const menu = ref(false)
const fileInput = ref<HTMLInputElement>()
const confirmNew = ref<null | 'empty' | 'examples'>(null)
const SPEEDS = [
{ value: 0.5, label: '0.5 Hz' },
{ value: 1, label: '1 Hz' },
{ value: 2, label: '2 Hz' },
{ value: 5, label: '5 Hz' },
{ value: 10, label: '10 Hz' },
{ value: 30, label: '30 Hz' },
{ value: 0, label: 'Max' },
]
const hasClock = computed(() => (ed.sim.value?.nl.clocks.length ?? 0) > 0)
const statusText = computed(() => ({ stable: 'Stable', busy: 'Settling', oscillating: 'Oscillating' })[ed.status.value])
const backName = computed(() => {
const id = ed.nav.value.at(-1)
return id ? ed.getDef.value(id)?.name : undefined
})
function onFile(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (file) ed.importJson(file)
;(e.target as HTMLInputElement).value = ''
menu.value = false
}
function doNew() {
if (confirmNew.value) ed.newProject(confirmNew.value === 'examples')
confirmNew.value = null
menu.value = false
}
</script>
<template>
<header class="toolbar">
<div class="flex min-w-0 items-center gap-2">
<div class="brand">
<svg viewBox="0 0 32 32" class="size-6" aria-hidden="true">
<path d="M6 7h10a9 9 0 0 1 0 18H6Z" fill="none" stroke="currentColor" stroke-width="2.5" />
<circle cx="27" cy="16" r="2.6" fill="none" stroke="currentColor" stroke-width="2.2" />
</svg>
<span>Logigate</span>
</div>
<button v-if="backName" class="tb-btn" :title="`Back to ${backName}`" @click="ed.back()">
<Icon name="lucide:arrow-left" class="size-4" />
<span class="hidden truncate lg:inline">{{ backName }}</span>
</button>
<label class="circuit-select" title="Circuit you are editing">
<Icon name="lucide:cpu" class="size-4 shrink-0 text-(--muted)" />
<select :value="ed.def.value.id" @change="ed.open(($event.target as HTMLSelectElement).value)">
<option v-for="d in ed.project.value.components" :key="d.id" :value="d.id">{{ d.name }}</option>
</select>
</label>
</div>
<div class="flex items-center gap-1.5">
<button
class="tb-btn"
:class="{ active: ed.running.value }"
:title="ed.running.value ? 'Pause the clock' : 'Run the clock'"
:disabled="!hasClock"
@click="ed.running.value = !ed.running.value"
>
<Icon :name="ed.running.value ? 'lucide:pause' : 'lucide:play'" class="size-4" />
</button>
<button class="tb-btn" title="One clock cycle" :disabled="!hasClock" @click="ed.running.value = false; ed.step()">
<Icon name="lucide:step-forward" class="size-4" />
</button>
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select>
<span v-if="hasClock" class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }} ticks</span>
<span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'">
<span class="dot" />{{ statusText }}
</span>
</div>
<div class="flex items-center gap-1.5">
<button class="tb-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
<button class="tb-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
<div class="seg" title="Gate symbols">
<button :class="{ active: ed.project.value.settings.symbols === 'iec' }" @click="ed.project.value.settings.symbols = 'iec'; ed.commit(false)">IEC</button>
<button :class="{ active: ed.project.value.settings.symbols === 'ansi' }" @click="ed.project.value.settings.symbols = 'ansi'; ed.commit(false)">ANSI</button>
</div>
<button
class="tb-btn"
:class="{ active: ed.project.value.settings.flow }"
title="Animate current flow"
@click="ed.project.value.settings.flow = !ed.project.value.settings.flow; ed.commit(false)"
>
<Icon name="lucide:zap" class="size-4" />
</button>
<div class="relative">
<button class="tb-btn" title="Project" @click="menu = !menu"><Icon name="lucide:folder" class="size-4" /><span class="hidden md:inline">Project</span></button>
<div v-if="menu" class="menu-backdrop" @click="menu = false; confirmNew = null" />
<div v-if="menu" class="menu">
<template v-if="!confirmNew">
<button @click="ed.exportJson(); menu = false"><Icon name="lucide:download" class="size-4" /> Export as file</button>
<button @click="fileInput?.click()"><Icon name="lucide:upload" class="size-4" /> Import file</button>
<hr />
<button @click="ed.loadExamples(); menu = false"><Icon name="lucide:library" class="size-4" /> Add example parts</button>
<button @click="confirmNew = 'empty'"><Icon name="lucide:file" class="size-4" /> New project (NAND only)</button>
<button @click="confirmNew = 'examples'"><Icon name="lucide:file-plus" class="size-4" /> New project with examples</button>
</template>
<div v-else class="p-2 text-sm">
<p class="mb-2">Replace the current project? Export it first if you want to keep it.</p>
<div class="flex gap-2">
<button class="btn btn-danger grow" @click="doNew">Replace</button>
<button class="btn grow" @click="confirmNew = null">Cancel</button>
</div>
</div>
</div>
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
</div>
<button class="tb-btn" title="Help (?)" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /></button>
</div>
</header>
</template>

View File

@ -0,0 +1,509 @@
// 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
}

103
app/lib/draw.ts Normal file
View File

@ -0,0 +1,103 @@
// SVG geometry for gate symbols, in pixels relative to the node origin.
import { GRID as G, type Shape } from './logic/geometry'
import type { SymbolKind } from './logic/types'
const NEGATED = new Set<SymbolKind>(['nand', 'nor', 'xnor', 'not'])
const IEC_LABEL: Record<SymbolKind, string> = {
and: '&',
nand: '&',
or: '≥1',
nor: '≥1',
xor: '=1',
xnor: '=1',
not: '1',
buf: '1',
box: '',
}
export interface GateDrawing {
stubs: string
body: string
/** Extra stroke-only path (second curve of an ANSI XOR). */
extra?: string
bubble?: { cx: number; cy: number; r: number }
label?: { x: number; y: number; text: string }
}
export function gateDrawing(shape: Shape, style: 'iec' | 'ansi'): GateDrawing {
const symbol = shape.gate!
const { body } = shape
const W = body.w * G
const out = shape.outputs[0]!
const oy = out.dy * G
const negated = NEGATED.has(symbol)
const r = 0.22 * G
const one = shape.inputs.length === 1
const top = (one ? body.y + 0.25 : body.y) * G
const bottom = (one ? body.y + body.h - 0.25 : body.y + body.h) * G
const mid = (top + bottom) / 2
const x0 = 0.5 * G
const x1 = W - 0.5 * G - (negated ? 2 * r : 0)
const stubs = [
...shape.inputs.map(p => `M0 ${p.dy * G}H${x0 + 0.5 * G}`),
`M${x1 - 0.3 * G} ${oy}H${W}`,
].join('')
const bubble = negated ? { cx: x1 + r, cy: oy, r } : undefined
if (style === 'iec') {
return {
stubs,
body: `M${x0} ${top}H${x1}V${bottom}H${x0}Z`,
bubble,
label: { x: (x0 + x1) / 2, y: top + 0.62 * G, text: IEC_LABEL[symbol] },
}
}
const h = bottom - top
switch (symbol) {
case 'and':
case 'nand': {
const rad = h / 2
const xm = Math.max(x0, x1 - rad)
return { stubs, bubble, body: `M${x0} ${top}H${xm}A${rad} ${rad} 0 0 1 ${xm} ${bottom}H${x0}Z` }
}
case 'or':
case 'nor':
case 'xor':
case 'xnor': {
const xs = symbol.startsWith('x') ? x0 + 0.3 * G : x0
const w = x1 - xs
const path = `M${xs} ${top}Q${xs + 0.28 * w} ${mid} ${xs} ${bottom}Q${xs + 0.62 * w} ${bottom} ${x1} ${mid}Q${xs + 0.62 * w} ${top} ${xs} ${top}Z`
const extra = xs !== x0 ? `M${x0} ${top}Q${x0 + 0.28 * w} ${mid} ${x0} ${bottom}` : undefined
return { stubs, bubble, body: path, extra }
}
default:
return { stubs, bubble, body: `M${x0} ${top}L${x1} ${mid}L${x0} ${bottom}Z` }
}
}
// 7-segment patterns for 0–F, segments a..g as bits 0..6.
const SEGMENTS = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71]
export function sevenSegment(value: number) {
const xa = 1.15 * G
const xb = 2.35 * G
const y0 = -0.05 * G
const y1 = 1.5 * G
const y2 = 3.05 * G
const g = 3
const segs: [number, number, number, number][] = [
[xa + g, y0, xb - g, y0],
[xb, y0 + g, xb, y1 - g],
[xb, y1 + g, xb, y2 - g],
[xa + g, y2, xb - g, y2],
[xa, y1 + g, xa, y2 - g],
[xa, y0 + g, xa, y1 - g],
[xa + g, y1, xb - g, y1],
]
const bits = SEGMENTS[value & 15]!
return segs.map((s, i) => ({ d: `M${s[0]} ${s[1]}L${s[2]} ${s[3]}`, on: (bits >> i) & 1 }))
}

124
app/lib/logic/analyze.ts Normal file
View File

@ -0,0 +1,124 @@
// Analysis on a compiled component: truth table, NAND count, gate delay,
// and step-by-step tests (used by challenges).
import { compile, type Netlist } from './compile'
import { chipPins, type DefLookup } from './geometry'
import { Simulator } from './sim'
const SETTLE_BUDGET = 2_000_000
export interface TruthRow {
ins: number[]
outs: number[]
/** False when the circuit kept oscillating for this input. */
settled: boolean
}
export interface TruthTable {
inputs: string[]
outputs: string[]
rows: TruthRow[]
}
export const MAX_TABLE_INPUTS = 10
export function truthTable(getDef: DefLookup, defId: string): TruthTable | { error: string } {
const def = getDef(defId)
if (!def) return { error: 'Component not found' }
const pins = chipPins(def)
const n = pins.inputs.length
if (n > MAX_TABLE_INPUTS) return { error: `Too many inputs for a table (${n}, max ${MAX_TABLE_INPUTS})` }
if (pins.outputs.length === 0) return { error: 'Add at least one output pin' }
const sim = new Simulator(compile(getDef, defId))
sim.run(SETTLE_BUDGET)
const rows: TruthRow[] = []
for (let i = 0; i < 1 << n; i++) {
const ins = pins.inputs.map((_, k) => (i >> (n - 1 - k)) & 1)
pins.inputs.forEach((p, k) => sim.setSource(p.key, ins[k] === 1))
const settled = sim.run(SETTLE_BUDGET)
rows.push({ ins, outs: pins.outputs.map(p => sim.pin(p.key, 'a')), settled })
}
return { inputs: pins.inputs.map(p => p.label), outputs: pins.outputs.map(p => p.label), rows }
}
export interface Stats {
nands: number
/** Has feedback loops, so it can store state (latch, flip-flop, counter). */
sequential: boolean
/** Longest path in NAND gates; null when there are loops. */
delay: number | null
}
export function stats(nl: Netlist): Stats {
const gates = nl.gateOut.length
const driver = new Int32Array(nl.netCount).fill(-1)
for (let g = 0; g < gates; g++) driver[nl.gateOut[g]!] = g
const indeg = new Int32Array(gates)
for (let g = 0; g < gates; g++) {
const a = nl.gateA[g]!
const b = nl.gateB[g]!
if (driver[a]! >= 0) indeg[g]!++
if (b !== a && driver[b]! >= 0) indeg[g]!++
}
const depth = new Int32Array(gates)
const queue: number[] = []
for (let g = 0; g < gates; g++) if (indeg[g] === 0) queue.push(g)
let done = 0
let delay = 0
while (done < queue.length) {
const g = queue[done++]!
const d = depth[g]! + 1
delay = Math.max(delay, d)
const out = nl.gateOut[g]!
for (let j = nl.fanStart[out]!; j < nl.fanStart[out + 1]!; j++) {
const r = nl.fanList[j]!
depth[r] = Math.max(depth[r]!, d)
if (--indeg[r]! === 0) queue.push(r)
}
}
const sequential = done < gates
return { nands: gates, sequential, delay: sequential ? null : delay }
}
/** One test step: set inputs (by pin label), let it settle, check outputs. */
export interface TestStep {
set: Record<string, number>
expect: Record<string, number>
}
export interface TestResult {
pass: boolean
message: string
failedStep?: number
}
export function runSteps(getDef: DefLookup, defId: string, steps: TestStep[]): TestResult {
const def = getDef(defId)
if (!def) return { pass: false, message: 'Component not found' }
const pins = chipPins(def)
const find = (list: { key: string; label: string }[], label: string) =>
list.find(p => p.label.toLowerCase() === label.toLowerCase())
for (const step of steps) {
for (const l of Object.keys(step.set)) {
if (!find(pins.inputs, l)) return { pass: false, message: `Missing input pin "${l}"` }
}
for (const l of Object.keys(step.expect)) {
if (!find(pins.outputs, l)) return { pass: false, message: `Missing output pin "${l}"` }
}
}
const sim = new Simulator(compile(getDef, defId))
sim.run(SETTLE_BUDGET)
for (let i = 0; i < steps.length; i++) {
const step = steps[i]!
for (const [l, v] of Object.entries(step.set)) sim.setSource(find(pins.inputs, l)!.key, v === 1)
if (!sim.run(SETTLE_BUDGET)) return { pass: false, message: 'The circuit oscillates and never settles', failedStep: i }
for (const [l, want] of Object.entries(step.expect)) {
const got = sim.pin(find(pins.outputs, l)!.key, 'a')
if (got !== want) {
const inputs = Object.entries(step.set).map(([k, v]) => `${k}=${v}`).join(' ')
return { pass: false, message: `With ${inputs}: ${l} is ${got}, expected ${want}`, failedStep: i }
}
}
}
return { pass: true, message: `All ${steps.length} checks pass` }
}

100
app/lib/logic/challenges.ts Normal file
View File

@ -0,0 +1,100 @@
// Challenges in the spirit of "Turing Complete": a target behaviour, you
// build it from NAND (and your earlier parts), the checker runs the tests.
import type { TestStep } from './analyze'
import type { SymbolKind } from './types'
export interface Challenge {
id: string
name: string
goal: string
inputs: string[]
outputs: string[]
symbol?: SymbolKind
/** Combinational: outputs as a function of the inputs, checked for every combination. */
fn?: (ins: number[]) => number[]
/** Sequential: explicit steps, checked in order. */
steps?: TestStep[]
}
const b = (v: boolean) => (v ? 1 : 0)
export const CHALLENGES: Challenge[] = [
{ id: 'not', name: 'NOT', symbol: 'not', inputs: ['A'], outputs: ['Q'], goal: 'Q is the opposite of A.', fn: ([a]) => [b(!a)] },
{ id: 'and', name: 'AND', symbol: 'and', inputs: ['A', 'B'], outputs: ['Q'], goal: 'Q is 1 only when A and B are both 1.', fn: ([a, c]) => [b(!!a && !!c)] },
{ id: 'or', name: 'OR', symbol: 'or', inputs: ['A', 'B'], outputs: ['Q'], goal: 'Q is 1 when A or B (or both) are 1.', fn: ([a, c]) => [b(!!a || !!c)] },
{ id: 'nor', name: 'NOR', symbol: 'nor', inputs: ['A', 'B'], outputs: ['Q'], goal: 'Q is 1 only when both inputs are 0.', fn: ([a, c]) => [b(!a && !c)] },
{ id: 'xor', name: 'XOR', symbol: 'xor', inputs: ['A', 'B'], outputs: ['Q'], goal: 'Q is 1 when exactly one input is 1.', fn: ([a, c]) => [b(a !== c)] },
{ id: 'xnor', name: 'XNOR', symbol: 'xnor', inputs: ['A', 'B'], outputs: ['Q'], goal: 'Q is 1 when both inputs are equal.', fn: ([a, c]) => [b(a === c)] },
{ id: 'and3', name: 'AND 3', symbol: 'and', inputs: ['A', 'B', 'C'], outputs: ['Q'], goal: 'Q is 1 only when all three inputs are 1.', fn: ([a, c, d]) => [b(!!a && !!c && !!d)] },
{ id: 'mux', name: 'Mux', inputs: ['A', 'B', 'S'], outputs: ['Q'], goal: 'Q follows A while S is 0, and B while S is 1.', fn: ([a, c, s]) => [s ? c! : a!] },
{ id: 'demux', name: 'Demux', inputs: ['D', 'S'], outputs: ['A', 'B'], goal: 'Send D to A while S is 0, to B while S is 1. The other output stays 0.', fn: ([d, s]) => [b(!!d && !s), b(!!d && !!s)] },
{ id: 'dec2', name: 'Decoder 2→4', inputs: ['A1', 'A0'], outputs: ['Y0', 'Y1', 'Y2', 'Y3'], goal: 'Exactly one output is 1: the one whose number is A1 A0 in binary.', fn: ([a1, a0]) => { const n = a1! * 2 + a0!; return [0, 1, 2, 3].map(i => b(i === n)) } },
{ id: 'ha', name: 'Half Adder', inputs: ['A', 'B'], outputs: ['S', 'C'], goal: 'A + B as a two-bit number: C is the carry, S the sum bit.', fn: ([a, c]) => { const s = a! + c!; return [s & 1, s >> 1] } },
{ id: 'fa', name: 'Full Adder', inputs: ['A', 'B', 'Cin'], outputs: ['S', 'Cout'], goal: 'A + B + Cin: Cout is the carry, S the sum bit.', fn: ([a, c, d]) => { const s = a! + c! + d!; return [s & 1, s >> 1] } },
{ id: 'eq2', name: 'Equal 2', inputs: ['A1', 'A0', 'B1', 'B0'], outputs: ['EQ'], goal: 'EQ is 1 when the two-bit numbers A1A0 and B1B0 are equal.', fn: ([a1, a0, b1, b0]) => [b(a1 === b1 && a0 === b0)] },
{ id: 'add2', name: 'Adder 2', inputs: ['A1', 'A0', 'B1', 'B0'], outputs: ['C', 'S1', 'S0'], goal: 'Add two 2-bit numbers. C S1 S0 is the 3-bit result.', fn: ([a1, a0, b1, b0]) => { const s = a1! * 2 + a0! + b1! * 2 + b0!; return [(s >> 2) & 1, (s >> 1) & 1, s & 1] } },
{
id: 'sr',
name: 'SR Latch',
inputs: ['S', 'R'],
outputs: ['Q'],
goal: 'Memory! S = 1 sets Q to 1, R = 1 resets Q to 0. With both at 0, Q keeps its value.',
steps: [
{ set: { S: 1, R: 0 }, expect: { Q: 1 } },
{ set: { S: 0, R: 0 }, expect: { Q: 1 } },
{ set: { S: 0, R: 1 }, expect: { Q: 0 } },
{ set: { S: 0, R: 0 }, expect: { Q: 0 } },
{ set: { S: 1, R: 0 }, expect: { Q: 1 } },
{ set: { S: 0, R: 0 }, expect: { Q: 1 } },
],
},
{
id: 'dlatch',
name: 'D Latch',
inputs: ['D', 'E'],
outputs: ['Q'],
goal: 'While E is 1, Q follows D. While E is 0, Q holds the last value.',
steps: [
{ set: { D: 1, E: 1 }, expect: { Q: 1 } },
{ set: { D: 0, E: 1 }, expect: { Q: 0 } },
{ set: { D: 1, E: 0 }, expect: { Q: 0 } },
{ set: { D: 1, E: 1 }, expect: { Q: 1 } },
{ set: { D: 1, E: 0 }, expect: { Q: 1 } },
{ set: { D: 0, E: 0 }, expect: { Q: 1 } },
],
},
{
id: 'dff',
name: 'D Flip-Flop',
inputs: ['D', 'CLK'],
outputs: ['Q'],
goal: 'Q takes the value of D only at the moment CLK goes from 0 to 1 (rising edge), and holds it otherwise.',
steps: [
{ set: { D: 1, CLK: 0 }, expect: {} },
{ set: { D: 1, CLK: 1 }, expect: { Q: 1 } },
{ set: { D: 0, CLK: 1 }, expect: { Q: 1 } },
{ set: { D: 0, CLK: 0 }, expect: { Q: 1 } },
{ set: { D: 0, CLK: 1 }, expect: { Q: 0 } },
{ set: { D: 1, CLK: 1 }, expect: { Q: 0 } },
{ set: { D: 1, CLK: 0 }, expect: { Q: 0 } },
{ set: { D: 1, CLK: 1 }, expect: { Q: 1 } },
],
},
]
/** Test steps for a challenge: explicit ones, or every input combination. */
export function challengeSteps(c: Challenge): TestStep[] {
if (c.steps) return c.steps
const n = c.inputs.length
const steps: TestStep[] = []
for (let i = 0; i < 1 << n; i++) {
const ins = c.inputs.map((_, k) => (i >> (n - 1 - k)) & 1)
const outs = c.fn!(ins)
steps.push({
set: Object.fromEntries(c.inputs.map((l, k) => [l, ins[k]!])),
expect: Object.fromEntries(c.outputs.map((l, k) => [l, outs[k]!])),
})
}
return steps
}

254
app/lib/logic/compile.ts Normal file
View File

@ -0,0 +1,254 @@
// Flattens a component tree into a flat list of NAND gates over numbered
// nets. Chip boundaries and input/output pins disappear: they are aliases,
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
import { chipPins, type ChipPins, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0
export const HIGH = 1
export interface Netlist {
netCount: number
gateA: Int32Array
gateB: Int32Array
gateOut: Int32Array
/** Stable identity per gate ("chipNode/chipNode/nandNode"), to keep state across recompiles. */
gateKeys: string[]
/** CSR fanout: gates reading net n are fanList[fanStart[n] .. fanStart[n + 1]). */
fanStart: Int32Array
fanList: Int32Array
/** Net of every pin of the root circuit's nodes, keyed "nodeId:pin". */
pinNet: Map<string, number>
/** Same, for nodes at any depth, keyed "chipNode/…/nodeId:pin". Only with `trace`. */
tracePinNet?: Map<string, number>
/** User-driven sources in the root circuit (switches, buttons): nodeId → net. */
sources: Map<string, number>
clocks: Int32Array
errors: string[]
}
export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
switch (node.kind) {
case 'nand':
return ['a', 'b']
case 'output':
case 'lamp':
return ['a']
case 'hex':
return ['b0', 'b1', 'b2', 'b3']
case 'chip':
return pins ? pins.inputs.map(p => p.key) : []
default:
return []
}
}
export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
switch (node.kind) {
case 'nand':
case 'input':
case 'high':
case 'low':
case 'button':
case 'clock':
return ['q']
case 'chip':
return pins ? pins.outputs.map(p => p.key) : []
default:
return []
}
}
const MAX_DEPTH = 64
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
const parent: number[] = [LOW, HIGH]
const make = () => {
parent.push(parent.length)
return parent.length - 1
}
const find = (x: number) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]!]!
x = parent[x]!
}
return x
}
const union = (a: number, b: number) => {
a = find(a)
b = find(b)
if (a === b) return
// Constants stay roots so they keep their fixed values.
if (a <= HIGH) parent[b] = a
else parent[a] = b
}
const gA: number[] = []
const gB: number[] = []
const gOut: number[] = []
const gateKeys: string[] = []
const clocks: number[] = []
const sources = new Map<string, number>()
const rawPinNet = new Map<string, number>()
const rawTrace = opts.trace ? new Map<string, number>() : undefined
const errors: string[] = []
const pinCache = new Map<string, ChipPins>()
const pinsOf = (node: CircuitNode): ChipPins | undefined => {
if (node.kind !== 'chip' || !node.chip) return undefined
let p = pinCache.get(node.chip)
if (!p) {
const def = getDef(node.chip)
if (!def) return undefined
p = chipPins(def)
pinCache.set(node.chip, p)
}
return p
}
const expand = (def: ComponentDef, inNets: Map<string, number> | null, path: string, stack: string[]): Map<string, number> => {
const result = new Map<string, number>()
if (stack.includes(def.id)) {
errors.push(`"${def.name}" contains itself`)
return result
}
if (stack.length >= MAX_DEPTH) {
errors.push(`Nesting deeper than ${MAX_DEPTH} levels`)
return result
}
const inner = [...stack, def.id]
const wiresTo = new Map<string, Wire>()
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
const outNet = new Map<string, number>()
for (const n of def.nodes) {
for (const k of outputKeys(n, pinsOf(n))) outNet.set(`${n.id}:${k}`, make())
}
const inNet = (nodeId: string, pin: string) => {
const w = wiresTo.get(`${nodeId}:${pin}`)
return w ? (outNet.get(`${w.from.node}:${w.from.pin}`) ?? LOW) : LOW
}
for (const n of def.nodes) {
const q = outNet.get(`${n.id}:q`)!
switch (n.kind) {
case 'nand':
gA.push(inNet(n.id, 'a'))
gB.push(inNet(n.id, 'b'))
gOut.push(q)
gateKeys.push(path + n.id)
break
case 'input':
if (inNets) union(q, inNets.get(n.id) ?? LOW)
else sources.set(n.id, q)
break
case 'button':
if (!inNets) sources.set(n.id, q)
break
case 'high':
union(q, HIGH)
break
case 'low':
union(q, LOW)
break
case 'clock':
clocks.push(q)
break
case 'output':
result.set(n.id, inNet(n.id, 'a'))
break
case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined
const pins = pinsOf(n)
if (!child || !pins) {
errors.push(`Missing component in "${def.name}"`)
break
}
const childIn = new Map<string, number>()
for (const p of pins.inputs) childIn.set(p.key, inNet(n.id, p.key))
const childOut = expand(child, childIn, `${path}${n.id}/`, inner)
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
break
}
}
}
if (inNets === null || rawTrace) {
const record = (n: CircuitNode, k: string, net: number) => {
if (inNets === null) rawPinNet.set(`${n.id}:${k}`, net)
rawTrace?.set(`${path}${n.id}:${k}`, net)
}
for (const n of def.nodes) {
const pins = pinsOf(n)
for (const k of inputKeys(n, pins)) record(n, k, inNet(n.id, k))
for (const k of outputKeys(n, pins)) record(n, k, outNet.get(`${n.id}:${k}`)!)
}
}
return result
}
const root = getDef(rootId)
if (root) expand(root, null, '', [])
else errors.push('Circuit not found')
// Renumber union-find roots to 0..netCount-1, constants first.
const idx = new Int32Array(parent.length).fill(-1)
idx[find(LOW)] = LOW
idx[find(HIGH)] = HIGH
let netCount = 2
const canon = (x: number) => {
const r = find(x)
if (idx[r]! < 0) idx[r] = netCount++
return idx[r]!
}
const gateCount = gOut.length
const gateA = new Int32Array(gateCount)
const gateB = new Int32Array(gateCount)
const gateOut = new Int32Array(gateCount)
for (let i = 0; i < gateCount; i++) {
gateA[i] = canon(gA[i]!)
gateB[i] = canon(gB[i]!)
gateOut[i] = canon(gOut[i]!)
}
const mapNets = (m: Map<string, number>) => {
const out = new Map<string, number>()
for (const [k, v] of m) out.set(k, canon(v))
return out
}
const pinNet = mapNets(rawPinNet)
const tracePinNet = rawTrace ? mapNets(rawTrace) : undefined
const srcs = mapNets(sources)
const clockNets = Int32Array.from(new Set(clocks.map(canon)))
// Fanout in CSR form.
const fanStart = new Int32Array(netCount + 1)
for (let i = 0; i < gateCount; i++) {
fanStart[gateA[i]! + 1]!++
if (gateB[i] !== gateA[i]) fanStart[gateB[i]! + 1]!++
}
for (let n = 0; n < netCount; n++) fanStart[n + 1]! += fanStart[n]!
const fanList = new Int32Array(fanStart[netCount]!)
const fill = fanStart.slice(0, netCount)
for (let i = 0; i < gateCount; i++) {
fanList[fill[gateA[i]!]!++] = i
if (gateB[i] !== gateA[i]) fanList[fill[gateB[i]!]!++] = i
}
return {
netCount,
gateA,
gateB,
gateOut,
gateKeys,
fanStart,
fanList,
pinNet,
tracePinNet,
sources: srcs,
clocks: clockNets,
errors: [...new Set(errors)],
}
}

274
app/lib/logic/examples.ts Normal file
View File

@ -0,0 +1,274 @@
// Example library: every part below is built from NAND gates only, then
// reused as a chip by the next one (NOT → AND → … → 4-bit counter).
// Coordinates are grid units, hand-placed so the wiring reads cleanly.
import { chipPins } from './geometry'
import type { CircuitNode, ComponentDef, PinRef, SymbolKind } from './types'
type Pt = [number, number]
export type Src = PinRef & { pts?: Pt[] }
/** Route a wire through corner points. */
export const via = (src: Src, ...pts: Pt[]): Src => ({ ...src, pts })
export class Builder {
readonly def: ComponentDef
private seq = 0
constructor(
private lib: Map<string, ComponentDef>,
init: { id: string; name: string; symbol?: SymbolKind; group?: string; description?: string },
) {
this.def = { symbol: 'box', ...init, nodes: [], wires: [] }
}
private add(node: Omit<CircuitNode, 'id'>): string {
const id = `n${++this.seq}`
this.def.nodes.push({ id, ...node })
return id
}
link(from: Src, to: PinRef) {
const wire: ComponentDef['wires'][number] = { id: `w${++this.seq}`, from: { node: from.node, pin: from.pin }, to }
if (from.pts) wire.pts = from.pts
this.def.wires.push(wire)
}
input(label: string, x: number, y: number): Src {
return { node: this.add({ kind: 'input', x, y, label }), pin: 'q' }
}
output(label: string, x: number, y: number, src?: Src) {
const id = this.add({ kind: 'output', x, y, label })
if (src) this.link(src, { node: id, pin: 'a' })
return id
}
nand(x: number, y: number, a?: Src, b?: Src): Src {
const id = this.add({ kind: 'nand', x, y })
if (a) this.link(a, { node: id, pin: 'a' })
if (b) this.link(b, { node: id, pin: 'b' })
return { node: id, pin: 'q' }
}
/** Place a library part; inputs and returned outputs follow its pin order. */
chip(chipId: string, x: number, y: number, ...ins: (Src | undefined)[]): Src[] {
const def = this.lib.get(chipId)
if (!def) throw new Error(`Unknown part ${chipId}`)
const pins = chipPins(def)
const id = this.add({ kind: 'chip', chip: chipId, x, y })
ins.forEach((src, i) => {
const pin = pins.inputs[i]
if (src && pin) this.link(src, { node: id, pin: pin.key })
})
return pins.outputs.map(p => ({ node: id, pin: p.key }))
}
source(kind: 'high' | 'low' | 'clock' | 'button', x: number, y: number, label?: string): Src {
return { node: this.add({ kind, x, y, label }), pin: 'q' }
}
hex(x: number, y: number, bits: Src[]) {
const id = this.add({ kind: 'hex', x, y })
bits.forEach((src, i) => this.link(src, { node: id, pin: `b${i}` }))
}
lamp(x: number, y: number, src: Src, label?: string) {
const id = this.add({ kind: 'lamp', x, y, label })
this.link(src, { node: id, pin: 'a' })
}
note(x: number, y: number, text: string) {
this.add({ kind: 'note', x, y, label: text })
}
}
export function exampleLibrary(): ComponentDef[] {
const lib = new Map<string, ComponentDef>()
const make = (init: ConstructorParameters<typeof Builder>[1], build: (b: Builder) => void) => {
const b = new Builder(lib, init)
build(b)
lib.set(b.def.id, b.def)
}
make({ id: 'ex-not', name: 'NOT', symbol: 'not', group: 'Gates', description: 'Inverter: a NAND with both inputs tied together.' }, b => {
const A = b.input('A', 0, 1)
b.output('Q', 11, 1, b.nand(5, 0, A, A))
})
make({ id: 'ex-and', name: 'AND', symbol: 'and', group: 'Gates', description: 'NAND followed by NOT.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [q] = b.chip('ex-not', 11, 1, b.nand(5, 0, A, B))
b.output('Q', 16, 1, q)
})
make({ id: 'ex-or', name: 'OR', symbol: 'or', group: 'Gates', description: 'De Morgan: NAND of the inverted inputs.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 4)
const [na] = b.chip('ex-not', 5, 0, A)
const [nb] = b.chip('ex-not', 5, 4, B)
b.output('Q', 17, 2, b.nand(11, 1, na, nb))
})
make({ id: 'ex-nor', name: 'NOR', symbol: 'nor', group: 'Gates', description: 'OR followed by NOT.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [o] = b.chip('ex-or', 5, 0, A, B)
const [q] = b.chip('ex-not', 11, 1, o)
b.output('Q', 16, 1, q)
})
make({ id: 'ex-xor', name: 'XOR', symbol: 'xor', group: 'Gates', description: 'Exclusive OR from four NANDs: 1 when exactly one input is 1.' }, b => {
const A = b.input('A', 0, 1)
const B = b.input('B', 0, 7)
const n1 = b.nand(5, 3, A, B)
const n2 = b.nand(12, 1, A, n1)
const n3 = b.nand(12, 5, n1, B)
b.output('Q', 25, 4, b.nand(19, 3, n2, n3))
})
make({ id: 'ex-xnor', name: 'XNOR', symbol: 'xnor', group: 'Gates', description: 'XOR followed by NOT: 1 when both inputs are equal.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [x] = b.chip('ex-xor', 5, 0, A, B)
const [q] = b.chip('ex-not', 11, 1, x)
b.output('Q', 16, 1, q)
})
make({ id: 'ex-mux', name: 'Mux', group: 'Routing', description: 'Selector: Q = A when S is 0, Q = B when S is 1.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 4)
const S = b.input('S', 0, 8)
const [ns] = b.chip('ex-not', 4, 8, S)
const n1 = b.nand(10, 0, A, ns)
const n2 = b.nand(10, 4, B, via(S, [3, 8], [3, 6]))
b.output('Q', 23, 3, b.nand(17, 2, n1, n2))
})
make({ id: 'ex-ha', name: 'Half Adder', group: 'Arithmetic', description: 'Adds two bits: S is the sum bit, C the carry.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const [s] = b.chip('ex-xor', 6, 0, A, B)
const [c] = b.chip('ex-and', 6, 5, via(A, [3, 0], [3, 5]), via(B, [4, 2], [4, 7]))
b.output('S', 13, 1, s)
b.output('C', 13, 6, c)
})
make({ id: 'ex-fa', name: 'Full Adder', group: 'Arithmetic', description: 'Adds three bits (A, B and carry in) with two half adders.' }, b => {
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
const Cin = b.input('Cin', 0, 6)
const [s1, c1] = b.chip('ex-ha', 5, 0, A, B)
const [s2, c2] = b.chip('ex-ha', 16, 3, s1, Cin)
const [c] = b.chip('ex-or', 26, 5, via(c1!, [15, 1], [15, 5]), c2)
b.output('S', 33, 3, s2)
b.output('Cout', 33, 6, c)
})
make({ id: 'ex-sr', name: 'SR Latch', group: 'Memory', description: 'Stores one bit. S sets Q to 1, R resets it to 0; with both at 0 it remembers.' }, b => {
const S = b.input('S', 0, 0)
const R = b.input('R', 0, 7)
const [ns] = b.chip('ex-not', 4, 0, S)
const [nr] = b.chip('ex-not', 4, 7, R)
// The Q̄ gate goes first: the simulator settles gates in the order they
// were placed, so the latch (and every memory built on it) starts at 0.
const n2 = b.nand(10, 5)
const n1 = b.nand(10, 0, ns, via(n2, [15, 6], [15, 4], [8, 4], [8, 2]))
b.link(via(n1, [16, 1], [16, 3], [9, 3], [9, 5]), { node: n2.node, pin: 'a' })
b.link(nr, { node: n2.node, pin: 'b' })
b.output('Q', 19, 1, n1)
b.output('Q̄', 19, 6, n2)
})
make({ id: 'ex-dlatch', name: 'D Latch', group: 'Memory', description: 'While E is 1, Q follows D. When E drops to 0, Q keeps the last value.' }, b => {
const D = b.input('D', 0, 0)
const E = b.input('E', 0, 4)
const [s] = b.chip('ex-and', 8, 0, D, E)
const [nd] = b.chip('ex-not', 4, 8, D)
const [r] = b.chip('ex-and', 8, 6, E, nd)
const [q, nq] = b.chip('ex-sr', 15, 1, s, r)
b.output('Q', 25, 1, q)
b.output('Q̄', 25, 3, nq)
})
make({ id: 'ex-dff', name: 'D Flip-Flop', group: 'Memory', description: 'Takes over D at the rising edge of CLK and holds it until the next rising edge. Two D latches (master, slave).' }, b => {
const D = b.input('D', 0, 0)
const CLK = b.input('CLK', 0, 4)
const [nclk] = b.chip('ex-not', 5, 4, CLK)
const [mq] = b.chip('ex-dlatch', 11, 0, D, nclk)
const [q, nq] = b.chip('ex-dlatch', 21, 0, mq, via(CLK, [3, 6], [19, 6]))
b.output('Q', 30, 0, q)
b.output('Q̄', 30, 2, nq)
})
make({ id: 'ex-reg4', name: 'Register 4', group: 'Memory', description: 'Four D flip-flops on one clock: stores a 4-bit number.' }, b => {
const D = [0, 1, 2, 3].map(i => b.input(`D${i}`, 0, 4 * i))
const CLK = b.input('CLK', 0, 16)
D.forEach((d, i) => {
const [q] = b.chip('ex-dff', 6, 4 * i, d, CLK)
b.output(`Q${i}`, 18, 4 * i, q)
})
})
make({ id: 'ex-inc4', name: 'Increment 4', group: 'Arithmetic', description: 'Adds 1 to a 4-bit number with a chain of half adders.' }, b => {
const A = [0, 1, 2, 3].map(i => b.input(`A${i}`, 0, 4 * i))
let carry = b.source('high', 3, 1)
A.forEach((a, i) => {
const [s, c] = b.chip('ex-ha', 6 + 9 * i, 4 * i, a, carry)
b.output(`S${i}`, 43, 4 * i, s)
carry = c!
})
b.output('Cout', 43, 16, carry)
})
make({ id: 'ex-add4', name: 'Adder 4', group: 'Arithmetic', description: 'Adds two 4-bit numbers with four full adders (ripple carry).' }, b => {
const A = [0, 1, 2, 3].map(i => b.input(`A${i}`, 0, 2 * i))
const B = [0, 1, 2, 3].map(i => b.input(`B${i}`, 0, 8 + 2 * i))
let carry: Src = via(b.input('Cin', 0, 16), [13, 16], [13, 22])
for (let i = 0; i < 4; i++) {
const y = 20 + 4 * i
const [s, c] = b.chip('ex-fa', 14, y, via(A[i]!, [3 + i, 2 * i], [3 + i, y]), via(B[i]!, [8 + i, 8 + 2 * i], [8 + i, y + 1]), carry)
b.output(`S${i}`, 28, y, s)
carry = i < 3 ? via(c!, [24, y + 1], [24, y + 3], [12, y + 3], [12, y + 6]) : c!
}
b.output('Cout', 28, 36, carry)
})
make({ id: 'ex-cnt4', name: 'Counter 4', group: 'Memory', description: 'Counts 0 to 15 on each rising clock edge. RST = 1 sets it back to 0 at the next edge.' }, b => {
const CLK = b.input('CLK', 0, 21)
const RST = b.input('RST', 0, 24)
const inc = b.chip('ex-inc4', 6, 0)
const [nrst] = b.chip('ex-not', 4, 24, RST)
const ands = [0, 1, 2, 3].map(i => {
const [q] = b.chip('ex-and', 22, 5 * i, i === 0 ? inc[0] : via(inc[i]!, [16 + i, i], [16 + i, 5 * i]), via(nrst!, [20, 24], [20, 5 * i + 2]))
return via(q!, [27 + i, 5 * i + 1], [27 + i, i])
})
const Q = b.chip('ex-reg4', 32, 0, ...ands, via(CLK, [31, 21], [31, 4]))
const incNode = inc[0]!.node
const incIns = chipPins(lib.get('ex-inc4')!).inputs
Q.forEach((q, i) => {
b.link(via(q, [41 + i, i], [41 + i, -1 - i], [5 - i, -1 - i], [5 - i, i]), { node: incNode, pin: incIns[i]!.key })
b.output(`Q${i}`, 52, 2 * i, i === 0 ? q : via(q, [50 - i, i], [50 - i, 2 * i]))
})
})
make({ id: 'ex-demo-counter', name: 'Demo: Counter', group: 'Demos', description: 'A clock drives the 4-bit counter; the hex display shows the count.' }, b => {
b.note(0, -3, 'The clock drives a 4-bit counter.\nHold Reset during a tick to go back to 0.')
const clk = b.source('clock', 0, 2)
const rst = b.source('button', 0, 6, 'Reset')
const Q = b.chip('ex-cnt4', 8, 2, clk, rst)
b.hex(24, 2, Q)
})
return [...lib.values()]
}
export function starterCircuit(): ComponentDef {
const b = new Builder(new Map(), { id: 'main', name: 'Main' })
b.note(0, -4, 'Click a switch to flip it. NAND is the only gate:\nbuild the rest from it and save them as components.')
const A = b.input('A', 0, 0)
const B = b.input('B', 0, 2)
b.lamp(12, 1, b.nand(5, 0, A, B))
return b.def
}

204
app/lib/logic/geometry.ts Normal file
View File

@ -0,0 +1,204 @@
// Node shapes and pin positions, all in grid units relative to the node's
// (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, SymbolKind } from './types'
export const GRID = 16
export interface PinInfo {
key: string
label: string
dx: number
dy: number
}
export interface Shape {
body: { x: number; y: number; w: number; h: number }
inputs: PinInfo[]
outputs: PinInfo[]
/** Set when the node draws as a logic gate symbol. */
gate?: SymbolKind
}
export type DefLookup = (id: string) => ComponentDef | undefined
const LABEL_CHAR = 0.4 // grid units per character of a pin label
const NAME_CHAR = 0.44
export interface ChipPins {
inputs: { key: string; label: string }[]
outputs: { key: string; label: string }[]
}
/** A component's pins are its input/output nodes, ordered top to bottom. */
export function chipPins(def: ComponentDef): ChipPins {
const byPos = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
const pins = (kind: 'input' | 'output', fallback: string) =>
def.nodes
.filter(n => n.kind === kind)
.sort(byPos)
.map((n, i) => ({ key: n.id, label: n.label?.trim() || `${fallback}${i + 1}` }))
return { inputs: pins('input', 'in'), outputs: pins('output', 'out') }
}
function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[], output: { key: string; label: string }): Shape {
const n = inputs.length
if (n === 1) {
return {
gate: symbol,
body: { x: 0, y: -1, w: 3, h: 2 },
inputs: [{ ...inputs[0]!, dx: 0, dy: 0 }],
outputs: [{ ...output, dx: 3, dy: 0 }],
}
}
if (n === 2) {
return {
gate: symbol,
body: { x: 0, y: -0.5, w: 4, h: 3 },
inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i * 2 })),
outputs: [{ ...output, dx: 4, dy: 1 }],
}
}
return {
gate: symbol,
body: { x: 0, y: -0.5, w: 4, h: n },
inputs: inputs.map((p, i) => ({ ...p, dx: 0, dy: i })),
outputs: [{ ...output, dx: 4, dy: Math.floor((n - 1) / 2) }],
}
}
function boxShape(name: string, pins: ChipPins): Shape {
const nIn = pins.inputs.length
const nOut = pins.outputs.length
const n = Math.max(nIn, nOut, 1)
const inOff = Math.floor((n - nIn) / 2)
const outOff = Math.floor((n - nOut) / 2)
const longest = (ps: { label: string }[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0)
const w = Math.max(
3,
Math.ceil(longest(pins.inputs) * LABEL_CHAR + longest(pins.outputs) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
)
return {
body: n === 1 ? { x: 0, y: -1, w, h: 2 } : { x: 0, y: -0.5, w, h: n },
inputs: pins.inputs.map((p, i) => ({ ...p, dx: 0, dy: inOff + i })),
outputs: pins.outputs.map((p, i) => ({ ...p, dx: w, dy: outOff + i })),
}
}
const NAND_SHAPE = gateShape('nand', [{ key: 'a', label: 'A' }, { key: 'b', label: 'B' }], { key: 'q', label: 'Q' })
const SOURCE_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [],
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
const SINK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 2, h: 1.5 },
inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }],
outputs: [],
}
const HEX_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 3, h: 4 },
inputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `b${i}`, label, dx: 0, dy: i })),
outputs: [],
}
const CLOCK_SHAPE: Shape = {
body: { x: 0, y: -0.75, w: 3, h: 1.5 },
inputs: [],
outputs: [{ key: 'q', label: '', dx: 3, dy: 0 }],
}
const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] }
export function noteLines(node: CircuitNode): string[] {
return (node.label || 'Note').split('\n')
}
export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
switch (node.kind) {
case 'nand':
return NAND_SHAPE
case 'input':
case 'high':
case 'low':
case 'button':
return SOURCE_SHAPE
case 'clock':
return CLOCK_SHAPE
case 'output':
case 'lamp':
return SINK_SHAPE
case 'hex':
return HEX_SHAPE
case 'note': {
const lines = noteLines(node)
const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR + 1))
return { body: { x: 0, y: -0.75, w, h: lines.length + 0.5 }, inputs: [], outputs: [] }
}
case 'chip': {
const def = node.chip ? getDef(node.chip) : undefined
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
if (def.symbol !== 'box' && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 8) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
return boxShape(def.name, pins)
}
}
}
export function pinPos(node: CircuitNode, shape: Shape, key: string, dir: 'in' | 'out') {
const pin = (dir === 'in' ? shape.inputs : shape.outputs).find(p => p.key === key)
return pin ? { x: node.x + pin.dx, y: node.y + pin.dy } : undefined
}
export type Pt = [number, number]
/** Drop repeated points and points in the middle of a straight run. */
export function simplify(pts: Pt[]): Pt[] {
const out: Pt[] = []
for (const p of pts) {
const last = out[out.length - 1]
if (last && last[0] === p[0] && last[1] === p[1]) continue
const prev = out[out.length - 2]
if (prev && last && ((prev[0] === last[0] && last[0] === p[0]) || (prev[1] === last[1] && last[1] === p[1]))) {
out[out.length - 1] = p
continue
}
out.push(p)
}
return out
}
/**
* Orthogonal route from an output pin to an input pin, as a list of points.
* With corner points set, the route runs through them. Otherwise forward
* wires get one vertical segment halfway; backward wires (feedback loops) go
* out to the right, around, and back in from the left.
*/
export function routeWire(a: Pt, b: Pt, corners?: Pt[]): Pt[] {
const [x1, y1] = a
const [x2, y2] = b
if (corners?.length) {
const out: Pt[] = [a]
let prev = a
for (const p of corners) {
if (p[0] !== prev[0] && p[1] !== prev[1]) out.push([p[0], prev[1]])
out.push(p)
prev = p
}
if (b[0] !== prev[0] && b[1] !== prev[1]) out.push([prev[0], b[1]])
out.push(b)
return simplify(out)
}
if (y1 === y2 && x2 > x1) return [a, b]
if (x2 >= x1 + 1) {
const m = Math.round((x1 + x2) / 2)
return [a, [m, y1], [m, y2], b]
}
const ym = Math.abs(y2 - y1) >= 3 ? Math.round((y1 + y2) / 2) : Math.max(y1, y2) + 2
return [a, [x1 + 1, y1], [x1 + 1, ym], [x2 - 1, ym], [x2 - 1, y2], b]
}

292
app/lib/logic/ops.ts Normal file
View File

@ -0,0 +1,292 @@
// Project operations that don't depend on the UI: creating, packaging,
// copying and cleaning up components. They mutate the project in place.
import type { Challenge } from './challenges'
import { inputKeys, outputKeys } from './compile'
import { exampleLibrary, starterCircuit } from './examples'
import { chipPins, shapeOf, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Project, Wire } from './types'
export function uid(prefix = ''): string {
return prefix + Math.random().toString(36).slice(2, 10)
}
/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T
}
export function lookup(project: Project): DefLookup {
const map = new Map(project.components.map(d => [d.id, d]))
return id => map.get(id)
}
export function createProject(opts: { examples: boolean }): Project {
return {
version: 1,
components: [starterCircuit(), ...(opts.examples ? exampleLibrary() : [])],
openId: 'main',
settings: { symbols: 'iec', flow: true },
solved: [],
}
}
/** Adds the example parts that are missing. Returns how many were added. */
export function addExamples(project: Project): number {
const have = new Set(project.components.map(d => d.id))
const missing = exampleLibrary().filter(d => !have.has(d.id))
project.components.push(...missing)
return missing.length
}
/** True when `defId` is `targetId` or has it somewhere inside. */
export function containsDef(project: Project, defId: string, targetId: string): boolean {
const get = lookup(project)
const seen = new Set<string>()
const walk = (id: string): boolean => {
if (id === targetId) return true
if (seen.has(id)) return false
seen.add(id)
const def = get(id)
return !!def && def.nodes.some(n => n.kind === 'chip' && !!n.chip && walk(n.chip))
}
return walk(defId)
}
/** Components that can go into `openId` without making it contain itself. */
export function placeable(project: Project, openId: string): ComponentDef[] {
return project.components.filter(d => !containsDef(project, d.id, openId))
}
export function usages(project: Project, defId: string): ComponentDef[] {
return project.components.filter(d => d.id !== defId && d.nodes.some(n => n.kind === 'chip' && n.chip === defId))
}
export function uniqueName(project: Project, base: string): string {
const names = new Set(project.components.map(d => d.name.toLowerCase()))
if (!names.has(base.toLowerCase())) return base
for (let i = 2; ; i++) if (!names.has(`${base} ${i}`.toLowerCase())) return `${base} ${i}`
}
export function newComponent(project: Project, name: string): ComponentDef {
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, name),
symbol: 'box',
nodes: [
{ id: uid('n'), kind: 'input', x: 0, y: 0, label: 'A' },
{ id: uid('n'), kind: 'output', x: 16, y: 0, label: 'Q' },
],
wires: [],
}
project.components.push(def)
return def
}
export function startChallenge(project: Project, c: Challenge): ComponentDef {
const def: ComponentDef = {
id: uid('c'),
name: uniqueName(project, project.components.some(d => d.name.toLowerCase() === c.name.toLowerCase()) ? `My ${c.name}` : c.name),
symbol: c.symbol ?? 'box',
description: c.goal,
challenge: c.id,
nodes: [
...c.inputs.map((label, i) => ({ id: uid('n'), kind: 'input' as const, x: 0, y: i * 3, label })),
...c.outputs.map((label, i) => ({ id: uid('n'), kind: 'output' as const, x: 24, y: i * 3, label })),
],
wires: [],
}
project.components.push(def)
return def
}
export function duplicateComponent(project: Project, id: string): ComponentDef | undefined {
const src = project.components.find(d => d.id === id)
if (!src) return undefined
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
delete copy.challenge
project.components.push(copy)
return copy
}
/** Deletes a component. Refuses when other components still use it. */
export function deleteComponent(project: Project, id: string): string | null {
const users = usages(project, id)
if (users.length) return `Still used in ${users.map(u => u.name).join(', ')}`
if (project.components.length <= 1) return 'The last circuit cannot be deleted'
project.components = project.components.filter(d => d.id !== id)
if (project.openId === id) project.openId = project.components[0]!.id
return null
}
/**
* Removes wires whose pins no longer exist (a component lost a pin) and
* keeps one wire per input pin. Returns true if anything changed.
*/
export function pruneWires(project: Project): boolean {
const get = lookup(project)
let changed = false
for (const def of project.components) {
const ins = new Set<string>()
const outs = new Set<string>()
for (const n of def.nodes) {
const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined
for (const k of inputKeys(n, pins)) ins.add(`${n.id}:${k}`)
for (const k of outputKeys(n, pins)) outs.add(`${n.id}:${k}`)
}
const taken = new Set<string>()
const kept: Wire[] = []
for (let i = def.wires.length - 1; i >= 0; i--) {
const w = def.wires[i]!
const to = `${w.to.node}:${w.to.pin}`
if (!ins.has(to) || !outs.has(`${w.from.node}:${w.from.pin}`) || taken.has(to)) continue
taken.add(to)
kept.push(w)
}
if (kept.length !== def.wires.length) {
def.wires = kept.reverse()
changed = true
}
}
return changed
}
export interface Clip {
nodes: CircuitNode[]
wires: Wire[]
}
export function copySelection(def: ComponentDef, ids: Set<string>): Clip {
return clone({
nodes: def.nodes.filter(n => ids.has(n.id)),
wires: def.wires.filter(w => ids.has(w.from.node) && ids.has(w.to.node)),
})
}
/** Pastes a clip shifted by (dx, dy). Returns the new node ids. */
export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number): string[] {
const ids = new Map<string, string>()
for (const n of clip.nodes) {
const id = uid('n')
ids.set(n.id, id)
def.nodes.push({ ...clone(n), id, x: n.x + dx, y: n.y + dy })
}
for (const w of clip.wires) {
const from = ids.get(w.from.node)
const to = ids.get(w.to.node)
if (!from || !to) continue
const wire: Wire = { id: uid('w'), from: { node: from, pin: w.from.pin }, to: { node: to, pin: w.to.pin } }
if (w.pts) wire.pts = w.pts.map(([x, y]) => [x + dx, y + dy])
def.wires.push(wire)
}
return [...ids.values()]
}
/**
* Turns the selected parts into a new component and puts one instance of it
* in their place. Wires that crossed the selection border become pins.
*/
export function packageSelection(
project: Project,
defId: string,
ids: Set<string>,
name: string,
): { ok: true; def: ComponentDef; chipNode: string } | { ok: false; error: string } {
const get = lookup(project)
const def = get(defId)
if (!def) return { ok: false, error: 'Circuit not found' }
const sel = def.nodes.filter(n => ids.has(n.id))
if (sel.some(n => n.kind === 'input' || n.kind === 'output')) {
return { ok: false, error: 'Leave the circuit’s own input/output pins out of the selection' }
}
if (!sel.some(n => n.kind !== 'note')) return { ok: false, error: 'Select some parts first' }
const inside = (id: string) => ids.has(id)
const incoming = def.wires.filter(w => !inside(w.from.node) && inside(w.to.node))
const outgoing = def.wires.filter(w => inside(w.from.node) && !inside(w.to.node))
const internal = def.wires.filter(w => inside(w.from.node) && inside(w.to.node))
const minX = Math.min(...sel.map(n => n.x))
const minY = Math.min(...sel.map(n => n.y))
const maxX = Math.max(...sel.map(n => n.x + shapeOf(n, get).body.w))
const ox = 6 - minX
const oy = -minY
const nodeById = new Map(def.nodes.map(n => [n.id, n]))
const pinY = (ref: { node: string; pin: string }, dir: 'in' | 'out') => {
const n = nodeById.get(ref.node)!
const s = shapeOf(n, get)
const p = (dir === 'in' ? s.inputs : s.outputs).find(p => p.key === ref.pin)
return n.y + (p?.dy ?? 0)
}
const labelOf = (nodeId: string) => {
const n = nodeById.get(nodeId)
return n && ['input', 'output', 'lamp', 'button', 'clock'].includes(n.kind) ? n.label?.trim() : undefined
}
// One input pin per distinct outside source, one output pin per distinct inside source.
const group = (wires: Wire[], dir: 'in' | 'out') => {
const map = new Map<string, { src: Wire['from']; wires: Wire[]; y: number }>()
for (const w of wires) {
const key = `${w.from.node}:${w.from.pin}`
const y = dir === 'in' ? pinY(w.to, 'in') : pinY(w.from, 'out')
const g = map.get(key)
if (g) {
g.wires.push(w)
g.y = Math.min(g.y, y)
} else map.set(key, { src: w.from, wires: [w], y })
}
return [...map.values()].sort((a, b) => a.y - b.y)
}
const ins = group(incoming, 'in')
const outs = group(outgoing, 'out')
const child: ComponentDef = { id: uid('c'), name: uniqueName(project, name.trim() || 'Part'), symbol: 'box', nodes: [], wires: [] }
for (const n of sel) child.nodes.push({ ...clone(n), x: n.x + ox, y: n.y + oy })
for (const w of internal) {
const copy = clone(w)
if (copy.pts) copy.pts = copy.pts.map(([x, y]) => [x + ox, y + oy])
child.wires.push(copy)
}
const used = new Set<string>()
const pinLabel = (preferred: string | undefined, fallback: string) => {
let label = preferred || fallback
for (let i = 2; used.has(label); i++) label = `${preferred || fallback}${i}`
used.add(label)
return label
}
let nextY = -Infinity
const inPins = ins.map((g, i) => {
const y = Math.max(nextY, g.y + oy)
nextY = y + 2
const node: CircuitNode = { id: uid('n'), kind: 'input', x: 0, y, label: pinLabel(labelOf(g.src.node), `I${i + 1}`) }
child.nodes.push(node)
for (const w of g.wires) child.wires.push({ id: uid('w'), from: { node: node.id, pin: 'q' }, to: w.to })
return { group: g, node }
})
nextY = -Infinity
const outPins = outs.map((g, i) => {
const y = Math.max(nextY, g.y + oy)
nextY = y + 2
const node: CircuitNode = { id: uid('n'), kind: 'output', x: maxX + ox + 4, y, label: pinLabel(labelOf(g.wires[0]!.to.node), `O${i + 1}`) }
child.nodes.push(node)
child.wires.push({ id: uid('w'), from: g.src, to: { node: node.id, pin: 'a' } })
return { group: g, node }
})
project.components.push(child)
// Replace the selection with one chip.
const chipNode: CircuitNode = { id: uid('n'), kind: 'chip', chip: child.id, x: minX, y: minY }
def.nodes = def.nodes.filter(n => !inside(n.id))
def.nodes.push(chipNode)
def.wires = def.wires.filter(w => !inside(w.from.node) && !inside(w.to.node))
for (const { group: g, node } of inPins) {
def.wires.push({ id: uid('w'), from: g.src, to: { node: chipNode.id, pin: node.id } })
}
for (const { group: g, node } of outPins) {
for (const w of g.wires) def.wires.push({ id: uid('w'), from: { node: chipNode.id, pin: node.id }, to: w.to })
}
return { ok: true, def: child, chipNode: chipNode.id }
}

110
app/lib/logic/sim.ts Normal file
View File

@ -0,0 +1,110 @@
// Event-driven NAND simulator. A changed net queues the gates that read it;
// gates run in FIFO order and see the newest values. That settles latches
// and flip-flops built from NANDs deterministically, while a loop with an
// odd number of inversions (a ring oscillator) never settles and shows as
// "oscillating".
import { HIGH, type Netlist } from './compile'
export interface SimCarry {
gates: Map<string, number>
clock: number
}
export class Simulator {
readonly nl: Netlist
readonly values: Uint8Array
private queue: Int32Array
private head = 0
private count = 0
private queued: Uint8Array
clock = 0
/** Increments on every net change, so views know when to redraw. */
changes = 0
constructor(nl: Netlist, carry?: SimCarry) {
this.nl = nl
this.values = new Uint8Array(nl.netCount)
this.values[HIGH] = 1
const gates = nl.gateOut.length
this.queue = new Int32Array(Math.max(1, gates))
this.queued = new Uint8Array(gates)
if (carry) {
for (let i = 0; i < gates; i++) {
const v = carry.gates.get(nl.gateKeys[i]!)
if (v !== undefined) this.values[nl.gateOut[i]!] = v
}
this.clock = carry.clock
for (const c of nl.clocks) this.values[c] = carry.clock
}
for (let i = 0; i < gates; i++) this.push(i)
}
private push(g: number) {
if (this.queued[g]) return
this.queued[g] = 1
this.queue[(this.head + this.count) % this.queue.length] = g
this.count++
}
get settled() {
return this.count === 0
}
get pending() {
return this.count
}
/** Drive a net from outside (switch, button, clock). */
set(net: number, v: number) {
if (net <= HIGH || this.values[net] === v) return
this.values[net] = v
this.changes++
const { fanStart, fanList } = this.nl
for (let j = fanStart[net]!; j < fanStart[net + 1]!; j++) this.push(fanList[j]!)
}
setSource(nodeId: string, on: boolean) {
const net = this.nl.sources.get(nodeId)
if (net !== undefined) this.set(net, on ? 1 : 0)
}
setClock(v: number) {
this.clock = v
for (const c of this.nl.clocks) this.set(c, v)
}
/** Evaluate up to `budget` gates. Returns true once nothing is left to do. */
run(budget = 1_000_000): boolean {
const { gateA, gateB, gateOut, fanStart, fanList } = this.nl
const values = this.values
const len = this.queue.length
while (this.count > 0 && budget-- > 0) {
const g = this.queue[this.head]!
this.head = (this.head + 1) % len
this.count--
this.queued[g] = 0
const v = (values[gateA[g]!]! & values[gateB[g]!]!) ^ 1
const out = gateOut[g]!
if (values[out] !== v) {
values[out] = v
this.changes++
for (let j = fanStart[out]!; j < fanStart[out + 1]!; j++) this.push(fanList[j]!)
}
}
return this.count === 0
}
/** Value at a root-circuit pin, 0 if unknown. */
pin(nodeId: string, pin: string): number {
const net = this.nl.pinNet.get(`${nodeId}:${pin}`)
return net === undefined ? 0 : this.values[net]!
}
carry(): SimCarry {
const gates = new Map<string, number>()
const { gateKeys, gateOut } = this.nl
for (let i = 0; i < gateKeys.length; i++) gates.set(gateKeys[i]!, this.values[gateOut[i]!]!)
return { gates, clock: this.clock }
}
}

50
app/lib/logic/storage.ts Normal file
View File

@ -0,0 +1,50 @@
// 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
}
}

76
app/lib/logic/types.ts Normal file
View File

@ -0,0 +1,76 @@
// Data model. Every circuit is a component: the "Main" circuit is just the
// one you happen to have open. NAND is the only logic primitive; everything
// else is built from it and placed as a chip.
export type BuiltinKind =
| 'nand' // the one logic primitive
| 'input' // circuit input pin; a switch when the circuit runs on its own
| 'output' // circuit output pin; a lamp when the circuit runs on its own
| 'high' // constant 1 (supply)
| 'low' // constant 0 (ground)
| 'button' // momentary push button
| 'clock' // square wave, shared global clock
| 'lamp' // indicator light
| 'hex' // 4-bit hex display
| 'note' // text annotation, no pins
export type NodeKind = BuiltinKind | 'chip'
export type SymbolKind = 'box' | 'and' | 'or' | 'xor' | 'not' | 'buf' | 'nand' | 'nor' | 'xnor'
export interface CircuitNode {
id: string
kind: NodeKind
/** Component id, only for kind 'chip'. */
chip?: string
/** Grid units. */
x: number
y: number
label?: string
/** Switch position for 'input' nodes. */
on?: boolean
}
export interface PinRef {
node: string
pin: string
}
export interface Wire {
id: string
/** Always an output pin. */
from: PinRef
/** Always an input pin. An input pin has at most one wire. */
to: PinRef
/** Corner points (grid units) between the two pins, set by dragging a segment. */
pts?: [number, number][]
}
export interface ComponentDef {
id: string
name: string
symbol: SymbolKind
description?: string
/** Palette section; empty means "My components". */
group?: string
nodes: CircuitNode[]
wires: Wire[]
/** Set when the component was started from a challenge. */
challenge?: string
}
export interface Settings {
/** IEC 60617 (DIN, rectangular) or ANSI (US, curved) gate symbols. */
symbols: 'iec' | 'ansi'
/** Animate current flow on wires carrying a 1. */
flow: boolean
}
export interface Project {
version: 1
components: ComponentDef[]
openId: string
settings: Settings
/** Challenge ids the user has passed. */
solved: string[]
}

31
app/pages/index.vue Normal file
View File

@ -0,0 +1,31 @@
<script setup lang="ts">
const ed = useEditor()
onMounted(() => {
const stop = ed.startLoop()
onBeforeUnmount(stop)
try {
if (!localStorage.getItem('logigate:help-seen')) ed.showHelp.value = true
} catch {}
})
</script>
<template>
<div class="app">
<EditorToolbar />
<div class="workspace">
<EditorPalette />
<main class="stage">
<EditorCanvas />
</main>
<EditorInspector />
</div>
<Transition name="fade">
<div v-if="ed.notice.value" class="toast" :class="ed.notice.value.kind">{{ ed.notice.value.text }}</div>
</Transition>
<div v-if="ed.placing.value" class="placing-hint">
Click on the canvas to place. <kbd>Shift</kbd> places several, <kbd>Esc</kbd> stops.
</div>
<EditorHelp v-if="ed.showHelp.value" />
</div>
</template>

112
deploy.sh Executable file
View File

@ -0,0 +1,112 @@
#!/bin/bash
set -e
SELF="$0"
COMPOSE_CMD=(docker compose -f docker-compose.yml)
# ── Parse arguments ──────────────────────────────────────────────────
FLAG=""
for arg in "$@"; do
case "$arg" in
--after-pull)
FLAG="$arg" ;;
*) ;;
esac
done
echo "==> Starting deploy script..."
# ── Self-update check (first run only) ───────────────────────────────
if [ "$FLAG" != "--after-pull" ]; then
echo "==> Checking for updates..."
ORIGINAL_HASH=$(md5sum "$SELF" | cut -d' ' -f1)
git pull --rebase --stat
UPDATED_HASH=$(md5sum "$SELF" | cut -d' ' -f1)
PASSTHROUGH_ARGS=("--after-pull")
if [ "$ORIGINAL_HASH" != "$UPDATED_HASH" ]; then
echo "==> Script updated — re-running..."
echo
"$SELF" "${PASSTHROUGH_ARGS[@]}"
exit $?
fi
echo "==> No script changes detected."
echo
"$SELF" "${PASSTHROUGH_ARGS[@]}"
exit $?
fi
echo "==> Running deployment steps..."
# ── Build + deploy ───────────────────────────────────────────────────
REPO_UID=$(stat -c '%u' . 2>/dev/null || id -u)
REPO_GID=$(stat -c '%g' . 2>/dev/null || id -g)
DEPLOY_UID=${DEPLOY_UID:-$REPO_UID}
DEPLOY_GID=${DEPLOY_GID:-$REPO_GID}
echo "==> Using production compose file only (docker-compose.yml)."
echo "==> Deployment user for build container: ${DEPLOY_UID}:${DEPLOY_GID}"
if [ ! -f .env ]; then
if [ -f .env.example ]; then
echo "==> .env missing — creating it from .env.example"
cp .env.example .env
else
echo "ERROR: Missing .env file and no .env.example available."
exit 1
fi
fi
echo "==> Preparing docker data directories..."
mkdir -p docker-data/node_modules
if [ "$(id -u)" -eq 0 ]; then
echo "==> Fixing ownership on writable directories (root mode)..."
chown -R "${DEPLOY_UID}:${DEPLOY_GID}" docker-data .output 2>/dev/null || true
else
echo "==> Skipping host chown (not root)."
fi
# Remove stale build output so we never accidentally serve an old build.
rm -rf .output
# Build/rebuild the builder and serve images (only rebuilds when Dockerfiles change).
"${COMPOSE_CMD[@]}" --profile build build
# Run the Nuxt build (installs deps + builds, writes .output to host).
# -T disables pseudo-TTY to prevent interactive prompts during deploy.
"${COMPOSE_CMD[@]}" --profile build run --rm -T -u "${DEPLOY_UID}:${DEPLOY_GID}" build
# Verify the build actually produced output.
if [ ! -f .output/server/index.mjs ]; then
echo "ERROR: Build did not produce .output/server/index.mjs — aborting deploy"
exit 1
fi
# Defense-in-depth: strip sourcemaps and sourcemap references from production artifacts.
echo "==> Hardening build output (strip sourcemaps)..."
find .output -type f -name '*.map' -delete
find .output -type f \( -name '*.js' -o -name '*.mjs' -o -name '*.css' \) \
-exec sed -i \
-e '/^[[:space:]]*\/\/# sourceMappingURL=.*$/d' \
-e '/^[[:space:]]*\/\*# sourceMappingURL=.*\*\/[[:space:]]*$/d' {} +
if find .output -type f -name '*.map' -print -quit | grep -q .; then
echo "ERROR: Sourcemap artifacts still present in .output — aborting deploy"
exit 1
fi
# (Re)start the SSR server with the fresh .output.
"${COMPOSE_CMD[@]}" up -d --force-recreate frontend
echo "==> Deployment complete!"

45
docker-compose.yml Normal file
View File

@ -0,0 +1,45 @@
services:
# One-shot build container. Bind-mounts the repo, runs pnpm install + build,
# writes .output to the host, then exits.
# Usage: docker compose --profile build run --rm build
build:
image: "logigate-build:latest"
build:
context: .
dockerfile: Dockerfile.build
volumes:
- .:/app
- ./docker-data/node_modules:/app/node_modules
env_file:
- .env
profiles:
- build
# Long-running server. Serves the pre-built .output from the host.
frontend:
image: "logigate-serve:latest"
container_name: logigate
build:
context: .
dockerfile: Dockerfile.serve
restart: unless-stopped
env_file:
- .env
volumes:
- ./.output:/app/.output:ro
labels:
traefik.enable: "true"
traefik.docker.network: "web"
# nginx on the host terminates TLS with the *.blax.at wildcard cert and
# forwards plain HTTP to traefik's `web` entrypoint. This router beats
# blax-nuxt-website's *.blax.at fallback router (priority -100).
traefik.http.routers.logigate.rule: "Host(`logicate.blax.at`) || Host(`logigate.blax.at`) || Host(`logigate.localhost.at`)"
traefik.http.routers.logigate.entrypoints: "web"
traefik.http.routers.logigate.service: "logigate-http"
traefik.http.services.logigate-http.loadbalancer.server.port: "3000"
networks:
default:
name: web
external: true
driver: bridge

76
nuxt.config.ts Normal file
View File

@ -0,0 +1,76 @@
import tailwindcss from '@tailwindcss/vite'
export default defineNuxtConfig({
compatibilityDate: '2025-05-01',
devtools: { enabled: false },
// The editor lives in the browser (canvas, localStorage), so no SSR.
ssr: false,
modules: ['@nuxt/fonts', '@nuxt/icon'],
fonts: {
families: [
{ name: 'Inter', weights: [400, 500, 600, 700], provider: 'google' },
{ name: 'JetBrains Mono', weights: [400, 600], provider: 'google' },
],
},
css: ['~/assets/css/main.css'],
vite: {
plugins: [tailwindcss()],
},
icon: {
serverBundle: { collections: ['lucide'] },
cssLayer: 'base',
clientBundle: { scan: true },
},
runtimeConfig: {
public: {
siteUrl: 'https://logicate.blax.at',
},
},
app: {
head: {
htmlAttrs: { lang: 'en' },
title: 'Logigate: build a computer from NAND gates',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
name: 'description',
content: 'Draw logic circuits, simulate them live, and package them into reusable components. Start with a NAND gate and work up to a computer.',
},
{ name: 'theme-color', content: '#0e1116' },
],
link: [{ rel: 'icon', type: 'image/svg+xml', href: '/favicon.svg' }],
},
},
routeRules: {
'/**': {
headers: {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()',
'Content-Security-Policy': [
"default-src 'self'",
"img-src 'self' data: blob:",
"font-src 'self' data:",
"style-src 'self' 'unsafe-inline'",
"script-src 'self' 'unsafe-inline'",
"connect-src 'self'",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
].join('; '),
'x-powered-by': '',
},
},
},
})

29
package.json Normal file
View File

@ -0,0 +1,29 @@
{
"name": "logigate",
"private": true,
"type": "module",
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"typecheck": "nuxt typecheck",
"test": "vitest run"
},
"packageManager": "pnpm@10.15.1",
"dependencies": {
"nuxt": "^4.6.2",
"vue": "^3.5.44",
"vue-router": "^5.4.0"
},
"devDependencies": {
"@iconify-json/lucide": "^1.2.145",
"@nuxt/fonts": "^1.0.1",
"@nuxt/icon": "^2.5.1",
"@tailwindcss/vite": "^4.3.3",
"tailwindcss": "^4.3.3",
"typescript": "^5.9.3",
"vitest": "^5.0.5",
"vue-tsc": "^3.3.13"
}
}

6974
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

5
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,5 @@
# pnpm only runs install scripts for packages listed here.
# esbuild downloads its platform binary in a postinstall step.
onlyBuiltDependencies:
- esbuild
- '@parcel/watcher'

1
public/favicon.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#0e1116"/><path d="M6 8h9a8 8 0 0 1 0 16H6Z" fill="none" stroke="#3ddc84" stroke-width="2.5"/><circle cx="26" cy="16" r="2.4" fill="none" stroke="#3ddc84" stroke-width="2.2"/></svg>

After

Width:  |  Height:  |  Size: 284 B

2
public/robots.txt Normal file
View File

@ -0,0 +1,2 @@
User-agent: *
Allow: /

165
tests/logic.test.ts Normal file
View File

@ -0,0 +1,165 @@
import { describe, expect, it } from 'vitest'
import { runSteps, stats, truthTable } from '../app/lib/logic/analyze'
import { CHALLENGES, challengeSteps } from '../app/lib/logic/challenges'
import { compile } from '../app/lib/logic/compile'
import { chipPins } from '../app/lib/logic/geometry'
import { containsDef, createProject, lookup, packageSelection, placeable, pruneWires } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
import type { Project } from '../app/lib/logic/types'
const project = (): Project => createProject({ examples: true })
const solvedBy: Record<string, string> = {
not: 'ex-not', and: 'ex-and', or: 'ex-or', nor: 'ex-nor', xor: 'ex-xor', xnor: 'ex-xnor',
mux: 'ex-mux', ha: 'ex-ha', fa: 'ex-fa', sr: 'ex-sr', dlatch: 'ex-dlatch', dff: 'ex-dff',
}
describe('example library built from NAND', () => {
const p = project()
const get = lookup(p)
for (const [challenge, defId] of Object.entries(solvedBy)) {
it(`${defId} passes the ${challenge} challenge`, () => {
const c = CHALLENGES.find(c => c.id === challenge)!
const res = runSteps(get, defId, challengeSteps(c))
expect(res.message).toMatch(/pass/)
expect(res.pass).toBe(true)
})
}
it('compiles every example without errors', () => {
for (const d of p.components) expect(compile(get, d.id).errors, d.name).toEqual([])
})
it('Adder 4 adds all 512 input combinations', () => {
const t = truthTable(get, 'ex-add4')
if ('error' in t) throw new Error(t.error)
expect(t.inputs).toEqual(['A0', 'A1', 'A2', 'A3', 'B0', 'B1', 'B2', 'B3', 'Cin'])
expect(t.outputs).toEqual(['S0', 'S1', 'S2', 'S3', 'Cout'])
expect(t.rows).toHaveLength(512)
for (const r of t.rows) {
const num = (bits: number[]) => bits.reduce((n, b, i) => n + (b << i), 0)
const sum = num(r.ins.slice(0, 4)) + num(r.ins.slice(4, 8)) + r.ins[8]!
expect(num(r.outs)).toBe(sum)
}
})
it('Increment 4 adds one', () => {
const t = truthTable(get, 'ex-inc4')
if ('error' in t) throw new Error(t.error)
for (const r of t.rows) {
const num = (bits: number[]) => bits.reduce((n, b, i) => n + (b << i), 0)
expect(num(r.outs)).toBe(num(r.ins) + 1)
}
})
it('Counter 4 starts at 0, resets, counts clock edges and wraps at 16', () => {
const def = get('ex-cnt4')!
const pins = chipPins(def)
const sim = new Simulator(compile(get, 'ex-cnt4'))
sim.run()
const set = (label: string, v: number) => {
sim.setSource(pins.inputs.find(p => p.label === label)!.key, v === 1)
expect(sim.run()).toBe(true)
}
const value = () => pins.outputs.reduce((n, p, i) => n + (sim.pin(p.key, 'a') << i), 0)
const tick = () => {
set('CLK', 1)
set('CLK', 0)
}
expect(value()).toBe(0)
set('RST', 1)
tick()
expect(value()).toBe(0)
set('RST', 0)
for (let i = 1; i <= 20; i++) {
tick()
expect(value()).toBe(i % 16)
}
})
it('reports NAND count, delay and memory', () => {
expect(stats(compile(get, 'ex-not'))).toEqual({ nands: 1, sequential: false, delay: 1 })
expect(stats(compile(get, 'ex-xor'))).toEqual({ nands: 4, sequential: false, delay: 3 })
expect(stats(compile(get, 'ex-fa')).nands).toBe(15)
expect(stats(compile(get, 'ex-dff')).sequential).toBe(true)
})
})
describe('simulator', () => {
it('a NOT wired to itself oscillates and never settles', () => {
const p = project()
p.components.push({
id: 'ring', name: 'Ring', symbol: 'box',
nodes: [{ id: 'g', kind: 'chip', chip: 'ex-not', x: 0, y: 0 }],
wires: [],
})
const pin = chipPins(lookup(p)('ex-not')!)
p.components.at(-1)!.wires.push({ id: 'w', from: { node: 'g', pin: pin.outputs[0]!.key }, to: { node: 'g', pin: pin.inputs[0]!.key } })
const sim = new Simulator(compile(lookup(p), 'ring'))
expect(sim.run(10_000)).toBe(false)
})
it('keeps latch state across a recompile', () => {
const p = project()
const get = lookup(p)
const pins = chipPins(get('ex-sr')!)
const key = (l: string) => pins.inputs.find(p => p.label === l)!.key
const sim = new Simulator(compile(get, 'ex-sr'))
sim.run()
sim.setSource(key('R'), true)
sim.run()
sim.setSource(key('R'), false)
sim.setSource(key('S'), true)
sim.run()
sim.setSource(key('S'), false)
sim.run()
const q = pins.outputs[0]!.key
expect(sim.pin(q, 'a')).toBe(1)
const again = new Simulator(compile(get, 'ex-sr'), sim.carry())
again.run()
expect(again.pin(q, 'a')).toBe(1)
})
})
describe('project operations', () => {
it('packages a selection into a new component without changing behaviour', () => {
const p = project()
const xor = p.components.find(d => d.id === 'ex-xor')!
const nands = new Set(xor.nodes.filter(n => n.kind === 'nand').map(n => n.id))
const res = packageSelection(p, 'ex-xor', nands, 'Core')
if (!res.ok) throw new Error(res.error)
expect(xor.nodes.filter(n => n.kind === 'nand')).toHaveLength(0)
const pins = chipPins(res.def)
expect(pins.inputs.map(p => p.label)).toEqual(['A', 'B'])
expect(pins.outputs.map(p => p.label)).toEqual(['Q'])
const xorChallenge = CHALLENGES.find(c => c.id === 'xor')!
expect(runSteps(lookup(p), 'ex-xor', challengeSteps(xorChallenge)).pass).toBe(true)
expect(runSteps(lookup(p), res.def.id, challengeSteps(xorChallenge)).pass).toBe(true)
})
it('refuses to package the circuit’s own pins', () => {
const p = project()
const not = p.components.find(d => d.id === 'ex-not')!
const res = packageSelection(p, 'ex-not', new Set(not.nodes.map(n => n.id)), 'X')
expect(res.ok).toBe(false)
})
it('drops wires to pins that were removed from a component', () => {
const p = project()
const not = p.components.find(d => d.id === 'ex-not')!
const before = p.components.find(d => d.id === 'ex-and')!.wires.length
not.nodes = not.nodes.filter(n => n.kind !== 'output')
expect(pruneWires(p)).toBe(true)
expect(p.components.find(d => d.id === 'ex-and')!.wires.length).toBe(before - 1)
})
it('never lets a component contain itself', () => {
const p = project()
expect(containsDef(p, 'ex-and', 'ex-not')).toBe(true)
const ids = placeable(p, 'ex-not').map(d => d.id)
expect(ids).not.toContain('ex-not')
expect(ids).not.toContain('ex-and')
expect(ids).toContain('main')
})
})

1
tsconfig.json Normal file
View File

@ -0,0 +1 @@
{ "extends": "./.nuxt/tsconfig.json" }

5
vitest.config.ts Normal file
View File

@ -0,0 +1,5 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: { include: ['tests/**/*.test.ts'] },
})