A input panels, automatic names, one-by-one wiring, tidy routing, truth table export
- Input panel part: rows of switches, buttons and clocks. "Attach input panel" docks one to a component with a row per free input; it moves with the component and follows its pins. - Copies and new pins continue name series (D0 -> D1, A -> B); unnamed switches, lamps and pins take the name of the component pin they are wired to. - Connecting: target pins are ringed, dropping on a part uses its next free pin, click-then-click works, and "Connect one by one" (W) wires a selection's pins in turn. - Tidy wiring option and "Tidy all wires": sorted, evenly spaced columns per gap, one trunk per signal, fewer crossings. - Truth table full screen, CSV download, copy as Markdown, current row highlighted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
08b086a71e
commit
861b161c8b
11
README.md
11
README.md
|
|
@ -6,18 +6,22 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
|||
|
||||
## What it does
|
||||
|
||||
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, note.
|
||||
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, input panel, note.
|
||||
- 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.
|
||||
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
||||
- Lamps and hex displays inside a component show on its box, with their labels, lit by that instance's state. They are laid out in rows the way they sit inside. A checkbox in the inspector turns this off per component.
|
||||
- Clicking anything opens its settings on the right. Parts can be swapped in place (wires stay on the pins in the same position): NAND and components with each other, switch/button/clock/constants with each other, output/lamp/display with each other. Clocks have their own frequency or follow the top bar. Switches and buttons can get a keyboard key. Lamps and displays have colours, notes have sizes, components a name on the canvas. Components can be unpacked into their parts or given their own copy of the definition; any part can have all its wires unlinked.
|
||||
- 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.
|
||||
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Display settings on the right with nothing selected). Clicking a junction dot selects its whole signal.
|
||||
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
|
||||
- Tidy wiring (Display settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds, wires sharing a gap get their own evenly spaced column in the order that crosses least, and one signal shares one trunk. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
|
||||
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
|
||||
- Several projects per browser (Projects dialog: open, rename, duplicate, delete). Export a project file, open a file as a new project, or add the components of a file to the open project.
|
||||
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). If two computers changed the same project, both versions are kept. The untouched starter project of a new browser is not uploaded; signing in there opens your latest project instead.
|
||||
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
|
||||
- Truth table, NAND count, gate delay, and loop detection for the open circuit.
|
||||
- Truth table, NAND count, gate delay, and loop detection for the open circuit. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
|
||||
- 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.
|
||||
|
||||
|
|
@ -30,7 +34,8 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
|
|||
- 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).
|
||||
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings).
|
||||
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
|
||||
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
||||
- `wires.ts` edits wire routes (segment and corner drags, splits, branches); `project.ts` validates project data for both the browser and the server; `storage.ts` is the browser's project library.
|
||||
|
||||
The editor UI is in [app/components/editor/](app/components/editor/) with state in [app/composables/useEditor.ts](app/composables/useEditor.ts).
|
||||
|
|
|
|||
|
|
@ -1019,6 +1019,78 @@ kbd {
|
|||
fill: rgb(76 194 255 / 0.3);
|
||||
}
|
||||
|
||||
/* Where a wire being drawn can go. */
|
||||
.pin-target {
|
||||
fill: none;
|
||||
stroke: var(--accent);
|
||||
stroke-width: 1.5;
|
||||
opacity: 0.75;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.pin-target.taken {
|
||||
stroke: var(--muted);
|
||||
stroke-dasharray: 2 2;
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.pin-snap {
|
||||
fill: rgb(76 194 255 / 0.25);
|
||||
stroke: var(--accent);
|
||||
stroke-width: 2;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.queue-badge {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.queue-badge rect {
|
||||
fill: var(--panel-2);
|
||||
stroke: var(--border);
|
||||
}
|
||||
|
||||
.queue-badge text {
|
||||
fill: var(--muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 9px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.queue-badge.current rect {
|
||||
fill: var(--accent);
|
||||
stroke: var(--accent);
|
||||
}
|
||||
|
||||
.queue-badge.current text {
|
||||
fill: var(--bg);
|
||||
}
|
||||
|
||||
/* Input panel */
|
||||
.node .body.panel {
|
||||
fill: #161d27;
|
||||
}
|
||||
|
||||
.node .body.panel.docked {
|
||||
stroke: #4f7fa3;
|
||||
}
|
||||
|
||||
.panel-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.panel-row .row-hit {
|
||||
fill: transparent;
|
||||
}
|
||||
|
||||
.panel-row:hover .row-hit {
|
||||
fill: rgb(255 255 255 / 0.04);
|
||||
}
|
||||
|
||||
.panel-row .pin-label.named {
|
||||
fill: var(--text);
|
||||
}
|
||||
|
||||
.zoom-controls {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
|
|
@ -1486,3 +1558,54 @@ kbd {
|
|||
.modal .hint a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
/* ── Truth table, full screen ───────────────────────────────────── */
|
||||
.modal.table-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(1100px, 100%);
|
||||
height: calc(100dvh - 32px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.truth.large {
|
||||
flex: 1;
|
||||
max-height: none;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.truth.large table {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.truth.large th,
|
||||
.truth.large td {
|
||||
padding: 5px 10px;
|
||||
}
|
||||
|
||||
.truth tr.current td {
|
||||
background: rgb(76 194 255 / 0.12);
|
||||
}
|
||||
|
||||
/* ── Panel rows in the inspector ────────────────────────────────── */
|
||||
.panel-rows {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.panel-rows li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.panel-rows input,
|
||||
.panel-rows select {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.panel-rows input.hz {
|
||||
flex: 0 0 56px;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
<script setup lang="ts">
|
||||
const ed = useEditor()
|
||||
|
||||
const link = computed(() => {
|
||||
const l = ed.linking.value
|
||||
const end = l?.queue[l.at]
|
||||
return l && end ? { n: l.at + 1, total: l.queue.length, label: end.label, dir: end.dir } : null
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
const stop = ed.startLoop()
|
||||
onBeforeUnmount(stop)
|
||||
|
|
@ -27,6 +33,13 @@ onMounted(() => {
|
|||
<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>
|
||||
<div v-else-if="link" class="placing-hint">
|
||||
<template v-if="link.total > 1">
|
||||
<strong>{{ link.n }} of {{ link.total }}<template v-if="link.label">: {{ link.label }}</template></strong> ·
|
||||
</template>
|
||||
Click the pin {{ link.dir === 'out' ? 'it goes to' : 'it comes from' }}, or a part to use its next free pin. <kbd>Esc</kbd> stops.
|
||||
</div>
|
||||
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
|
||||
<EditorHelp v-if="ed.showHelp.value" />
|
||||
<EditorProjectsDialog v-if="ed.dialog.value === 'projects'" />
|
||||
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup lang="ts">
|
||||
import { GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
|
||||
import type { CircuitNode, Wire } from '~/lib/logic/types'
|
||||
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
|
||||
import { branchCorners, branchTo, moveCorner, moveSegment, segmentDrag, splitDrag } from '~/lib/logic/wires'
|
||||
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
|
||||
import { wirePath } from '~/lib/draw'
|
||||
|
|
@ -31,7 +31,7 @@ interface Route {
|
|||
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
|
||||
|
||||
const routes = computed<Route[]>(() => {
|
||||
const routed = circuitRoutes(def.value, shapes.value)
|
||||
const routed = circuitRoutes(def.value, shapes.value, { tidy: !!ed.project.value.settings.tidy })
|
||||
const hops = new Map<number, Map<number, number[]>>()
|
||||
for (const c of findCrossings(routed)) {
|
||||
const segs = hops.get(c.wire) ?? hops.set(c.wire, new Map()).get(c.wire)!
|
||||
|
|
@ -183,8 +183,19 @@ function onDrop(e: DragEvent) {
|
|||
// ── 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; branch?: Pt[] }
|
||||
| {
|
||||
kind: 'move'
|
||||
start: Pt
|
||||
orig: Map<string, Pt>
|
||||
/** Docked panels moved without their component: they only slide sideways. */
|
||||
lockY: Set<string>
|
||||
wires: Map<Wire, Pt[]>
|
||||
moved: boolean
|
||||
node: CircuitNode
|
||||
toggle: boolean
|
||||
row?: PanelRow
|
||||
}
|
||||
| { kind: 'wire'; node: string; pin: string; dir: 'in' | 'out'; start: Pt; cur: Pt; moved: boolean; branch?: Pt[] }
|
||||
| { kind: 'box'; start: Pt; cur: Pt; nodes: string[]; wires: string[] }
|
||||
| { kind: 'segment'; wire: Wire; base: Pt[]; k: number; axis: 0 | 1; start: number; moved: boolean }
|
||||
| { kind: 'corner'; wire: Wire; route: Pt[]; i: number; moved: boolean }
|
||||
|
|
@ -221,6 +232,23 @@ function onPointerDown(e: PointerEvent) {
|
|||
if (e.button !== 0) return
|
||||
root.value!.setPointerCapture(e.pointerId)
|
||||
|
||||
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')
|
||||
if (target) return ed.linkTo(target)
|
||||
const pinEl = (e.target as Element).closest('[data-pin]')
|
||||
if (pinEl && link.queue.length === 1) {
|
||||
// Another pin of the same kind: start from that one instead.
|
||||
const node = pinEl.getAttribute('data-node')!
|
||||
const pin = pinEl.getAttribute('data-pin')!
|
||||
ed.linking.value = { queue: [{ node, pin, dir: pinEl.getAttribute('data-dir') as 'in' | 'out', label: '' }], at: 0 }
|
||||
return
|
||||
}
|
||||
return ed.stopLinking()
|
||||
}
|
||||
|
||||
const placing = ed.placing.value
|
||||
if (placing) {
|
||||
if (placing.chip && !ed.canPlace(placing.chip)) {
|
||||
|
|
@ -241,7 +269,9 @@ function onPointerDown(e: PointerEvent) {
|
|||
node: pinEl.getAttribute('data-node')!,
|
||||
pin: pinEl.getAttribute('data-pin')!,
|
||||
dir: pinEl.getAttribute('data-dir') as 'in' | 'out',
|
||||
start: w,
|
||||
cur: w,
|
||||
moved: false,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
@ -271,16 +301,32 @@ function onPointerDown(e: PointerEvent) {
|
|||
ed.wireSel.value = []
|
||||
}
|
||||
|
||||
if (isDoubleClick(`n:${id}`)) return onDoubleClick(node)
|
||||
const rowId = target.closest('[data-row]')?.getAttribute('data-row')
|
||||
const row = rowId ? node.rows?.find(r => r.id === rowId) : undefined
|
||||
if (!row && isDoubleClick(`n:${id}`)) return onDoubleClick(node)
|
||||
|
||||
if (node.kind === 'button') ed.press(node, true)
|
||||
const ids = selected.value.has(id) ? ed.selection.value : [id]
|
||||
if (row && !multi) ed.pressRow(node, row, true)
|
||||
const ids = ed.withDocked(selected.value.has(id) ? ed.selection.value : [id])
|
||||
const orig = new Map<string, Pt>()
|
||||
const lockY = new Set<string>()
|
||||
for (const sid of ids) {
|
||||
const n = nodeMap.value.get(sid)
|
||||
if (n) orig.set(sid, [n.x, n.y])
|
||||
if (!n) continue
|
||||
orig.set(sid, [n.x, n.y])
|
||||
if (n.attach && !ids.has(n.attach)) lockY.add(sid)
|
||||
}
|
||||
drag.value = {
|
||||
kind: 'move',
|
||||
start: w,
|
||||
orig,
|
||||
lockY,
|
||||
wires: wiresToShift(ids),
|
||||
moved: false,
|
||||
node,
|
||||
toggle: (node.kind === 'input' || !!row) && !multi,
|
||||
row,
|
||||
}
|
||||
drag.value = { kind: 'move', start: w, orig, wires: wiresToShift(new Set(ids)), moved: false, node, toggle: node.kind === 'input' && !multi }
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -302,7 +348,7 @@ function onWireDown(e: PointerEvent, el: Element, w: Pt) {
|
|||
const index = Number(el.getAttribute('data-seg'))
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
// Branch: a new wire from the same signal, starting at this point.
|
||||
drag.value = { kind: 'wire', node: wire.from.node, pin: wire.from.pin, dir: 'out', cur: w, branch: branchCorners(route.pts, index, w) }
|
||||
drag.value = { kind: 'wire', node: wire.from.node, pin: wire.from.pin, dir: 'out', start: w, cur: w, moved: true, branch: branchCorners(route.pts, index, w) }
|
||||
return
|
||||
}
|
||||
if (e.shiftKey) {
|
||||
|
|
@ -337,12 +383,13 @@ function onPointerMove(e: PointerEvent) {
|
|||
if (!d.moved && (dx || dy)) {
|
||||
d.moved = true
|
||||
if (d.node.kind === 'button') ed.press(d.node, false)
|
||||
if (d.row) ed.pressRow(d.node, d.row, 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
|
||||
n.y = d.lockY.has(id) ? y : y + dy
|
||||
}
|
||||
}
|
||||
for (const [wire, pts] of d.wires) wire.pts = pts.map(([x, y]) => [x + dx, y + dy])
|
||||
|
|
@ -350,6 +397,7 @@ function onPointerMove(e: PointerEvent) {
|
|||
}
|
||||
case 'wire':
|
||||
d.cur = w
|
||||
if (Math.hypot(w[0] - d.start[0], w[1] - d.start[1]) > 0.4) d.moved = true
|
||||
break
|
||||
case 'box': {
|
||||
d.cur = w
|
||||
|
|
@ -386,9 +434,37 @@ function onPointerMove(e: PointerEvent) {
|
|||
}
|
||||
}
|
||||
|
||||
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
|
||||
/** Pin keys that already have a wire, as "node:pin": inputs by their wire, outputs by any wire. */
|
||||
const linked = computed(() => {
|
||||
const ins = new Set<string>()
|
||||
const outs = new Set<string>()
|
||||
for (const w of def.value.wires) {
|
||||
ins.add(`${w.to.node}:${w.to.pin}`)
|
||||
outs.add(`${w.from.node}:${w.from.pin}`)
|
||||
}
|
||||
return { in: ins, out: outs }
|
||||
})
|
||||
|
||||
/** The part whose body is under the point; the one drawn on top wins. */
|
||||
function nodeAt(at: Pt): CircuitNode | undefined {
|
||||
const list = def.value.nodes
|
||||
for (let i = list.length - 1; i >= 0; i--) {
|
||||
const n = list[i]!
|
||||
if (n.kind === 'note') continue
|
||||
const b = shapes.value.get(n.id)!.body
|
||||
if (at[0] >= n.x + b.x - 0.3 && at[0] <= n.x + b.x + b.w + 0.3 && at[1] >= n.y + b.y - 0.3 && at[1] <= n.y + b.y + b.h + 0.3) return n
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a wire would go: a pin of the wanted direction close to the point,
|
||||
* else, over a part, that part's first free pin (or its nearest one when
|
||||
* all are taken). So dropping a wire anywhere on a component works.
|
||||
*/
|
||||
function targetAt(at: Pt, dir: 'in' | 'out'): PinRef | null {
|
||||
let best: PinRef | null = null
|
||||
let bestD = 1.1 * 1.1
|
||||
for (const n of def.value.nodes) {
|
||||
const s = shapes.value.get(n.id)!
|
||||
for (const p of dir === 'in' ? s.inputs : s.outputs) {
|
||||
|
|
@ -401,7 +477,16 @@ function nearestPin(at: Pt, dir: 'in' | 'out'): { node: string; pin: string } |
|
|||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
if (best) return best
|
||||
const n = nodeAt(at)
|
||||
if (!n) return null
|
||||
const pins = dir === 'in' ? shapes.value.get(n.id)!.inputs : shapes.value.get(n.id)!.outputs
|
||||
if (!pins.length) return null
|
||||
const taken = linked.value[dir]
|
||||
const free = pins.find(p => !taken.has(`${n.id}:${p.key}`))
|
||||
if (free) return { node: n.id, pin: free.key }
|
||||
const near = pins.reduce((a, p) => (Math.abs(n.y + p.dy - at[1]) < Math.abs(n.y + a.dy - at[1]) ? p : a))
|
||||
return { node: n.id, pin: near.key }
|
||||
}
|
||||
|
||||
function onPointerUp() {
|
||||
|
|
@ -411,13 +496,20 @@ function onPointerUp() {
|
|||
switch (d.kind) {
|
||||
case 'move':
|
||||
if (d.node.kind === 'button') ed.press(d.node, false)
|
||||
if (d.row && !d.moved) ed.pressRow(d.node, d.row, false)
|
||||
if (d.moved) ed.commit(false)
|
||||
else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
|
||||
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.moved) {
|
||||
// A click on a pin: the wire follows the mouse until the next click.
|
||||
ed.linking.value = { queue: [{ ...here, dir: d.dir, label: '' }], at: 0 }
|
||||
break
|
||||
}
|
||||
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out')
|
||||
if (!target) break
|
||||
if (d.dir === 'in') {
|
||||
ed.connect(target, here)
|
||||
break
|
||||
|
|
@ -442,7 +534,7 @@ function onPointerUp() {
|
|||
|
||||
function onDoubleClick(node: CircuitNode) {
|
||||
if (node.kind === 'chip' && node.chip) ed.open(node.chip)
|
||||
else if (['input', 'output', 'lamp', 'button', 'note', 'hex'].includes(node.kind)) {
|
||||
else if (['input', 'output', 'lamp', 'button', 'note', 'hex', 'panel'].includes(node.kind)) {
|
||||
ed.selection.value = [node.id]
|
||||
ed.labelFocus.value++
|
||||
}
|
||||
|
|
@ -455,17 +547,17 @@ function onWheel(e: WheelEvent) {
|
|||
}
|
||||
|
||||
// ── Keyboard ────────────────────────────────────────────────────────
|
||||
const QUICK: Record<string, CircuitNode['kind']> = { n: 'nand', i: 'input', o: 'output', l: 'lamp', c: 'clock', b: 'button', h: 'hex', t: 'note' }
|
||||
const QUICK: Record<string, CircuitNode['kind']> = { n: 'nand', i: 'input', o: 'output', l: 'lamp', c: 'clock', b: 'button', h: 'hex', t: 'note', p: 'panel' }
|
||||
const ARROWS: Record<string, Pt> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
|
||||
|
||||
/** Arrow keys: move the selected parts and wires one grid step (four with Shift). */
|
||||
function nudge(dx: number, dy: number) {
|
||||
const ids = new Set(ed.selection.value)
|
||||
const ids = ed.withDocked(ed.selection.value)
|
||||
if (!ids.size && !ed.wireSel.value.length) return
|
||||
for (const n of def.value.nodes) {
|
||||
if (!ids.has(n.id)) continue
|
||||
n.x += dx
|
||||
n.y += dy
|
||||
if (!n.attach || ids.has(n.attach)) n.y += dy
|
||||
}
|
||||
for (const r of routes.value) {
|
||||
const both = ids.has(r.wire.from.node) && ids.has(r.wire.to.node)
|
||||
|
|
@ -519,6 +611,7 @@ function onKey(e: KeyboardEvent) {
|
|||
e.preventDefault()
|
||||
ed.deleteSelected()
|
||||
} else if (e.key === 'Escape') {
|
||||
if (ed.linking.value) return ed.stopLinking()
|
||||
ed.placing.value = null
|
||||
ed.clearSelection()
|
||||
} else if (ARROWS[e.key]) {
|
||||
|
|
@ -532,7 +625,8 @@ function onKey(e: KeyboardEvent) {
|
|||
} 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 && key === 'w' && ed.selection.value.length) ed.startLinking(ed.selection.value, e.shiftKey ? 'in' : undefined)
|
||||
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]! }
|
||||
}
|
||||
|
|
@ -544,24 +638,64 @@ function onKeyUp(e: KeyboardEvent) {
|
|||
}
|
||||
|
||||
// ── Overlays ────────────────────────────────────────────────────────
|
||||
const tempWire = computed(() => {
|
||||
/** The wire being drawn: dragged from a pin, or following the mouse after a click on a pin. */
|
||||
const pending = computed(() => {
|
||||
const d = drag.value
|
||||
if (d?.kind !== 'wire') return null
|
||||
if (d?.kind === 'wire') return d.moved ? { node: d.node, pin: d.pin, dir: d.dir, cur: d.cur, branch: d.branch } : null
|
||||
const l = ed.linking.value
|
||||
const end = l?.queue[l.at]
|
||||
return end && cursor.value ? { node: end.node, pin: end.pin, dir: end.dir, cur: cursor.value, branch: undefined } : null
|
||||
})
|
||||
|
||||
const tempWire = computed(() => {
|
||||
const d = pending.value
|
||||
if (!d) 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')
|
||||
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)
|
||||
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')!
|
||||
const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, want)!
|
||||
end = [tp.x, tp.y]
|
||||
}
|
||||
const pts =
|
||||
d.dir === 'out'
|
||||
? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end))
|
||||
: routeWire(end, [p.x, p.y])
|
||||
return { d: toPath(pts), snapped: !!target }
|
||||
return { d: toPath(pts), snapped: !!target, end }
|
||||
})
|
||||
|
||||
/** Pins a wire being drawn can go to: free ones stand out, taken ones would be replaced. */
|
||||
const targets = computed(() => {
|
||||
const d = pending.value
|
||||
if (!d) return []
|
||||
const want = d.dir === 'out' ? 'in' : 'out'
|
||||
const taken = linked.value[want]
|
||||
const out: { x: number; y: number; free: boolean }[] = []
|
||||
for (const n of def.value.nodes) {
|
||||
const s = shapes.value.get(n.id)!
|
||||
for (const p of want === 'in' ? s.inputs : s.outputs) {
|
||||
// An output can always take one more wire; an input only has room for one.
|
||||
out.push({ x: n.x + p.dx, y: n.y + p.dy, free: want === 'out' || !taken.has(`${n.id}:${p.key}`) })
|
||||
}
|
||||
}
|
||||
return out
|
||||
})
|
||||
|
||||
/** Numbers on the pins still waiting in "connect one by one". */
|
||||
const queueBadges = computed(() => {
|
||||
const l = ed.linking.value
|
||||
if (!l || l.queue.length < 2) return []
|
||||
return l.queue.flatMap((e, i) => {
|
||||
if (i < l.at) return []
|
||||
const n = nodeMap.value.get(e.node)
|
||||
const p = n && pinPos(n, shapes.value.get(n.id)!, e.pin, e.dir)
|
||||
return p ? [{ x: p.x + (e.dir === 'out' ? 0.75 : -0.75), y: p.y - 0.55, n: i + 1, current: i === l.at }] : []
|
||||
})
|
||||
})
|
||||
|
||||
const boxRect = computed(() => {
|
||||
|
|
@ -588,6 +722,7 @@ const cursorStyle = computed(() => {
|
|||
if (drag.value?.kind === 'pan') return 'grabbing'
|
||||
if (spaceDown.value) return 'grab'
|
||||
if (ed.placing.value) return 'copy'
|
||||
if (ed.linking.value) return 'crosshair'
|
||||
return 'default'
|
||||
})
|
||||
|
||||
|
|
@ -673,7 +808,15 @@ defineExpose({ fit, zoomAt })
|
|||
:data-corner="h.i"
|
||||
/>
|
||||
|
||||
<g class="targets">
|
||||
<circle v-for="(t, i) in targets" :key="`t${i}`" :cx="t.x * G" :cy="t.y * G" r="5.5" class="pin-target" :class="{ taken: !t.free }" />
|
||||
</g>
|
||||
<path v-if="tempWire" :d="tempWire.d" class="temp-wire" :class="{ snapped: tempWire.snapped }" />
|
||||
<circle v-if="tempWire?.snapped" :cx="tempWire.end[0] * G" :cy="tempWire.end[1] * G" r="6.5" class="pin-snap" />
|
||||
<g v-for="b in queueBadges" :key="`q${b.n}`" class="queue-badge" :class="{ current: b.current }">
|
||||
<rect :x="b.x * G - 7" :y="b.y * G - 6" width="14" height="12" rx="3" />
|
||||
<text :x="b.x * G" :y="b.y * G + 3.5" text-anchor="middle">{{ b.n }}</text>
|
||||
</g>
|
||||
<EditorNodeView v-if="ghost" :node="ghost" :shape="ed.shape(ghost)" :selected="false" ghost />
|
||||
<rect v-if="boxRect" v-bind="boxRect" class="box-select" />
|
||||
</g>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,9 @@ const ed = useEditor()
|
|||
const SHORTCUTS: [string, string][] = [
|
||||
['Click switch', 'Flip an input between 0 and 1 (give it a keyboard key in its settings)'],
|
||||
['Click anything', 'Its settings appear on the right: swap the part, clock speed, colours, keys, position'],
|
||||
['Drag from a pin', 'Draw a wire to another pin'],
|
||||
['Drag from a pin', 'Draw a wire to another pin; dropping it on a part uses that part’s next free pin'],
|
||||
['Click a pin, then another', 'The same without holding the mouse button'],
|
||||
['Select parts, then W', 'Connect one by one: click where each of their pins goes, in order (Shift+W: their inputs)'],
|
||||
['Drag a wire segment', 'Move that segment; drag a corner square to move a bend'],
|
||||
['Alt + drag a wire', 'Pull a new bend out of it'],
|
||||
['Ctrl + drag a wire', 'Start a new wire from the same signal'],
|
||||
|
|
@ -15,9 +17,9 @@ const SHORTCUTS: [string, string][] = [
|
|||
['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'],
|
||||
['N, I, O, L, B, C, H, T, P', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel'],
|
||||
['Shift + click on canvas', 'Keep placing the same part'],
|
||||
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate'],
|
||||
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
|
||||
['Delete', 'Remove the selection'],
|
||||
['Ctrl+Z, Ctrl+Shift+Z', 'Undo, redo'],
|
||||
['F', 'Fit the circuit to the screen'],
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
<script setup lang="ts">
|
||||
import type { TestResult, TruthTable } from '~/lib/logic/analyze'
|
||||
import { tableMarkdown, type TestResult, type TruthTable } from '~/lib/logic/analyze'
|
||||
import { CHALLENGES } from '~/lib/logic/challenges'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
import { usages } from '~/lib/logic/ops'
|
||||
|
|
@ -104,6 +104,9 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
|
|||
<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 mt-2 w-full" title="Their pins in order, top to bottom: click where each one goes (W)" @click="ed.startLinking()">
|
||||
<Icon name="lucide:cable" class="size-4" /> Connect one by one
|
||||
</button>
|
||||
<div class="mt-2 grid grid-cols-2 gap-2">
|
||||
<button class="btn" title="Remove every wire attached to the selected parts" @click="ed.unlink(ed.selection.value)"><Icon name="lucide:unlink" class="size-4" /> Unlink all</button>
|
||||
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||
|
|
@ -234,35 +237,34 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
|
|||
<input type="checkbox" :checked="settings.flow" @change="settings.flow = !settings.flow; ed.persist()" />
|
||||
Animate current flow on wires that carry a 1
|
||||
</label>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="!!settings.tidy" @change="ed.setTidy(!settings.tidy)" />
|
||||
Tidy wiring: sorted parallel runs, one trunk per signal, fewer crossings
|
||||
</label>
|
||||
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
|
||||
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<button class="section-toggle" @click="showTable = !showTable">
|
||||
<div class="flex items-center gap-1">
|
||||
<button class="section-toggle grow" @click="showTable = !showTable">
|
||||
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||
Truth table
|
||||
</button>
|
||||
<template v-if="showTable && table && !('error' in table)">
|
||||
<button class="icon-btn" title="Download as CSV" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-3.5" /></button>
|
||||
<button class="icon-btn" title="Copy as a Markdown table" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
||||
<Icon name="lucide:clipboard-copy" class="size-3.5" />
|
||||
</button>
|
||||
</template>
|
||||
<button class="icon-btn" title="Full screen" @click="ed.dialog.value = 'table'"><Icon name="lucide:maximize-2" class="size-3.5" /></button>
|
||||
</div>
|
||||
<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>
|
||||
<EditorTruthTable :table="table" />
|
||||
</template>
|
||||
</template>
|
||||
</section>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
<script setup lang="ts">
|
||||
import { stats } from '~/lib/logic/analyze'
|
||||
import { compile } from '~/lib/logic/compile'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
import { chipPins, rowLabel } from '~/lib/logic/geometry'
|
||||
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
||||
import { LAMP_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
|
||||
import { LAMP_COLORS, type CircuitNode, type NodeKind, type PanelControl, type PanelRow } from '~/lib/logic/types'
|
||||
|
||||
const props = defineProps<{ node: CircuitNode }>()
|
||||
const ed = useEditor()
|
||||
|
|
@ -19,8 +19,15 @@ const KIND_NAMES: Record<string, string> = {
|
|||
low: 'Ground (0)',
|
||||
hex: 'Hex display',
|
||||
note: 'Note',
|
||||
panel: 'Input panel',
|
||||
}
|
||||
|
||||
const CONTROLS: { value: PanelControl; label: string }[] = [
|
||||
{ value: 'switch', label: 'Switch' },
|
||||
{ value: 'button', label: 'Button' },
|
||||
{ value: 'clock', label: 'Clock' },
|
||||
]
|
||||
|
||||
const HINTS: Record<string, string> = {
|
||||
input: 'Click it on the canvas to flip it. Inside a component it becomes an input pin; pins are ordered top to bottom.',
|
||||
output: 'Inside a component it becomes an output pin; pins are ordered top to bottom.',
|
||||
|
|
@ -30,6 +37,7 @@ const HINTS: Record<string, string> = {
|
|||
button: 'Gives 1 while held down with the mouse or its key.',
|
||||
lamp: 'Lights up at 1. Inside a component it also shows on the component box.',
|
||||
hex: 'Shows inputs 1, 2, 4, 8 as one hex digit. Inside a component it also shows on the component box.',
|
||||
panel: 'Click a row on the canvas to flip its switch or hold its button. Rows without a name take the name of the pin they are wired to.',
|
||||
}
|
||||
|
||||
const n = computed(() => props.node)
|
||||
|
|
@ -118,6 +126,36 @@ function setSize(size: 'sm' | 'md' | 'lg') {
|
|||
function setOn(on: boolean) {
|
||||
if (!!n.value.on !== on) ed.toggleInput(n.value)
|
||||
}
|
||||
|
||||
/** A name typed by hand is kept from then on; clearing it lets connections name the part again. */
|
||||
function onLabel() {
|
||||
delete n.value.autoLabel
|
||||
ed.commit(false)
|
||||
}
|
||||
|
||||
const dock = computed(() => {
|
||||
const id = n.value.attach
|
||||
const chip = id ? ed.def.value.nodes.find(x => x.id === id) : undefined
|
||||
return chip ? chip.label?.trim() || (chip.chip ? ed.getDef.value(chip.chip)?.name : undefined) || 'component' : null
|
||||
})
|
||||
|
||||
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))
|
||||
|
||||
function setRowLabel(row: PanelRow, e: Event) {
|
||||
const v = (e.target as HTMLInputElement).value.trim()
|
||||
if (v) row.label = v
|
||||
else delete row.label
|
||||
ed.commit()
|
||||
}
|
||||
|
||||
function setRowHz(row: PanelRow, e: Event) {
|
||||
const v = Number((e.target as HTMLInputElement).value)
|
||||
if (v > 0 && v <= 1000) row.hz = v
|
||||
else delete row.hz
|
||||
ed.commit()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -148,11 +186,49 @@ function setOn(on: boolean) {
|
|||
v-else
|
||||
ref="labelInput"
|
||||
v-model="n.label"
|
||||
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : ''"
|
||||
@change="ed.commit(false)"
|
||||
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : ''"
|
||||
@change="onLabel"
|
||||
@keydown.enter="($event.target as HTMLInputElement).blur()"
|
||||
/>
|
||||
</label>
|
||||
<p v-if="n.autoLabel && n.label" class="hint -mt-1">Named automatically. Typing a name keeps it.</p>
|
||||
|
||||
<!-- Input panel rows -->
|
||||
<template v-if="n.kind === 'panel'">
|
||||
<p v-if="dock" class="result pass">
|
||||
<Icon name="lucide:link" class="size-4 shrink-0" />
|
||||
<span class="grow">Attached to {{ dock }}. It moves with it and gets a row for each new input.</span>
|
||||
<button class="btn-sm" title="Keep the panel and its wires, but stop following the component" @click="ed.undock(n)">Detach</button>
|
||||
</p>
|
||||
<div class="field">
|
||||
<span>Rows</span>
|
||||
<ul class="panel-rows">
|
||||
<li v-for="(r, i) in n.rows ?? []" :key="r.id">
|
||||
<input :value="r.label ?? ''" :placeholder="rowLabel({ ...r, label: undefined }, i)" title="Name" @change="setRowLabel(r, $event)" />
|
||||
<select :value="r.type" title="Kind" @change="ed.setRowType(r, ($event.target as HTMLSelectElement).value as PanelControl)">
|
||||
<option v-for="c in CONTROLS" :key="c.value" :value="c.value">{{ c.label }}</option>
|
||||
</select>
|
||||
<input
|
||||
v-if="r.type === 'clock'"
|
||||
type="number"
|
||||
min="0.1"
|
||||
max="1000"
|
||||
step="any"
|
||||
class="hz"
|
||||
:value="r.hz ?? ''"
|
||||
placeholder="Hz"
|
||||
title="Frequency in Hz; empty follows the top bar"
|
||||
@change="setRowHz(r, $event)"
|
||||
/>
|
||||
<button class="icon-btn" title="Remove this row" @click="ed.dropRow(n, r.id)"><Icon name="lucide:x" class="size-3.5" /></button>
|
||||
</li>
|
||||
</ul>
|
||||
<button v-if="!n.attach" class="btn-sm self-start" @click="ed.addRow(n)"><Icon name="lucide:plus" class="size-3.5" /> Add row</button>
|
||||
</div>
|
||||
<button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id])">
|
||||
<Icon name="lucide:cable" class="size-4" /> Wire rows one by one
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<!-- Kind-specific settings -->
|
||||
<template v-if="n.kind === 'input'">
|
||||
|
|
@ -220,6 +296,25 @@ function setOn(on: boolean) {
|
|||
</dl>
|
||||
<div class="grid gap-2">
|
||||
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
|
||||
<button
|
||||
v-if="chipInputs && !hasPanel"
|
||||
class="btn w-full"
|
||||
title="A switch for every free input, docked to the left; each one can become a button or clock"
|
||||
@click="ed.addPanel(n.id)"
|
||||
>
|
||||
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
|
||||
</button>
|
||||
<div v-if="chipInputs || chipOutputs" class="field mb-0">
|
||||
<span>Wire one by one</span>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button class="btn" :disabled="!chipInputs" title="Click the source for each input in turn" @click="ed.startLinking([n.id], 'in')">
|
||||
<Icon name="lucide:cable" class="size-4" /> Inputs
|
||||
</button>
|
||||
<button class="btn" :disabled="!chipOutputs" title="Click the target for each output in turn" @click="ed.startLinking([n.id], 'out')">
|
||||
<Icon name="lucide:cable" class="size-4" /> Outputs
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn w-full" title="Replace it with the parts inside; outside wires join them directly" @click="ed.unpack(n.id)">
|
||||
<Icon name="lucide:ungroup" class="size-4" /> Unpack into parts
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
<script setup lang="ts">
|
||||
import { gateDrawing, sevenSegment } from '~/lib/draw'
|
||||
import { GRID as G, noteLines, noteScale, type Shape } from '~/lib/logic/geometry'
|
||||
import { GRID as G, noteLines, noteScale, PANEL_CONTROL_W, type Shape } from '~/lib/logic/geometry'
|
||||
import type { CircuitNode } from '~/lib/logic/types'
|
||||
|
||||
const props = defineProps<{
|
||||
|
|
@ -16,6 +16,7 @@ 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 rows = computed(() => props.node.rows ?? [])
|
||||
|
||||
const v = (pin: string) => (props.ghost ? 0 : ed.val(props.node.id, pin))
|
||||
/** Value inside this chip, for its lamps and displays. */
|
||||
|
|
@ -133,6 +134,33 @@ const title = computed(() => {
|
|||
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
|
||||
</template>
|
||||
|
||||
<!-- Input panel: a switch, button or clock per row -->
|
||||
<template v-else-if="node.kind === 'panel'">
|
||||
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
|
||||
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body panel" :class="{ docked: !!node.attach }" />
|
||||
<g v-for="(p, i) in shape.outputs" :key="p.key" :data-row="p.key" class="panel-row" :transform="`translate(0 ${p.dy * G})`">
|
||||
<rect :x="0" :y="-0.5 * G" :width="b.w * G" :height="G" class="row-hit" />
|
||||
<text :x="5" y="3.5" class="pin-label" :class="{ named: !!rows[i]?.label || !!rows[i]?.name }">{{ p.label }}</text>
|
||||
<g :transform="`translate(${(b.w - PANEL_CONTROL_W) * G} 0)`">
|
||||
<template v-if="rows[i]?.type === 'button'">
|
||||
<rect x="2" :y="-0.4 * G" :width="1.3 * G" :height="0.8 * G" rx="2" class="body" />
|
||||
<circle :cx="2 + 0.65 * G" cy="0" :r="0.27 * G" class="button" :class="{ on: v(p.key) === 1 }" />
|
||||
</template>
|
||||
<path
|
||||
v-else-if="rows[i]?.type === 'clock'"
|
||||
:d="`M2 ${0.25 * G}H${0.4 * G}V${-0.25 * G}H${0.75 * G}V${0.25 * G}H${1.1 * G}V${-0.25 * G}H${1.4 * G}`"
|
||||
class="wave"
|
||||
:class="{ on: v(p.key) === 1 }"
|
||||
/>
|
||||
<template v-else>
|
||||
<rect x="2" :y="-0.38 * G" :width="1.3 * G" :height="0.76 * G" :rx="0.38 * G" class="switch" :class="{ on: v(p.key) === 1 }" />
|
||||
<circle :cx="v(p.key) === 1 ? 2 + 0.92 * G : 2 + 0.38 * G" cy="0" :r="0.27 * G" class="knob" />
|
||||
</template>
|
||||
<path :d="`M${1.55 * G} 0H${PANEL_CONTROL_W * G}`" class="stub" />
|
||||
</g>
|
||||
</g>
|
||||
</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" />
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint:
|
|||
{ 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: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks. On a component, "Attach input panel" makes one for its inputs.' },
|
||||
{ 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.' },
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
<script setup lang="ts">
|
||||
import type { TruthTable } from '~/lib/logic/analyze'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
|
||||
defineProps<{ table: TruthTable; large?: boolean }>()
|
||||
const ed = useEditor()
|
||||
|
||||
/** The row the switches are set to right now. */
|
||||
const current = computed(() => {
|
||||
const d = ed.def.value
|
||||
const on = new Map(d.nodes.map(n => [n.id, !!n.on]))
|
||||
return chipPins(d).inputs.reduce((i, p) => i * 2 + (on.get(p.key) ? 1 : 0), 0)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="truth" :class="{ large }">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="(l, i) in table.inputs" :key="`i${i}`">{{ l }}</th>
|
||||
<th class="sep" />
|
||||
<th v-for="(l, i) in table.outputs" :key="`o${i}`" class="out">{{ l }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(r, i) in table.rows" :key="i" :class="{ unstable: !r.settled, current: i === current }">
|
||||
<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>
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
<script setup lang="ts">
|
||||
import { tableMarkdown } from '~/lib/logic/analyze'
|
||||
|
||||
const ed = useEditor()
|
||||
const close = () => (ed.dialog.value = null)
|
||||
|
||||
const table = computed(() => {
|
||||
void ed.sim.value
|
||||
return ed.table()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-backdrop" @click.self="close">
|
||||
<div class="modal table-modal" role="dialog" aria-labelledby="table-title">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 id="table-title">Truth table: {{ ed.def.value.name }}</h2>
|
||||
<p v-if="!('error' in table)" class="hint mt-1">
|
||||
{{ table.inputs.length }} input{{ table.inputs.length === 1 ? '' : 's' }}, {{ table.outputs.length }} output{{ table.outputs.length === 1 ? '' : 's' }},
|
||||
{{ table.rows.length }} rows. The highlighted row is what the switches are set to now.
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<template v-if="!('error' in table)">
|
||||
<button class="btn" title="Download as CSV, for spreadsheets" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-4" /> CSV</button>
|
||||
<button class="btn" title="Copy as a Markdown table (pastes as plain text too)" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
||||
<Icon name="lucide:clipboard-copy" class="size-4" /> Copy
|
||||
</button>
|
||||
</template>
|
||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
<EditorTruthTable :table="table" large />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -2,10 +2,12 @@
|
|||
// history, share links 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 { runSteps, stats, tableCsv, 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 { compile, rowSource } from '~/lib/logic/compile'
|
||||
import { shapeOf, type Pt } from '~/lib/logic/geometry'
|
||||
import { adoptName, continueSeries, newPinLabel } from '~/lib/logic/labels'
|
||||
import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
|
||||
import {
|
||||
addExamples,
|
||||
containsDef,
|
||||
|
|
@ -47,7 +49,15 @@ import {
|
|||
type AccountUser,
|
||||
type ProjectMeta,
|
||||
} from '~/lib/logic/storage'
|
||||
import type { CircuitNode, NodeKind, PinRef, Project, WireColor } from '~/lib/logic/types'
|
||||
import type { CircuitNode, NodeKind, PanelControl, PanelRow, PinRef, Project, WireColor } from '~/lib/logic/types'
|
||||
|
||||
/** One pin waiting to be wired in "connect one by one". */
|
||||
export interface LinkEnd {
|
||||
node: string
|
||||
pin: string
|
||||
dir: 'in' | 'out'
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface Placing {
|
||||
kind: NodeKind
|
||||
|
|
@ -105,7 +115,9 @@ function create() {
|
|||
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
|
||||
const labelFocus = ref(0)
|
||||
const showHelp = ref(false)
|
||||
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions'>(null)
|
||||
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table'>(null)
|
||||
/** Pins being wired one after another; `at` is the one the next click connects. */
|
||||
const linking = ref<{ queue: LinkEnd[]; at: number } | null>(null)
|
||||
/** Project whose savegames the versions dialog shows. */
|
||||
const versionsFor = ref<string | null>(null)
|
||||
|
||||
|
|
@ -160,7 +172,10 @@ function create() {
|
|||
|
||||
/** Record a change. Structural changes (parts, wires) rebuild the simulation. */
|
||||
function commit(structural = true) {
|
||||
if (structural) pruneWires(project.value)
|
||||
if (structural) {
|
||||
syncPanels(project.value)
|
||||
pruneWires(project.value)
|
||||
}
|
||||
const s = snap()
|
||||
if (s === last) return
|
||||
undoStack.push(last)
|
||||
|
|
@ -223,6 +238,13 @@ function create() {
|
|||
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))
|
||||
else if (n.kind === 'panel') {
|
||||
for (const r of n.rows ?? []) {
|
||||
const key = rowSource(n.id, r.id)
|
||||
if (r.type === 'switch') s.setSource(key, !!r.on)
|
||||
else if (r.type === 'button') s.setSource(key, pressed.has(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
s.run(BUDGET)
|
||||
if (simRoot !== key) cycles.value = 0
|
||||
|
|
@ -335,6 +357,7 @@ function create() {
|
|||
project.value.openId = id
|
||||
clearSelection()
|
||||
placing.value = null
|
||||
linking.value = null
|
||||
persist()
|
||||
rebuild()
|
||||
}
|
||||
|
|
@ -345,21 +368,15 @@ function create() {
|
|||
}
|
||||
|
||||
// ── 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 === 'input' || p.kind === 'output') {
|
||||
node.label = newPinLabel(def.value, p.kind)
|
||||
node.autoLabel = true
|
||||
}
|
||||
if (p.kind === 'note') node.label = 'Note'
|
||||
if (p.kind === 'panel') node.rows = newPanelRows()
|
||||
def.value.nodes.push(node)
|
||||
selection.value = [node.id]
|
||||
wireSel.value = []
|
||||
|
|
@ -380,14 +397,28 @@ function create() {
|
|||
const sameNet = d.wires.find(w => w.from.node === from.node && w.from.pin === from.pin && w.color)
|
||||
if (sameNet?.color) wire.color = sameNet.color
|
||||
d.wires.push(wire)
|
||||
// An unnamed switch, lamp or pin takes the name of the component pin it now connects to.
|
||||
const fn = d.nodes.find(n => n.id === from.node)
|
||||
const tn = d.nodes.find(n => n.id === to.node)
|
||||
if (fn && tn) {
|
||||
adoptName(d, fn, from.pin, tn, to.pin, getDef.value)
|
||||
adoptName(d, tn, to.pin, fn, from.pin, getDef.value)
|
||||
}
|
||||
wireSel.value = []
|
||||
commit()
|
||||
}
|
||||
|
||||
/** Parts plus the panels docked to them: they move, copy and delete together. */
|
||||
function withDocked(ids: Iterable<string>): Set<string> {
|
||||
const set = new Set(ids)
|
||||
for (const p of dockedPanels(def.value, set)) set.add(p.id)
|
||||
return set
|
||||
}
|
||||
|
||||
function deleteSelected() {
|
||||
const d = def.value
|
||||
if (!selection.value.length && !wireSel.value.length) return
|
||||
const ids = new Set(selection.value)
|
||||
const ids = withDocked(selection.value)
|
||||
const wires = new Set(wireSel.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) && !wires.has(w.id))
|
||||
|
|
@ -459,11 +490,59 @@ function create() {
|
|||
sim.value?.setSource(node.id, down)
|
||||
}
|
||||
|
||||
/** Click on a panel row: flips a switch row. */
|
||||
function toggleRow(node: CircuitNode, row: PanelRow) {
|
||||
if (row.type !== 'switch') return
|
||||
row.on = !row.on
|
||||
sim.value?.setSource(rowSource(node.id, row.id), row.on)
|
||||
persist()
|
||||
}
|
||||
|
||||
function pressRow(node: CircuitNode, row: PanelRow, down: boolean) {
|
||||
if (row.type !== 'button') return
|
||||
const key = rowSource(node.id, row.id)
|
||||
if (down) pressed.add(key)
|
||||
else pressed.delete(key)
|
||||
sim.value?.setSource(key, down)
|
||||
}
|
||||
|
||||
// ── Panels ────────────────────────────────────────────────────────
|
||||
function addPanel(chipId: string) {
|
||||
const panel = attachPanel(project.value, def.value, chipId)
|
||||
if (!panel) return notify('Every input of this component is already connected', 'error')
|
||||
selection.value = [panel.id]
|
||||
wireSel.value = []
|
||||
commit()
|
||||
notify(`Input panel with ${panel.rows!.length} switch${panel.rows!.length === 1 ? '' : 'es'} attached`)
|
||||
}
|
||||
|
||||
function undock(panel: CircuitNode) {
|
||||
detachPanel(panel)
|
||||
commit()
|
||||
}
|
||||
|
||||
function setRowType(row: PanelRow, type: PanelControl) {
|
||||
row.type = type
|
||||
if (type !== 'switch') delete row.on
|
||||
if (type !== 'clock') delete row.hz
|
||||
commit()
|
||||
}
|
||||
|
||||
function addRow(panel: CircuitNode) {
|
||||
panel.rows = [...(panel.rows ?? []), ...newPanelRows(1)]
|
||||
commit()
|
||||
}
|
||||
|
||||
function dropRow(panel: CircuitNode, rowId: string) {
|
||||
removeRow(def.value, panel, rowId)
|
||||
commit()
|
||||
}
|
||||
|
||||
let clip: Clip | null = null
|
||||
let pasteCount = 0
|
||||
function copy() {
|
||||
if (!selection.value.length) return
|
||||
clip = copySelection(def.value, new Set(selection.value))
|
||||
clip = copySelection(def.value, withDocked(selection.value))
|
||||
pasteCount = 0
|
||||
notify(`Copied ${clip.nodes.length} part${clip.nodes.length === 1 ? '' : 's'}`)
|
||||
}
|
||||
|
|
@ -474,7 +553,10 @@ function create() {
|
|||
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)
|
||||
const ids = pasteClip(def.value, usable, 2 * pasteCount, 2 * pasteCount)
|
||||
const fresh = new Set(ids)
|
||||
continueSeries(def.value, def.value.nodes.filter(n => fresh.has(n.id)))
|
||||
selection.value = ids
|
||||
wireSel.value = []
|
||||
commit()
|
||||
}
|
||||
|
|
@ -484,6 +566,70 @@ function create() {
|
|||
paste()
|
||||
}
|
||||
|
||||
// ── Connect one by one ────────────────────────────────────────────
|
||||
/**
|
||||
* Pins of the given parts, top to bottom, ready to be wired one after the
|
||||
* other: their outputs, or their inputs when asked for (or when they have
|
||||
* no outputs, like lamps).
|
||||
*/
|
||||
function linkQueue(ids: string[], want?: 'in' | 'out'): LinkEnd[] {
|
||||
const nodes = def.value.nodes.filter(n => ids.includes(n.id) && n.kind !== 'note').sort((a, b) => a.y - b.y || a.x - b.x)
|
||||
const shapes = nodes.map(n => ({ n, s: shapeOf(n, getDef.value) }))
|
||||
const dir = want ?? (shapes.some(({ s }) => s.outputs.length) ? 'out' : 'in')
|
||||
const queue: LinkEnd[] = []
|
||||
for (const { n, s } of shapes) {
|
||||
for (const p of dir === 'out' ? s.outputs : s.inputs) {
|
||||
const label = p.label || n.label?.trim() || ''
|
||||
queue.push({ node: n.id, pin: p.key, dir, label })
|
||||
}
|
||||
}
|
||||
return queue
|
||||
}
|
||||
|
||||
function startLinking(ids = selection.value, want?: 'in' | 'out') {
|
||||
const queue = linkQueue(ids, want)
|
||||
if (!queue.length) return notify('Nothing to connect: select parts with pins', 'error')
|
||||
placing.value = null
|
||||
linking.value = null
|
||||
linking.value = { queue, at: 0 }
|
||||
}
|
||||
|
||||
/** Wires the pin whose turn it is to `target`, then moves on to the next one. */
|
||||
function linkTo(target: PinRef) {
|
||||
const l = linking.value
|
||||
const cur = l?.queue[l.at]
|
||||
if (!l || !cur) return
|
||||
const here = { node: cur.node, pin: cur.pin }
|
||||
if (cur.dir === 'out') connect(here, target)
|
||||
else connect(target, here)
|
||||
l.at++
|
||||
if (l.at >= l.queue.length) {
|
||||
linking.value = null
|
||||
if (l.queue.length > 1) notify(`Connected ${l.queue.length} pins`)
|
||||
}
|
||||
}
|
||||
|
||||
function stopLinking() {
|
||||
linking.value = null
|
||||
}
|
||||
|
||||
// ── Tidy wiring ───────────────────────────────────────────────────
|
||||
function setTidy(on: boolean) {
|
||||
if (on) project.value.settings.tidy = true
|
||||
else delete project.value.settings.tidy
|
||||
persist()
|
||||
}
|
||||
|
||||
/** Removes all hand-placed bends in the open circuit and lays every wire out tidily. */
|
||||
function tidyAll() {
|
||||
const bent = def.value.wires.filter(w => w.pts).length
|
||||
for (const w of def.value.wires) delete w.pts
|
||||
project.value.settings.tidy = true
|
||||
commit(false)
|
||||
persist()
|
||||
notify(bent ? `Tidied. ${bent} hand-placed bend${bent === 1 ? ' was' : 's were'} removed (Ctrl+Z brings ${bent === 1 ? 'it' : 'them'} back)` : 'Tidy wiring is on')
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
selection.value = def.value.nodes.map(n => n.id)
|
||||
wireSel.value = def.value.wires.map(w => w.id)
|
||||
|
|
@ -556,6 +702,7 @@ function create() {
|
|||
nav.value = []
|
||||
clearSelection()
|
||||
placing.value = null
|
||||
linking.value = null
|
||||
for (const k of Object.keys(views)) delete views[k]
|
||||
linkState.value = m.link ? (m.link.key ? 'saved' : 'viewer') : 'none'
|
||||
projects.value = listProjects()
|
||||
|
|
@ -634,8 +781,8 @@ function create() {
|
|||
notify(n ? `Added ${n} example parts` : 'All examples are already here')
|
||||
}
|
||||
|
||||
function download(name: string, text: string) {
|
||||
const blob = new Blob([text], { type: 'application/json' })
|
||||
function download(name: string, text: string, type = 'application/json') {
|
||||
const blob = new Blob([text], { type })
|
||||
const a = document.createElement('a')
|
||||
a.href = URL.createObjectURL(blob)
|
||||
a.download = name
|
||||
|
|
@ -643,10 +790,15 @@ function create() {
|
|||
URL.revokeObjectURL(a.href)
|
||||
}
|
||||
|
||||
const slug = (name: string, fallback: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || fallback
|
||||
|
||||
function exportJson() {
|
||||
persistNow()
|
||||
const slug = project.value.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project'
|
||||
download(`${slug}.logigate.json`, JSON.stringify(project.value, null, 1))
|
||||
download(`${slug(project.value.name, 'project')}.logigate.json`, JSON.stringify(project.value, null, 1))
|
||||
}
|
||||
|
||||
function exportTable(t: TruthTable) {
|
||||
download(`${slug(def.value.name, 'circuit')}-truth-table.csv`, tableCsv(t), 'text/csv')
|
||||
}
|
||||
|
||||
/** Opens a project file as a new project in the library. */
|
||||
|
|
@ -777,12 +929,12 @@ function create() {
|
|||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
async function copyText(text: string, done = 'Link copied') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
notify('Link copied')
|
||||
notify(done)
|
||||
} catch {
|
||||
notify('Copy failed; select the link and copy it by hand', 'error')
|
||||
notify('Copy failed: the browser did not allow it', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1134,6 +1286,21 @@ function create() {
|
|||
selectNet,
|
||||
toggleInput,
|
||||
press,
|
||||
toggleRow,
|
||||
pressRow,
|
||||
addPanel,
|
||||
undock,
|
||||
setRowType,
|
||||
addRow,
|
||||
dropRow,
|
||||
withDocked,
|
||||
linking,
|
||||
startLinking,
|
||||
linkTo,
|
||||
stopLinking,
|
||||
setTidy,
|
||||
tidyAll,
|
||||
exportTable,
|
||||
swap,
|
||||
unlink,
|
||||
unpack,
|
||||
|
|
|
|||
|
|
@ -41,6 +41,25 @@ export function truthTable(getDef: DefLookup, defId: string): TruthTable | { err
|
|||
return { inputs: pins.inputs.map(p => p.label), outputs: pins.outputs.map(p => p.label), rows }
|
||||
}
|
||||
|
||||
const cell = (r: TruthRow, v: number) => (r.settled ? String(v) : '~')
|
||||
|
||||
/** Comma-separated, for spreadsheets. A row that never settled shows ~ for its outputs. */
|
||||
export function tableCsv(t: TruthTable): string {
|
||||
const quote = (s: string) => (/[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s)
|
||||
const lines = [[...t.inputs, ...t.outputs].map(quote).join(',')]
|
||||
for (const r of t.rows) lines.push([...r.ins.map(String), ...r.outs.map(v => cell(r, v))].join(','))
|
||||
return `${lines.join('\n')}\n`
|
||||
}
|
||||
|
||||
/** Markdown table, which also reads fine as plain text. */
|
||||
export function tableMarkdown(t: TruthTable): string {
|
||||
const esc = (s: string) => s.replace(/\|/g, '\\|')
|
||||
const head = [...t.inputs, ...t.outputs].map(esc)
|
||||
const lines = [`| ${head.join(' | ')} |`, `|${head.map(() => ':-:').join('|')}|`]
|
||||
for (const r of t.rows) lines.push(`| ${[...r.ins.map(String), ...r.outs.map(v => cell(r, v))].join(' | ')} |`)
|
||||
return `${lines.join('\n')}\n`
|
||||
}
|
||||
|
||||
export interface Stats {
|
||||
nands: number
|
||||
/** Has feedback loops, so it can store state (latch, flip-flop, counter). */
|
||||
|
|
|
|||
|
|
@ -61,11 +61,16 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
|
|||
return ['q']
|
||||
case 'chip':
|
||||
return pins ? pins.outputs.map(p => p.key) : []
|
||||
case 'panel':
|
||||
return (node.rows ?? []).map(r => r.id)
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
||||
export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}`
|
||||
|
||||
const MAX_DEPTH = 64
|
||||
|
||||
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
|
||||
|
|
@ -163,6 +168,16 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
|
|||
case 'clock':
|
||||
clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id })
|
||||
break
|
||||
case 'panel':
|
||||
// In the open circuit the rows are switches and buttons you use;
|
||||
// inside a component a switch row keeps its position, a button is 0.
|
||||
for (const r of n.rows ?? []) {
|
||||
const net = outNet.get(`${n.id}:${r.id}`)!
|
||||
if (r.type === 'clock') clocks.push({ net, hz: r.hz ?? 0, key: `${path}${n.id}:${r.id}` })
|
||||
else if (!inNets) sources.set(rowSource(n.id, r.id), net)
|
||||
else if (r.type === 'switch' && r.on) union(net, HIGH)
|
||||
}
|
||||
break
|
||||
case 'output':
|
||||
result.set(n.id, inNet(n.id, 'a'))
|
||||
break
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// 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, LampColor, SymbolKind } from './types'
|
||||
import type { CircuitNode, ComponentDef, LampColor, PanelRow, SymbolKind } from './types'
|
||||
|
||||
export const GRID = 16
|
||||
|
||||
|
|
@ -174,6 +174,37 @@ const CLOCK_SHAPE: Shape = {
|
|||
|
||||
const MISSING_SHAPE: Shape = { body: { x: 0, y: -1, w: 4, h: 2 }, inputs: [], outputs: [] }
|
||||
|
||||
/** Grid offset of every panel row below the first one. */
|
||||
export function panelOffsets(rows: PanelRow[]): number[] {
|
||||
const out: number[] = []
|
||||
for (const r of rows) {
|
||||
const prev = out.length ? out[out.length - 1]! : -1
|
||||
out.push(r.dy !== undefined && r.dy > prev ? r.dy : prev + 1)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Name shown next to a panel row: the user's, the driven pin's, or its number. */
|
||||
export function rowLabel(row: PanelRow, i: number): string {
|
||||
return row.label?.trim() || row.name?.trim() || String(i + 1)
|
||||
}
|
||||
|
||||
/** Width of the control drawn in each panel row, in grid units. */
|
||||
export const PANEL_CONTROL_W = 2.2
|
||||
|
||||
function panelShape(node: CircuitNode): Shape {
|
||||
const rows = node.rows ?? []
|
||||
const dys = panelOffsets(rows)
|
||||
const labels = rows.map(rowLabel)
|
||||
const w = Math.max(4, Math.ceil(labels.reduce((m, l) => Math.max(m, l.length), 0) * LABEL_CHAR + PANEL_CONTROL_W + 1.1))
|
||||
const last = dys.length ? dys[dys.length - 1]! : 0
|
||||
return {
|
||||
body: { x: 0, y: -0.5, w, h: last + 1 },
|
||||
inputs: [],
|
||||
outputs: rows.map((r, i) => ({ key: r.id, label: labels[i]!, dx: w, dy: dys[i]! })),
|
||||
}
|
||||
}
|
||||
|
||||
export function noteLines(node: CircuitNode): string[] {
|
||||
return (node.label || 'Note').split('\n')
|
||||
}
|
||||
|
|
@ -198,6 +229,8 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
|
|||
return SINK_SHAPE
|
||||
case 'hex':
|
||||
return HEX_SHAPE
|
||||
case 'panel':
|
||||
return panelShape(node)
|
||||
case 'note': {
|
||||
const lines = noteLines(node)
|
||||
const k = noteScale(node)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,125 @@
|
|||
// Automatic names. Copies and new parts continue a series (D0, D1, D2;
|
||||
// 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 type { CircuitNode, ComponentDef, NodeKind } from './types'
|
||||
|
||||
const SERIES = /^(.*?)(\d+)$/
|
||||
const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
||||
|
||||
/** Kinds whose labels share one set of names, so D0 the input and D0 the output can both exist. */
|
||||
export function labelSpace(kind: NodeKind): string | null {
|
||||
if (kind === 'input' || kind === 'button' || kind === 'clock' || kind === 'panel') return 'in'
|
||||
if (kind === 'output' || kind === 'lamp' || kind === 'hex') return 'out'
|
||||
if (kind === 'chip') return 'chip'
|
||||
return null
|
||||
}
|
||||
|
||||
export function usedLabels(def: ComponentDef, space: string, except?: Set<string>): Set<string> {
|
||||
const used = new Set<string>()
|
||||
for (const n of def.nodes) {
|
||||
if (except?.has(n.id) || labelSpace(n.kind) !== space) continue
|
||||
const l = n.label?.trim()
|
||||
if (l) used.add(l)
|
||||
}
|
||||
return used
|
||||
}
|
||||
|
||||
/**
|
||||
* The next free name after `label` in its series: D0 → D1 (D07 → D08), and a
|
||||
* single capital letter → the next free letter. Null for names without a series.
|
||||
*/
|
||||
export function nextInSeries(label: string, used: Set<string>): string | null {
|
||||
const m = SERIES.exec(label)
|
||||
if (m) {
|
||||
const [, stem, digits] = m
|
||||
for (let i = Number(digits) + 1; ; i++) {
|
||||
const next = `${stem}${String(i).padStart(digits!.length, '0')}`
|
||||
if (!used.has(next)) return next
|
||||
}
|
||||
}
|
||||
const at = label.length === 1 ? LETTERS.indexOf(label) : -1
|
||||
if (at >= 0) {
|
||||
for (const c of LETTERS.slice(at + 1)) if (!used.has(c)) return c
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** `base` itself when free, else a numbered variant (Cin → Cin2, D0 → D0_2). */
|
||||
export function uniqueLabel(base: string, used: Set<string>): string {
|
||||
if (!used.has(base)) return base
|
||||
const sep = /\d$/.test(base) ? '_' : ''
|
||||
for (let i = 2; ; i++) if (!used.has(`${base}${sep}${i}`)) return `${base}${sep}${i}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames pasted parts so their series continue: copying D0..D3 next to
|
||||
* themselves gives D4..D7. Names without a series stay as they are.
|
||||
*/
|
||||
export function continueSeries(def: ComponentDef, pasted: CircuitNode[]) {
|
||||
const ids = new Set(pasted.map(n => n.id))
|
||||
const order = (n: CircuitNode) => Number(SERIES.exec(n.label?.trim() ?? '')?.[2] ?? Infinity)
|
||||
const list = pasted.filter(n => labelSpace(n.kind) && n.label?.trim()).sort((a, b) => order(a) - order(b) || a.y - b.y || a.x - b.x)
|
||||
const used = new Map<string, Set<string>>()
|
||||
for (const n of list) {
|
||||
const space = labelSpace(n.kind)!
|
||||
if (!used.has(space)) used.set(space, usedLabels(def, space, ids))
|
||||
const taken = used.get(space)!
|
||||
const label = n.label!.trim()
|
||||
const next = taken.has(label) ? nextInSeries(label, taken) : label
|
||||
if (next) n.label = next
|
||||
taken.add(n.label!)
|
||||
}
|
||||
}
|
||||
|
||||
/** Name of a component pin as its inside calls it, without the in1/out1 fallback. */
|
||||
export function pinName(node: CircuitNode, pin: string, get: DefLookup): string | undefined {
|
||||
if (node.kind === 'panel') {
|
||||
const row = node.rows?.find(r => r.id === pin)
|
||||
return row?.label?.trim() || row?.name?.trim() || undefined
|
||||
}
|
||||
if (node.kind !== 'chip' || !node.chip) return undefined
|
||||
const def = get(node.chip)
|
||||
return def?.nodes.find(n => n.id === pin)?.label?.trim() || undefined
|
||||
}
|
||||
|
||||
const ADOPTERS = new Set<NodeKind>(['input', 'button', 'output', 'lamp'])
|
||||
|
||||
/**
|
||||
* After a new wire: a switch, button, output pin or lamp that has no name
|
||||
* of its own (or only an automatic one) takes the name of the component pin
|
||||
* at the other end, as long as this is its only connection. A panel row
|
||||
* without a name does the same. Returns true if a name changed.
|
||||
*/
|
||||
export function adoptName(def: ComponentDef, node: CircuitNode, pin: string, other: CircuitNode, otherPin: string, get: DefLookup): boolean {
|
||||
const name = pinName(other, otherPin, get)
|
||||
if (!name) return false
|
||||
const links = def.wires.filter(w => (w.from.node === node.id && w.from.pin === pin) || w.to.node === node.id).length
|
||||
if (links !== 1) return false
|
||||
if (node.kind === 'panel') {
|
||||
const row = node.rows?.find(r => r.id === pin)
|
||||
if (!row || row.label?.trim() || row.name === name) return false
|
||||
row.name = name
|
||||
return true
|
||||
}
|
||||
if (!ADOPTERS.has(node.kind) || (node.label?.trim() && !node.autoLabel)) return false
|
||||
const label = uniqueLabel(name, usedLabels(def, labelSpace(node.kind)!, new Set([node.id])))
|
||||
if (node.label === label) return false
|
||||
node.label = label
|
||||
node.autoLabel = true
|
||||
return true
|
||||
}
|
||||
|
||||
/** Label for a new input or output pin: continues the series of the last one placed, else the next free letter. */
|
||||
export function newPinLabel(def: ComponentDef, kind: 'input' | 'output'): string {
|
||||
const used = usedLabels(def, labelSpace(kind)!)
|
||||
const last = def.nodes.filter(n => n.kind === kind && n.label?.trim()).at(-1)?.label?.trim()
|
||||
if (last && SERIES.test(last)) return nextInSeries(last, used)!
|
||||
if (kind === 'input') {
|
||||
for (const c of 'ABCDEFGHIJKLMNOPRSTUVWXYZ') if (!used.has(c)) return c
|
||||
return uniqueLabel('I1', used)
|
||||
}
|
||||
if (!used.has('Q')) return 'Q'
|
||||
for (let i = 1; ; i++) if (!used.has(`Q${i}`)) return `Q${i}`
|
||||
}
|
||||
|
|
@ -199,6 +199,8 @@ export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number)
|
|||
ids.set(n.id, id)
|
||||
def.nodes.push({ ...clone(n), id, x: n.x + dx, y: n.y + dy })
|
||||
}
|
||||
const fresh = new Set(ids.values())
|
||||
redock(def.nodes.filter(n => fresh.has(n.id)), ids)
|
||||
for (const w of clip.wires) {
|
||||
const from = ids.get(w.from.node)
|
||||
const to = ids.get(w.to.node)
|
||||
|
|
@ -210,6 +212,19 @@ export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number)
|
|||
return [...ids.values()]
|
||||
}
|
||||
|
||||
/** Copied panels dock to the copy of their component, or to nothing when it was not copied along. */
|
||||
function redock(nodes: CircuitNode[], ids: Map<string, string>) {
|
||||
for (const n of nodes) {
|
||||
if (!n.attach) continue
|
||||
const to = ids.get(n.attach)
|
||||
if (to) n.attach = to
|
||||
else {
|
||||
delete n.attach
|
||||
delete n.skip
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -403,6 +418,8 @@ export function unpackChip(project: Project, defId: string, nodeId: string): { o
|
|||
ids.set(n.id, id)
|
||||
def.nodes.push({ ...clone(n), id, x: n.x + ox, y: n.y + oy })
|
||||
}
|
||||
const fresh = new Set(ids.values())
|
||||
redock(def.nodes.filter(n => fresh.has(n.id)), ids)
|
||||
|
||||
const kindOf = new Map(child.nodes.map(n => [n.id, n.kind]))
|
||||
const feed = new Map<string, Wire['from']>()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,134 @@
|
|||
// Input panels: one part with a column of switches, buttons and clocks.
|
||||
// A panel can be wired like any other part, or docked to a component, where
|
||||
// it gets one row per free input pin. A docked panel moves with its
|
||||
// component and follows it when the component gains or loses pins.
|
||||
|
||||
import { chipPins, shapeOf, type DefLookup } from './geometry'
|
||||
import { lookup, uid } from './ops'
|
||||
import type { CircuitNode, ComponentDef, PanelRow, Project } from './types'
|
||||
|
||||
/** Free space between a docked panel and its component, in grid units. */
|
||||
const DOCK_GAP = 3
|
||||
|
||||
export function newPanelRows(count = 4): PanelRow[] {
|
||||
return Array.from({ length: count }, () => ({ id: uid('r'), type: 'switch' as const }))
|
||||
}
|
||||
|
||||
/** Panels docked to one of the given chip nodes. */
|
||||
export function dockedPanels(def: ComponentDef, chipIds: Set<string>): CircuitNode[] {
|
||||
return def.nodes.filter(n => n.kind === 'panel' && n.attach && chipIds.has(n.attach))
|
||||
}
|
||||
|
||||
interface ChipInput {
|
||||
key: string
|
||||
label: string
|
||||
dy: number
|
||||
}
|
||||
|
||||
function chipInputs(chip: CircuitNode, get: DefLookup): ChipInput[] | null {
|
||||
const child = chip.kind === 'chip' && chip.chip ? get(chip.chip) : undefined
|
||||
if (!child) return null
|
||||
const labels = new Map(chipPins(child).inputs.map(p => [p.key, p.label]))
|
||||
return shapeOf(chip, get).inputs.map(p => ({ key: p.key, label: labels.get(p.key) ?? p.label, dy: p.dy }))
|
||||
}
|
||||
|
||||
/** Lines the rows up with the chip's pins and names them after the pins. */
|
||||
function layout(panel: CircuitNode, pins: ChipInput[]) {
|
||||
const byKey = new Map(pins.map(p => [p.key, p]))
|
||||
const order = new Map(pins.map((p, i) => [p.key, i]))
|
||||
const rows = (panel.rows ?? []).filter(r => byKey.has(r.id)).sort((a, b) => order.get(a.id)! - order.get(b.id)!)
|
||||
const top = rows.length ? byKey.get(rows[0]!.id)!.dy : 0
|
||||
for (const r of rows) {
|
||||
const p = byKey.get(r.id)!
|
||||
r.dy = p.dy - top
|
||||
r.name = p.label
|
||||
}
|
||||
panel.rows = rows
|
||||
return top
|
||||
}
|
||||
|
||||
/**
|
||||
* Docks a new panel to the left of a placed component, with a switch for
|
||||
* every input that is not wired yet. Returns the panel, or null when every
|
||||
* input is already in use.
|
||||
*/
|
||||
export function attachPanel(project: Project, def: ComponentDef, chipId: string): CircuitNode | null {
|
||||
const get = lookup(project)
|
||||
const chip = def.nodes.find(n => n.id === chipId)
|
||||
const pins = chip && chipInputs(chip, get)
|
||||
if (!chip || !pins) return null
|
||||
const wired = new Set(def.wires.filter(w => w.to.node === chipId).map(w => w.to.pin))
|
||||
const free = pins.filter(p => !wired.has(p.key))
|
||||
if (!free.length) return null
|
||||
const panel: CircuitNode = {
|
||||
id: uid('n'),
|
||||
kind: 'panel',
|
||||
x: 0,
|
||||
y: 0,
|
||||
attach: chipId,
|
||||
rows: free.map(p => ({ id: p.key, type: 'switch' })),
|
||||
}
|
||||
if (free.length < pins.length) panel.skip = pins.filter(p => wired.has(p.key)).map(p => p.key)
|
||||
const top = layout(panel, pins)
|
||||
panel.x = chip.x - DOCK_GAP - shapeOf(panel, get).body.w
|
||||
panel.y = chip.y + top
|
||||
def.nodes.push(panel)
|
||||
for (const r of panel.rows!) def.wires.push({ id: uid('w'), from: { node: panel.id, pin: r.id }, to: { node: chipId, pin: r.id } })
|
||||
return panel
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps docked panels in step with their components: rows for pins that are
|
||||
* gone are dropped, new free pins get a switch, and rows stay lined up with
|
||||
* the pins. A panel whose component was removed is undocked. Runs on every
|
||||
* structural change; wires to dropped rows are cleaned up afterwards.
|
||||
*/
|
||||
export function syncPanels(project: Project) {
|
||||
const get = lookup(project)
|
||||
for (const def of project.components) {
|
||||
if (!def.nodes.some(n => n.kind === 'panel' && n.attach)) continue
|
||||
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
||||
for (const panel of def.nodes) {
|
||||
if (panel.kind !== 'panel' || !panel.attach) continue
|
||||
const chip = nodes.get(panel.attach)
|
||||
const pins = chip && chipInputs(chip, get)
|
||||
if (!chip || !pins) {
|
||||
delete panel.attach
|
||||
delete panel.skip
|
||||
continue
|
||||
}
|
||||
const keys = new Set(pins.map(p => p.key))
|
||||
const rows = panel.rows ?? []
|
||||
const skip = (panel.skip ?? []).filter(k => keys.has(k))
|
||||
const known = new Set([...rows.map(r => r.id), ...skip])
|
||||
const wired = new Set(def.wires.filter(w => w.to.node === chip.id).map(w => w.to.pin))
|
||||
for (const p of pins) {
|
||||
if (known.has(p.key)) continue
|
||||
if (wired.has(p.key)) skip.push(p.key)
|
||||
else {
|
||||
rows.push({ id: p.key, type: 'switch' })
|
||||
def.wires.push({ id: uid('w'), from: { node: panel.id, pin: p.key }, to: { node: chip.id, pin: p.key } })
|
||||
}
|
||||
}
|
||||
panel.rows = rows
|
||||
if (skip.length) panel.skip = skip
|
||||
else delete panel.skip
|
||||
const top = layout(panel, pins)
|
||||
// Keep the first row on its pin, wherever the panel was moved sideways.
|
||||
if (panel.rows.length) panel.y = chip.y + top
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes one row; on a docked panel that pin is left alone from then on. */
|
||||
export function removeRow(def: ComponentDef, panel: CircuitNode, rowId: string) {
|
||||
panel.rows = (panel.rows ?? []).filter(r => r.id !== rowId)
|
||||
def.wires = def.wires.filter(w => !(w.from.node === panel.id && w.from.pin === rowId))
|
||||
if (panel.attach) panel.skip = [...new Set([...(panel.skip ?? []), rowId])]
|
||||
}
|
||||
|
||||
/** A docked panel's pins drive the component; undocking keeps rows, wires and position. */
|
||||
export function detachPanel(panel: CircuitNode) {
|
||||
delete panel.attach
|
||||
delete panel.skip
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
// Reading project data from files, links and storage. Shared by the browser
|
||||
// and the share-link server, so it must stay free of browser APIs.
|
||||
|
||||
import { CROSSING_STYLES, LAMP_COLORS, WIRE_COLORS, type CircuitNode, type Project } from './types'
|
||||
import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project } from './types'
|
||||
|
||||
/** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */
|
||||
function cleanNode(n: CircuitNode) {
|
||||
|
|
@ -9,6 +9,28 @@ function cleanNode(n: CircuitNode) {
|
|||
if (n.color !== undefined && !LAMP_COLORS.includes(n.color)) delete n.color
|
||||
if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key
|
||||
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
|
||||
if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel
|
||||
if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach
|
||||
if (n.skip !== undefined) {
|
||||
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
|
||||
else delete n.skip
|
||||
}
|
||||
if (n.rows !== undefined) {
|
||||
if (!Array.isArray(n.rows)) delete n.rows
|
||||
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_ROWS = 256
|
||||
|
||||
function cleanRow(r: PanelRow): boolean {
|
||||
if (!r || typeof r !== 'object' || typeof r.id !== 'string' || !r.id) return false
|
||||
if (!PANEL_CONTROLS.includes(r.type)) r.type = 'switch'
|
||||
for (const k of ['label', 'name'] as const) if (r[k] !== undefined && typeof r[k] !== 'string') delete r[k]
|
||||
if (r.on !== undefined && typeof r.on !== 'boolean') delete r.on
|
||||
if (r.hz !== undefined && !(typeof r.hz === 'number' && r.hz > 0 && r.hz <= 1000)) delete r.hz
|
||||
if (r.dy !== undefined && !(Number.isInteger(r.dy) && r.dy >= 0 && r.dy <= 10_000)) delete r.dy
|
||||
return true
|
||||
}
|
||||
|
||||
/** Upper bounds for a project that comes from outside. */
|
||||
|
|
@ -41,6 +63,7 @@ export function toProject(data: unknown): Project {
|
|||
symbols: p.settings?.symbols === 'ansi' ? 'ansi' : 'iec',
|
||||
flow: p.settings?.flow ?? true,
|
||||
...(p.settings?.crossing && CROSSING_STYLES.includes(p.settings.crossing) ? { crossing: p.settings.crossing } : {}),
|
||||
...(p.settings?.tidy === true ? { tidy: true } : {}),
|
||||
},
|
||||
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
|
||||
}
|
||||
|
|
|
|||
|
|
@ -333,7 +333,114 @@ export function findCrossings(routes: Routed[]): Crossing[] {
|
|||
return out
|
||||
}
|
||||
|
||||
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[]): Routed[] {
|
||||
// ── Tidy routing ────────────────────────────────────────────────────
|
||||
// The way a panel builder wires a cabinet. Every forward wire takes its
|
||||
// vertical step in the free gap right in front of the part it feeds. All
|
||||
// wires that share a gap get their own column there, evenly spaced, in the
|
||||
// order that crosses the fewest other wires; wires of one signal share one
|
||||
// trunk with branches off it.
|
||||
|
||||
interface TidyNet {
|
||||
net: string
|
||||
/** Row of the source pin. */
|
||||
y1: number
|
||||
/** Rows of the target pins in this gap. */
|
||||
ys: number[]
|
||||
min: number
|
||||
max: number
|
||||
wires: RouteInput[]
|
||||
}
|
||||
|
||||
const inside = (y: number, n: TidyNet) => y > n.min + EPS && y < n.max - EPS
|
||||
|
||||
/** Crossings between two signals in one gap when `a` takes the column left of `b`. */
|
||||
function crossings(a: TidyNet, b: TidyNet): number {
|
||||
let n = inside(b.y1, a) ? 1 : 0
|
||||
for (const y of a.ys) if (inside(y, b)) n++
|
||||
return n
|
||||
}
|
||||
|
||||
/** Columns for k signals in the gap lo+1 .. hi-1, as far from other signals' columns as it gets. */
|
||||
function columns(k: number, lo: number, hi: number, spans: TidyNet[], occ: Occupancy): number[] {
|
||||
const width = hi - lo - 1
|
||||
if (k > width) return Array.from({ length: k }, (_, i) => lo + 1 + Math.floor((i * width) / k))
|
||||
const step = width >= 2 * k + 1 ? 2 : 1
|
||||
const block = (k - 1) * step + 1
|
||||
const center = lo + 1 + Math.floor((width - block) / 2)
|
||||
let best: number[] = []
|
||||
let bestCost = Infinity
|
||||
for (let d = 0; d <= width; d++) {
|
||||
for (const start of d ? [center - d, center + d] : [center]) {
|
||||
if (start < lo + 1 || start + block - 1 > hi - 1) continue
|
||||
const cols = Array.from({ length: k }, (_, i) => start + i * step)
|
||||
let c = 0
|
||||
cols.forEach((x, i) => (c += occ.overlap([x, spans[i]!.min], [x, spans[i]!.max], spans[i]!.net)))
|
||||
if (c < bestCost) {
|
||||
best = cols
|
||||
bestCost = c
|
||||
}
|
||||
if (c === 0) return cols
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies: BodyIndex, pins: Set<number>, grid: Map<string, Pt[]>) {
|
||||
const gaps = new Map<string, { lo: number; hi: number; nets: Map<string, TidyNet> }>()
|
||||
for (const w of inputs) {
|
||||
if (grid.has(w.id)) continue
|
||||
const [x1, y1] = w.a
|
||||
const [x2, y2] = w.b
|
||||
if (x2 < x1 + 2) continue // feedback wires keep the usual router
|
||||
if (y1 === y2 && cost([w.a, w.b], w.net, occ, bodies, pins).penalty === 0) {
|
||||
grid.set(w.id, [w.a, w.b])
|
||||
occ.add([w.a, w.b], w.net)
|
||||
continue
|
||||
}
|
||||
const min = Math.min(y1, y2)
|
||||
const max = Math.max(y1, y2)
|
||||
// The gap starts at the nearest part on the left that the vertical step would cut through.
|
||||
let lo = x1
|
||||
for (const b of boxes) {
|
||||
const right = b.x + b.w
|
||||
if (right > lo && right < x2 && b.y < max && b.y + b.h > min) lo = Math.ceil(right)
|
||||
}
|
||||
if (lo + 1 > x2 - 1) continue
|
||||
const key = `${lo},${x2}`
|
||||
const gap = gaps.get(key) ?? gaps.set(key, { lo, hi: x2, nets: new Map() }).get(key)!
|
||||
const net = gap.nets.get(w.net)
|
||||
if (net) {
|
||||
net.ys.push(y2)
|
||||
net.min = Math.min(net.min, y2)
|
||||
net.max = Math.max(net.max, y2)
|
||||
net.wires.push(w)
|
||||
} else gap.nets.set(w.net, { net: w.net, y1, ys: [y2], min, max, wires: [w] })
|
||||
}
|
||||
|
||||
const ordered = [...gaps.values()].sort((p, q) => p.hi - q.hi || p.lo - q.lo)
|
||||
for (const gap of ordered) {
|
||||
const nets = [...gap.nets.values()].sort((a, b) => crossings(a, b) - crossings(b, a) || a.y1 - b.y1 || a.min - b.min)
|
||||
const cols = columns(nets.length, gap.lo, gap.hi, nets, occ)
|
||||
nets.forEach((n, i) => {
|
||||
const x = cols[i]!
|
||||
for (const w of n.wires) {
|
||||
const route = simplify([w.a, [x, w.a[1]], [x, w.b[1]], w.b])
|
||||
let blocked = false
|
||||
for (let s = 0; s < route.length - 1 && !blocked; s++) blocked = bodies.hits(route[s]!, route[s + 1]!) > 0
|
||||
if (blocked) continue // the usual router finds a way around
|
||||
grid.set(w.id, route)
|
||||
occ.add(route, w.net)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface RouteOptions {
|
||||
/** Electrician-style layout for wires without hand-placed corners. */
|
||||
tidy?: boolean
|
||||
}
|
||||
|
||||
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts: RouteOptions = {}): Routed[] {
|
||||
const occ = new Occupancy()
|
||||
const pinSet = new Set(pins.map(([x, y]) => pinKey(x, y)))
|
||||
const bodyIndex = new BodyIndex(bodies)
|
||||
|
|
@ -345,8 +452,9 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[]): Route
|
|||
grid.set(w.id, r)
|
||||
occ.add(r, w.net)
|
||||
}
|
||||
if (opts.tidy) tidyRoutes(inputs, bodies, occ, bodyIndex, pinSet, grid)
|
||||
for (const w of inputs) {
|
||||
if (w.pts?.length) continue
|
||||
if (grid.has(w.id)) continue
|
||||
const r = autoRoute(w, occ, bodyIndex, pinSet)
|
||||
grid.set(w.id, r)
|
||||
occ.add(r, w.net)
|
||||
|
|
@ -360,7 +468,7 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[]): Route
|
|||
}
|
||||
|
||||
/** Routes every wire of a circuit, given the shapes of its parts. */
|
||||
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>): Routed[] {
|
||||
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions = {}): Routed[] {
|
||||
const nodes = new Map(def.nodes.map(n => [n.id, n]))
|
||||
const bodies: Box[] = []
|
||||
const pins: Pt[] = []
|
||||
|
|
@ -380,5 +488,5 @@ export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>): Ro
|
|||
if (!a || !b) continue
|
||||
inputs.push({ id: w.id, net: `${w.from.node}:${w.from.pin}`, a: [a.x, a.y], b: [b.x, b.y], pts: w.pts })
|
||||
}
|
||||
return routeAll(inputs, bodies, pins)
|
||||
return routeAll(inputs, bodies, pins, opts)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ export type BuiltinKind =
|
|||
| 'lamp' // indicator light
|
||||
| 'hex' // 4-bit hex display
|
||||
| 'note' // text annotation, no pins
|
||||
| 'panel' // column of switches, buttons and clocks, one output per row
|
||||
|
||||
export type NodeKind = BuiltinKind | 'chip'
|
||||
|
||||
|
|
@ -37,6 +38,33 @@ export interface CircuitNode {
|
|||
key?: string
|
||||
/** Text size of a note. */
|
||||
size?: NoteSize
|
||||
/** Set while the label was given automatically, so a new connection may rename it. */
|
||||
autoLabel?: boolean
|
||||
/** Rows of a panel, top to bottom. */
|
||||
rows?: PanelRow[]
|
||||
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
|
||||
attach?: string
|
||||
/** Chip pins an attached panel leaves alone (wired elsewhere, or a row the user removed). */
|
||||
skip?: string[]
|
||||
}
|
||||
|
||||
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
|
||||
export type PanelControl = (typeof PANEL_CONTROLS)[number]
|
||||
|
||||
export interface PanelRow {
|
||||
/** Output pin key. On an attached panel: the key of the chip pin it drives. */
|
||||
id: string
|
||||
type: PanelControl
|
||||
/** Name set by the user. */
|
||||
label?: string
|
||||
/** Name taken from the pin the row drives. */
|
||||
name?: string
|
||||
/** Switch position. */
|
||||
on?: boolean
|
||||
/** Clock frequency in Hz. Empty: follows the speed in the top bar. */
|
||||
hz?: number
|
||||
/** Offset below the first row in grid units; default one below the row before. */
|
||||
dy?: number
|
||||
}
|
||||
|
||||
export const LAMP_COLORS = ['yellow', 'red', 'green', 'blue', 'white'] as const
|
||||
|
|
@ -85,6 +113,8 @@ export interface Settings {
|
|||
flow: boolean
|
||||
/** How a wire is drawn where it crosses another, unconnected one. */
|
||||
crossing?: CrossingStyle
|
||||
/** Route wires electrician style: sorted parallel runs, one trunk per signal, few crossings. */
|
||||
tidy?: boolean
|
||||
}
|
||||
|
||||
export const CROSSING_STYLES = ['bow', 'triangle', 'bridge', 'gap', 'plain'] as const
|
||||
|
|
|
|||
|
|
@ -0,0 +1,345 @@
|
|||
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('works as a source inside a component: a switch row keeps its position, a clock row is a clock', () => {
|
||||
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 }, { 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: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 }], wires: [] }
|
||||
p.components.push(inner, root)
|
||||
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(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<number, { lo: number; hi: number; net: string }[]>()
|
||||
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)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue