logigate/tests/panels.test.ts

76 lines
3.1 KiB
TypeScript
Raw Normal View History

import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { chipPins, panelOffsets } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { mergePanels } from '../app/lib/logic/panels'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
describe('merging input panels', () => {
it('rows of the lower panel follow below, with their wires, as one panel', () => {
const def: ComponentDef = {
id: 'd',
name: 'D',
symbol: 'box',
nodes: [
{ id: 'p2', kind: 'panel', x: 0, y: 10, rows: [{ id: 'r1', type: 'switch', label: 'B0' }, { id: 'r2', type: 'button', label: 'B1', dy: 2 }] },
{ id: 'p1', kind: 'panel', x: 0, y: 0, attach: 'x', rows: [{ id: 'r1', type: 'switch', label: 'A0' }] },
{ id: 'l', kind: 'lamp', x: 10, y: 0 },
{ id: 'm', kind: 'lamp', x: 10, y: 4 },
],
wires: [
{ id: 'w1', from: { node: 'p1', pin: 'r1' }, to: { node: 'l', pin: 'a' } },
{ id: 'w2', from: { node: 'p2', pin: 'r2' }, to: { node: 'm', pin: 'a' } },
],
}
const res = mergePanels(def, ['p1', 'p2'])!
expect(res.panel.id).toBe('p1')
expect(def.nodes.some(n => n.id === 'p2')).toBe(false)
expect(res.panel.attach).toBeUndefined()
const rows = res.panel.rows!
expect(rows.map(r => r.label)).toEqual(['A0', 'B0', 'B1'])
// Spacing kept: B1 was two rows under B0.
expect(panelOffsets(rows)).toEqual([0, 1, 3])
// The wire from B1 now leaves the merged panel; the clashing row id got a new one.
const w2 = def.wires.find(w => w.id === 'w2')!
expect(w2.from.node).toBe('p1')
expect(rows.find(r => r.label === 'B1')!.id).toBe(w2.from.pin)
expect(new Set(rows.map(r => r.id)).size).toBe(3)
expect(res.renamed.get('p2:r2')).toBe(`p1:${w2.from.pin}`)
})
it('a merged panel inside a component gives one pin per row, in order', () => {
const p = createProject({ examples: false })
const inner: ComponentDef = {
id: 'inner',
name: 'Inner',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r', type: 'switch', label: 'X' }] },
{ id: 'b', kind: 'panel', x: 0, y: 5, rows: [{ id: 'r', type: 'switch', label: 'Y' }] },
{ id: 'q', kind: 'output', x: 10, y: 5, label: 'Q' },
],
wires: [{ id: 'w', from: { node: 'b', pin: 'r' }, to: { node: 'q', pin: 'a' } }],
}
p.components.push(inner)
mergePanels(inner, ['a', 'b'])
const pins = chipPins(inner).inputs
expect(pins.map(x => x.label)).toEqual(['X', 'Y'])
const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: -5, y: 0 },
{ id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 },
],
wires: [{ id: 'x', from: { node: 's', pin: 'q' }, to: { node: 'u', pin: pins[1]!.key } }],
}
p.components.push(root)
const sim = new Simulator(compile(lookup(p), 'root'))
sim.setSource('s', true)
sim.run()
expect(sim.pin('u', 'q')).toBe(1)
})
})