import { describe, expect, it } from 'vitest' import { tableCsv, tableMarkdown, truthTable } from '../app/lib/logic/analyze' import { compile, rowSource } from '../app/lib/logic/compile' import { chipPins, shapeOf } from '../app/lib/logic/geometry' import { adoptName, continueSeries, newPinLabel, nextInSeries } from '../app/lib/logic/labels' import { copySelection, createProject, lookup, pasteClip, pruneWires } from '../app/lib/logic/ops' import { attachPanel, removeRow, syncPanels } from '../app/lib/logic/panels' import { toProject } from '../app/lib/logic/project' import { circuitRoutes, findCrossings, type Routed } from '../app/lib/logic/routing' import { Simulator } from '../app/lib/logic/sim' import type { CircuitNode, ComponentDef, Project, Wire } from '../app/lib/logic/types' /** A 3-input AND (A, B, Cin → Q) placed once in a root circuit. */ function andProject(): { p: Project; root: ComponentDef; part: ComponentDef } { const p = createProject({ examples: false }) const part: ComponentDef = { id: 'and3', name: 'AND3', symbol: 'box', nodes: [ { id: 'a', kind: 'input', x: 0, y: 0, label: 'A' }, { id: 'b', kind: 'input', x: 0, y: 2, label: 'B' }, { id: 'c', kind: 'input', x: 0, y: 4, label: 'Cin' }, { id: 'n1', kind: 'nand', x: 4, y: 0 }, { id: 'n2', kind: 'nand', x: 8, y: 0 }, { id: 'n3', kind: 'nand', x: 12, y: 2 }, { id: 'n4', kind: 'nand', x: 16, y: 2 }, { id: 'q', kind: 'output', x: 20, y: 2, label: 'Q' }, ], wires: [ // n2 = AND(A, B), n4 = AND(n2, Cin) { id: 'w1', from: { node: 'a', pin: 'q' }, to: { node: 'n1', pin: 'a' } }, { id: 'w2', from: { node: 'b', pin: 'q' }, to: { node: 'n1', pin: 'b' } }, { id: 'w3', from: { node: 'n1', pin: 'q' }, to: { node: 'n2', pin: 'a' } }, { id: 'w4', from: { node: 'n1', pin: 'q' }, to: { node: 'n2', pin: 'b' } }, { id: 'w5', from: { node: 'n2', pin: 'q' }, to: { node: 'n3', pin: 'a' } }, { id: 'w6', from: { node: 'c', pin: 'q' }, to: { node: 'n3', pin: 'b' } }, { id: 'w7', from: { node: 'n3', pin: 'q' }, to: { node: 'n4', pin: 'a' } }, { id: 'w8', from: { node: 'n3', pin: 'q' }, to: { node: 'n4', pin: 'b' } }, { id: 'w9', from: { node: 'n4', pin: 'q' }, to: { node: 'q', pin: 'a' } }, ], } const root: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [{ id: 'u', kind: 'chip', chip: 'and3', x: 20, y: 0 }], wires: [] } p.components.push(part, root) p.openId = 'root' return { p, root, part } } describe('series names', () => { it('continues numbers and letters', () => { expect(nextInSeries('D0', new Set(['D0']))).toBe('D1') expect(nextInSeries('D0', new Set(['D0', 'D1', 'D2']))).toBe('D3') expect(nextInSeries('D07', new Set())).toBe('D08') expect(nextInSeries('A', new Set(['A', 'B']))).toBe('C') expect(nextInSeries('Carry', new Set())).toBeNull() }) it('renames pasted parts so D0..D3 copied become D4..D7', () => { const def: ComponentDef = { id: 'x', name: 'X', symbol: 'box', nodes: [0, 1, 2, 3].map(i => ({ id: `d${i}`, kind: 'input' as const, x: 0, y: i * 2, label: `D${i}` })), wires: [], } const clip = copySelection(def, new Set(def.nodes.map(n => n.id))) const ids = new Set(pasteClip(def, clip, 4, 0)) continueSeries(def, def.nodes.filter(n => ids.has(n.id))) expect(def.nodes.filter(n => ids.has(n.id)).map(n => n.label)).toEqual(['D4', 'D5', 'D6', 'D7']) }) it('keeps names without a series, and treats inputs and outputs apart', () => { const def: ComponentDef = { id: 'x', name: 'X', symbol: 'box', nodes: [ { id: 'i', kind: 'input', x: 0, y: 0, label: 'D0' }, { id: 'l', kind: 'lamp', x: 9, y: 0, label: 'Busy' }, ], wires: [], } const clip = copySelection(def, new Set(['l'])) const ids = new Set(pasteClip(def, clip, 0, 2)) continueSeries(def, def.nodes.filter(n => ids.has(n.id))) expect(def.nodes.at(-1)!.label).toBe('Busy') def.nodes.push({ id: 'o', kind: 'output', x: 9, y: 4, label: 'D0' }) expect(newPinLabel(def, 'output')).toBe('D1') expect(newPinLabel(def, 'input')).toBe('D1') }) }) describe('names from connections', () => { const wire = (def: ComponentDef, from: [string, string], to: [string, string]) => { const w: Wire = { id: `w${def.wires.length}`, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } } def.wires.push(w) return w } it('an unnamed switch takes the name of the component pin it feeds', () => { const { p, root } = andProject() const s: CircuitNode = { id: 's', kind: 'input', x: 0, y: 4 } root.nodes.push(s) wire(root, ['s', 'q'], ['u', 'c']) expect(adoptName(root, s, 'q', root.nodes[0]!, 'c', lookup(p))).toBe(true) expect(s.label).toBe('Cin') expect(s.autoLabel).toBe(true) }) it('a hand-given name stays, and a second connection does not rename', () => { const { p, root } = andProject() const own: CircuitNode = { id: 's', kind: 'input', x: 0, y: 0, label: 'Mine' } const auto: CircuitNode = { id: 't', kind: 'input', x: 0, y: 2, label: 'C', autoLabel: true } root.nodes.push(own, auto) const chip = root.nodes[0]! wire(root, ['s', 'q'], ['u', 'a']) expect(adoptName(root, own, 'q', chip, 'a', lookup(p))).toBe(false) expect(own.label).toBe('Mine') wire(root, ['t', 'q'], ['u', 'b']) expect(adoptName(root, auto, 'q', chip, 'b', lookup(p))).toBe(true) wire(root, ['t', 'q'], ['u', 'c']) expect(adoptName(root, auto, 'q', chip, 'c', lookup(p))).toBe(false) expect(auto.label).toBe('B') }) it('an output pin takes the name of the component output feeding it, made unique', () => { const { p, root } = andProject() const o1: CircuitNode = { id: 'o1', kind: 'output', x: 40, y: 0, label: 'Q', autoLabel: true } const o2: CircuitNode = { id: 'o2', kind: 'output', x: 40, y: 2, autoLabel: true } root.nodes.push(o1, o2) root.nodes.push({ id: 'u2', kind: 'chip', chip: 'and3', x: 20, y: 10 }) wire(root, ['u', 'q'], ['o1', 'a']) wire(root, ['u2', 'q'], ['o2', 'a']) adoptName(root, o1, 'a', root.nodes[0]!, 'q', lookup(p)) adoptName(root, o2, 'a', root.nodes.at(-1)!, 'q', lookup(p)) expect(o2.label).toBe('Q2') }) }) describe('input panels', () => { const run = (p: Project, root: ComponentDef, set: (s: Simulator) => void) => { const s = new Simulator(compile(lookup(p), root.id)) set(s) s.run() return s.pin('u', 'q') } it('attaches a switch per input, lined up with the pins, that drives the component', () => { const { p, root } = andProject() const panel = attachPanel(p, root, 'u')! expect(panel.rows!.map(r => r.name)).toEqual(['A', 'B', 'Cin']) const chipShape = shapeOf(root.nodes[0]!, lookup(p)) const panelShape = shapeOf(panel, lookup(p)) panelShape.outputs.forEach((o, i) => expect(panel.y + o.dy).toBe(root.nodes[0]!.y + chipShape.inputs[i]!.dy)) expect(panel.x + panelShape.body.w).toBeLessThan(root.nodes[0]!.x) expect(run(p, root, () => {})).toBe(0) expect(run(p, root, s => ['a', 'b', 'c'].forEach(k => s.setSource(rowSource(panel.id, k), true)))).toBe(1) }) it('leaves wired inputs alone and follows the component when it gains or loses pins', () => { const { p, root, part } = andProject() root.nodes.push({ id: 'k', kind: 'high', x: 0, y: 0 }) root.wires.push({ id: 'wk', from: { node: 'k', pin: 'q' }, to: { node: 'u', pin: 'a' } }) const panel = attachPanel(p, root, 'u')! expect(panel.rows!.map(r => r.id)).toEqual(['b', 'c']) expect(panel.skip).toEqual(['a']) part.nodes.push({ id: 'd', kind: 'input', x: 0, y: 6, label: 'En' }) syncPanels(p) expect(panel.rows!.map(r => r.name)).toEqual(['B', 'Cin', 'En']) expect(root.wires.some(w => w.from.node === panel.id && w.to.pin === 'd')).toBe(true) part.nodes = part.nodes.filter(n => n.id !== 'b') syncPanels(p) pruneWires(p) expect(panel.rows!.map(r => r.id)).toEqual(['c', 'd']) expect(root.wires.some(w => w.from.node === panel.id && w.from.pin === 'b')).toBe(false) // A removed row is not brought back. removeRow(root, panel, 'd') syncPanels(p) expect(panel.rows!.map(r => r.id)).toEqual(['c']) }) it('undocks when its component is deleted, and copies dock to the copied component', () => { const { p, root } = andProject() const panel = attachPanel(p, root, 'u')! const clip = copySelection(root, new Set(['u', panel.id])) const ids = pasteClip(root, clip, 0, 10) const copy = root.nodes.find(n => ids.includes(n.id) && n.kind === 'panel')! const chip = root.nodes.find(n => ids.includes(n.id) && n.kind === 'chip')! expect(copy.attach).toBe(chip.id) root.nodes = root.nodes.filter(n => n.id !== 'u') syncPanels(p) expect(panel.attach).toBeUndefined() }) it('inside a component its switch rows are input pins, a clock row is a clock; kept inside, a switch keeps its position', () => { const p = createProject({ examples: false }) const inner: ComponentDef = { id: 'inner', name: 'Inner', symbol: 'box', nodes: [ { id: 'pn', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r1', type: 'switch', on: true, label: 'EN' }, { id: 'r2', type: 'clock' }] }, { id: 'q', kind: 'output', x: 10, y: 0, label: 'Q' }, ], wires: [{ id: 'w', from: { node: 'pn', pin: 'r1' }, to: { node: 'q', pin: 'a' } }], } const root: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [ { id: 'sw', kind: 'input', x: -6, y: 0 }, { id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 }, ], wires: [{ id: 'x', from: { node: 'sw', pin: 'q' }, to: { node: 'u', pin: 'pn:r1' } }], } p.components.push(inner, root) expect(chipPins(inner).inputs).toEqual([{ key: 'pn:r1', label: 'EN' }]) const nl = compile(lookup(p), 'root') expect(nl.clocks.length).toBe(1) const s = new Simulator(nl) s.run() expect(s.pin('u', 'q')).toBe(0) s.setSource('sw', true) s.run() expect(s.pin('u', 'q')).toBe(1) // Kept inside: no pin, and the switch stays as it was set. inner.nodes[0]!.inner = true expect(chipPins(inner).inputs).toEqual([]) const kept = new Simulator(compile(lookup(p), 'root')) kept.run() expect(kept.pin('u', 'q')).toBe(1) }) it('survives a round trip through project validation, and bad rows are dropped', () => { const { p, root } = andProject() attachPanel(p, root, 'u') const data = JSON.parse(JSON.stringify(p)) const panel = (data.components as ComponentDef[]).find(d => d.id === 'root')!.nodes.find(n => n.kind === 'panel')! ;(panel.rows as unknown[]).push({ id: 5 }, { id: 'ok', type: 'laser', hz: -1 }) const back = toProject(data) const rows = back.components.find(d => d.id === 'root')!.nodes.find(n => n.kind === 'panel')!.rows! expect(rows.map(r => r.id)).toEqual(['a', 'b', 'c', 'ok']) expect(rows.at(-1)).toEqual({ id: 'ok', type: 'switch' }) }) }) describe('truth table export', () => { it('writes CSV and Markdown', () => { const { p } = andProject() const t = truthTable(lookup(p), 'and3') if ('error' in t) throw new Error(t.error) const csv = tableCsv(t).trim().split('\n') expect(csv[0]).toBe('A,B,Cin,Q') expect(csv).toHaveLength(9) expect(csv.at(-1)).toBe('1,1,1,1') const md = tableMarkdown(t).trim().split('\n') expect(md[0]).toBe('| A | B | Cin | Q |') expect(md[1]).toBe('|:-:|:-:|:-:|:-:|') expect(md).toHaveLength(10) }) }) describe('tidy wiring', () => { /** Eight switches at scattered heights fanned into two 4-input parts. */ function fan(): ComponentDef { const nodes: CircuitNode[] = [] const wires: Wire[] = [] const ys = [0, 9, 3, 12, 6, 15, 1, 10] ys.forEach((y, i) => nodes.push({ id: `s${i}`, kind: 'input', x: 0, y, label: `S${i}` })) nodes.push({ id: 'u', kind: 'chip', chip: 'four', x: 20, y: 2 }, { id: 'v', kind: 'chip', chip: 'four', x: 20, y: 9 }) ys.forEach((_, i) => wires.push({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: i < 4 ? 'u' : 'v', pin: `i${i % 4}` } })) // S0 also feeds the second part, so its net branches. wires.push({ id: 'wx', from: { node: 's0', pin: 'q' }, to: { node: 'v', pin: 'i0' } }) return { id: 'root', name: 'Root', symbol: 'box', nodes, wires: wires.filter(w => w.id !== 'w4') } } const four: ComponentDef = { id: 'four', name: 'Four', symbol: 'box', nodes: [...[0, 1, 2, 3].map(i => ({ id: `i${i}`, kind: 'input' as const, x: 0, y: i, label: `I${i}` })), { id: 'o', kind: 'output', x: 6, y: 0, label: 'O' }], wires: [], } const get = (id: string) => (id === 'four' ? four : undefined) const shapesOf = (def: ComponentDef) => new Map(def.nodes.map(n => [n.id, shapeOf(n, get)])) /** Lengths of vertical runs that two different signals share. */ function sharedVerticals(routes: Routed[]): number { const cols = new Map() let shared = 0 for (const r of routes) { for (let i = 0; i < r.grid.length - 1; i++) { const [ax, ay] = r.grid[i]! const [bx, by] = r.grid[i + 1]! if (ax !== bx || ay === by) continue const seg = { lo: Math.min(ay, by), hi: Math.max(ay, by), net: r.net } for (const o of cols.get(ax) ?? []) if (o.net !== seg.net) shared += Math.max(0, Math.min(o.hi, seg.hi) - Math.max(o.lo, seg.lo)) cols.set(ax, [...(cols.get(ax) ?? []), seg]) } } return shared } it('gives every signal its own column and crosses less than the usual routing', () => { const def = fan() const shapes = shapesOf(def) const usual = circuitRoutes(def, shapes) const tidy = circuitRoutes(def, shapes, { tidy: true }) expect(sharedVerticals(tidy)).toBe(0) expect(findCrossings(tidy).length).toBeLessThanOrEqual(findCrossings(usual).length) // Wires of one signal into the same gap share one trunk. const s0 = tidy.filter(r => r.net === 's0:q') expect(s0).toHaveLength(2) }) it('keeps every route on the grid from pin to pin, and leaves hand-placed bends alone', () => { const def = fan() def.wires[0]!.pts = [[5, 0], [5, 2]] const shapes = shapesOf(def) const tidy = circuitRoutes(def, shapes, { tidy: true }) const nodes = new Map(def.nodes.map(n => [n.id, n])) for (const r of tidy) { const w = def.wires.find(x => x.id === r.id)! const from = nodes.get(w.from.node)! const to = nodes.get(w.to.node)! const a = shapes.get(from.id)!.outputs[0]! const b = shapes.get(to.id)!.inputs.find(p => p.key === w.to.pin)! expect(r.grid[0]).toEqual([from.x + a.dx, from.y + a.dy]) expect(r.grid.at(-1)).toEqual([to.x + b.dx, to.y + b.dy]) for (let i = 0; i < r.grid.length - 1; i++) { const [ax, ay] = r.grid[i]! const [bx, by] = r.grid[i + 1]! expect(ax === bx || ay === by).toBe(true) } } expect(tidy.find(r => r.id === 'w0')!.grid).toEqual([[2, 0], [5, 0], [5, 2], [20, 2]]) }) it('does not run through a part that stands in the way', () => { const def = fan() def.nodes.push({ id: 'blk', kind: 'nand', x: 8, y: 4 }) const shapes = shapesOf(def) const b = shapes.get('blk')!.body const box = { x0: 8 + b.x + 0.2, x1: 8 + b.x + b.w - 0.2, y0: 4 + b.y + 0.2, y1: 4 + b.y + b.h - 0.2 } const tidy = circuitRoutes(def, shapes, { tidy: true }) expect(tidy).toHaveLength(def.wires.length) for (const r of tidy) { for (let i = 0; i < r.grid.length - 1; i++) { const [ax, ay] = r.grid[i]! const [bx, by] = r.grid[i + 1]! const through = ay === by ? ay > box.y0 && ay < box.y1 && Math.max(ax, bx) > box.x0 && Math.min(ax, bx) < box.x1 : ax > box.x0 && ax < box.x1 && Math.max(ay, by) > box.y0 && Math.min(ay, by) < box.y1 expect(through, `${r.id} segment ${i}`).toBe(false) } } expect(chipPins(four).inputs).toHaveLength(4) }) })