Merge branch 'feat/ports'

This commit is contained in:
Fabian @ Blax Software 2026-10-26 18:54:28 +01:00
commit 313f1849f4
18 changed files with 742 additions and 74 deletions

View File

@ -15,7 +15,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
- Connectors (your own HDMI, RJ45, buses): in the bottom bar's Connectors, "New connector type" makes one: a name, a colour, and lines that each run out → in or back (acknowledge, hot-plug, a receive pair). Each type gives two parts, "<type> out" and "<type> in". Inside a component, a port shows its lines as pins on its inner side (lines coming in are outputs, lines going out inputs) and has a cable pin at the top to hand the whole cable on to a part inside; on the component's box it is one port, in ports on the left, out ports on the right, drawn as a socket in the type's colour. One cable joins an out port to an in port of the same type and carries every line, forward and back; it is drawn as a sleeve in the type's colour with its name. Ports of different types never join, and a cable whose ends stop matching (a port changed type) is removed. Editing a type changes every port and cable of it; lines are matched by their place in the list. A type can only be deleted once no port uses it.
- Connectors (your own HDMI, RJ45, buses): in the bottom bar's Connectors, "New connector type" makes one: a name, a colour, and lines that each run out → in or back (acknowledge, hot-plug, a receive pair). Each type gives two parts, "<type> out" and "<type> in". Inside a component, a port shows its lines as pins on its inner side (lines coming in are outputs, lines going out inputs) and has a cable pin at the top to hand the whole cable on to a part inside; on the component's box it is one port at the very top of its side, in ports on the left, out ports on the right, drawn as a socket in the type's colour. "Split … into lines" (selection panel or right click on the component) gives that box a pin per line right below the socket, named after the line, to wire lines by hand without an adapter: lines going into the component are inputs, lines coming out outputs, and a cable still plugs into the socket. Dropping a single wire on a socket does the same and takes the first free line (with a cable in the socket, only a line coming out: the cable feeds the others). "Join … lines" takes the line pins and their wires away again. One cable joins an out port to an in port of the same type and carries every line, forward and back; it is drawn as a sleeve in the type's colour with its name. Ports of different types never join, and a cable whose ends stop matching (a port changed type) is removed. Editing a type changes every port and cable of it; lines are matched by their place in the list. A type can only be deleted once no port uses it.
- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen".
- Input panel: one part with a column of controls; each row is a switch, button or clock. "Attach input panel" on a placed component docks one to its left with a row per free input, lined up with the pins and named after them. A docked panel moves with its component, gets a row when the component gains an input and loses it when the pin goes; inputs that are wired elsewhere, and rows you remove, are left alone. Inside a component a switch row keeps its position and a button row is 0.
- Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. On the canvas, a switch, button, clock, lamp or output pin without a name typed by hand shows the name of the component pin it is wired to, dimmed and in italics (or its automatic name, also dimmed); the name follows the wiring as it changes.

View File

@ -4347,6 +4347,15 @@ table.board {
pointer-events: none;
}
/* A port split on a component's box: its lines hang off the socket. */
.port-bar {
fill: none;
stroke-width: 2;
stroke-linecap: round;
opacity: 0.8;
pointer-events: none;
}
.wire.port-cable .cable-sleeve {
stroke: var(--w-on, #8592a3);
opacity: 0.9;

View File

@ -1,5 +1,5 @@
<script setup lang="ts">
import { cableKeys, INVERTIBLE } from '~/lib/logic/compile'
import { cableKeys } from '~/lib/logic/compile'
import { CHECKED_INPUTS } from '~/lib/logic/check'
import { cableBits, GRID as G, pinKindOf, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
@ -14,6 +14,7 @@ import { wirePath, type HopSpan } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
import { inputCount } from '~/lib/logic/wide'
import { pinName } from '~/lib/logic/labels'
import { lineForWire } from '~/lib/logic/ops'
const ed = useEditor()
const root = ref<HTMLDivElement>()
@ -550,8 +551,9 @@ function onPointerDown(e: PointerEvent) {
const link = ed.linking.value
const end = link?.queue[link.at]
if (end) {
// Connecting: a click on a pin or a part wires the current pin there.
const target = targetAt(w, end.dir === 'out' ? 'in' : 'out', ed.pinKind(end.node, end.pin, end.dir))
// Connecting: a click on a pin or a part wires the current pin there (on a port's socket, to one of its lines).
const socket = socketAt({ ...end, cur: w })
const target = socket ? ed.lineAt(end.dir, socket.node, socket.port) : targetAt(w, end.dir === 'out' ? 'in' : 'out', ed.pinKind(end.node, end.pin, end.dir))
if (target) return ed.linkTo(target, e.shiftKey)
const pinEl = (e.target as Element).closest('[data-pin]')
if (pinEl && link.queue.length === 1) {
@ -604,7 +606,7 @@ function onPointerDown(e: PointerEvent) {
if (pinEl && e.altKey && pinEl.getAttribute('data-dir') === 'in') {
// Alt + click on an input: invert it (a bubble), or take the bubble off.
const n = nodeMap.value.get(pinEl.getAttribute('data-node')!)
if (n && INVERTIBLE.has(n.kind)) return ed.toggleInvert(n, pinEl.getAttribute('data-pin')!)
if (n && ed.canInvert(n, pinEl.getAttribute('data-pin')!)) return ed.toggleInvert(n, pinEl.getAttribute('data-pin')!)
}
if (pinEl) {
drag.value = {
@ -843,7 +845,9 @@ const openPins = computed(() => {
const out = new Map<string, Set<string>>()
for (const n of def.value.nodes) {
if (!CHECKED_INPUTS.has(n.kind)) continue
const open = shapes.value.get(n.id)!.inputs.filter(p => !p.bus && !linked.value.in.has(`${n.id}:${p.key}`)).map(p => p.key)
// A line of a split port is fed by the cable when one is in its socket.
const cabled = (port: string) => linked.value.in.has(`${n.id}:${port}`) || linked.value.out.has(`${n.id}:${port}`)
const open = shapes.value.get(n.id)!.inputs.filter(p => !p.bus && !(p.port && cabled(p.port)) && !linked.value.in.has(`${n.id}:${p.key}`)).map(p => p.key)
if (open.length) out.set(n.id, new Set(open))
}
return out
@ -904,6 +908,32 @@ function targetAt(at: Pt, dir: 'in' | 'out', bus = ''): PinRef | null {
return { node: n.id, pin: near.key }
}
/**
* Port sockets on components' boxes, not split yet, that a single wire can
* go onto (the port then splits into its lines): with a free line going in,
* for a wire from an output, or a line coming out, for a wire to an input.
*/
const openSockets = computed(() => {
const out: Record<'in' | 'out', { node: string; port: string; x: number; y: number; face: 1 | -1 }[]> = { in: [], out: [] }
for (const n of def.value.nodes) {
if (n.kind !== 'chip') continue
const s = shapes.value.get(n.id)!
for (const p of [...s.inputs, ...s.outputs]) {
if (!p.conn || n.splitPorts?.includes(p.key)) continue
const at = { node: n.id, port: p.key, x: n.x + p.dx, y: n.y + p.dy, face: p.dx > 0 ? (1 as const) : (-1 as const) }
if (lineForWire(ed.project.value, def.value, n.id, p.key, true)) out.in.push(at)
if (lineForWire(ed.project.value, def.value, n.id, p.key, false)) out.out.push(at)
}
}
return out
})
/** The socket a single wire being drawn from this pin is dropped on, if any. */
function socketAt(d: { node: string; pin: string; dir: 'in' | 'out'; cur: Pt }) {
if (ed.isBus(d.node, d.pin, d.dir)) return undefined
return openSockets.value[d.dir === 'out' ? 'in' : 'out'].find(s => Math.abs(s.x - d.cur[0]) <= 0.5 && Math.abs(s.y - d.cur[1]) <= 0.5)
}
function onPointerUp(e: PointerEvent) {
const d = drag.value
drag.value = null
@ -945,6 +975,13 @@ function onPointerUp(e: PointerEvent) {
ed.linking.value = { queue: [{ ...here, dir: d.dir, label: '' }], at: 0 }
break
}
// A single wire dropped on a port's socket: the port splits and the wire takes one of its lines.
const socket = d.replace ? undefined : socketAt(d)
if (socket) {
const line = ed.lineAt(d.dir, socket.node, socket.port)
if (line) ed.connect(d.dir === 'out' ? here : line, d.dir === 'out' ? line : here)
break
}
const onWire = wireDrop(d)
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.pinKind(d.node, d.pin, d.dir)) ?? onWire?.pin
if (!target) break
@ -1170,11 +1207,16 @@ const tempWire = computed(() => {
const p = pinPos(n, shapes.value.get(n.id)!, d.pin, d.dir)
if (!p) return null
const want = d.dir === 'out' ? 'in' : 'out'
const target = targetAt(d.cur, want, ed.pinKind(d.node, d.pin, d.dir))
// Over a port's socket the wire ends there, as it does when let go (the port splits into its lines).
const socket = drag.value?.kind === 'wire' && drag.value.replace ? undefined : socketAt(d)
const target = socket ? null : targetAt(d.cur, want, ed.pinKind(d.node, d.pin, d.dir))
let end: Pt = [Math.round(d.cur[0]), Math.round(d.cur[1])]
// The side the far end faces: a snapped pin's own, else the usual one.
let endFace: 1 | -1 = want === 'in' ? -1 : 1
if (target) {
if (socket) {
end = [socket.x, socket.y]
endFace = socket.face
} else if (target) {
const tn = nodeMap.value.get(target.node)!
const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, want)!
end = [tp.x, tp.y]
@ -1184,7 +1226,7 @@ const tempWire = computed(() => {
d.dir === 'out'
? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end), p.face, endFace)
: routeWire(end, [p.x, p.y], undefined, endFace, p.face)
return { d: toPath(pts), snapped: !!target, end }
return { d: toPath(pts), snapped: !!(socket || target), end }
})
const isCable = (w: Wire) => nodeMap.value.get(w.from.node)?.kind === 'bundle'
@ -1249,6 +1291,8 @@ const targets = computed(() => {
out.push({ x: n.x + p.dx, y: n.y + p.dy, free: want === 'out' || !taken.has(`${n.id}:${p.key}`) })
}
}
// A single wire can go onto a port's socket too: the port splits into its lines.
if (!bus) for (const s of openSockets.value[want]) out.push({ x: s.x, y: s.y, free: true })
return out
})
@ -1396,7 +1440,7 @@ function openMenuAt(target: Element, at: Pt, x: number, y: number) {
// On an input pin: its bubble first (the same as Alt + click, which some desktops take for themselves).
const pin = target.closest('[data-pin][data-dir="in"]')?.getAttribute('data-pin')
const n = nodeId ? nodeMap.value.get(nodeId) : undefined
if (pin && n && INVERTIBLE.has(n.kind)) {
if (pin && n && ed.canInvert(n, pin)) {
const on = n.invert?.includes(pin)
entries.unshift({ label: on ? 'Take the bubble off this input' : 'Invert this input', icon: 'lucide:circle-dot', keys: 'Alt+click', run: () => ed.toggleInvert(n, pin) }, 'sep')
}

View File

@ -29,6 +29,7 @@ const SHORTCUTS: [string, string][] = [
['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'],
['[', 'Hide or show the panel on the left (This and Pins)'],
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
['Split into lines (right-click a component)', 'A pin per line below a port\'s socket, to wire lines by hand; dropping a wire on the socket does the same. Join lines takes them away'],
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
['Select a component, cable button beside its pins', 'A cable plugged onto S0–S3 (or any group); drop its free end on the next part\'s pins'],
['Drag a part from the list onto pins', 'It lands on them and connects (green rings show where); Alt just places it'],

View File

@ -4,7 +4,7 @@ import { stats } from '~/lib/logic/analyze'
import { compile } from '~/lib/logic/compile'
import { cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, rowLabel } from '~/lib/logic/geometry'
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, portName, rowLabel } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
@ -152,7 +152,7 @@ const cables = computed(() => ed.cableChoices(n.value))
const invertible = computed(() => {
if (!INVERTIBLE.has(n.value.kind)) return []
const inv = new Set(n.value.invert ?? [])
return ed.shape(n.value).inputs.filter(p => !p.bus).map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
return ed.shape(n.value).inputs.filter(p => !p.bus && !p.port).map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
})
const inverted = computed(() => invertible.value.filter(p => p.on).length)
@ -200,6 +200,11 @@ const cableBundle = computed(() => {
const sleeveColor = computed(() => (cableBundle.value ? ed.def.value.wires.find(w => w.from.node === cableBundle.value!.id)?.color : undefined))
/** Connector ports on the component's box: each one can show its lines as pins on this box. */
const boxPorts = computed(() =>
(chipDef.value ? (chipPins(chipDef.value).ports ?? []) : []).map(p => ({ key: p.key, name: portName(p, ed.getDef.value), split: !!n.value.splitPorts?.includes(p.key) })),
)
const chipInputs = computed(() => (chipDef.value ? chipPins(chipDef.value).inputs.length : 0))
const chipOutputs = computed(() => (chipDef.value ? chipPins(chipDef.value).outputs.length : 0))
const hasPanel = computed(() => ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.value.id))
@ -741,6 +746,15 @@ function setRowHz(row: PanelRow, e: Event) {
<button class="btn w-full" title="Move its lamps and displays, draw on it, size it: for every copy" @click="ed.designFace(chipDef.id)">
<Icon name="lucide:pen-tool" class="size-4" /> Design its box
</button>
<button
v-for="p in boxPorts"
:key="p.key"
class="btn w-full"
:title="p.split ? 'Only the socket again; wires on its lines are removed' : 'A pin per line below the socket, to wire lines by hand; a cable still plugs into the socket'"
@click="ed.toggleSplit(n, p.key)"
>
<Icon :name="p.split ? 'lucide:merge' : 'lucide:split'" class="size-4" /> {{ p.split ? `Join ${p.name} lines` : `Split ${p.name} into lines` }}
</button>
<div v-if="(chipInputs && !hasPanel) || (chipOutputs && !hasOutPanel)" class="sel-row">
<button v-if="chipInputs && !hasPanel" class="btn grow" title="A switch for every free input, docked to the left" @click="ed.addPanel(n.id)">
<Icon name="lucide:sliders-vertical" class="size-4" /> Input panel

View File

@ -124,6 +124,28 @@ const bubbles = computed(() => {
return props.shape.inputs.filter(p => inv.has(p.key)).map(p => ({ key: p.key, x: (p.dx + dx) * G, y: p.dy * G }))
})
/** Pin names on a component's box, each on its own edge; the lines of a split port sit in a little from their socket. */
const boxLabels = computed(() =>
[...props.shape.inputs, ...props.shape.outputs].map(p => {
const left = p.dx === 0
const inset = p.port ? 11 : 5
return { key: p.key, label: p.label, y: p.dy * G + 3.5, x: left ? inset : p.dx * G - inset, anchor: left ? 'start' : 'end' }
}),
)
/** Split ports on a component's box: a bar in the type's colour from the socket down along its lines. */
const portBars = computed(() => {
const pins = [...props.shape.inputs, ...props.shape.outputs]
return pins.flatMap(p => {
const lines = p.conn ? pins.filter(l => l.port === p.key) : []
if (!lines.length) return []
// From the socket's inner corner, down between the line pins and their names.
const inward = p.dx === 0 ? 1 : -1
const x = p.dx * G
return [{ key: p.key, conn: p.conn, d: `M${x + inward * 4} ${p.dy * G + 5}H${x + inward * 7}V${Math.max(...lines.map(l => l.dy)) * G + 3}` }]
})
})
/** The edge a plugged cable end touches its part with. */
const seam = computed(() => (props.node.kind === 'bundle' ? 0 : G))
@ -227,8 +249,8 @@ const title = computed(() => {
</template>
<text v-if="f.label" :x="(f.x + f.w / 2) * G" :y="(f.y + f.h - 0.15) * G" text-anchor="middle" class="face-label">{{ f.label }}</text>
</g>
<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>
<path v-for="g in portBars" :key="`bar-${g.key}`" :d="g.d" class="port-bar" :style="{ stroke: connColor(g.conn) }" />
<text v-for="p in boxLabels" :key="p.key" :x="p.x" :y="p.y" :text-anchor="p.anchor" class="pin-label">{{ p.label }}</text>
</template>
<!-- Switch (input pin) -->

View File

@ -35,6 +35,7 @@ import {
createProject,
deleteComponent,
duplicateComponent,
lineForWire,
lookup,
makeUnique,
pinKeys,
@ -43,6 +44,7 @@ import {
packageSelection,
pasteClip,
pruneWires,
splitPort,
startChallenge,
startPuzzle,
swapNode,
@ -248,6 +250,9 @@ function create() {
const canRedo = ref(false)
function resetHistory() {
// Docked panels line up with pins that moved since the project was saved (ports went to the top), now rather than at the next edit.
syncPanels(project.value)
pruneWires(project.value)
syncLatches(project.value)
syncCables(project.value)
undoStack.length = 0
@ -834,6 +839,30 @@ function create() {
selection.value = res.nodes
wireSel.value = []
commit()
if (res.dropped) notify(`Unpacked. ${res.dropped} wire${res.dropped === 1 ? '' : 's'} on split lines had nowhere to go and ${res.dropped === 1 ? 'was' : 'were'} removed.`)
}
/** Splits a port on a placed component's box into a pin per line, or joins it into its socket again (the wires on its lines go). */
function toggleSplit(n: CircuitNode, port: string) {
const removed = splitPort(project.value, def.value, n.id, port, !n.splitPorts?.includes(port))
commit()
if (removed) notify(`Joined. ${removed} wire${removed === 1 ? '' : 's'} on its lines removed.`)
}
/**
* A single wire brought to a port's socket on a component's box (`dir`: the
* side of the wire it comes from): the port splits, and the first free line
* that runs that way is the pin to wire to. Null when there is none.
*/
function lineAt(dir: 'in' | 'out', chipId: string, port: string): PinRef | null {
const key = lineForWire(project.value, def.value, chipId, port, dir === 'out')
if (!key) {
play('error')
notify(dir === 'out' ? 'No free line of this port goes into the component' : 'No line of this port comes out of the component', 'error')
return null
}
splitPort(project.value, def.value, chipId, port, true)
return { node: chipId, pin: key }
}
function makeIndependent(nodeId: string) {
@ -1192,8 +1221,9 @@ function create() {
const cabled = new Set(d.wires.filter(w => w.from.node === n.id && kinds.get(w.to.node)?.plug === n.id).map(w => w.from.pin))
// Inputs already fed by a plugged cable are taken; inputs with a plain wire can take a cable (the wire goes into it).
const fed = new Set(d.wires.filter(w => w.to.node === n.id && kinds.get(w.from.node)?.plug === n.id).map(w => w.to.pin))
const outs = s.outputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
const ins = n.kind === 'panel' ? [] : s.inputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
// Pins on their usual edge only: a split port's lines that run the other way sit on the far edge, where no cable end fits.
const outs = s.outputs.filter(p => !p.bus && p.face !== -1).sort((a, b) => a.dy - b.dy)
const ins = n.kind === 'panel' ? [] : s.inputs.filter(p => !p.bus && p.face !== 1).sort((a, b) => a.dy - b.dy)
return { out: pinGroups(outs, k => !cabled.has(k)), in: pinGroups(ins, k => !fed.has(k)) }
}
@ -1680,9 +1710,16 @@ function create() {
return (n.kind === 'chip' && n.chip ? transistors(n.chip) : 0) + bubbles
}
/** Inputs that take a bubble: single wires into gates, components, outputs and lamps, not the lines of a split port. */
function canInvert(n: CircuitNode, pin: string): boolean {
if (!INVERTIBLE.has(n.kind)) return false
const p = shape(n).inputs.find(p => p.key === pin)
return !!p && !p.bus && !p.port
}
/** Puts a bubble on an input (it reads the signal inverted, through one NAND), or takes it off. */
function toggleInvert(n: CircuitNode, pin: string) {
if (!INVERTIBLE.has(n.kind)) return
if (!canInvert(n, pin)) return
const set = new Set(n.invert ?? [])
if (!set.delete(pin)) set.add(pin)
if (set.size) n.invert = [...set]
@ -2473,6 +2510,7 @@ function create() {
exportTable,
transistors,
transistorsOfNode,
canInvert,
toggleInvert,
nands,
panelTab,
@ -2524,6 +2562,8 @@ function create() {
swap,
unlink,
unpack,
toggleSplit,
lineAt,
makeIndependent,
copy,
paste,

View File

@ -5,7 +5,7 @@
import { byPosition, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
import { cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, chipPins, type Pt } from '~/lib/logic/geometry'
import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
@ -172,7 +172,7 @@ export function useMenu() {
}
if (INVERTIBLE.has(n.kind)) {
const inv = new Set(n.invert ?? [])
const pins = ed.shape(n).inputs
const pins = ed.shape(n).inputs.filter(p => !p.bus && !p.port)
if (pins.length) {
out.push({
label: 'Invert input',
@ -229,6 +229,12 @@ export function useMenu() {
if (pins.outputs.length && !dockedOut) out.push({ label: 'Attach output panel', icon: 'lucide:list-checks', run: () => ed.addPanel(n.id, 'out') })
if (pins.inputs.length) out.push({ label: 'Wire inputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'in') })
if (pins.outputs.length) out.push({ label: 'Wire outputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'out') })
// Ports: split into a pin per line on this box, to wire lines by hand, or joined again.
for (const p of pins.ports ?? []) {
const split = !!n.splitPorts?.includes(p.key)
const name = portName(p, get)
out.push({ label: split ? `Join ${name} lines` : `Split ${name} into lines`, icon: split ? 'lucide:merge' : 'lucide:split', run: () => ed.toggleSplit(n, p.key) })
}
out.push(
{ label: 'Unpack into parts', icon: 'lucide:ungroup', run: () => ed.unpack(n.id) },
{ label: 'Make independent copy', icon: 'lucide:copy-plus', run: () => ed.makeIndependent(n.id) },

View File

@ -499,7 +499,8 @@ function clearSpot(def: ComponentDef, get: DefLookup, x: number, y: number, h: n
export function cableFromPins(def: ComponentDef, partId: string, pins: string[], get: DefLookup): { ok: true; bundle: CircuitNode; split: CircuitNode } | { ok: false; error: string } {
const part = def.nodes.find(n => n.id === partId)
if (!part) return { ok: false, error: 'Part not found' }
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && pins.includes(p.key)).sort((a, b) => a.dy - b.dy)
// Outputs on the right edge only: a cable end on the left would sit inside the box.
const outs = shapeOf(part, get).outputs.filter(p => !p.bus && p.face !== -1 && pins.includes(p.key)).sort((a, b) => a.dy - b.dy)
if (outs.length < 2) return { ok: false, error: 'A cable needs at least two pins' }
if (outs.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
const bundle: CircuitNode = { id: uid('n'), kind: 'bundle', bits: outs.length, x: part.x + outs[0]!.dx, y: part.y + outs[0]!.dy }
@ -524,7 +525,8 @@ export function cableIntoPins(def: ComponentDef, partId: string, pins: string[],
const part = def.nodes.find(n => n.id === partId)
if (!part) return { ok: false, error: 'Part not found' }
const fed = new Set(def.wires.filter(w => w.to.node === part.id).map(w => w.to.pin))
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy)
// Inputs on the left edge only: a cable end on the right would sit inside the box.
const ins = shapeOf(part, get).inputs.filter(p => !p.bus && p.face !== 1 && pins.includes(p.key) && !fed.has(p.key)).sort((a, b) => a.dy - b.dy)
if (ins.length < 2) return { ok: false, error: 'A cable needs at least two free inputs' }
if (ins.length > MAX_BITS) return { ok: false, error: `A cable holds at most ${MAX_BITS} wires` }
const split: CircuitNode = { id: uid('n'), kind: 'split', bits: ins.length, x: part.x + ins[0]!.dx - 1, y: part.y + ins[0]!.dy }

View File

@ -25,11 +25,22 @@ function partName(n: CircuitNode, get: DefLookup): string {
return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
}
/** Input pins of a part that have no wire. */
/** Pins of a part with a wire or cable, coming in or going out. */
const linkedPins = (def: ComponentDef, n: CircuitNode) => new Set(def.wires.flatMap(w => [w.to.node === n.id ? w.to.pin : '', w.from.node === n.id ? w.from.pin : '']))
/** Input pins of a part that have no wire (a line of a split port is fed by the cable when one is in its socket). */
export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (!CHECKED_INPUTS.has(n.kind)) return []
const linked = linkedPins(def, n)
const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
return shapeOf(n, get).inputs.filter(p => !p.bus && !wired.has(p.key)).map(p => p.key)
return shapeOf(n, get).inputs.filter(p => !p.bus && !(p.port && linked.has(p.port)) && !wired.has(p.key)).map(p => p.key)
}
/** Lines of split ports on a component's box that are wired by hand while a cable is plugged into their port. */
export function doublyFedLines(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
if (n.kind !== 'chip' || !n.splitPorts?.length) return []
const linked = linkedPins(def, n)
return shapeOf(n, get).inputs.filter(p => p.port && linked.has(p.key) && linked.has(p.port)).map(p => p.key)
}
export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
@ -54,6 +65,12 @@ export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
issues.push({ level: 'warn', text, nodes: [n.id] })
}
if (n.kind === 'split' && !def.wires.some(w => w.to.node === n.id)) issues.push({ level: 'warn', text: 'Cable split without a cable', nodes: [n.id] })
const twice = doublyFedLines(def, n, get)
if (twice.length) {
const shape = shapeOf(n, get)
const labels = twice.map(k => shape.inputs.find(p => p.key === k)?.label || k)
issues.push({ level: 'error', text: `${name(n)}: ${labels.join(', ')} wired and fed by the cable as well: they drive ${twice.length === 1 ? 'it' : 'them'} against each other`, nodes: [n.id] })
}
// Parts that drive nothing.
if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {
issues.push({ level: 'info', text: n.kind === 'nand' ? 'NAND gate: its output goes nowhere' : `${name(n)}: goes nowhere`, nodes: [n.id] })

View File

@ -2,7 +2,7 @@
// 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 { cableBits, chipPins, isPinRow, portLines, rowPin, type ChipPins, type DefLookup } from './geometry'
import { cableBits, chipPins, isPinRow, portLines, rowPin, splitLines, type ChipPins, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0
@ -57,7 +57,7 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
case 'bundle':
return cableKeys(node)
case 'chip':
return pins ? [...pins.inputs.map(p => p.key), ...portKeys(pins, 'in')] : []
return pins ? [...pins.inputs.map(p => p.key), ...portKeys(pins, 'in'), ...lineKeys(node, pins, get, true)] : []
default:
return []
}
@ -66,6 +66,9 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
/** Keys of a component's connector ports on one side. */
const portKeys = (pins: ChipPins, side: 'in' | 'out') => (pins.ports ?? []).filter(p => p.side === side).map(p => p.key)
/** Keys of the lines of ports split on a placed component's box that go in (or come out). */
const lineKeys = (node: CircuitNode, pins: ChipPins, get: DefLookup | undefined, enters: boolean) => splitLines(node, pins, get).filter(l => l.enters === enters).map(l => l.key)
export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
switch (node.kind) {
case 'portin':
@ -84,7 +87,7 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup):
case 'ref':
return ['q']
case 'chip':
return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out')] : []
return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out'), ...lineKeys(node, pins, get, false)] : []
case 'hex':
return ['q0', 'q1', 'q2', 'q3']
case 'panel':
@ -189,6 +192,8 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
const nodeById = new Map(def.nodes.map(n => [n.id, n]))
// Ends of typed cables ("node:pin"): the nets of their lines, joined line by line below.
const ends = new Map<string, number[]>()
// Line pins of ports split on boxes ("node:pin"): the line's net, wired by hand or fed through the cable.
const lineNets = new Map<string, number>()
const outNet = new Map<string, number>()
for (const n of def.nodes) {
@ -323,6 +328,15 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
childPorts.set(p.key, nets)
ends.set(`${n.id}:${p.key}`, nets)
}
// A port split on the box: each line is a pin of its own as well. A
// wire into a line drives it like the cable would (both at once is a short).
for (const l of splitLines(n, pins, getDef)) {
const net = childPorts.get(l.port)?.[l.index]
if (net === undefined) continue
lineNets.set(`${n.id}:${l.key}`, net)
if (!l.enters) union(outNet.get(`${n.id}:${l.key}`)!, net)
else if (wiresTo.has(`${n.id}:${l.key}`)) union(inNet(n.id, l.key), net)
}
const childOut = expand(child, childIn, `${path}${n.id}/`, inner, childPorts)
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
break
@ -351,7 +365,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
for (const n of def.nodes) {
const pins = pinsOf(n)
for (const k of inputKeys(n, pins, getDef)) record(n, k, inNet(n.id, k))
for (const k of inputKeys(n, pins, getDef)) record(n, k, lineNets.get(`${n.id}:${k}`) ?? inNet(n.id, k))
for (const k of outputKeys(n, pins, getDef)) record(n, k, outNet.get(`${n.id}:${k}`)!)
}
}

View File

@ -16,6 +16,8 @@ export interface PinInfo {
conn?: string
/** Side the wire leaves (outputs) or arrives from (inputs): 1 right, -1 left. Default: outputs right, inputs left. */
face?: 1 | -1
/** A line of a port split on a component's box: the port's key. */
port?: string
}
export interface Shape {
@ -93,6 +95,40 @@ export const pinKindOf = (p: { bus?: boolean; conn?: string }) => (p.conn ? `c:$
/** Pin key of a panel row: the same key the row has as a switch in the simulator. */
export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
/** What a port is called on a component's box: its own name, else its connector type's. */
export const portName = (p: PortPin, get?: DefLookup) => p.label || get?.conn?.(p.conn)?.name || 'port'
/** Pin key of a line of a port split on a component's box: port.line (a dot, so it never reads as a panel row). */
export const linePin = (port: string, line: string) => `${port}.${line}`
export interface SplitLine {
/** Pin key on the box. */
key: string
name: string
/** The port's key, and the line's place in its connector type. */
port: string
index: number
/** The line goes into the component (an input pin on the box); otherwise it comes out (an output). */
enters: boolean
}
/**
* The lines of the ports split on a placed component's box, top to bottom,
* as pins of their own: inputs for lines going into the component, outputs
* for lines coming out. An in port brings its forward lines in, an out port
* its back lines.
*/
export function splitLines(node: CircuitNode, pins: ChipPins, get?: DefLookup): SplitLine[] {
if (!node.splitPorts?.length) return []
const split = new Set(node.splitPorts)
const out: SplitLine[] = []
for (const p of pins.ports ?? []) {
if (!split.has(p.key)) continue
get?.conn?.(p.conn)?.lines.forEach((l, i) => out.push({ key: linePin(p.key, `l${i}`), name: l.name, port: p.key, index: i, enters: (p.side === 'in') !== !!l.back }))
}
return out
}
/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
@ -339,27 +375,30 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
* need), everything placed where it was put, the rest where it would go
* anyway, and its drawings.
*/
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup): Shape {
const auto = boxShape(def.name, pins, face, get)
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup, node?: CircuitNode): Shape {
const auto = boxShape(def.name, pins, face, get, node)
const d = def.design!
const top = auto.body.y
const hide = new Set(d.hide ?? [])
const place = d.place ?? {}
// Pins on their edges: where they were put, the others one row under the pin above.
const placePins = <P extends PinInfo>(list: P[]) => {
// Pins on each edge, top to bottom: where they were put, the others one row under the pin above.
const placePins = (list: PinInfo[]) => {
let prev = -Infinity
return list.map(p => {
return list
.sort((a, b) => a.dy - b.dy)
.map(p => {
const want = d.pinAt?.[p.key]
const dy = Math.max(want ?? (prev === -Infinity ? p.dy : prev + 1), prev + 1, 0)
prev = dy
return { ...p, dy }
return [p.key, dy] as const
})
}
const inputs = placePins(auto.inputs)
const lowest = Math.max(0, ...inputs.map(p => p.dy), ...auto.outputs.map(p => d.pinAt?.[p.key] ?? p.dy))
const edgePins = [...auto.inputs, ...auto.outputs]
const rightPins = edgePins.filter(p => p.dx > 0)
const rows = new Map([...placePins(edgePins.filter(p => p.dx === 0)), ...placePins(rightPins)])
const lowest = Math.max(0, ...rightPins.map(p => d.pinAt?.[p.key] ?? p.dy))
const w = Math.max(2, d.w)
const outputs = placePins(auto.outputs).map(p => ({ ...p, dx: w }))
const bottom = Math.max(...inputs.map(p => p.dy), ...outputs.map(p => p.dy), lowest)
const bottom = Math.max(lowest, ...rows.values())
const h = Math.max(d.h, bottom - top + 0.5, 2)
// Own items where auto layout put them unless placed; displays of parts inside only when shown.
const show = new Set(d.show ?? [])
@ -395,10 +434,11 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
floor = Math.max(floor, cy + ih / 2 + 0.3)
}
const bw = Math.ceil(right * 2) / 2
const onEdge = (p: PinInfo) => ({ ...p, dx: p.dx > 0 ? bw : 0, dy: rows.get(p.key)! })
return {
...auto,
inputs,
outputs: bw === w ? outputs : outputs.map(p => ({ ...p, dx: bw })),
inputs: auto.inputs.map(onEdge),
outputs: auto.outputs.map(onEdge),
body: { x: 0, y: top, w: bw, h: Math.ceil((floor - top) * 2) / 2 },
face: shown,
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
@ -406,32 +446,55 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
}
}
function boxShape(name: string, plain: ChipPins, face: ReturnType<typeof faceLayout>, get?: DefLookup): Shape {
// Ports sit below the single pins of their side, as one cable pin each.
const port = (side: 'in' | 'out') =>
(plain.ports ?? [])
.filter(p => p.side === side)
.map(p => ({ key: p.key, label: p.label || get?.conn?.(p.conn)?.name || 'port', bus: true, conn: p.conn }))
const pins = { inputs: [...plain.inputs, ...port('in')], outputs: [...plain.outputs, ...port('out')] }
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)
/** A pin on one edge of a component's box, and whether a signal goes in or comes out there. */
interface EdgePin {
pin: Omit<PinInfo, 'dx' | 'dy'>
dir: 'in' | 'out'
}
function boxShape(name: string, plain: ChipPins, face: ReturnType<typeof faceLayout>, get?: DefLookup, node?: CircuitNode): Shape {
// Ports sit at the very top of their side, as one cable pin each. A port
// split on this box has a pin per line right below it, facing out of its side.
const lines = node ? splitLines(node, plain, get) : []
const edge = (side: 'in' | 'out'): EdgePin[] => {
const out: EdgePin[] = []
for (const p of plain.ports ?? []) {
if (p.side !== side) continue
out.push({ dir: side, pin: { key: p.key, label: portName(p, get), bus: true, conn: p.conn } })
for (const l of lines) {
if (l.port === p.key) out.push({ dir: l.enters ? 'in' : 'out', pin: { key: l.key, label: l.name, face: side === 'in' ? -1 : 1, port: p.key } })
}
}
for (const p of side === 'in' ? plain.inputs : plain.outputs) out.push({ dir: side, pin: p })
return out
}
const left = edge('in')
const right = edge('out')
const n = Math.max(left.length, right.length, 1)
const longest = (ps: EdgePin[]) => ps.reduce((m, p) => Math.max(m, p.pin.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),
Math.ceil(longest(left) * LABEL_CHAR + longest(right) * LABEL_CHAR + name.length * NAME_CHAR + 1.5),
Math.ceil(face.w + 1.2),
)
// An edge with ports starts at the top; one of single pins only is centred,
// on the box as it is without split lines, so splitting a port never moves it.
const unsplit = Math.max(...[left, right].map(ps => ps.filter(p => !p.pin.port).length), 1)
const place = (ps: EdgePin[], dx: number) => {
const off = ps.some(p => p.pin.bus) ? 0 : Math.floor((unsplit - ps.length) / 2)
return ps.map((p, i) => ({ dir: p.dir, pin: { ...p.pin, dx, dy: off + i } }))
}
// Each edge's own pins first: code that takes the first free input or output finds one on its usual edge.
const onLeft = place(left, 0)
const onRight = place(right, w)
const top = n === 1 ? -1 : -0.5
const pinBottom = n === 1 ? 1 : n - 0.5
const faceTop = pinBottom + 0.2
const faceLeft = (w - face.w) / 2
return {
body: { x: 0, y: top, w, h: pinBottom - top + (face.items.length ? face.h + 0.6 : 0) },
inputs: pins.inputs.map((p, i) => ({ ...p, dx: 0, dy: inOff + i })),
outputs: pins.outputs.map((p, i) => ({ ...p, dx: w, dy: outOff + i })),
inputs: [...onLeft, ...onRight].filter(p => p.dir === 'in').map(p => p.pin),
outputs: [...onRight, ...onLeft].filter(p => p.dir === 'out').map(p => p.pin),
nameY: (top + pinBottom) / 2,
face: face.items.map(it => ({ ...it, x: it.x + faceLeft, y: it.y + faceTop })),
}
@ -650,11 +713,11 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
const face = faceLayout(def)
if (def.design) return designedShape(def, pins, face, getDef)
if (def.design) return designedShape(def, pins, face, getDef, node)
if (def.symbol !== 'box' && !face.items.length && !pins.ports && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
return boxShape(def.name, pins, face, getDef)
return boxShape(def.name, pins, face, getDef, node)
}
case 'portin':
case 'portout':

View File

@ -2,7 +2,7 @@
// A, B, C), and a switch, lamp or pin without a name of its own takes the
// name of the component pin it is wired to.
import type { DefLookup } from './geometry'
import { chipPins, splitLines, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, NodeKind } from './types'
const SERIES = /^(.*?)(\d+)$/
@ -84,6 +84,9 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip)
// A line of a port split on the box: port.line, named after the line.
const line = def && node.splitPorts?.length ? splitLines(node, chipPins(def), get).find(l => l.key === pin) : undefined
if (line) return line.name
// A pin made from a panel row: panel:row.
const at = pin.indexOf(':')
if (at > 0) {

View File

@ -4,7 +4,7 @@
import type { Challenge } from './challenges'
import { inputKeys, outputKeys } from './compile'
import { exampleLibrary, starterCircuit } from './examples'
import { chipPins, shapeOf, type DefLookup } from './geometry'
import { chipPins, linePin, shapeOf, splitLines, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, NodeKind, Project, PuzzleSpec, Wire } from './types'
export function uid(prefix = ''): string {
@ -439,9 +439,52 @@ export function swapNode(project: Project, def: ComponentDef, nodeId: string, ta
if (target.kind !== 'input' && target.kind !== 'button') delete node.key
if (target.kind !== 'lamp' && target.kind !== 'hex') delete node.color
if (target.kind !== 'note') delete node.size
if (target.kind !== 'chip') delete node.splitPorts
return removed
}
/**
* Shows a port of a placed component split into a pin per line below its
* socket, to wire lines by hand, or joined into the socket alone again.
* Joining removes the wires on its lines; returns how many.
*/
export function splitPort(project: Project, def: ComponentDef, nodeId: string, port: string, split: boolean): number {
const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId)
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
if (!node || !child || !chipPins(child).ports?.some(p => p.key === port)) return 0
const ports = new Set(node.splitPorts ?? [])
if (split) ports.add(port)
else ports.delete(port)
if (ports.size) node.splitPorts = [...ports]
else delete node.splitPorts
// The lines' pins are gone, and so are the wires on them.
const before = def.wires.length
pruneWires(project)
return before - def.wires.length
}
/**
* The line of a component's port a single wire takes when dropped on its
* socket: the first free one going into the component (`enters`, for a wire
* from an output), or coming out of it (for a wire to an input; every line
* can feed more wires, an unused one first). Null when no line runs that way,
* and for lines going in while a cable is in the socket: the cable feeds them.
*/
export function lineForWire(project: Project, def: ComponentDef, nodeId: string, port: string, enters: boolean): string | null {
const get = lookup(project)
const node = def.nodes.find(n => n.id === nodeId)
const child = node?.kind === 'chip' && node.chip ? get(node.chip) : undefined
if (!node || !child) return null
const into = new Set(def.wires.filter(w => w.to.node === nodeId).map(w => w.to.pin))
const from = new Set(def.wires.filter(w => w.from.node === nodeId).map(w => w.from.pin))
// A wire on a line the cable feeds would drive it against the cable.
if (enters && (into.has(port) || from.has(port))) return null
const lines = splitLines({ ...node, splitPorts: [port] }, chipPins(child), get).filter(l => l.enters === enters)
const used = enters ? into : from
return (lines.find(l => !used.has(l.key)) ?? (enters ? undefined : lines[0]))?.key ?? null
}
/**
* Removes every wire attached to the given parts. Returns how many. A cable
* (bundle to split) is part of the cable, not a connection: it stays, only
@ -458,9 +501,10 @@ export function unlinkWires(def: ComponentDef, ids: Set<string>): number {
/**
* Replaces a placed component with the parts inside it (the reverse of
* "Make component"). Its pins disappear: outside wires are joined straight
* to the parts they reached inside. Returns the ids of the new parts.
* to the parts they reached inside, the lines of split ports too. Returns
* the ids of the new parts, and how many wires on lines had nowhere to go.
*/
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[] } | { ok: false; error: string } {
export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[]; dropped: number } | { ok: false; error: string } {
const get = lookup(project)
const def = get(defId)
const chip = def?.nodes.find(n => n.id === nodeId)
@ -484,8 +528,21 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
const feed = new Map<string, Wire['from']>()
for (const w of def.wires) if (w.to.node === chip.id) feed.set(w.to.pin, w.from)
const resolve = (ref: Wire['from']): Wire['from'] | undefined =>
kindOf.get(ref.node) === 'input' ? feed.get(ref.node) : ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
// Lines of split ports on the box, and those whose wires found a place.
const lines = new Map(splitLines(chip, chipPins(child), get).map(l => [l.key, l]))
const carried = new Set<string>()
const resolve = (ref: Wire['from']): Wire['from'] | undefined => {
if (kindOf.get(ref.node) === 'input') return feed.get(ref.node)
// A line of a port going in: what was wired into it on the box, if anything.
const port = kindOf.get(ref.node) === 'portin' || kindOf.get(ref.node) === 'portout'
const line = linePin(ref.node, ref.pin)
const hand = port ? feed.get(line) : undefined
if (hand) {
carried.add(line)
return hand
}
return ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined
}
const added: Wire[] = []
for (const w of child.wires) {
@ -493,20 +550,25 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
const from = resolve(w.from)
if (!from) continue
const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } }
if (ids.has(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
if (from.node === ids.get(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy])
if (w.color) wire.color = w.color
added.push(wire)
}
for (const w of def.wires) {
if (w.from.node !== chip.id) continue
const inside = child.wires.find(x => x.to.node === w.from.pin)
// An output pin is fed by the wire into its output part; a line coming out, by the wire into that line of its port.
const line = lines.get(w.from.pin)
const inside = line ? child.wires.find(x => x.to.node === line.port && x.to.pin === `l${line.index}`) : child.wires.find(x => x.to.node === w.from.pin)
const from = inside && resolve(inside.from)
if (from) added.push({ id: uid('w'), from, to: w.to })
if (!from) continue
added.push({ id: uid('w'), from, to: w.to })
if (line) carried.add(line.key)
}
const dropped = def.wires.filter(w => (w.to.node === chip.id && lines.has(w.to.pin) && !carried.has(w.to.pin)) || (w.from.node === chip.id && lines.has(w.from.pin) && !carried.has(w.from.pin))).length
def.nodes = def.nodes.filter(n => n !== chip)
def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added]
return { ok: true, nodes: [...ids.values()] }
return { ok: true, nodes: [...ids.values()], dropped }
}
/** Points one placed component at its own copy of the definition, so edits to it don't change the others. */

View File

@ -29,14 +29,18 @@ interface ChipInput {
dy: number
}
/** The pins of a chip a panel docks to: its inputs for an input panel, its outputs for an output panel. */
/**
* The pins of a chip a panel docks to: its inputs for an input panel, its
* outputs for an output panel. Port sockets and the lines of split ports are
* left alone: a cable feeds those.
*/
function chipInputs(chip: CircuitNode, get: DefLookup, side: 'in' | 'out' = 'in'): ChipInput[] | null {
const child = chip.kind === 'chip' && chip.chip ? get(chip.chip) : undefined
if (!child) return null
const pins = chipPins(child)
const labels = new Map((side === 'in' ? pins.inputs : pins.outputs).map(p => [p.key, p.label]))
const shape = shapeOf(chip, get)
return (side === 'in' ? shape.inputs : shape.outputs).map(p => ({ key: p.key, label: labels.get(p.key) ?? p.label, dy: p.dy }))
return (side === 'in' ? shape.inputs : shape.outputs).filter(p => !p.bus && !p.port).map(p => ({ key: p.key, label: labels.get(p.key) ?? p.label, dy: p.dy }))
}
const sideOf = (panel: CircuitNode) => (panel.kind === 'outpanel' ? 'out' : 'in')

View File

@ -40,7 +40,7 @@ function cleanNode(n: CircuitNode) {
if (n.latch !== undefined && typeof n.latch !== 'string') delete n.latch
if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
for (const k of ['names', 'invert'] as const) {
for (const k of ['names', 'invert', 'splitPorts'] as const) {
if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
}
if (n.inner !== undefined && n.inner !== true) delete n.inner

View File

@ -74,6 +74,8 @@ export interface CircuitNode {
inner?: boolean
/** Pixel: the screen it belongs to on the component's box; pixels without one make the main screen. */
screen?: string
/** Component: its connector ports (port node ids inside) shown split on this box, with a pin per line to wire by hand. */
splitPorts?: string[]
}
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const

365
tests/ports.test.ts Normal file
View File

@ -0,0 +1,365 @@
import { describe, expect, it } from 'vitest'
import { cableFromPins, cableIntoPins } from '../app/lib/logic/cables'
import { checkCircuit, doublyFedLines } from '../app/lib/logic/check'
import { compile } from '../app/lib/logic/compile'
import { pinKindOf, shapeOf } from '../app/lib/logic/geometry'
import { pinName } from '../app/lib/logic/labels'
import { createProject, lineForWire, lookup, pruneWires, splitPort, unpackChip } from '../app/lib/logic/ops'
import { attachPanel, syncPanels } from '../app/lib/logic/panels'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import type { CircuitNode, ComponentDef, Project, Wire } from '../app/lib/logic/types'
const w = (id: string, from: [string, string], to: [string, string]): Wire => ({ id, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } })
/**
* The "Mini HDMI" of the connector tests: D0 and D1 out → in, HPD back.
* Source sends A and B out of its out port and reports HPD; Sink shows the
* data as X and Y and drives HPD from H. Root places one of each, unwired.
*/
function project(): Project {
const p = createProject({ examples: false })
p.connectors = [{ id: 'hdmi', name: 'Mini HDMI', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }, { name: 'HPD', back: true }] }]
const source: ComponentDef = {
id: 'source',
name: 'Source',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
{ id: 'tx', kind: 'portout', conn: 'hdmi', x: 20, y: 0, label: 'OUT' },
{ id: 'hpd', kind: 'output', x: 10, y: 8, label: 'HPD' },
],
wires: [w('w1', ['a', 'q'], ['tx', 'l0']), w('w2', ['b', 'q'], ['tx', 'l1']), w('w3', ['tx', 'l2'], ['hpd', 'a'])],
}
const sink: ComponentDef = {
id: 'sink',
name: 'Sink',
symbol: 'box',
nodes: [
{ id: 'rx', kind: 'portin', conn: 'hdmi', x: 0, y: 0, label: 'IN' },
{ id: 'x', kind: 'output', x: 20, y: 0, label: 'X' },
{ id: 'y', kind: 'output', x: 20, y: 2, label: 'Y' },
{ id: 'h', kind: 'input', x: 10, y: 8, label: 'H' },
],
wires: [w('w1', ['rx', 'l0'], ['x', 'a']), w('w2', ['rx', 'l1'], ['y', 'a']), w('w3', ['h', 'q'], ['rx', 'l2'])],
}
const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 'sa', kind: 'input', x: 0, y: 0 },
{ id: 'sb', kind: 'input', x: 0, y: 2 },
{ id: 'sh', kind: 'input', x: 0, y: 8 },
{ id: 'src', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'snk', kind: 'chip', chip: 'sink', x: 30, y: 0 },
{ id: 'lamp', kind: 'lamp', x: 50, y: 0 },
],
wires: [w('r1', ['sa', 'q'], ['src', 'a']), w('r2', ['sb', 'q'], ['src', 'b']), w('r3', ['sh', 'q'], ['snk', 'h'])],
}
p.components.push(source, sink, root)
return p
}
const node = (p: Project, def: string, id: string) => p.components.find(d => d.id === def)!.nodes.find(n => n.id === id)!
const root = (p: Project) => p.components.find(d => d.id === 'root')!
function run(p: Project, on: Record<string, boolean>) {
const s = new Simulator(compile(lookup(p), 'root'))
for (const [k, v] of Object.entries(on)) s.setSource(k, v)
s.run()
return s
}
describe('ports on a component box', () => {
it('sit at the very top of their side, above the single pins', () => {
const p = project()
// More single pins than before, so a port at the bottom would show.
node(p, 'sink', 'h').y = -4
p.components.find(d => d.id === 'sink')!.nodes.push({ id: 'k', kind: 'input', x: 10, y: 10, label: 'K' })
const get = lookup(p)
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0 }, get)
expect(snk.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['h', 1], ['k', 2]])
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get)
expect(src.outputs.map(o => [o.key, o.dx, o.dy])).toEqual([['tx', src.body.w, 0], ['hpd', src.body.w, 1]])
})
it('also at the top of a box drawn by hand', () => {
const p = project()
const sink = p.components.find(d => d.id === 'sink')!
sink.design = { w: 6, h: 3, pinAt: { h: 0, x: 2 } }
const s = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0 }, lookup(p))
expect(s.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['h', 1]])
expect(s.outputs.map(o => [o.key, o.dx, o.dy])).toEqual([['x', 6, 2], ['y', 6, 3]])
})
it('split, a port shows a pin per line right below its socket, each facing out of its side', () => {
const p = project()
const get = lookup(p)
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, get)
// In port on the left: D0 and D1 come in (inputs), HPD goes back out (an output on the left).
expect(snk.inputs.map(i => [i.key, i.label, i.dx, i.dy, i.face])).toEqual([
['rx', 'IN', 0, 0, undefined],
['rx.l0', 'D0', 0, 1, -1],
['rx.l1', 'D1', 0, 2, -1],
['h', 'H', 0, 4, undefined],
])
expect(snk.outputs.find(o => o.key === 'rx.l2')).toMatchObject({ label: 'HPD', dx: 0, dy: 3, face: -1, port: 'rx' })
// Out port on the right: D0 and D1 go out, HPD comes back in (an input on the right).
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts: ['tx'] }, get)
const right = src.body.w
expect(src.outputs.map(o => [o.key, o.dx, o.dy, o.face])).toEqual([
['tx', right, 0, undefined],
['tx.l0', right, 1, 1],
['tx.l1', right, 2, 1],
['hpd', right, 4, undefined],
])
expect(src.inputs.find(i => i.key === 'tx.l2')).toMatchObject({ label: 'HPD', dx: right, dy: 3, face: 1 })
// Lines take single wires; the socket still takes the cable.
expect(pinKindOf(snk.inputs[1]!)).toBe('')
expect(pinKindOf(snk.inputs[0]!)).toBe('c:hdmi')
})
it('split on a box drawn by hand, the lines follow the socket and push the pins below down', () => {
const p = project()
p.components.find(d => d.id === 'sink')!.design = { w: 6, h: 3, pinAt: { h: 1 } }
const s = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, lookup(p))
expect(s.inputs.map(i => [i.key, i.dy])).toEqual([['rx', 0], ['rx.l0', 1], ['rx.l1', 2], ['h', 4]])
expect(s.outputs.find(o => o.key === 'rx.l2')).toMatchObject({ dx: 0, dy: 3 })
})
it('a line wired from outside drives the inside, and a back line brings the inside out', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
for (const [a, h] of [[0, 0], [1, 0], [0, 1], [1, 1]] as const) {
const s = run(p, { sa: !!a, sh: !!h })
expect([s.pin('snk', 'x'), s.pin('snk', 'rx.l2'), s.pin('lamp', 'q')]).toEqual([a, h, h])
}
})
it('an out port split the same way: its lines leave on the right, the back line comes in there', () => {
const p = project()
node(p, 'root', 'src').splitPorts = ['tx']
root(p).wires.push(w('d1', ['src', 'tx.l1'], ['lamp', 'a']), w('hp', ['sh', 'q'], ['src', 'tx.l2']))
for (const [b, h] of [[0, 1], [1, 0], [1, 1]] as const) {
const s = run(p, { sb: !!b, sh: !!h })
expect([s.pin('lamp', 'q'), s.pin('src', 'hpd')]).toEqual([b, h])
}
})
it('a cable on the socket and wires on the lines work together', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
const s = run(p, { sa: true, sb: false, sh: true })
// The cable still carries every line; the line pins show what it carries.
expect([s.pin('snk', 'x'), s.pin('snk', 'y'), s.pin('src', 'hpd')]).toEqual([1, 0, 1])
expect([s.pin('snk', 'rx.l0'), s.pin('snk', 'rx.l1'), s.pin('lamp', 'q')]).toEqual([1, 0, 1])
expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual([])
// A wire into a line the cable feeds as well: both drive it, and the check says so.
root(p).wires.push(w('d0', ['sb', 'q'], ['snk', 'rx.l0']))
expect(doublyFedLines(root(p), node(p, 'root', 'snk'), lookup(p))).toEqual(['rx.l0'])
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'error' && i.text.includes('D0'))).toBe(true)
})
it('passes split lines through a component that offers an inner part’s port as its own', () => {
const p = project()
p.components.push({
id: 'box',
name: 'Box',
symbol: 'box',
nodes: [
{ id: 'i', kind: 'input', x: 0, y: 0, label: 'I' },
{ id: 'inner', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'p2', kind: 'portout', conn: 'hdmi', x: 30, y: 0 },
],
wires: [w('b1', ['i', 'q'], ['inner', 'a']), w('b2', ['inner', 'tx'], ['p2', 'bus'])],
})
root(p).nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20, splitPorts: ['p2'] })
root(p).wires.push(w('r9', ['sa', 'q'], ['bx', 'i']), w('l0', ['bx', 'p2.l0'], ['lamp', 'a']))
expect(run(p, { sa: true }).pin('lamp', 'q')).toBe(1)
expect(run(p, { sa: false }).pin('lamp', 'q')).toBe(0)
})
it('joining a port again removes the wires on its lines and keeps the cable', () => {
const p = project()
const r = root(p)
expect(splitPort(p, r, 'snk', 'rx', true)).toBe(0)
expect(node(p, 'root', 'snk').splitPorts).toEqual(['rx'])
r.wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']), w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
expect(pruneWires(p)).toBe(false)
expect(splitPort(p, r, 'snk', 'rx', false)).toBe(2)
expect(node(p, 'root', 'snk').splitPorts).toBeUndefined()
expect(r.wires.map(x => x.id)).toEqual(['r1', 'r2', 'r3', 'cable'])
// No port of that name: nothing changes.
expect(splitPort(p, r, 'snk', 'nope', true)).toBe(0)
expect(node(p, 'root', 'snk').splitPorts).toBeUndefined()
})
it('a single wire dropped on a socket takes the first free line that runs its way', () => {
const p = project()
const r = root(p)
// Into the sink's in port: D0, then D1; from it: HPD.
expect(lineForWire(p, r, 'snk', 'rx', true)).toBe('rx.l0')
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
r.wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
expect(lineForWire(p, r, 'snk', 'rx', true)).toBe('rx.l1')
r.wires.push(w('d1', ['sb', 'q'], ['snk', 'rx.l1']))
expect(lineForWire(p, r, 'snk', 'rx', true)).toBeNull()
// A line coming out can feed another wire.
r.wires.push(w('hp', ['snk', 'rx.l2'], ['lamp', 'a']))
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
// The source's out port: its back line goes in, D0 comes out first.
expect(lineForWire(p, r, 'src', 'tx', true)).toBe('tx.l2')
expect(lineForWire(p, r, 'src', 'tx', false)).toBe('tx.l0')
expect(lineForWire(p, r, 'src', 'nope', true)).toBeNull()
})
it('cleans up wires on lines whose port is no longer split', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
expect(pruneWires(p)).toBe(false)
delete node(p, 'root', 'snk').splitPorts
expect(pruneWires(p)).toBe(true)
expect(root(p).wires.some(x => x.id === 'd0')).toBe(false)
})
it('a typed cable never plugs into a line, a single wire never into a socket', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('bad1', ['src', 'tx'], ['snk', 'rx.l0']), w('bad2', ['sa', 'q'], ['snk', 'rx']))
expect(pruneWires(p)).toBe(true)
expect(root(p).wires.map(x => x.id)).toEqual(['r1', 'r2', 'r3'])
})
it('names a line pin after its line, keeps the setting through loading and leaves line pins off docked panels', () => {
const p = project()
const snk = node(p, 'root', 'snk')
snk.splitPorts = ['rx']
expect(pinName(snk, 'rx.l1', lookup(p))).toBe('D1')
const data = JSON.parse(JSON.stringify(p))
data.components.find((d: ComponentDef) => d.id === 'root').nodes.find((n: CircuitNode) => n.id === 'src').splitPorts = 'tx'
const back = toProject(data)
expect(node(back, 'root', 'snk').splitPorts).toEqual(['rx'])
expect(node(back, 'root', 'src').splitPorts).toBeUndefined()
// A docked input panel gets a switch for H only: the socket and the lines are the cable's.
root(p).wires = root(p).wires.filter(x => x.id !== 'r3')
const panel = attachPanel(p, root(p), 'snk')!
expect(panel.rows!.map(r => r.id)).toEqual(['h'])
})
it('with a cable in the socket, a dropped wire takes no line going in: the cable feeds those', () => {
const p = project()
const r = root(p)
r.wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
// Into the sink's in port: D0 and D1 come through the cable. HPD can still be read.
expect(lineForWire(p, r, 'snk', 'rx', true)).toBeNull()
expect(lineForWire(p, r, 'snk', 'rx', false)).toBe('rx.l2')
// The source's out port: HPD comes back through the cable, D0 can still be read.
expect(lineForWire(p, r, 'src', 'tx', true)).toBeNull()
expect(lineForWire(p, r, 'src', 'tx', false)).toBe('tx.l0')
})
it('a line going in with neither a wire nor a cable is an open input', () => {
const p = project()
node(p, 'root', 'snk').splitPorts = ['rx']
root(p).wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']))
expect(checkCircuit(root(p), lookup(p)).some(i => i.level === 'warn' && i.text === 'Sink: D1 not connected (reads 0)')).toBe(true)
// A cable in the socket feeds D1.
root(p).wires = root(p).wires.filter(x => x.id !== 'd0')
root(p).wires.push(w('cable', ['src', 'tx'], ['snk', 'rx']))
expect(checkCircuit(root(p), lookup(p)).some(i => i.text.includes('not connected'))).toBe(false)
})
it('splitting or joining a port leaves the pins of the other side where they are', () => {
const p = project()
const get = lookup(p)
for (const design of [undefined, { w: 6, h: 3 }]) {
p.components.find(d => d.id === 'source')!.design = design
const rows = (splitPorts?: string[]) => shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts }, get).inputs.filter(i => !i.port).map(i => [i.key, i.dy])
expect(rows(['tx'])).toEqual(rows())
}
// A side of single pins only is still centred when nothing is split.
p.components.find(d => d.id === 'source')!.design = undefined
p.components.find(d => d.id === 'source')!.nodes.push({ id: 'z', kind: 'output', x: 10, y: 10, label: 'Z' }, { id: 'z2', kind: 'output', x: 10, y: 12, label: 'Z2' })
expect(shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get).inputs.map(i => [i.key, i.dy])).toEqual([['a', 1], ['b', 2]])
})
it('lists the pins of the usual edge first, so a wire dropped on the box takes those', () => {
const p = project()
const get = lookup(p)
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0, splitPorts: ['rx'] }, get)
expect(snk.outputs.map(o => o.key)).toEqual(['x', 'y', 'rx.l2'])
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0, splitPorts: ['tx'] }, get)
expect(src.inputs.map(i => i.key)).toEqual(['a', 'b', 'tx.l2'])
})
it('a cable onto split lines only takes those on their usual edge, so its end never sits in the box', () => {
const p = project()
p.connectors![0]!.lines = [{ name: 'D0' }, { name: 'D1' }, { name: 'RX0', back: true }, { name: 'RX1', back: true }]
const r = root(p)
const get = lookup(p)
node(p, 'root', 'src').splitPorts = ['tx']
node(p, 'root', 'snk').splitPorts = ['rx']
// RX0 and RX1 run back: into the source on its right edge, out of the sink on its left.
expect(cableIntoPins(r, 'src', ['tx.l2', 'tx.l3'], get).ok).toBe(false)
expect(cableFromPins(r, 'snk', ['rx.l2', 'rx.l3'], get).ok).toBe(false)
// D0 and D1 leave the source on the right and enter the sink on the left: there a cable fits.
const src = node(p, 'root', 'src')
const out = cableFromPins(r, 'src', ['tx.l0', 'tx.l1'], get)
expect(out.ok && out.bundle.x).toBe(src.x + shapeOf(src, get).body.w)
const into = cableIntoPins(r, 'snk', ['rx.l0', 'rx.l1'], get)
expect(into.ok && into.split.x).toBe(node(p, 'root', 'snk').x - 1)
})
it('unpacking joins wires on split lines to the parts inside', () => {
const p = project()
const r = root(p)
node(p, 'root', 'snk').splitPorts = ['rx']
r.nodes.push({ id: 'lamp2', kind: 'lamp', x: 50, y: 4 })
r.wires.push(w('d0', ['sa', 'q'], ['snk', 'rx.l0']), w('xl', ['snk', 'x'], ['lamp', 'a']), w('hp', ['snk', 'rx.l2'], ['lamp2', 'a']))
const res = unpackChip(p, 'root', 'snk')
expect(res.ok && res.dropped).toBe(0)
for (const [a, h] of [[0, 1], [1, 0]] as const) {
const s = run(p, { sa: !!a, sh: !!h })
expect([s.pin('lamp', 'q'), s.pin('lamp2', 'q')]).toEqual([a, h])
}
})
it('unpacking says how many wires on lines had nowhere to go', () => {
const p = project()
p.components.push({
id: 'box',
name: 'Box',
symbol: 'box',
nodes: [
{ id: 'inner', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'p2', kind: 'portout', conn: 'hdmi', x: 30, y: 0 },
],
wires: [w('b2', ['inner', 'tx'], ['p2', 'bus'])],
})
// D0 of the box comes from a part inside through a cable: no single wire inside to join it to.
root(p).nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20, splitPorts: ['p2'] })
root(p).wires.push(w('l0', ['bx', 'p2.l0'], ['lamp', 'a']))
const res = unpackChip(p, 'root', 'bx')
expect(res.ok && res.dropped).toBe(1)
})
it('a docked panel made before ports moved to the top loses its row for the socket and lines up again', () => {
const p = project()
const r = root(p)
r.wires = r.wires.filter(x => x.id !== 'r3')
// As docked by earlier releases: a row for H and one for the socket below it, the port at the bottom.
r.nodes.push({ id: 'pan', kind: 'panel', x: 24, y: 0, attach: 'snk', rows: [{ id: 'h', type: 'switch', dy: 0 }, { id: 'rx', type: 'switch', dy: 1 }] })
r.wires.push(w('ph', ['pan', 'h'], ['snk', 'h']))
syncPanels(p)
pruneWires(p)
const pan = node(p, 'root', 'pan')
expect(pan.rows!.map(x => x.id)).toEqual(['h'])
const h = shapeOf(node(p, 'root', 'snk'), lookup(p)).inputs.find(i => i.key === 'h')!
expect(pan.y).toBe(node(p, 'root', 'snk').y + h.dy)
})
})