diff --git a/app/assets/css/main.css b/app/assets/css/main.css
index 001ae04..02f9e37 100644
--- a/app/assets/css/main.css
+++ b/app/assets/css/main.css
@@ -755,6 +755,28 @@ kbd {
stroke: var(--w-on);
}
+/* A wire end being moved, and the wire a dragged wire would drop onto. */
+.wire.moving .wire-line {
+ opacity: 0.3;
+ stroke-dasharray: 4 4;
+}
+
+.wire.drop-target .wire-line {
+ stroke: var(--on);
+ stroke-width: 3.5;
+}
+
+.wire-grip {
+ fill: var(--bg);
+ stroke: var(--accent);
+ stroke-width: 1.5;
+ cursor: grab;
+}
+
+.wire-grip:hover {
+ fill: var(--accent);
+}
+
.wire.hover .wire-line {
stroke-width: 3;
}
@@ -788,6 +810,15 @@ kbd {
font-weight: 600;
}
+.cable-mark .cable-value {
+ fill: var(--muted);
+ font-weight: 500;
+}
+
+.wire.on .cable-mark .cable-value {
+ fill: var(--on);
+}
+
/* Bundle and split: the ends of a cable. */
.node .body.cable-end {
fill: #2a3240;
@@ -847,6 +878,192 @@ kbd {
fill: var(--muted);
}
+.invert-pins {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.invert-pin {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ height: 24px;
+ padding: 0 8px 0 6px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--panel-2);
+ color: var(--muted);
+ font-family: var(--font-mono);
+ font-size: 11px;
+}
+
+.invert-pin .dot {
+ width: 9px;
+ height: 9px;
+ border: 1.5px solid currentColor;
+ border-radius: 50%;
+}
+
+.invert-pin.on {
+ border-color: var(--accent);
+ color: var(--text);
+}
+
+.invert-pin.on .dot {
+ background: var(--bg);
+ border-color: var(--accent);
+}
+
+/* + and − under a selected gate. */
+.widen-btn {
+ cursor: pointer;
+}
+
+.widen-btn circle {
+ fill: var(--panel-2);
+ stroke: var(--accent);
+ stroke-width: 1.2;
+}
+
+.widen-btn path {
+ stroke: var(--text);
+ stroke-width: 1.6;
+ stroke-linecap: round;
+}
+
+.widen-btn:hover circle {
+ fill: var(--accent);
+}
+
+.widen-btn:hover path {
+ stroke: #0e1116;
+}
+
+/* An input with no wire (reads 0). */
+.node .open-pin {
+ fill: #e8a23a;
+ opacity: 0.85;
+ pointer-events: none;
+}
+
+/* Check: problems in the open circuit. */
+.problems-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 6px;
+}
+
+.problems-head h3 {
+ margin: 0;
+}
+
+.problems-head .ok {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ color: var(--on);
+ font-size: 12px;
+}
+
+.problems-head .check {
+ font-size: 11px;
+}
+
+.issue-list {
+ display: grid;
+ gap: 2px;
+}
+
+.issue {
+ display: flex;
+ align-items: flex-start;
+ gap: 7px;
+ width: 100%;
+ padding: 4px 6px;
+ border-radius: 5px;
+ color: var(--text);
+ font-size: 12px;
+ line-height: 1.35;
+ text-align: left;
+}
+
+.issue:hover:not(:disabled) {
+ background: var(--panel-2);
+}
+
+.issue:disabled {
+ cursor: default;
+}
+
+.issue.error .issue-icon { color: #ff7a7a; }
+.issue.warn .issue-icon { color: #e8a23a; }
+.issue.info .issue-icon { color: var(--muted); }
+.issue.info { color: var(--muted); }
+
+.unused-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 2px 6px;
+ font-size: 12px;
+}
+
+.btn-sm.danger {
+ border-color: rgb(255 107 107 / 0.5);
+ color: #ff8787;
+}
+
+.itabs .badge.warn {
+ background: #e8a23a;
+ color: #14181f;
+}
+
+/* An inverted input: the classic bubble. */
+.node .invert-bubble {
+ fill: var(--bg);
+ stroke: var(--chip-stroke);
+ stroke-width: 1.5;
+ pointer-events: none;
+}
+
+/* Signal tags and references: a flag with the name. */
+.node .signal-flag {
+ fill: #1d2430;
+ stroke: #8a7bd8;
+ stroke-width: 1.5;
+ stroke-linejoin: round;
+}
+
+.node .signal-flag.use {
+ fill: #191f29;
+}
+
+.node .signal-flag.on {
+ fill: rgb(61 220 132 / 0.2);
+ stroke: var(--on);
+}
+
+.node .signal-flag.orphan {
+ stroke: #e8a23a;
+ stroke-dasharray: 3 2;
+}
+
+.node .signal-flag.linked {
+ stroke: #c9bfff;
+ stroke-width: 2.5;
+ filter: drop-shadow(0 0 4px rgb(138 123 216 / 0.8));
+}
+
+.node .signal-name {
+ fill: var(--text);
+ font-family: var(--font-mono);
+ font-size: 10px;
+ font-weight: 600;
+ pointer-events: none;
+}
+
/* Pixel and pixel screens. */
.node .pixel {
fill: #141a22;
@@ -2697,3 +2914,92 @@ kbd {
border-color: var(--accent);
outline: none;
}
+
+/* ── Search (Ctrl+F) ────────────────────────────────────────────── */
+.search-backdrop {
+ align-items: start;
+ padding-top: 12vh;
+}
+
+.modal.search-modal {
+ width: min(600px, 100%);
+ padding: 0;
+ overflow: hidden;
+}
+
+.search-field {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ border-bottom: 1px solid var(--border);
+ color: var(--muted);
+}
+
+.search-field input {
+ flex: 1;
+ min-width: 0;
+ border: 0;
+ background: transparent;
+ color: var(--text);
+ font-size: 15px;
+ outline: none;
+}
+
+.search-empty {
+ padding: 14px 16px;
+}
+
+.search-results {
+ max-height: 60vh;
+ overflow-y: auto;
+ padding: 4px 6px 10px;
+}
+
+.search-results h3 {
+ margin: 10px 8px 4px;
+}
+
+.search-hit {
+ display: block;
+ width: 100%;
+ border-radius: 6px;
+}
+
+.search-hit.active {
+ background: var(--panel-2);
+}
+
+.search-main {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ width: 100%;
+ min-height: 32px;
+ padding: 0 10px;
+ color: var(--text);
+ font-size: 13px;
+ text-align: left;
+}
+
+.search-main .iconify,
+.search-main > svg {
+ color: var(--muted);
+}
+
+.search-where {
+ color: var(--muted);
+ font-size: 12px;
+ white-space: nowrap;
+}
+
+.search-uses {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 0 10px 8px 35px;
+}
+
+.search-results .muted {
+ color: var(--muted);
+}
diff --git a/app/components/editor/App.vue b/app/components/editor/App.vue
index 82bcdc8..042fb2b 100644
--- a/app/components/editor/App.vue
+++ b/app/components/editor/App.vue
@@ -53,5 +53,6 @@ onMounted(() => {
+
diff --git a/app/components/editor/Canvas.vue b/app/components/editor/Canvas.vue
index 4ba0856..78effc3 100644
--- a/app/components/editor/Canvas.vue
+++ b/app/components/editor/Canvas.vue
@@ -1,14 +1,17 @@
+
+
+
Check
+ {{ infoCount ? 'No problems' : 'All good' }}
+ Notes ({{ infoCount }})
+
+
+
+
+
+ {{ i.text }}
+
+
+
+ and {{ shownIssues.length - 40 }} more
+
+
+
+ Not used in another circuit ({{ unused.length }})
+
+
+ Circuits you work in directly show up here too. Delete only what you don't need.
+
+
+
+
+
This circuit
@@ -101,6 +147,19 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
+
diff --git a/app/components/editor/Help.vue b/app/components/editor/Help.vue
index 8374636..ba5f453 100644
--- a/app/components/editor/Help.vue
+++ b/app/components/editor/Help.vue
@@ -25,6 +25,12 @@ const SHORTCUTS: [string, string][] = [
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
['Drag a plugged cable end away', 'Pull it out; drop its pins on a part\'s pins to plug it in again'],
['Drag a part onto a pin', 'Connects there when dropped (a green ring shows where); hold Alt to just place it'],
+ ['Drag a wire by its end', 'Moves that end to another pin (grab it near the pin, or by the small circle)'],
+ ['Drop a wire on a wire', 'From an input: it taps that wire\'s signal. From an output: it feeds what that wire fed'],
+ ['Alt + click an input pin', 'Inverts it (a bubble); counted honestly as one NAND'],
+ ['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 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/Inspector.vue b/app/components/editor/Inspector.vue
index e231f1e..921d556 100644
--- a/app/components/editor/Inspector.vue
+++ b/app/components/editor/Inspector.vue
@@ -14,10 +14,12 @@ const pinCount = computed(() => {
return io.inputs.length + io.outputs.length
})
const hasTask = computed(() => !!ed.task.value)
+/** Errors and warnings in the open circuit, on the Circuit tab. */
+const problems = computed(() => ed.issues.value.filter(i => i.level !== 'info').length)
const tabs = computed(() => [
{ id: 'selection' as Tab, label: 'Selection', icon: 'lucide:mouse-pointer-2', badge: selected.value || '' },
- { id: 'circuit' as Tab, label: 'Circuit', icon: 'lucide:cpu', badge: '' },
+ { id: 'circuit' as Tab, label: 'Circuit', icon: 'lucide:cpu', badge: problems.value || '', warn: problems.value > 0 },
{ id: 'pins' as Tab, label: 'Pins', icon: 'lucide:list', badge: pinCount.value || '' },
{ id: 'test' as Tab, label: 'Test', icon: hasTask.value ? 'lucide:flag' : 'lucide:table', badge: '' },
])
@@ -66,7 +68,7 @@ watch(
>
{{ t.label }}
- {{ t.badge }}
+ {{ t.badge }}
+
(null)
const labelFocus = ref(0)
const showHelp = ref(false)
- const dialog = ref(null)
+ const dialog = ref(null)
/** Tab shown in the right panel. */
const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit')
/** Which side panels are open; remembered in this browser. */
@@ -428,6 +429,12 @@ function create() {
node.autoLabel = true
}
if (p.kind === 'note') node.label = 'Note'
+ if (p.kind === 'tag') {
+ node.label = uniqueLabel('SIG', usedLabels(def.value, 'signal'))
+ node.autoLabel = true
+ }
+ // A new reference uses the signal sent last.
+ if (p.kind === 'ref') node.label = def.value.nodes.filter(n => n.kind === 'tag' && n.label?.trim()).at(-1)?.label?.trim() ?? ''
if (p.kind === 'panel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
def.value.nodes.push(node)
@@ -498,6 +505,29 @@ function create() {
play('connect')
}
+ /**
+ * Moves a wire's end to another pin: the wire now runs from `from` to
+ * `to`, keeping its colour. An input that had a wire gets this one instead.
+ */
+ function rewire(wireId: string, from: PinRef, to: PinRef) {
+ const d = def.value
+ const old = d.wires.find(w => w.id === wireId)
+ if (!old) return
+ if (old.from.node === from.node && old.from.pin === from.pin && old.to.node === to.node && old.to.pin === to.pin) return
+ if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) {
+ play('error')
+ return notify('A cable pin only joins another cable pin', 'error')
+ }
+ d.wires = d.wires.filter(w => w !== old)
+ addWire(from, to)
+ const made = d.wires[d.wires.length - 1]!
+ if (old.color && !made.color) made.color = old.color
+ wireSel.value = [made.id]
+ selection.value = []
+ commit()
+ play('connect')
+ }
+
/** Several wires as one undo step. */
function connectMany(links: Link[]) {
const made = links.filter(l => addWire(l.from, l.to)).length
@@ -508,6 +538,26 @@ function create() {
if (made > 1) notify(`Connected ${made} wires`)
}
+ /** Asks the canvas for the open circuit as a sheet: printed (or saved as PDF), or as an SVG file. */
+ const sheetRequest = ref<{ mode: 'print' | 'svg'; n: number } | null>(null)
+ function exportSheet(mode: 'print' | 'svg') {
+ sheetRequest.value = { mode, n: (sheetRequest.value?.n ?? 0) + 1 }
+ }
+
+ /** What looks wrong in the open circuit, worst first; a loop that never settles too. */
+ const issues = computed(() => {
+ const list = checkCircuit(def.value, getDef.value)
+ if (status.value === 'oscillating') list.unshift({ level: 'warn', text: 'The circuit keeps changing: a loop that never settles', nodes: [] })
+ return list
+ })
+
+ /** Shows the parts of a problem: selects them and centres on the first. */
+ function showIssue(nodes: string[]) {
+ if (!nodes.length) return
+ focusNode(nodes[0]!)
+ selection.value = nodes
+ }
+
/** Where the selected parts fit as a group (green boxes on the canvas), nearest first. */
const fits = computed(() => (selection.value.length < 2 ? [] : fitSpots(def.value, getDef.value, selection.value)))
/** The fit pointed at: which spot, and its first pin. */
@@ -1069,7 +1119,8 @@ function create() {
else delete n.label
delete n.autoLabel
})
- commit(false)
+ // Signal names decide what connects.
+ commit(nodes.some(n => n.kind === 'tag' || n.kind === 'ref'))
}
/** A name typed by hand (Pins list); empty lets connections name the part again. */
@@ -1121,6 +1172,25 @@ function create() {
wireSel.value = []
}
+ /** A reference to a signal, placed to the right of its tag and selected. */
+ function useSignal(tag: CircuitNode) {
+ const name = tag.label?.trim()
+ if (!name) return notify('Give the signal a name first', 'error')
+ const b = shapeOf(tag, getDef.value).body
+ const ref: CircuitNode = { id: uid('n'), kind: 'ref', x: Math.round(tag.x + b.x + b.w + 3), y: tag.y, label: name }
+ def.value.nodes.push(ref)
+ selection.value = [ref.id]
+ wireSel.value = []
+ commit()
+ play('place')
+ }
+
+ /** Every tag and reference of a signal. */
+ function selectSignal(name: string) {
+ selection.value = def.value.nodes.filter(n => (n.kind === 'tag' || n.kind === 'ref') && n.label?.trim() === name).map(n => n.id)
+ wireSel.value = []
+ }
+
/** Selects a part and centres the view on it. */
function focusNode(id: string) {
selection.value = [id]
@@ -1138,8 +1208,20 @@ function create() {
/** Transistors in one placed part: 4 for a NAND, its whole inside for a component, 0 for switches, lamps and cables. */
function transistorsOfNode(n: CircuitNode): number {
- if (n.kind === 'nand') return TRANSISTORS_PER_NAND
- return n.kind === 'chip' && n.chip ? transistors(n.chip) : 0
+ const child = n.kind === 'chip' && n.chip ? getDef.value(n.chip) : undefined
+ const bubbles = invertedPins(n, child ? chipPins(child) : undefined).length * TRANSISTORS_PER_NAND
+ if (n.kind === 'nand') return TRANSISTORS_PER_NAND + bubbles
+ return (n.kind === 'chip' && n.chip ? transistors(n.chip) : 0) + bubbles
+ }
+
+ /** Puts a bubble on an input (it reads the signal inverted, through one NAND), or takes it off. */
+ function toggleInvert(n: CircuitNode, pin: string) {
+ if (!INVERTIBLE.has(n.kind)) return
+ const set = new Set(n.invert ?? [])
+ if (!set.delete(pin)) set.add(pin)
+ if (set.size) n.invert = [...set]
+ else delete n.invert
+ commit()
}
// ── Cables ────────────────────────────────────────────────────────
@@ -1802,6 +1884,10 @@ function create() {
dropRow,
withDocked,
withFollowers,
+ issues,
+ showIssue,
+ sheetRequest,
+ exportSheet,
fits,
fitHover,
connectFit,
@@ -1824,6 +1910,7 @@ function create() {
exportTable,
transistors,
transistorsOfNode,
+ toggleInvert,
nands,
rightTab,
sidebars,
@@ -1832,6 +1919,7 @@ function create() {
swapMany,
connectMany,
connectSelectionTo,
+ rewire,
renameMany,
setLabel,
setSwitches,
@@ -1839,6 +1927,8 @@ function create() {
arrangeSelected,
selectOnly,
focusNode,
+ useSignal,
+ selectSignal,
canPlaceKind,
setInputs,
sound,
diff --git a/app/composables/useMenu.ts b/app/composables/useMenu.ts
index b5811d6..7595b19 100644
--- a/app/composables/useMenu.ts
+++ b/app/composables/useMenu.ts
@@ -4,6 +4,7 @@
import { byPosition, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
import { cableOf } from '~/lib/logic/cables'
+import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, chipPins, type Pt } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
@@ -68,10 +69,12 @@ const ADD: { kind: NodeKind; label: string; icon: string; keys?: string }[] = [
{ kind: 'clock', label: 'Clock', icon: 'lucide:audio-waveform', keys: 'C' },
{ kind: 'panel', label: 'Input panel', icon: 'lucide:sliders-vertical', keys: 'P' },
{ kind: 'hex', label: 'Hex display', icon: 'lucide:binary', keys: 'H' },
+ { kind: 'tag', label: 'Send signal', icon: 'lucide:flag' },
+ { kind: 'ref', label: 'Use signal', icon: 'lucide:tag' },
{ kind: 'note', label: 'Note', icon: 'lucide:sticky-note', keys: 'T' },
]
-const NAMED = ['input', 'output', 'lamp', 'button', 'clock', 'hex', 'note', 'panel', 'chip']
+const NAMED = ['input', 'output', 'lamp', 'button', 'clock', 'hex', 'note', 'panel', 'chip', 'tag', 'ref']
export function useMenu() {
const ed = useEditor()
@@ -150,6 +153,23 @@ export function useMenu() {
children: [2, 3, 4, 5, 6, 8].map(k => ({ label: `${k} inputs`, checked: k === now, run: () => ed.setInputs(n, k) })),
})
}
+ if (INVERTIBLE.has(n.kind)) {
+ const inv = new Set(n.invert ?? [])
+ const pins = ed.shape(n).inputs
+ if (pins.length) {
+ out.push({
+ label: 'Invert input',
+ icon: 'lucide:circle-dot',
+ note: inv.size ? String(inv.size) : undefined,
+ keys: 'Alt+click',
+ children: pins.map((p, i) => ({
+ label: p.label || (n.kind === 'nand' ? 'AB'[i]! : 'In'),
+ checked: inv.has(p.key),
+ run: () => ed.toggleInvert(n, p.key),
+ })),
+ })
+ }
+ }
if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') {
out.push({
label: 'Colour',
@@ -202,6 +222,14 @@ export function useMenu() {
out.push({ label: 'Wire rows one by one', icon: 'lucide:cable', disabled: !n.rows?.length, run: () => ed.startLinking([n.id]) })
}
if (n.kind === 'bundle' || n.kind === 'split') out.push('sep', ...cableEnd(n))
+ if (n.kind === 'tag' || n.kind === 'ref') {
+ const name = n.label?.trim() ?? ''
+ const sender = ed.def.value.nodes.find(x => x.kind === 'tag' && x.label?.trim() === name)
+ out.push('sep')
+ if (n.kind === 'tag') out.push({ label: 'Use this signal here', icon: 'lucide:tag', disabled: !name, run: () => ed.useSignal(n) })
+ else out.push({ label: 'Go to where it is sent', icon: 'lucide:locate-fixed', disabled: !sender, run: () => ed.focusNode(sender!.id) })
+ out.push({ label: 'Select every place of this signal', icon: 'lucide:scan-search', disabled: !name, run: () => ed.selectSignal(name) })
+ }
return [...out, ...common([n.id])]
}
@@ -352,6 +380,8 @@ export function useMenu() {
{ label: 'Select all', icon: 'lucide:box-select', keys: 'Ctrl+A', disabled: !ed.def.value.nodes.length, run: () => ed.selectAll() },
{ label: 'Fit to screen', icon: 'lucide:scan', keys: 'F', run: ops.fit },
{ label: 'Tidy all wires', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
+ { label: 'Find…', icon: 'lucide:search', keys: 'Ctrl+F', run: () => (ed.dialog.value = 'search') },
+ { label: 'Print sheet / PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: !ed.def.value.nodes.length, run: () => ed.exportSheet('print') },
'sep',
{ label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', disabled: !ed.canUndo.value, run: () => ed.undo() },
{ label: 'Redo', icon: 'lucide:redo-2', keys: 'Ctrl+Shift+Z', disabled: !ed.canRedo.value, run: () => ed.redo() },
diff --git a/app/lib/logic/analyze.ts b/app/lib/logic/analyze.ts
index 4bf2185..7904006 100644
--- a/app/lib/logic/analyze.ts
+++ b/app/lib/logic/analyze.ts
@@ -1,7 +1,7 @@
// Analysis on a compiled component: truth table, NAND count, gate delay,
// and step-by-step tests (used by challenges).
-import { compile, type Netlist } from './compile'
+import { compile, invertedPins, type Netlist } from './compile'
import { chipPins, type DefLookup } from './geometry'
import { Simulator } from './sim'
import type { ComponentDef } from './types'
@@ -83,6 +83,11 @@ export function nandCounts(components: ComponentDef[]): Map {
for (const node of def.nodes) {
if (node.kind === 'nand') n++
else if (node.kind === 'chip' && node.chip) n += count(node.chip)
+ // An inverted input is one more NAND.
+ if (node.invert?.length) {
+ const child = node.kind === 'chip' && node.chip ? byId.get(node.chip) : undefined
+ n += invertedPins(node, child ? chipPins(child) : undefined).length
+ }
}
busy.delete(id)
memo.set(id, n)
diff --git a/app/lib/logic/bulk.ts b/app/lib/logic/bulk.ts
index 43ce144..62ecf28 100644
--- a/app/lib/logic/bulk.ts
+++ b/app/lib/logic/bulk.ts
@@ -3,6 +3,8 @@
// and lining parts up.
import { TRANSISTORS_PER_NAND } from './analyze'
+import { invertedPins } from './compile'
+import { chipPins } from './geometry'
import type { DefLookup } from './geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PanelRow } from './types'
@@ -92,7 +94,15 @@ export interface CostLine {
*/
export function transistorBreakdown(def: ComponentDef, nandsPerDef: Map, get: DefLookup): CostLine[] {
const lines = new Map()
+ const bubbles: CostLine = { key: 'invert', name: 'Inverted inputs', count: 0, each: TRANSISTORS_PER_NAND, total: 0, ids: [] }
for (const n of def.nodes) {
+ const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined
+ const inv = invertedPins(n, child ? chipPins(child) : undefined).length
+ if (inv) {
+ bubbles.count += inv
+ bubbles.total += inv * TRANSISTORS_PER_NAND
+ bubbles.ids.push(n.id)
+ }
let each = 0
let name = ''
if (n.kind === 'nand') {
@@ -110,6 +120,7 @@ export function transistorBreakdown(def: ComponentDef, nandsPerDef: Map b.total - a.total || a.name.localeCompare(b.name))
}
diff --git a/app/lib/logic/check.ts b/app/lib/logic/check.ts
new file mode 100644
index 0000000..c5e2098
--- /dev/null
+++ b/app/lib/logic/check.ts
@@ -0,0 +1,108 @@
+// Checking a circuit for mistakes that still simulate but rarely mean what
+// was intended: inputs left open (they read 0), parts that drive nothing,
+// pins that share a name, and signals nothing sends or two parts send.
+
+import { chipPins, shapeOf, type DefLookup } from './geometry'
+import { KIND_NAMES } from './progress'
+import type { CircuitNode, ComponentDef, Project } from './types'
+
+export type IssueLevel = 'error' | 'warn' | 'info'
+
+export interface Issue {
+ level: IssueLevel
+ text: string
+ /** Parts to show for it; the first one is centred. */
+ nodes: string[]
+}
+
+/** Parts whose open inputs are worth a warning (a cable bundle's spare wires are not). */
+export const CHECKED_INPUTS = new Set(['nand', 'chip', 'output', 'lamp', 'hex', 'pixel', 'tag'])
+
+function partName(n: CircuitNode, get: DefLookup): string {
+ const own = !n.autoLabel && n.label?.trim()
+ const kind = n.kind === 'chip' ? ((n.chip && get(n.chip)?.name) ?? 'Missing component') : (KIND_NAMES[n.kind] ?? n.kind)
+ if (n.kind === 'tag' || n.kind === 'ref') return `${kind} "${n.label?.trim() || '?'}"`
+ return own ? `${kind} ${own}` : (n.label?.trim() ? `${kind} ${n.label.trim()}` : kind)
+}
+
+/** Input pins of a part that have no wire. */
+export function openInputs(def: ComponentDef, n: CircuitNode, get: DefLookup): string[] {
+ if (!CHECKED_INPUTS.has(n.kind)) return []
+ const wired = new Set(def.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
+ return shapeOf(n, get).inputs.filter(p => !p.bus && !wired.has(p.key)).map(p => p.key)
+}
+
+export function checkCircuit(def: ComponentDef, get: DefLookup): Issue[] {
+ const issues: Issue[] = []
+ const fed = new Set(def.wires.map(w => `${w.from.node}:${w.from.pin}`))
+ const name = (n: CircuitNode) => partName(n, get)
+
+ for (const n of def.nodes) {
+ if (n.kind === 'chip' && (!n.chip || !get(n.chip))) {
+ issues.push({ level: 'error', text: 'A placed component no longer exists', nodes: [n.id] })
+ continue
+ }
+ const open = openInputs(def, n, get)
+ if (open.length) {
+ const shape = shapeOf(n, get)
+ const labels = open.map(k => shape.inputs.find(p => p.key === k)?.label || k)
+ const all = open.length === shape.inputs.length
+ const text =
+ n.kind === 'chip' || n.kind === 'nand' || n.kind === 'hex'
+ ? `${name(n)}: ${all ? 'no input connected' : `${labels.join(', ')} not connected`} (reads 0)`
+ : `${name(n)}: nothing connected`
+ issues.push({ level: 'warn', text, nodes: [n.id] })
+ }
+ if (n.kind === 'split' && !def.wires.some(w => w.to.node === n.id)) issues.push({ level: 'warn', text: 'Cable split without a cable', nodes: [n.id] })
+ // Parts that drive nothing.
+ if ((n.kind === 'input' || n.kind === 'button' || n.kind === 'clock' || n.kind === 'nand') && !fed.has(`${n.id}:q`)) {
+ issues.push({ level: 'info', text: n.kind === 'nand' ? 'NAND gate: its output goes nowhere' : `${name(n)}: goes nowhere`, nodes: [n.id] })
+ }
+ if (n.kind === 'chip' && n.chip) {
+ const outs = chipPins(get(n.chip)!).outputs
+ if (outs.length && !outs.some(p => fed.has(`${n.id}:${p.key}`))) issues.push({ level: 'info', text: `${name(n)}: none of its outputs is used`, nodes: [n.id] })
+ }
+ }
+
+ // Pins of the same name can't be told apart from outside.
+ for (const kind of ['input', 'output'] as const) {
+ const by = new Map()
+ for (const n of def.nodes) {
+ const l = n.kind === kind ? n.label?.trim() : ''
+ if (l) by.set(l.toLowerCase(), [...(by.get(l.toLowerCase()) ?? []), n])
+ }
+ for (const list of by.values()) {
+ if (list.length > 1) issues.push({ level: 'warn', text: `${list.length} ${kind} pins are called ${list[0]!.label!.trim()}`, nodes: list.map(n => n.id) })
+ }
+ }
+
+ // Signals: sent once, used somewhere.
+ const tags = new Map()
+ const refs = new Map()
+ for (const n of def.nodes) {
+ const l = n.label?.trim() ?? ''
+ if (n.kind === 'tag') tags.set(l, [...(tags.get(l) ?? []), n])
+ if (n.kind === 'ref') refs.set(l, [...(refs.get(l) ?? []), n])
+ }
+ for (const [l, list] of tags) {
+ if (!l) issues.push({ level: 'warn', text: 'A "Send signal" has no name', nodes: list.map(n => n.id) })
+ else if (list.length > 1) issues.push({ level: 'error', text: `Signal "${l}" is sent by ${list.length} parts: they drive it against each other`, nodes: list.map(n => n.id) })
+ else if (!refs.has(l)) issues.push({ level: 'info', text: `Signal "${l}" is sent but not used`, nodes: list.map(n => n.id) })
+ }
+ for (const [l, list] of refs) {
+ if (!tags.has(l)) issues.push({ level: 'error', text: l ? `Nothing sends signal "${l}" (reads 0)` : 'A "Use signal" has no name', nodes: list.map(n => n.id) })
+ }
+
+ const rank: Record = { error: 0, warn: 1, info: 2 }
+ return issues.sort((a, b) => rank[a.level] - rank[b.level])
+}
+
+/**
+ * Components made in this project that no other circuit places. Some are
+ * circuits you work in directly; the rest can go. The examples are left out.
+ */
+export function unusedComponents(project: Project): ComponentDef[] {
+ const used = new Set()
+ for (const d of project.components) for (const n of d.nodes) if (n.kind === 'chip' && n.chip && n.chip !== d.id) used.add(n.chip)
+ return project.components.filter(d => !used.has(d.id) && !d.id.startsWith('ex-') && !d.challenge)
+}
diff --git a/app/lib/logic/compile.ts b/app/lib/logic/compile.ts
index cf0e284..da3c465 100644
--- a/app/lib/logic/compile.ts
+++ b/app/lib/logic/compile.ts
@@ -42,6 +42,7 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
case 'lamp':
case 'pixel':
case 'split':
+ case 'tag':
return ['a']
case 'hex':
return ['b0', 'b1', 'b2', 'b3']
@@ -65,6 +66,7 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
case 'low':
case 'button':
case 'clock':
+ case 'ref':
return ['q']
case 'chip':
return pins ? pins.outputs.map(p => p.key) : []
@@ -79,6 +81,16 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
}
}
+/** Kinds whose inputs can be inverted with a bubble. */
+export const INVERTIBLE = new Set(['nand', 'chip', 'output', 'lamp'])
+
+/** The inverted inputs of a part that it really has, each once. */
+export function invertedPins(node: CircuitNode, pins?: ChipPins): string[] {
+ if (!node.invert?.length || !INVERTIBLE.has(node.kind)) return []
+ const keys = new Set(inputKeys(node, pins))
+ return [...new Set(node.invert)].filter(k => keys.has(k))
+}
+
/** Pin keys of the single wires on a bundle or split: b0, b1, … */
export function cableKeys(node: CircuitNode): string[] {
return Array.from({ length: cableBits(node) }, (_, i) => `b${i}`)
@@ -159,16 +171,42 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
const w = wiresTo.get(`${nodeId}:${pin}`)
return w ? (outNet.get(`${w.from.node}:${w.from.pin}`) ?? LOW) : LOW
}
+ // An inverted input: the wire's signal through a NAND with both inputs tied, made once per pin.
+ const inverters = new Map()
+ const pinIn = (n: CircuitNode, pin: string) => {
+ const raw = inNet(n.id, pin)
+ if (!n.invert?.length || !invertedPins(n, pinsOf(n)).includes(pin)) return raw
+ const key = `${n.id}:${pin}`
+ let net = inverters.get(key)
+ if (net === undefined) {
+ net = make()
+ gA.push(raw)
+ gB.push(raw)
+ gOut.push(net)
+ gateKeys.push(`${path}${n.id}~${pin}`)
+ inverters.set(key, net)
+ }
+ return net
+ }
+ // Signal tags by name: a reference carries what is wired into the tag of its name.
+ const tags = new Map()
+ for (const n of def.nodes) {
+ const name = n.kind === 'tag' ? n.label?.trim() : ''
+ if (name) tags.set(name, [...(tags.get(name) ?? []), n])
+ }
for (const n of def.nodes) {
const q = outNet.get(`${n.id}:q`)!
switch (n.kind) {
- case 'nand':
- gA.push(inNet(n.id, 'a'))
- gB.push(inNet(n.id, 'b'))
+ case 'nand': {
+ const a = pinIn(n, 'a')
+ const b = pinIn(n, 'b')
+ gA.push(a)
+ gB.push(b)
gOut.push(q)
gateKeys.push(path + n.id)
break
+ }
case 'input':
if (inNets) union(q, inNets.get(n.id) ?? LOW)
else sources.set(n.id, q)
@@ -205,12 +243,16 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
break
case 'output':
- result.set(n.id, inNet(n.id, 'a'))
- union(q, inNet(n.id, 'a'))
+ result.set(n.id, pinIn(n, 'a'))
+ union(q, pinIn(n, 'a'))
+ break
+ case 'ref':
+ // Two tags of one name drive one signal: a short, like two wires on one input.
+ for (const t of tags.get(n.label?.trim() ?? '') ?? []) union(q, inNet(t.id, 'a'))
break
case 'lamp':
// A lamp passes its signal on to whatever its right pin feeds.
- union(q, inNet(n.id, 'a'))
+ union(q, pinIn(n, 'a'))
break
case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined
@@ -220,7 +262,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
break
}
const childIn = new Map()
- for (const p of pins.inputs) childIn.set(p.key, inNet(n.id, p.key))
+ for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key))
const childOut = expand(child, childIn, `${path}${n.id}/`, inner)
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
break
@@ -230,7 +272,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
if (stack.length === 1) {
for (const n of def.nodes) {
- if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, inNet(n.id, k))
+ if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, pinIn(n, k))
}
}
diff --git a/app/lib/logic/fit.ts b/app/lib/logic/fit.ts
index bf125c4..a93e92a 100644
--- a/app/lib/logic/fit.ts
+++ b/app/lib/logic/fit.ts
@@ -50,7 +50,7 @@ function plugPin(n: CircuitNode, dir: 'in' | 'out', shape: Shape, wired: ReturnT
const free = shape.inputs.filter(p => !p.bus && !wired.in.has(`${n.id}:${p.key}`))
return free.length === 1 ? free[0]!.key : null
}
- if (!SOURCE_KINDS.includes(n.kind) && n.kind !== 'nand' && n.kind !== 'chip') return null
+ if (!SOURCE_KINDS.includes(n.kind) && n.kind !== 'nand' && n.kind !== 'chip' && n.kind !== 'ref') return null
const outs = shape.outputs.filter(p => !p.bus)
return outs.length === 1 && !wired.out.has(`${n.id}:${outs[0]!.key}`) ? outs[0]!.key : null
}
diff --git a/app/lib/logic/geometry.ts b/app/lib/logic/geometry.ts
index 317b742..9f1aec9 100644
--- a/app/lib/logic/geometry.ts
+++ b/app/lib/logic/geometry.ts
@@ -207,6 +207,26 @@ const SINK_SHAPE: Shape = {
outputs: [{ key: 'q', label: '', dx: 2, dy: 0 }],
}
+/** Width of a signal tag's flag, from its name. */
+function tagWidth(node: CircuitNode): number {
+ return Math.max(2.5, Math.ceil((signalName(node) || '?').length * 0.45 + 1.4))
+}
+
+/** The name a signal tag sends, or a reference uses. */
+export const signalName = (node: CircuitNode) => node.label?.trim() ?? ''
+
+/** Send: the wire comes in on the left into a flag carrying the name. */
+function tagShape(node: CircuitNode): Shape {
+ const w = tagWidth(node)
+ return { body: { x: 0.5, y: -0.6, w, h: 1.2 }, inputs: [{ key: 'a', label: '', dx: 0, dy: 0 }], outputs: [] }
+}
+
+/** Use: a flag with the name, the signal leaves on the right. */
+function refShape(node: CircuitNode): Shape {
+ const w = tagWidth(node)
+ return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] }
+}
+
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 })),
@@ -320,6 +340,10 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
return cableShape(node)
case 'pixel':
return PIXEL_SHAPE
+ case 'tag':
+ return tagShape(node)
+ case 'ref':
+ return refShape(node)
case 'note': {
const lines = noteLines(node)
const k = noteScale(node)
diff --git a/app/lib/logic/labels.ts b/app/lib/logic/labels.ts
index c180a06..766f896 100644
--- a/app/lib/logic/labels.ts
+++ b/app/lib/logic/labels.ts
@@ -13,6 +13,7 @@ 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'
+ if (kind === 'tag') return 'signal'
return null
}
@@ -86,7 +87,7 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
return def?.nodes.find(n => n.id === pin)?.label?.trim() || undefined
}
-const ADOPTERS = new Set(['input', 'button', 'output', 'lamp'])
+const ADOPTERS = new Set(['input', 'button', 'output', 'lamp', 'tag'])
/**
* After a new wire: a switch, button, output pin or lamp that has no name
diff --git a/app/lib/logic/ops.ts b/app/lib/logic/ops.ts
index f1754d3..e521986 100644
--- a/app/lib/logic/ops.ts
+++ b/app/lib/logic/ops.ts
@@ -408,6 +408,12 @@ export function swapNode(project: Project, def: ComponentDef, nodeId: string, ta
w.from = { node: w.from.node, pin: from }
return true
})
+ // Bubbles stay on the input in the same position, like wires.
+ if (node.invert?.length) {
+ const kept = node.invert.map(k => map(k, before.ins, after.ins)).filter((k): k is string => !!k)
+ if (kept.length && ['nand', 'chip', 'output', 'lamp'].includes(target.kind)) node.invert = [...new Set(kept)]
+ else delete node.invert
+ }
node.kind = target.kind
if (target.chip) node.chip = target.chip
else delete node.chip
diff --git a/app/lib/logic/progress.ts b/app/lib/logic/progress.ts
index a2f2861..8771dfa 100644
--- a/app/lib/logic/progress.ts
+++ b/app/lib/logic/progress.ts
@@ -23,6 +23,8 @@ export const KIND_NAMES: Partial> = {
bundle: 'Cable bundle',
split: 'Cable split',
pixel: 'Pixel',
+ tag: 'Send signal',
+ ref: 'Use signal',
}
/** Challenges each one builds on. */
diff --git a/app/lib/logic/search.ts b/app/lib/logic/search.ts
new file mode 100644
index 0000000..aa2501c
--- /dev/null
+++ b/app/lib/logic/search.ts
@@ -0,0 +1,76 @@
+// Finding things across the whole project: parts by name, kind, component,
+// signal or panel row, in every circuit; and components with where they are
+// placed.
+
+import { KIND_NAMES } from './progress'
+import type { CircuitNode, ComponentDef, Project } from './types'
+
+export interface PartHit {
+ /** The circuit it is in. */
+ def: string
+ defName: string
+ node: string
+ /** What it is, e.g. "Input switch A0" or "Adder 4 U1". */
+ text: string
+ /** What matched, when it isn't in the text (a panel row, a note's words). */
+ detail?: string
+ kind: CircuitNode['kind']
+ score: number
+}
+
+export interface ComponentHit {
+ def: ComponentDef
+ /** Circuits that place it, with the parts placed. */
+ usedIn: { def: ComponentDef; nodes: string[] }[]
+ score: number
+}
+
+/** 3 for the whole text, 2 for its start, 1 for a word start, 0.5 anywhere inside, 0 not at all. */
+function rank(text: string, q: string): number {
+ const t = text.toLowerCase()
+ if (!t || !q) return 0
+ if (t === q) return 3
+ if (t.startsWith(q)) return 2
+ if (t.split(/[\s_\-/.:]+/).some(w => w.startsWith(q))) return 1
+ return t.includes(q) ? 0.5 : 0
+}
+
+export function searchProject(project: Project, query: string, limit = 60): { components: ComponentHit[]; parts: PartHit[] } {
+ const q = query.trim().toLowerCase()
+ if (!q) return { components: [], parts: [] }
+ const byId = new Map(project.components.map(d => [d.id, d]))
+
+ const components: ComponentHit[] = []
+ for (const d of project.components) {
+ const score = rank(d.name, q)
+ if (!score) continue
+ const usedIn = project.components
+ .map(u => ({ def: u, nodes: u.nodes.filter(n => n.kind === 'chip' && n.chip === d.id).map(n => n.id) }))
+ .filter(u => u.def.id !== d.id && u.nodes.length)
+ components.push({ def: d, usedIn, score: score + (usedIn.length ? 0.1 : 0) })
+ }
+
+ const parts: PartHit[] = []
+ for (const d of project.components) {
+ for (const n of d.nodes) {
+ const kind = n.kind === 'chip' ? ((n.chip && byId.get(n.chip)?.name) ?? 'Missing component') : (KIND_NAMES[n.kind] ?? n.kind)
+ const label = n.label?.trim() ?? ''
+ const text = n.kind === 'note' ? `Note` : label ? `${kind} ${label}` : kind
+ let score = Math.max(rank(label, q) * 2, rank(kind, q))
+ let detail: string | undefined
+ if (n.kind === 'note' && rank(label, q)) detail = label.split('\n')[0]
+ for (const r of n.rows ?? []) {
+ const row = r.label?.trim() || r.name?.trim() || ''
+ const s = rank(row, q) * 2
+ if (s > score) {
+ score = s
+ detail = `row ${row}`
+ }
+ }
+ if (score) parts.push({ def: d.id, defName: d.name, node: n.id, text, detail, kind: n.kind, score })
+ }
+ }
+ components.sort((a, b) => b.score - a.score || a.def.name.localeCompare(b.def.name))
+ parts.sort((a, b) => b.score - a.score || a.defName.localeCompare(b.defName) || a.text.localeCompare(b.text))
+ return { components: components.slice(0, 20), parts: parts.slice(0, limit) }
+}
diff --git a/app/lib/logic/types.ts b/app/lib/logic/types.ts
index 7a04a15..e327e1d 100644
--- a/app/lib/logic/types.ts
+++ b/app/lib/logic/types.ts
@@ -17,6 +17,8 @@ export type BuiltinKind =
| 'bundle' // gathers several wires into one cable
| 'split' // fans a cable out into its wires again
| 'pixel' // one square of a screen; inside a component, pixels form a screen on its box
+ | 'tag' // gives the signal wired into it a name (its label)
+ | 'ref' // carries the signal of the tag with the same name in this circuit, without a wire
export type NodeKind = BuiltinKind | 'chip'
@@ -59,6 +61,8 @@ export interface CircuitNode {
offsets?: number[]
/** Names of the wires in a cable, top to bottom, from what drives them or else what they drive. */
names?: string[]
+ /** Input pins with a bubble: the signal comes in inverted, through one NAND (counted like any other). */
+ invert?: string[]
}
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
diff --git a/app/lib/logic/wires.ts b/app/lib/logic/wires.ts
index a2cab10..2d39b17 100644
--- a/app/lib/logic/wires.ts
+++ b/app/lib/logic/wires.ts
@@ -126,3 +126,37 @@ export function routeTouchesBox(pts: Pt[], box: { x0: number; y0: number; x1: nu
}
return false
}
+
+/** The segment of a route passing within `tol` of a point, or -1. */
+export function segmentAt(pts: Pt[], p: Pt, tol = 0.4): number {
+ for (let i = 0; i < pts.length - 1; i++) {
+ const [ax, ay] = pts[i]!
+ const [bx, by] = pts[i + 1]!
+ if (ax === bx && ay === by) continue
+ if (p[0] >= Math.min(ax, bx) - tol && p[0] <= Math.max(ax, bx) + tol && p[1] >= Math.min(ay, by) - tol && p[1] <= Math.max(ay, by) + tol) return i
+ }
+ return -1
+}
+
+/**
+ * Where to grab a wire's end to move it to another pin: a little way along
+ * the route from that pin, on its first (or last) segment.
+ */
+export function endGrip(pts: Pt[], end: 'from' | 'to'): Pt | null {
+ if (pts.length < 2) return null
+ const [a, b] = end === 'from' ? [pts[0]!, pts[1]!] : [pts[pts.length - 1]!, pts[pts.length - 2]!]
+ const len = Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
+ if (!len) return null
+ const t = Math.min(0.9, len / 2) / len
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
+}
+
+/** The end of a route a point is close to (within `reach`, measured to the pin), if any. */
+export function nearEnd(pts: Pt[], p: Pt, reach = 1.1): 'from' | 'to' | null {
+ if (pts.length < 2) return null
+ const d = (q: Pt) => Math.hypot(q[0] - p[0], q[1] - p[1])
+ const from = d(pts[0]!)
+ const to = d(pts[pts.length - 1]!)
+ if (Math.min(from, to) > reach) return null
+ return from <= to ? 'from' : 'to'
+}
diff --git a/app/lib/sheet.ts b/app/lib/sheet.ts
new file mode 100644
index 0000000..e91f541
--- /dev/null
+++ b/app/lib/sheet.ts
@@ -0,0 +1,151 @@
+// A circuit as a sheet to print or keep: the drawing as plain SVG with its
+// styles written in, framed, with a title block (project, circuit, date,
+// sheet number) like a wiring diagram. For paper, every colour keeps its hue
+// and turns from dark to light, so the sheet prints black on white.
+
+const PROPS = [
+ 'fill',
+ 'fill-opacity',
+ 'stroke',
+ 'stroke-width',
+ 'stroke-opacity',
+ 'stroke-dasharray',
+ 'stroke-linecap',
+ 'stroke-linejoin',
+ 'opacity',
+ 'font-family',
+ 'font-size',
+ 'font-weight',
+ 'font-style',
+ 'text-anchor',
+ 'dominant-baseline',
+ 'letter-spacing',
+ 'visibility',
+]
+
+/** Handles, hit areas and selection marks: on screen only. */
+const SCREEN_ONLY =
+ '.pin-hit, .wire-hit, .sel-outline, .wire-halo, .wire-grip, .corner-handle, .fits, .targets, .drop-ring, .temp-wire, .pin-snap, .queue-badge, .row-hit, .cable-hit, title'
+
+export interface SheetInfo {
+ project: string
+ circuit: string
+ date: Date
+ /** Area of the drawing to show, in the drawing's own units. */
+ box: { x: number; y: number; w: number; h: number }
+ /** White paper instead of the dark screen colours. */
+ paper?: boolean
+}
+
+/** Same hue and saturation, lightness turned around: dark becomes light. */
+export function paperColor(value: string): string {
+ const m = /^rgba?\(([^)]+)\)$/.exec(value.trim())
+ if (!m) return value
+ const [r, g, b, a] = m[1]!.split(/[\s,/]+/).filter(Boolean).map(Number) as [number, number, number, number?]
+ const [h, s, l] = toHsl(r / 255, g / 255, b / 255)
+ const [nr, ng, nb] = fromHsl(h, s, 1 - l)
+ const rgb = [nr, ng, nb].map(v => Math.round(v * 255)).join(', ')
+ return a === undefined || Number.isNaN(a) ? `rgb(${rgb})` : `rgba(${rgb}, ${a})`
+}
+
+function toHsl(r: number, g: number, b: number): [number, number, number] {
+ const max = Math.max(r, g, b)
+ const min = Math.min(r, g, b)
+ const l = (max + min) / 2
+ if (max === min) return [0, 0, l]
+ const d = max - min
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
+ const h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4
+ return [h / 6, s, l]
+}
+
+function fromHsl(h: number, s: number, l: number): [number, number, number] {
+ if (!s) return [l, l, l]
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s
+ const p = 2 * l - q
+ const hue = (t: number) => {
+ const x = t < 0 ? t + 1 : t > 1 ? t - 1 : t
+ if (x < 1 / 6) return p + (q - p) * 6 * x
+ if (x < 1 / 2) return q
+ if (x < 2 / 3) return p + (q - p) * (2 / 3 - x) * 6
+ return p
+ }
+ return [hue(h + 1 / 3), hue(h), hue(h - 1 / 3)]
+}
+
+const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]!)
+
+/** The drawing inside `content` (the canvas's transformed group) as a standalone SVG sheet. */
+export function sheetSvg(content: SVGGElement, info: SheetInfo): string {
+ const clone = content.cloneNode(true) as SVGGElement
+ const from = [content, ...content.querySelectorAll('*')]
+ const to = [clone, ...clone.querySelectorAll('*')]
+ from.forEach((el, i) => {
+ if (el.matches(SCREEN_ONLY)) to[i]!.setAttribute('data-screen-only', '')
+ const cs = getComputedStyle(el)
+ let style = ''
+ for (const p of PROPS) {
+ let v = cs.getPropertyValue(p)
+ if (!v) continue
+ if (info.paper && (p === 'fill' || p === 'stroke')) v = paperColor(v)
+ style += `${p}:${v};`
+ }
+ to[i]!.setAttribute('style', style)
+ to[i]!.removeAttribute('class')
+ })
+ // Removed only now: the two trees had to stay in step while copying styles.
+ for (const el of [...clone.querySelectorAll('[data-screen-only]')]) el.remove()
+ clone.removeAttribute('transform')
+
+ const { x, y, w, h } = info.box
+ const titleH = 34
+ const W = Math.max(w, 560)
+ const H = h + titleH
+ const bg = info.paper ? '#ffffff' : '#0e1116'
+ const ink = info.paper ? '#1b2330' : '#dbe2ea'
+ const line = info.paper ? '#9aa4b2' : '#3a4554'
+ const muted = info.paper ? '#5b6676' : '#8592a3'
+ const when = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(info.date)
+ const ty = y + h
+ const font = 'Inter, ui-sans-serif, system-ui, sans-serif'
+ return `
+
+${clone.outerHTML}
+
+
+
+${esc(info.project)} / ${esc(info.circuit)}
+${esc(when)}
+Sheet 1 / 1 · logicate.blax.at
+
+ `
+}
+
+/** Opens the print dialog for a sheet (where it can be saved as PDF), landscape. */
+export function printSheet(svg: string, title: string) {
+ const frame = document.createElement('iframe')
+ frame.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0'
+ document.body.appendChild(frame)
+ const doc = frame.contentDocument!
+ doc.open()
+ doc.write(`${esc(title)} ${svg}`)
+ doc.close()
+ setTimeout(() => {
+ frame.contentWindow?.focus()
+ frame.contentWindow?.print()
+ setTimeout(() => frame.remove(), 2000)
+ }, 150)
+}
+
+export function downloadSheet(svg: string, name: string) {
+ const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `${name.replace(/[^\w\- ]+/g, '').trim() || 'circuit'}.svg`
+ a.click()
+ setTimeout(() => URL.revokeObjectURL(url), 1000)
+}
diff --git a/tests/check.test.ts b/tests/check.test.ts
new file mode 100644
index 0000000..6d14f6a
--- /dev/null
+++ b/tests/check.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest'
+import { checkCircuit, unusedComponents } from '../app/lib/logic/check'
+import { createProject, lookup } from '../app/lib/logic/ops'
+import { searchProject } from '../app/lib/logic/search'
+import { paperColor } from '../app/lib/sheet'
+import type { ComponentDef } from '../app/lib/logic/types'
+
+function project() {
+ const p = createProject({ examples: true })
+ const def: ComponentDef = {
+ id: 'root',
+ name: 'Bench',
+ symbol: 'box',
+ nodes: [
+ { id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
+ { id: 'a2', kind: 'input', x: 0, y: 4, label: 'A' },
+ { id: 'g', kind: 'nand', x: 6, y: 0 },
+ { id: 'add', kind: 'chip', chip: 'ex-add4', x: 20, y: 0, label: 'U1' },
+ { id: 't', kind: 'tag', x: 0, y: 10, label: 'CLK' },
+ { id: 't2', kind: 'tag', x: 0, y: 12, label: 'CLK' },
+ { id: 'r', kind: 'ref', x: 10, y: 10, label: 'RESET' },
+ { id: 'note', kind: 'note', x: 0, y: 20, label: 'Carry goes to the display' },
+ ],
+ wires: [{ id: 'w', from: { node: 'a', pin: 'q' }, to: { node: 'g', pin: 'a' } }],
+ }
+ p.components.push(def)
+ return { p, def }
+}
+
+describe('checking a circuit', () => {
+ it('finds open inputs, unused parts, duplicate pins and broken signals', () => {
+ const { p, def } = project()
+ const issues = checkCircuit(def, lookup(p))
+ const text = issues.map(i => i.text)
+ expect(text).toContain('NAND gate: B not connected (reads 0)')
+ expect(text.some(t => t.startsWith('Adder 4 U1: no input connected'))).toBe(true)
+ expect(text).toContain('2 input pins are called A')
+ expect(text).toContain('Signal "CLK" is sent by 2 parts: they drive it against each other')
+ expect(text).toContain('Nothing sends signal "RESET" (reads 0)')
+ expect(text).toContain('NAND gate: its output goes nowhere')
+ // Worst first.
+ expect(issues[0]!.level).toBe('error')
+ expect(issues.at(-1)!.level).toBe('info')
+ })
+
+ it('lists components no other circuit places, leaving the examples out', () => {
+ const { p } = project()
+ expect(unusedComponents(p).map(d => d.id)).toContain('root')
+ expect(unusedComponents(p).some(d => d.id.startsWith('ex-'))).toBe(false)
+ })
+})
+
+describe('search', () => {
+ it('finds parts by name, kind and note text, and components with where they are used', () => {
+ const { p } = project()
+ const res = searchProject(p, 'adder 4')
+ expect(res.components[0]!.def.id).toBe('ex-add4')
+ expect(res.components[0]!.usedIn.map(u => u.def.id)).toContain('root')
+ expect(searchProject(p, 'u1').parts[0]).toMatchObject({ node: 'add', def: 'root' })
+ expect(searchProject(p, 'display').parts.some(h => h.node === 'note')).toBe(true)
+ expect(searchProject(p, 'clk').parts.filter(h => h.def === 'root').map(h => h.node).sort()).toEqual(['t', 't2'])
+ expect(searchProject(p, ' ').parts).toEqual([])
+ })
+})
+
+describe('sheets', () => {
+ it('turns screen colours into paper colours of the same hue', () => {
+ expect(paperColor('rgb(14, 17, 22)')).toBe('rgb(233, 236, 241)')
+ expect(paperColor('rgb(219, 226, 234)')).toMatch(/^rgb\(\d+, \d+, \d+\)$/)
+ expect(paperColor('none')).toBe('none')
+ expect(paperColor('rgba(61, 220, 132, 0.2)')).toMatch(/, 0.2\)$/)
+ })
+})
diff --git a/tests/signals.test.ts b/tests/signals.test.ts
new file mode 100644
index 0000000..d49fd38
--- /dev/null
+++ b/tests/signals.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it } from 'vitest'
+import { nandCounts, stats } from '../app/lib/logic/analyze'
+import { transistorBreakdown } from '../app/lib/logic/bulk'
+import { compile } from '../app/lib/logic/compile'
+import { chipPins } from '../app/lib/logic/geometry'
+import { createProject, lookup, swapNode } from '../app/lib/logic/ops'
+import { Simulator } from '../app/lib/logic/sim'
+import type { ComponentDef, Project } from '../app/lib/logic/types'
+
+function circuit(nodes: ComponentDef['nodes'], wires: ComponentDef['wires']): { p: Project; def: ComponentDef } {
+ const p = createProject({ examples: true })
+ const def: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes, wires }
+ p.components.push(def)
+ return { p, def }
+}
+
+const run = (p: Project, def: ComponentDef, on: Record) => {
+ const s = new Simulator(compile(lookup(p), def.id))
+ for (const [k, v] of Object.entries(on)) s.setSource(k, v)
+ s.run()
+ return s
+}
+
+describe('named signals', () => {
+ it('a reference carries what is wired into the tag of its name, without a wire', () => {
+ const { p, def } = circuit(
+ [
+ { id: 'clk', kind: 'input', x: 0, y: 0 },
+ { id: 't', kind: 'tag', x: 4, y: 0, label: 'CLK' },
+ { id: 'r1', kind: 'ref', x: 20, y: 10, label: 'CLK' },
+ { id: 'r2', kind: 'ref', x: 20, y: 20, label: 'CLK' },
+ { id: 'l1', kind: 'lamp', x: 30, y: 10 },
+ { id: 'l2', kind: 'lamp', x: 30, y: 20 },
+ ],
+ [
+ { id: 'a', from: { node: 'clk', pin: 'q' }, to: { node: 't', pin: 'a' } },
+ { id: 'b', from: { node: 'r1', pin: 'q' }, to: { node: 'l1', pin: 'a' } },
+ { id: 'c', from: { node: 'r2', pin: 'q' }, to: { node: 'l2', pin: 'a' } },
+ ],
+ )
+ expect(run(p, def, { clk: false }).pin('l1', 'a')).toBe(0)
+ const s = run(p, def, { clk: true })
+ expect([s.pin('l1', 'a'), s.pin('l2', 'a')]).toEqual([1, 1])
+ // Another name: nothing sends it, it reads 0.
+ def.nodes.find(n => n.id === 'r2')!.label = 'RESET'
+ expect(run(p, def, { clk: true }).pin('l2', 'a')).toBe(0)
+ })
+
+ it('names stay inside their circuit', () => {
+ const { p, def } = circuit(
+ [
+ { id: 'sw', kind: 'input', x: 0, y: 0 },
+ { id: 't', kind: 'tag', x: 4, y: 0, label: 'X' },
+ ],
+ [{ id: 'a', from: { node: 'sw', pin: 'q' }, to: { node: 't', pin: 'a' } }],
+ )
+ const inner: ComponentDef = {
+ id: 'inner',
+ name: 'Inner',
+ symbol: 'box',
+ nodes: [
+ { id: 'r', kind: 'ref', x: 0, y: 0, label: 'X' },
+ { id: 'o', kind: 'output', x: 6, y: 0, label: 'Q' },
+ ],
+ wires: [{ id: 'w', from: { node: 'r', pin: 'q' }, to: { node: 'o', pin: 'a' } }],
+ }
+ p.components.push(inner)
+ def.nodes.push({ id: 'c', kind: 'chip', chip: 'inner', x: 10, y: 0 }, { id: 'l', kind: 'lamp', x: 20, y: 0 })
+ def.wires.push({ id: 'b', from: { node: 'c', pin: 'o' }, to: { node: 'l', pin: 'a' } })
+ expect(run(p, def, { sw: true }).pin('l', 'a')).toBe(0)
+ })
+})
+
+describe('inverted inputs', () => {
+ it('a bubble inverts the input through one NAND, and the counts agree', () => {
+ const { p, def } = circuit(
+ [
+ { id: 'a', kind: 'input', x: 0, y: 0 },
+ { id: 'b', kind: 'input', x: 0, y: 3 },
+ { id: 'g', kind: 'nand', x: 6, y: 0, invert: ['a'] },
+ { id: 'l', kind: 'lamp', x: 14, y: 1, invert: ['a'] },
+ ],
+ [
+ { id: 'w1', from: { node: 'a', pin: 'q' }, to: { node: 'g', pin: 'a' } },
+ { id: 'w2', from: { node: 'b', pin: 'q' }, to: { node: 'g', pin: 'b' } },
+ { id: 'w3', from: { node: 'g', pin: 'q' }, to: { node: 'l', pin: 'a' } },
+ ],
+ )
+ // g = NAND(!a, b); the lamp shows its inverse: AND(!a, b).
+ const table = [
+ [false, false],
+ [false, true],
+ [true, false],
+ [true, true],
+ ].map(([a, b]) => run(p, def, { a: a!, b: b! }).pin('l', 'q'))
+ expect(table).toEqual([0, 1, 0, 0])
+ // The wire's own value shows on the pin, before the bubble.
+ expect(run(p, def, { a: true, b: false }).pin('g', 'a')).toBe(1)
+ const nl = compile(lookup(p), def.id)
+ expect(stats(nl).nands).toBe(3)
+ expect(nandCounts(p.components).get('root')).toBe(3)
+ const lines = transistorBreakdown(def, nandCounts(p.components), lookup(p))
+ expect(lines.find(l => l.key === 'invert')).toMatchObject({ count: 2, total: 8 })
+ })
+
+ it('swapping a part keeps its bubbles on the inputs in the same position', () => {
+ const { p, def } = circuit([{ id: 'g', kind: 'nand', x: 0, y: 0, invert: ['b'] }], [])
+ const or = p.components.find(d => d.id === 'ex-or')!
+ swapNode(p, def, 'g', { kind: 'chip', chip: or.id })
+ const g = def.nodes[0]!
+ const ins = chipPins(or).inputs.map(x => x.key)
+ expect(g.invert).toEqual([ins[1]])
+ swapNode(p, def, 'g', { kind: 'lamp' })
+ expect(g.invert).toBeUndefined()
+ })
+
+ it('bubbles on component inputs count inside every circuit that places it', () => {
+ const p = createProject({ examples: true })
+ const not = p.components.find(d => d.id === 'ex-not')!
+ const outer: ComponentDef = {
+ id: 'outer',
+ name: 'Outer',
+ symbol: 'box',
+ nodes: [{ id: 'c', kind: 'chip', chip: not.id, x: 0, y: 0, invert: [...new Set(['x', ...not.nodes.filter(n => n.kind === 'input').map(n => n.id)])] }],
+ wires: [],
+ }
+ p.components.push(outer)
+ const counts = nandCounts(p.components)
+ expect(counts.get('outer')).toBe(counts.get(not.id)! + 1)
+ expect(stats(compile(lookup(p), 'outer')).nands).toBe(counts.get('outer'))
+ })
+})