diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 02f9e37..e2503c4 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -915,6 +915,38 @@ kbd {
border-color: var(--accent);
}
+/* Drawings on a hand-drawn component box. */
+.node .face-ink {
+ fill: none;
+ stroke-width: 1.5;
+ stroke-linecap: round;
+}
+
+.node .face-text {
+ font-family: var(--font-sans);
+ font-weight: 600;
+ pointer-events: none;
+}
+
+.node .face-ink.ink-muted { stroke: #6b778a; }
+.node .face-ink.ink-text { stroke: var(--text); }
+.node .face-ink.ink-red { stroke: #ff5c5c; }
+.node .face-ink.ink-yellow { stroke: #ffd34d; }
+.node .face-ink.ink-green { stroke: #3ddc84; }
+.node .face-ink.ink-blue { stroke: #4dabff; }
+.node .face-ink.filled.ink-muted { fill: rgb(107 119 138 / 0.25); }
+.node .face-ink.filled.ink-text { fill: rgb(219 226 234 / 0.18); }
+.node .face-ink.filled.ink-red { fill: rgb(255 92 92 / 0.22); }
+.node .face-ink.filled.ink-yellow { fill: rgb(255 211 77 / 0.22); }
+.node .face-ink.filled.ink-green { fill: rgb(61 220 132 / 0.22); }
+.node .face-ink.filled.ink-blue { fill: rgb(77 171 255 / 0.22); }
+.node .face-text.ink-muted { fill: #8592a3; }
+.node .face-text.ink-text { fill: var(--text); }
+.node .face-text.ink-red { fill: #ff5c5c; }
+.node .face-text.ink-yellow { fill: #ffd34d; }
+.node .face-text.ink-green { fill: #3ddc84; }
+.node .face-text.ink-blue { fill: #4dabff; }
+
/* + and − under a selected gate. */
.widen-btn {
cursor: pointer;
@@ -3003,3 +3035,128 @@ kbd {
.search-results .muted {
color: var(--muted);
}
+
+/* ── Face designer ──────────────────────────────────────────────── */
+.modal.face-modal {
+ width: min(760px, 100%);
+}
+
+.face-tools {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 10px;
+ margin: 14px 0 10px;
+}
+
+.face-tools .seg button {
+ padding: 0 9px;
+}
+
+.face-inks {
+ display: flex;
+ gap: 5px;
+}
+
+.face-size {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ color: var(--muted);
+ font-size: 12px;
+}
+
+.face-size input {
+ width: 56px;
+ height: 26px;
+ padding: 0 6px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg);
+ color: var(--text);
+}
+
+.btn-sm.on {
+ border-color: var(--accent);
+ color: var(--accent);
+}
+
+.face-canvas {
+ display: block;
+ user-select: none;
+ -webkit-user-select: none;
+ max-width: 100%;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--bg);
+ touch-action: none;
+}
+
+.face-canvas.drawing {
+ cursor: crosshair;
+}
+
+.face-thing {
+ fill: transparent;
+ stroke: rgb(76 194 255 / 0.25);
+ stroke-dasharray: 3 3;
+ cursor: move;
+}
+
+.face-thing.shape {
+ stroke: transparent;
+}
+
+.face-thing:hover,
+.face-thing.shape:hover {
+ stroke: rgb(76 194 255 / 0.6);
+}
+
+.face-thing.sel,
+.face-thing.shape.sel {
+ stroke: var(--accent);
+ stroke-dasharray: none;
+ stroke-width: 1.5;
+}
+
+.face-canvas.drawing .face-thing,
+.face-canvas.drawing .face-hit {
+ pointer-events: none;
+}
+
+.face-hit {
+ stroke: transparent;
+ stroke-width: 9;
+ stroke-linecap: round;
+ cursor: move;
+}
+
+.face-hit:hover {
+ stroke: rgb(76 194 255 / 0.3);
+}
+
+.face-hit.sel {
+ stroke: rgb(76 194 255 / 0.45);
+}
+
+.face-grip {
+ fill: var(--bg);
+ stroke: var(--accent);
+ stroke-width: 1.5;
+ cursor: nwse-resize;
+}
+
+.face-props,
+.face-hidden {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ min-height: 34px;
+ margin-top: 10px;
+}
+
+.face-props .text-input {
+ flex: 1;
+ min-width: 120px;
+}
diff --git a/app/components/editor/App.vue b/app/components/editor/App.vue
index 042fb2b..5c06a4c 100644
--- a/app/components/editor/App.vue
+++ b/app/components/editor/App.vue
@@ -54,5 +54,6 @@ onMounted(() => {
+
diff --git a/app/components/editor/BulkSettings.vue b/app/components/editor/BulkSettings.vue
index 4ed132c..718c3db 100644
--- a/app/components/editor/BulkSettings.vue
+++ b/app/components/editor/BulkSettings.vue
@@ -341,6 +341,13 @@ function pack() {
Or drag one wire from a selected part to a pin: the others follow onto the next pins.
+
Sheet
The circuit as a wiring sheet with a title block: print it, save it as PDF, or keep it as an SVG.
diff --git a/app/components/editor/FaceDialog.vue b/app/components/editor/FaceDialog.vue
new file mode 100644
index 0000000..8a0ed3f
--- /dev/null
+++ b/app/components/editor/FaceDialog.vue
@@ -0,0 +1,399 @@
+
+
+
+
+
+
+
+
The box of "{{ def.name }}"
+
Drag lamps, displays and the name where you want them, draw on it, size it. Every placed copy shows it.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Small
+ Normal
+ Large
+ Huge
+
+
+ {{ { line: 'Line', rect: 'Box', ellipse: 'Circle' }[selShape.kind] }}: drag it, or its dots to resize. Shift keeps a new line straight.
+ Delete
+
+
+ {{ selThing.id === 'name' ? 'The name' : selThing.label }}: drag it where it belongs.
+ Leave off the box
+
+ Pick a tool to draw, or drag things on the box. Delete removes a drawing.
+
+
+ Left off:
+
+ {{ h.label }}
+
+
+
+
+
diff --git a/app/components/editor/Help.vue b/app/components/editor/Help.vue
index ba5f453..ee99466 100644
--- a/app/components/editor/Help.vue
+++ b/app/components/editor/Help.vue
@@ -31,6 +31,8 @@ const SHORTCUTS: [string, string][] = [
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'],
['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'],
['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
+ ['Select input panels, Merge', 'One panel with all their rows; inside a component its rows are input pins'],
+ ['Design the box (Circuit tab)', 'Move lamps, displays and the name on a component\'s box, draw lines, boxes, circles and text'],
['Select several lamps, pins or switches', 'Green boxes show free pins in a row they fit; point along one, click to wire them all'],
['Shift + click on canvas', 'Keep placing the same part'],
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],
diff --git a/app/components/editor/NodeSettings.vue b/app/components/editor/NodeSettings.vue
index 814ea8d..b967c66 100644
--- a/app/components/editor/NodeSettings.vue
+++ b/app/components/editor/NodeSettings.vue
@@ -219,6 +219,12 @@ const undriven = computed(() => {
return cableBits(n.value) - fed.size
})
+function setInner(inner: boolean) {
+ if (inner) n.value.inner = true
+ else delete n.value.inner
+ ed.commit()
+}
+
function setRowHz(row: PanelRow, e: Event) {
const v = Number((e.target as HTMLInputElement).value)
if (v > 0 && v <= 1000) row.hz = v
@@ -394,6 +400,11 @@ function setRowHz(row: PanelRow, e: Event) {
Wire rows one by one
+
+
+ Rows are component inputs
+
+ Kept inside: in a component the switches stay as set here, buttons read 0.
@@ -522,6 +533,9 @@ function setRowHz(row: PanelRow, e: Event) {
Open component
+
+ Design its box
+
{
{{ node.label }}
- {{ chipDef?.name ?? 'Missing' }}
+
+
+
+
+
+ {{ d.text }}
+
+ {{ chipDef?.name ?? 'Missing' }}
diff --git a/app/components/editor/PinsPane.vue b/app/components/editor/PinsPane.vue
index 3baa75d..618330f 100644
--- a/app/components/editor/PinsPane.vue
+++ b/app/components/editor/PinsPane.vue
@@ -33,6 +33,7 @@ function pinNumber(e: IoEntry, entries: IoEntry[]) {
}
function kindText(e: IoEntry, entries: IoEntry[]): string {
+ if (e.row && e.pin) return `pin ${pinNumber(e, entries)} · ${e.row.type}`
if (e.row) return e.row.type === 'clock' && e.row.hz ? `clock ${e.row.hz} Hz` : e.row.type
if (e.pin) return `pin ${pinNumber(e, entries)}`
if (e.node.kind === 'clock') return e.node.hz ? `clock ${e.node.hz} Hz` : 'clock'
diff --git a/app/composables/useEditor.ts b/app/composables/useEditor.ts
index 085ea04..1cf0669 100644
--- a/app/composables/useEditor.ts
+++ b/app/composables/useEditor.ts
@@ -14,7 +14,7 @@ import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challeng
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
-import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
+import { attachPanel, detachPanel, dockedPanels, mergePanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
import {
addExamples,
containsDef,
@@ -145,7 +145,13 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
- const dialog = ref(null)
+ const dialog = ref(null)
+ /** The component whose box is being drawn in the face designer. */
+ const faceFor = ref(null)
+ function designFace(defId: string) {
+ faceFor.value = defId
+ dialog.value = 'face'
+ }
/** Tab shown in the right panel. */
const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit')
/** Which side panels are open; remembered in this browser. */
@@ -720,6 +726,25 @@ function create() {
notify(`Input panel with ${panel.rows!.length} switch${panel.rows!.length === 1 ? '' : 'es'} attached`)
}
+ /** Joins the selected panels into one; circuits that place this one keep their wires to the rows. */
+ function mergeSelectedPanels() {
+ const res = mergePanels(def.value, selection.value)
+ if (!res) return notify('Select at least two input panels', 'error')
+ const id = def.value.id
+ for (const d of project.value.components) {
+ const chips = new Set(d.nodes.filter(n => n.kind === 'chip' && n.chip === id).map(n => n.id))
+ if (!chips.size) continue
+ for (const w of d.wires) {
+ const to = chips.has(w.to.node) ? res.renamed.get(w.to.pin) : undefined
+ if (to) w.to = { node: w.to.node, pin: to }
+ }
+ }
+ selection.value = [res.panel.id]
+ wireSel.value = []
+ commit()
+ notify(`One panel with ${res.panel.rows?.length ?? 0} rows`)
+ }
+
function undock(panel: CircuitNode) {
detachPanel(panel)
commit()
@@ -1879,6 +1904,7 @@ function create() {
pressRow,
addPanel,
undock,
+ mergeSelectedPanels,
setRowType,
addRow,
dropRow,
@@ -1888,6 +1914,8 @@ function create() {
showIssue,
sheetRequest,
exportSheet,
+ faceFor,
+ designFace,
fits,
fitHover,
connectFit,
diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts
index 7595b19..d03377b 100644
--- a/app/composables/useMenu.ts
+++ b/app/composables/useMenu.ts
@@ -138,7 +138,12 @@ export function useMenu() {
function oneNode(n: CircuitNode): MenuEntry[] {
const get = ed.getDef.value
const out: MenuEntry[] = [{ head: n.label?.trim() && !n.autoLabel ? `${partName(n)} · ${n.label.trim()}` : partName(n) }]
- if (n.kind === 'chip' && n.chip) out.push({ label: 'Open component', icon: 'lucide:log-in', keys: 'Enter', run: () => ed.open(n.chip!) })
+ if (n.kind === 'chip' && n.chip) {
+ out.push(
+ { label: 'Open component', icon: 'lucide:log-in', keys: 'Enter', run: () => ed.open(n.chip!) },
+ { label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) },
+ )
+ }
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
const swaps = swapChoices([n])
@@ -270,6 +275,7 @@ export function useMenu() {
const fits = fitItems()
if (fits.length) out.push({ label: 'Wire them all to', icon: 'lucide:cable', children: fits })
out.push({ label: 'Connect one by one', icon: 'lucide:list-ordered', run: () => ed.startLinking() })
+ if (nodes.every(n => n.kind === 'panel')) out.push({ label: 'Merge into one panel', icon: 'lucide:combine', run: () => ed.mergeSelectedPanels() })
if (nodes.every(n => n.kind === 'input')) {
out.push({
label: 'Switches',
diff --git a/app/lib/logic/bulk.ts b/app/lib/logic/bulk.ts
index 62ecf28..3c2f70f 100644
--- a/app/lib/logic/bulk.ts
+++ b/app/lib/logic/bulk.ts
@@ -4,7 +4,7 @@
import { TRANSISTORS_PER_NAND } from './analyze'
import { invertedPins } from './compile'
-import { chipPins } from './geometry'
+import { chipPins, isPinRow, rowPin } from './geometry'
import type { DefLookup } from './geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PanelRow } from './types'
@@ -54,10 +54,20 @@ export interface IoEntry {
*/
export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } {
const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition)
+ // Pins in pin order: input switches and panel rows by where they sit.
+ const at = new Map()
+ for (const node of of(['input'])) at.set(node.id, { node, pin: true })
+ const inside: IoEntry[] = []
+ for (const node of of(['panel'])) {
+ for (const row of node.rows ?? []) {
+ if (isPinRow(node, row)) at.set(rowPin(node.id, row.id), { node, row, pin: true })
+ else inside.push({ node, row, pin: false })
+ }
+ }
const inputs: IoEntry[] = [
- ...of(['input']).map(node => ({ node, pin: true })),
+ ...chipPins(def).inputs.map(p => at.get(p.key)!).filter(Boolean),
...of(['button', 'clock']).map(node => ({ node, pin: false })),
- ...of(['panel']).flatMap(node => (node.rows ?? []).map(row => ({ node, row, pin: false }))),
+ ...inside,
]
const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))]
return { inputs, outputs }
diff --git a/app/lib/logic/cables.ts b/app/lib/logic/cables.ts
index 70be9a0..b086595 100644
--- a/app/lib/logic/cables.ts
+++ b/app/lib/logic/cables.ts
@@ -55,7 +55,14 @@ export function bundleWires(
return { w, a: pinPos(fn, shapeOf(fn, get), w.from.pin, 'out')!, b: pinPos(tn, shapeOf(tn, get), w.to.pin, 'in')! }
})
if (ends.some(e => !e.a || !e.b)) return { ok: false, error: 'Some wires have no pins' }
- ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y)
+ // Wire order: top to bottom at the targets, so the split can plug into them;
+ // when only the sources are all on one part, top to bottom there instead,
+ // so the bundle can plug into that part.
+ const one = (ids: Set) => ids.size === 1 && !CABLE_ENDS.has(nodes.get([...ids][0]!)!.kind)
+ const fromOne = one(new Set(wires.map(w => w.from.node)))
+ const toOne = one(new Set(wires.map(w => w.to.node)))
+ if (fromOne && !toOne) ends.sort((p, q) => p.a.y - q.a.y || p.b.y - q.b.y)
+ else ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y)
const n = ends.length
const mid = Math.floor((n - 1) / 2)
@@ -89,9 +96,10 @@ export function bundleWires(
})
// The sleeve starts neutral: the wires inside show their own colours.
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
- if (!at) {
+ {
// All the wires leave one part (or reach one part) in cable order: that end plugs straight in,
- // unless another part sits where it would go.
+ // unless another part sits where it would go. An end placed by hand plugs in when it was
+ // put right by those pins.
for (const [end, side] of [
[bundle, new Set(ends.map(e => e.w.from.node))],
[split, new Set(ends.map(e => e.w.to.node))],
@@ -99,6 +107,7 @@ export function bundleWires(
const part = side.size === 1 ? nodes.get([...side][0]!) : undefined
const lay = part && !CABLE_ENDS.has(part.kind) ? plugLayout(def, end, part, get) : null
if (!part || !lay) continue
+ if (at && Math.hypot(end.x - lay.x, end.y - lay.y) > 2.5) continue
const box = { x: lay.x, y: lay.y - 0.5, w: 1, h: lay.offsets[n - 1]! + 1 }
const clash = def.nodes.some(nd => {
if (nd === part || nd === bundle || nd === split || nd.kind === 'note') return false
@@ -170,13 +179,13 @@ export function plugInto(def: ComponentDef, end: CircuitNode, partId: string, ge
}
/**
- * The part a free cable end touches with all its wires, every one wired to
- * it, so it counts as plugged in. One wire landing on a lamp doesn't make
- * the whole end a plug.
+ * The part a free cable end touches with all its wires (at least two), every
+ * one wired to it, so it counts as plugged in. One wire landing on a lamp
+ * doesn't make the whole end a plug.
*/
function touching(def: ComponentDef, end: CircuitNode, nodes: Map, get: DefLookup): string | null {
const wires = singleWires(def, end)
- if (new Set(wires.map(w => bitOf(end, w))).size < cableBits(end)) return null
+ if (new Set(wires.map(w => bitOf(end, w))).size < 2) return null
const ids = new Set(wires.map(w => farEnd(end, w).node))
const part = ids.size === 1 ? nodes.get([...ids][0]!) : undefined
if (!part || CABLE_ENDS.has(part.kind)) return null
diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts
index da3c465..4a2e338 100644
--- a/app/lib/logic/compile.ts
+++ b/app/lib/logic/compile.ts
@@ -2,7 +2,7 @@
// nets. Chip boundaries and input/output pins disappear: they are aliases,
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
-import { cableBits, chipPins, type ChipPins, type DefLookup } from './geometry'
+import { cableBits, chipPins, isPinRow, rowPin, type ChipPins, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0
@@ -70,6 +70,8 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
return ['q']
case 'chip':
return pins ? pins.outputs.map(p => p.key) : []
+ case 'hex':
+ return ['q0', 'q1', 'q2', 'q3']
case 'panel':
return (node.rows ?? []).map(r => r.id)
case 'bundle':
@@ -97,7 +99,7 @@ export function cableKeys(node: CircuitNode): string[] {
}
/** 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}`
+export const rowSource = rowPin
const MAX_DEPTH = 64
@@ -234,11 +236,13 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
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.
+ // inside a component they are its input pins. A panel kept inside
+ // has fixed switches there (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 (isPinRow(n, r)) union(net, inNets.get(rowPin(n.id, r.id)) ?? LOW)
else if (r.type === 'switch' && r.on) union(net, HIGH)
}
break
@@ -254,6 +258,9 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
// A lamp passes its signal on to whatever its right pin feeds.
union(q, pinIn(n, 'a'))
break
+ case 'hex':
+ for (let i = 0; i < 4; i++) union(outNet.get(`${n.id}:q${i}`)!, inNet(n.id, `b${i}`))
+ break
case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined
const pins = pinsOf(n)
diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts
index 9f1aec9..f84c0a1 100644
--- a/app/lib/logic/geometry.ts
+++ b/app/lib/logic/geometry.ts
@@ -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, PanelRow, SymbolKind } from './types'
+import type { CircuitNode, ComponentDef, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
export const GRID = 16
@@ -24,6 +24,10 @@ export interface Shape {
nameY?: number
/** Lamps and displays from inside the component, shown on its box. */
face?: FaceItem[]
+ /** Where a box prints its name (its middle), or null when it is left off; empty: centred. */
+ nameAt?: { x: number; y: number } | null
+ /** Drawings on a hand-drawn box, in grid units relative to the chip node. */
+ drawing?: FaceShape[]
}
export interface ScreenPixel {
@@ -61,15 +65,34 @@ export interface ChipPins {
outputs: { key: string; label: string }[]
}
-/** A component's pins are its input/output nodes, ordered top to bottom. */
+/** Pin key of a panel row: the same key the row has as a switch in the simulator. */
+export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
+
+/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
+export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
+
+/**
+ * A component's pins, ordered top to bottom: its input and output nodes,
+ * and the switch and button rows of its input panels, which count as inputs.
+ */
export function chipPins(def: ComponentDef): ChipPins {
- const byPos = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
- const pins = (kind: 'input' | 'output', fallback: string) =>
- def.nodes
- .filter(n => n.kind === kind)
- .sort(byPos)
- .map((n, i) => ({ key: n.id, label: n.label?.trim() || `${fallback}${i + 1}` }))
- return { inputs: pins('input', 'in'), outputs: pins('output', 'out') }
+ const inputs: { key: string; label: string; x: number; y: number }[] = []
+ for (const n of def.nodes) {
+ if (n.kind === 'input') inputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y })
+ else if (n.kind === 'panel') {
+ const rows = n.rows ?? []
+ const at = panelOffsets(rows)
+ rows.forEach((r, i) => {
+ if (isPinRow(n, r)) inputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! })
+ })
+ }
+ }
+ inputs.sort((a, b) => a.y - b.y || a.x - b.x)
+ const outputs = def.nodes.filter(n => n.kind === 'output').sort((a, b) => a.y - b.y || a.x - b.x)
+ return {
+ inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })),
+ outputs: outputs.map((n, i) => ({ key: n.id, label: n.label?.trim() || `out${i + 1}` })),
+ }
}
/**
@@ -167,6 +190,35 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
}
}
+/**
+ * A box drawn by hand: the size it was given (never shorter than its pins
+ * need), everything placed where it was put, the rest where it would go
+ * anyway, and its drawings.
+ */
+function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType): Shape {
+ const auto = boxShape(def.name, pins, face)
+ const d = def.design!
+ const top = auto.body.y
+ const pinH = Math.max(pins.inputs.length, pins.outputs.length, 1)
+ const w = Math.max(2, d.w)
+ const h = Math.max(pinH === 1 ? 2 : pinH, d.h)
+ const hide = new Set(d.hide ?? [])
+ const place = d.place ?? {}
+ return {
+ ...auto,
+ body: { x: 0, y: top, w, h },
+ outputs: auto.outputs.map(p => ({ ...p, dx: w })),
+ face: (auto.face ?? [])
+ .filter(it => !hide.has(it.kind === 'screen' ? 'screen' : it.id))
+ .map(it => {
+ const at = place[it.kind === 'screen' ? 'screen' : it.id]
+ return at ? { ...it, x: at.x, y: top + at.y } : it
+ }),
+ nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
+ drawing: (d.shapes ?? []).map(sh => ({ ...sh, y: top + sh.y })),
+ }
+}
+
function boxShape(name: string, pins: ChipPins, face: ReturnType): Shape {
const nIn = pins.inputs.length
const nOut = pins.outputs.length
@@ -227,10 +279,11 @@ function refShape(node: CircuitNode): Shape {
return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] }
}
+// A hex display passes its four bits on, so it can sit in the middle of a bus.
const HEX_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 3, h: 4 },
inputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `b${i}`, label, dx: 0, dy: i })),
- outputs: [],
+ outputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `q${i}`, label, dx: 3, dy: i })),
}
const CLOCK_SHAPE: Shape = {
@@ -355,6 +408,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
const face = faceLayout(def)
+ if (def.design) return designedShape(def, pins, face)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
diff --git a/app/lib/logic/labels.ts b/app/lib/logic/labels.ts
index 766f896..41c7ed6 100644
--- a/app/lib/logic/labels.ts
+++ b/app/lib/logic/labels.ts
@@ -84,6 +84,12 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip)
+ // A pin made from a panel row: panel:row.
+ const at = pin.indexOf(':')
+ if (at > 0) {
+ const row = def?.nodes.find(n => n.id === pin.slice(0, at))?.rows?.find(r => r.id === pin.slice(at + 1))
+ return row?.label?.trim() || row?.name?.trim() || undefined
+ }
return def?.nodes.find(n => n.id === pin)?.label?.trim() || undefined
}
diff --git a/app/lib/logic/panels.ts b/app/lib/logic/panels.ts
index 22dce51..1ffbcd2 100644
--- a/app/lib/logic/panels.ts
+++ b/app/lib/logic/panels.ts
@@ -3,7 +3,7 @@
// 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 { chipPins, panelOffsets, rowPin, shapeOf, type DefLookup } from './geometry'
import { lookup, uid } from './ops'
import type { CircuitNode, ComponentDef, PanelRow, Project } from './types'
@@ -132,3 +132,42 @@ export function detachPanel(panel: CircuitNode) {
delete panel.attach
delete panel.skip
}
+
+/**
+ * Joins panels into one: the top one keeps its rows, the others' rows follow
+ * below in order, keeping their spacing, with their wires. The joined panel
+ * is free (no longer docked). Returns it with the pin keys that changed
+ * (old → new), so circuits that place this one can keep their wires; null
+ * for fewer than two panels.
+ */
+export function mergePanels(def: ComponentDef, ids: string[]): { panel: CircuitNode; renamed: Map } | null {
+ const panels = def.nodes.filter(n => n.kind === 'panel' && ids.includes(n.id)).sort((a, b) => a.y - b.y || a.x - b.x)
+ if (panels.length < 2) return null
+ const [target, ...rest] = panels as [CircuitNode, ...CircuitNode[]]
+ const rows = target.rows ?? []
+ const at = panelOffsets(rows)
+ rows.forEach((r, i) => (r.dy = at[i]!))
+ let bottom = at.length ? at[at.length - 1]! : -1
+ const used = new Set(rows.map(r => r.id))
+ const renamed = new Map()
+ for (const p of rest) {
+ const theirs = p.rows ?? []
+ const off = panelOffsets(theirs)
+ const shift = bottom + 1 - (off[0] ?? 0)
+ theirs.forEach((r, i) => {
+ const id = used.has(r.id) ? uid('r') : r.id
+ used.add(id)
+ for (const w of def.wires) if (w.from.node === p.id && w.from.pin === r.id) w.from = { node: target.id, pin: id }
+ renamed.set(rowPin(p.id, r.id), rowPin(target.id, id))
+ rows.push({ ...r, id, dy: off[i]! + shift })
+ })
+ if (theirs.length) bottom = rows[rows.length - 1]!.dy!
+ }
+ target.rows = rows
+ delete target.attach
+ delete target.skip
+ const gone = new Set(rest.map(p => p.id))
+ def.nodes = def.nodes.filter(n => !gone.has(n.id))
+ def.wires = def.wires.filter(w => !gone.has(w.from.node) && !gone.has(w.to.node))
+ return { panel: target, renamed }
+}
diff --git a/app/lib/logic/project.ts b/app/lib/logic/project.ts
index f23810a..b9f8d47 100644
--- a/app/lib/logic/project.ts
+++ b/app/lib/logic/project.ts
@@ -2,7 +2,19 @@
// and the share-link server, so it must stay free of browser APIs.
import { cleanPuzzle } from './puzzles'
-import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project, type PuzzleSpec } from './types'
+import {
+ CROSSING_STYLES,
+ FACE_INKS,
+ LAMP_COLORS,
+ PANEL_CONTROLS,
+ WIRE_COLORS,
+ type CircuitNode,
+ type ComponentDef,
+ type FaceDesign,
+ type PanelRow,
+ type Project,
+ type PuzzleSpec,
+} 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) {
@@ -21,6 +33,13 @@ function cleanNode(n: CircuitNode) {
if (!Array.isArray(n.rows)) delete n.rows
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
}
+ if (n.plug !== undefined && typeof n.plug !== 'string') delete n.plug
+ if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
+ if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
+ for (const k of ['names', 'invert'] as const) {
+ if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
+ }
+ if (n.inner !== undefined && n.inner !== true) delete n.inner
}
const MAX_ROWS = 256
@@ -32,9 +51,46 @@ function cleanRow(r: PanelRow): boolean {
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
+ if (r.key !== undefined && !(typeof r.key === 'string' && r.key.length === 1)) delete r.key
+ if (r.color !== undefined && !LAMP_COLORS.includes(r.color)) delete r.color
return true
}
+const num = (v: unknown, lo: number, hi: number) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi
+
+/** A hand-drawn box: sizes and places in range, drawings of known kinds; a broken one is dropped. */
+function cleanDesign(d: ComponentDef) {
+ const f = d.design as FaceDesign | undefined
+ if (!f || typeof f !== 'object' || !num(f.w, 1, 200) || !num(f.h, 1, 200)) {
+ delete d.design
+ return
+ }
+ if (f.place !== undefined) {
+ if (!f.place || typeof f.place !== 'object' || Array.isArray(f.place)) delete f.place
+ else for (const [k, v] of Object.entries(f.place)) if (!v || !num(v.x, -200, 400) || !num(v.y, -200, 400)) delete f.place[k]
+ }
+ if (f.hide !== undefined && !(Array.isArray(f.hide) && f.hide.every(v => typeof v === 'string'))) delete f.hide
+ if (f.shapes !== undefined) {
+ f.shapes = Array.isArray(f.shapes)
+ ? f.shapes
+ .filter(
+ sh =>
+ sh &&
+ typeof sh.id === 'string' &&
+ ['line', 'rect', 'ellipse', 'text'].includes(sh.kind) &&
+ [sh.x, sh.y, sh.w, sh.h].every(v => num(v, -400, 400)),
+ )
+ .slice(0, 500)
+ : []
+ for (const sh of f.shapes) {
+ if (sh.ink !== undefined && !FACE_INKS.includes(sh.ink)) delete sh.ink
+ if (sh.text !== undefined && typeof sh.text !== 'string') delete sh.text
+ if (sh.size !== undefined && !num(sh.size, 0.25, 4)) delete sh.size
+ if (sh.fill !== undefined && sh.fill !== true) delete sh.fill
+ }
+ }
+}
+
/** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
@@ -53,6 +109,7 @@ export function toProject(data: unknown): Project {
nodes += d.nodes.length
d.symbol ??= 'box'
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
+ if (d.design !== undefined) cleanDesign(d)
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
}
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index e327e1d..4fd8239 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -63,6 +63,8 @@ export interface CircuitNode {
names?: string[]
/** Input pins with a bubble: the signal comes in inverted, through one NAND (counted like any other). */
invert?: string[]
+ /** Panel whose rows stay inside a component (as fixed switches) instead of becoming its input pins. */
+ inner?: boolean
}
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
@@ -127,6 +129,43 @@ export interface ComponentDef {
challenge?: string
/** A gate with more inputs, built from a two-input gate (a component id, or "nand"). */
wide?: { base: string; n: number }
+ /** The component's box drawn by hand; empty: laid out automatically. */
+ design?: FaceDesign
+}
+
+export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
+export type FaceInk = (typeof FACE_INKS)[number]
+
+/**
+ * A component box drawn by hand: its size, where its lamps, displays,
+ * screen and name sit, what is left off, and drawings of its own. All in
+ * grid units from the box's top left corner; pins stay on the left and
+ * right edges.
+ */
+export interface FaceDesign {
+ w: number
+ h: number
+ /** Top left corner of lamps and displays (by node id), the pixel screen ('screen') and the name ('name'). */
+ place?: Record
+ /** Left off the box: lamp and display node ids, 'screen', 'name'. */
+ hide?: string[]
+ shapes?: FaceShape[]
+}
+
+export interface FaceShape {
+ id: string
+ kind: 'line' | 'rect' | 'ellipse' | 'text'
+ /** Top left corner and size; for a line, its start and the step to its end (w, h may be negative). */
+ x: number
+ y: number
+ w: number
+ h: number
+ text?: string
+ ink?: FaceInk
+ /** Rectangles and ellipses: filled lightly instead of only outlined. */
+ fill?: boolean
+ /** Text size: 1 is normal. */
+ size?: number
}
export interface Settings {
diff --git a/tests/bulk.test.ts b/tests/bulk.test.ts
index 3e4ed0f..a867757 100644
--- a/tests/bulk.test.ts
+++ b/tests/bulk.test.ts
@@ -38,11 +38,17 @@ describe('the list of inputs and outputs', () => {
wires: [],
}
- it('lists pins first in pin order, then the parts that stay inside, with panel rows', () => {
+ it('lists pins first in pin order (panel rows are pins too), then the parts that stay inside', () => {
const { inputs, outputs } = ioList(def)
- expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'clk:false', 'p/r1:false', 'p/r2:false'])
+ expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'p/r1:true', 'p/r2:true', 'clk:false'])
expect(outputs.map(e => e.node.id)).toEqual(['q', 'l'])
- expect(inputs.map(entryLabel)).toEqual(['A', 'B', '', 'EN', ''])
+ expect(inputs.map(entryLabel)).toEqual(['A', 'B', 'EN', '', ''])
+ })
+
+ it('a panel kept inside lists its rows after the pins', () => {
+ const inside = { ...def, nodes: def.nodes.map(n => (n.kind === 'panel' ? { ...n, inner: true } : n)) }
+ const { inputs } = ioList(inside)
+ expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'clk:false', 'p/r1:false', 'p/r2:false'])
})
it('flags names used twice on the same side only', () => {
diff --git a/tests/face.test.ts b/tests/face.test.ts
new file mode 100644
index 0000000..5cf8850
--- /dev/null
+++ b/tests/face.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest'
+import { compile } from '../app/lib/logic/compile'
+import { shapeOf } from '../app/lib/logic/geometry'
+import { createProject, lookup } from '../app/lib/logic/ops'
+import { toProject } from '../app/lib/logic/project'
+import { Simulator } from '../app/lib/logic/sim'
+import type { ComponentDef } from '../app/lib/logic/types'
+
+function shown(): { p: ReturnType; inner: ComponentDef } {
+ const p = createProject({ examples: false })
+ const inner: ComponentDef = {
+ id: 'inner',
+ name: 'Show',
+ symbol: 'box',
+ nodes: [
+ { id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
+ { id: 'b', kind: 'input', x: 0, y: 1, label: 'B' },
+ { id: 'l', kind: 'lamp', x: 6, y: 0, label: 'L' },
+ { id: 'h', kind: 'hex', x: 6, y: 4 },
+ { id: 'q', kind: 'output', x: 12, y: 0, label: 'Q' },
+ ],
+ wires: [{ id: 'w', from: { node: 'a', pin: 'q' }, to: { node: 'l', pin: 'a' } }],
+ }
+ p.components.push(inner)
+ return { p, inner }
+}
+
+describe('hex display', () => {
+ it('passes its four bits on, so it can sit in the middle of a bus', () => {
+ const p = createProject({ examples: false })
+ const def: ComponentDef = {
+ id: 'root',
+ name: 'Root',
+ symbol: 'box',
+ nodes: [
+ { id: 's', kind: 'input', x: 0, y: 0 },
+ { id: 'h', kind: 'hex', x: 4, y: 0 },
+ { id: 'l', kind: 'lamp', x: 10, y: 0 },
+ ],
+ wires: [
+ { id: 'a', from: { node: 's', pin: 'q' }, to: { node: 'h', pin: 'b0' } },
+ { id: 'b', from: { node: 'h', pin: 'q0' }, to: { node: 'l', pin: 'a' } },
+ ],
+ }
+ p.components.push(def)
+ expect(shapeOf(def.nodes[1]!, lookup(p)).outputs.map(o => o.key)).toEqual(['q0', 'q1', 'q2', 'q3'])
+ const sim = new Simulator(compile(lookup(p), 'root'))
+ sim.setSource('s', true)
+ sim.run()
+ expect(sim.pin('l', 'a')).toBe(1)
+ })
+})
+
+describe('a box drawn by hand', () => {
+ it('takes its size, places things where they were put, leaves hidden ones off, carries drawings', () => {
+ const { p, inner } = shown()
+ const chip = { id: 'c', kind: 'chip' as const, chip: 'inner', x: 0, y: 0 }
+ const auto = shapeOf(chip, lookup(p))
+ expect(auto.face?.map(f => f.id)).toEqual(['l', 'h'])
+ inner.design = {
+ w: 9,
+ h: 7,
+ place: { l: { x: 5, y: 1 }, name: { x: 3, y: 5 } },
+ hide: ['h'],
+ shapes: [{ id: 's1', kind: 'rect', x: 1, y: 1, w: 2, h: 2, ink: 'red' }],
+ }
+ const s = shapeOf(chip, lookup(p))
+ expect(s.body.w).toBe(9)
+ expect(s.body.h).toBe(7)
+ // Outputs move to the new right edge; inputs stay on the left.
+ expect(s.outputs.every(o => o.dx === 9)).toBe(true)
+ expect(s.face).toEqual([expect.objectContaining({ id: 'l', x: 5, y: s.body.y + 1 })])
+ expect(s.nameAt).toEqual({ x: 3, y: s.body.y + 5 })
+ expect(s.drawing?.[0]).toMatchObject({ id: 's1', y: s.body.y + 1 })
+ // Never shorter than its pins need.
+ inner.design.h = 1
+ expect(shapeOf(chip, lookup(p)).body.h).toBeGreaterThanOrEqual(2)
+ })
+
+ it('a broken design from a file is dropped, a broken drawing too', () => {
+ const { p, inner } = shown()
+ inner.design = { w: 6, h: 4, shapes: [{ id: 'x', kind: 'rect', x: 0, y: 0, w: 1, h: 1 }, { id: 'y', kind: 'laser' as 'rect', x: 0, y: 0, w: 1, h: 1 }] }
+ const back = toProject(JSON.parse(JSON.stringify(p)))
+ expect(back.components.find(d => d.id === 'inner')!.design!.shapes!.map(s => s.id)).toEqual(['x'])
+ ;(inner as { design: unknown }).design = { w: 'big' }
+ expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'inner')!.design).toBeUndefined()
+ })
+})
diff --git a/tests/panels.test.ts b/tests/panels.test.ts
new file mode 100644
index 0000000..aafe078
--- /dev/null
+++ b/tests/panels.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { compile } from '../app/lib/logic/compile'
+import { chipPins, panelOffsets } from '../app/lib/logic/geometry'
+import { createProject, lookup } from '../app/lib/logic/ops'
+import { mergePanels } from '../app/lib/logic/panels'
+import { Simulator } from '../app/lib/logic/sim'
+import type { ComponentDef } from '../app/lib/logic/types'
+
+describe('merging input panels', () => {
+ it('rows of the lower panel follow below, with their wires, as one panel', () => {
+ const def: ComponentDef = {
+ id: 'd',
+ name: 'D',
+ symbol: 'box',
+ nodes: [
+ { id: 'p2', kind: 'panel', x: 0, y: 10, rows: [{ id: 'r1', type: 'switch', label: 'B0' }, { id: 'r2', type: 'button', label: 'B1', dy: 2 }] },
+ { id: 'p1', kind: 'panel', x: 0, y: 0, attach: 'x', rows: [{ id: 'r1', type: 'switch', label: 'A0' }] },
+ { id: 'l', kind: 'lamp', x: 10, y: 0 },
+ { id: 'm', kind: 'lamp', x: 10, y: 4 },
+ ],
+ wires: [
+ { id: 'w1', from: { node: 'p1', pin: 'r1' }, to: { node: 'l', pin: 'a' } },
+ { id: 'w2', from: { node: 'p2', pin: 'r2' }, to: { node: 'm', pin: 'a' } },
+ ],
+ }
+ const res = mergePanels(def, ['p1', 'p2'])!
+ expect(res.panel.id).toBe('p1')
+ expect(def.nodes.some(n => n.id === 'p2')).toBe(false)
+ expect(res.panel.attach).toBeUndefined()
+ const rows = res.panel.rows!
+ expect(rows.map(r => r.label)).toEqual(['A0', 'B0', 'B1'])
+ // Spacing kept: B1 was two rows under B0.
+ expect(panelOffsets(rows)).toEqual([0, 1, 3])
+ // The wire from B1 now leaves the merged panel; the clashing row id got a new one.
+ const w2 = def.wires.find(w => w.id === 'w2')!
+ expect(w2.from.node).toBe('p1')
+ expect(rows.find(r => r.label === 'B1')!.id).toBe(w2.from.pin)
+ expect(new Set(rows.map(r => r.id)).size).toBe(3)
+ expect(res.renamed.get('p2:r2')).toBe(`p1:${w2.from.pin}`)
+ })
+
+ it('a merged panel inside a component gives one pin per row, in order', () => {
+ const p = createProject({ examples: false })
+ const inner: ComponentDef = {
+ id: 'inner',
+ name: 'Inner',
+ symbol: 'box',
+ nodes: [
+ { id: 'a', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r', type: 'switch', label: 'X' }] },
+ { id: 'b', kind: 'panel', x: 0, y: 5, rows: [{ id: 'r', type: 'switch', label: 'Y' }] },
+ { id: 'q', kind: 'output', x: 10, y: 5, label: 'Q' },
+ ],
+ wires: [{ id: 'w', from: { node: 'b', pin: 'r' }, to: { node: 'q', pin: 'a' } }],
+ }
+ p.components.push(inner)
+ mergePanels(inner, ['a', 'b'])
+ const pins = chipPins(inner).inputs
+ expect(pins.map(x => x.label)).toEqual(['X', 'Y'])
+ const root: ComponentDef = {
+ id: 'root',
+ name: 'Root',
+ symbol: 'box',
+ nodes: [
+ { id: 's', kind: 'input', x: -5, y: 0 },
+ { id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 },
+ ],
+ wires: [{ id: 'x', from: { node: 's', pin: 'q' }, to: { node: 'u', pin: pins[1]!.key } }],
+ }
+ p.components.push(root)
+ const sim = new Simulator(compile(lookup(p), 'root'))
+ sim.setSource('s', true)
+ sim.run()
+ expect(sim.pin('u', 'q')).toBe(1)
+ })
+})
diff --git a/tests/plugs.test.ts b/tests/plugs.test.ts
index 0f42617..3ec1190 100644
--- a/tests/plugs.test.ts
+++ b/tests/plugs.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { bundleWires, cablePanel, nameTags, plugInto, syncCables } from '../app/lib/logic/cables'
+import { bundleWires, cablePanel, nameTags, plugInto, plugLayout, syncCables } from '../app/lib/logic/cables'
import { compile, rowSource } from '../app/lib/logic/compile'
import { chipPins, panelOffsets, pinPos, shapeOf } from '../app/lib/logic/geometry'
import { copySelection, createProject, lookup, pasteClip } from '../app/lib/logic/ops'
@@ -269,3 +269,27 @@ describe('cables saved before plugs existed', () => {
expect(sums(p, def)).toEqual(before)
})
})
+
+describe('plugging in more often', () => {
+ it('outputs of one part bundled to scattered targets: the bundle plugs into the part', () => {
+ const { p, def, outs } = adder()
+ // Lamps in reverse order: wire order follows the Adder's pins, not the lamps.
+ for (const i of [0, 1, 2, 3, 4]) node(def, `l${i}`).y = 40 - i * 3
+ const res = bundleWires(def, outs.map((_, i) => `wo${i}`), lookup(p))
+ if (!res.ok) throw new Error(res.error)
+ expect(res.bundle.plug).toBe('add')
+ expect(touches(p, def, res.bundle)).toBe(true)
+ })
+
+ it('an end with only some of its wires on a part still plugs in', () => {
+ const { p, def, ins } = adder()
+ def.nodes.push({ id: 'sp', kind: 'split', bits: 5, x: 0, y: 30 })
+ for (const i of [0, 1, 2, 3]) def.wires.push({ id: `t${i}`, from: { node: 'sp', pin: `b${i}` }, to: { node: 'add', pin: ins[i]! } })
+ const sp = node(def, 'sp')
+ const lay = plugLayout(def, sp, node(def, 'add'), lookup(p))!
+ sp.x = lay.x
+ sp.y = lay.y
+ syncCables(p)
+ expect(sp.plug).toBe('add')
+ })
+})
diff --git a/tests/workflow.test.ts b/tests/workflow.test.ts
index bee866f..66a169b 100644
--- a/tests/workflow.test.ts
+++ b/tests/workflow.test.ts
@@ -196,25 +196,44 @@ describe('input panels', () => {
expect(panel.attach).toBeUndefined()
})
- it('works as a source inside a component: a switch row keeps its position, a clock row is a clock', () => {
+ it('inside a component its switch rows are input pins, a clock row is a clock; kept inside, a switch keeps its position', () => {
const p = createProject({ examples: false })
const inner: ComponentDef = {
id: 'inner',
name: 'Inner',
symbol: 'box',
nodes: [
- { id: 'pn', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r1', type: 'switch', on: true }, { id: 'r2', type: 'clock' }] },
+ { id: 'pn', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r1', type: 'switch', on: true, label: 'EN' }, { id: 'r2', type: 'clock' }] },
{ id: 'q', kind: 'output', x: 10, y: 0, label: 'Q' },
],
wires: [{ id: 'w', from: { node: 'pn', pin: 'r1' }, to: { node: 'q', pin: 'a' } }],
}
- const root: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [{ id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 }], wires: [] }
+ const root: ComponentDef = {
+ id: 'root',
+ name: 'Root',
+ symbol: 'box',
+ nodes: [
+ { id: 'sw', kind: 'input', x: -6, y: 0 },
+ { id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 },
+ ],
+ wires: [{ id: 'x', from: { node: 'sw', pin: 'q' }, to: { node: 'u', pin: 'pn:r1' } }],
+ }
p.components.push(inner, root)
+ expect(chipPins(inner).inputs).toEqual([{ key: 'pn:r1', label: 'EN' }])
const nl = compile(lookup(p), 'root')
expect(nl.clocks.length).toBe(1)
const s = new Simulator(nl)
s.run()
+ expect(s.pin('u', 'q')).toBe(0)
+ s.setSource('sw', true)
+ s.run()
expect(s.pin('u', 'q')).toBe(1)
+ // Kept inside: no pin, and the switch stays as it was set.
+ inner.nodes[0]!.inner = true
+ expect(chipPins(inner).inputs).toEqual([])
+ const kept = new Simulator(compile(lookup(p), 'root'))
+ kept.run()
+ expect(kept.pin('u', 'q')).toBe(1)
})
it('survives a round trip through project validation, and bad rows are dropped', () => {