A Loxone-style working aids: named signals, inverted inputs, a project check, values on cables, search, printable sheets; wire ends move by dragging

- Send signal / Use signal: name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire; selecting one lights up all of them, a use with no sender shows dashed
- Inverted inputs: Alt + click an input (or the menu/settings) puts a bubble on it; it reads the signal inverted through one NAND, counted in every transistor total
- Check (Circuit tab): open inputs, parts that drive nothing, duplicate pin names, unsent or doubly sent signals, loops that never settle; click one to show it. Open inputs get an orange marker on the canvas. Components no other circuit uses are listed with a delete
- Cables show the number they carry (= 13 · 0x0D); hovering a wire tells where it runs and its value
- Ctrl+F finds parts, signals, panel rows, notes and components in every circuit, with where each component is used
- Ctrl+P prints the circuit as a sheet with a title block on white paper (or save as PDF); also as an SVG file
- + and − under a selected gate change its number of inputs; swaps keep bubbles in place
- Drag a wire by its end to move that end to another pin; drop a dragged wire on another wire to tap its signal or feed what it fed

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-21 13:26:59 +02:00
parent f4e2c08658
commit 4d0e32d678
28 changed files with 1655 additions and 34 deletions

View File

@ -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);
}

View File

@ -53,5 +53,6 @@ onMounted(() => {
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
<EditorVersionsDialog v-if="ed.dialog.value === 'versions'" />
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
<EditorSearchDialog v-if="ed.dialog.value === 'search'" />
</div>
</template>

View File

@ -1,14 +1,17 @@
<script setup lang="ts">
import { cableKeys } from '~/lib/logic/compile'
import { cableKeys, INVERTIBLE } from '~/lib/logic/compile'
import { CHECKED_INPUTS } from '~/lib/logic/check'
import { cableBits, GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
import { branchCorners, branchTo, moveCorner, moveSegment, routeTouchesBox, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { branchCorners, branchTo, endGrip, moveCorner, moveSegment, nearEnd, routeTouchesBox, segmentAt, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { seriesLinks, type Link } from '~/lib/logic/bulk'
import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { wirePath } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
import { inputCount } from '~/lib/logic/wide'
import { pinName } from '~/lib/logic/labels'
const ed = useEditor()
@ -84,6 +87,31 @@ const routes = computed<Route[]>(() => {
const routeOf = (wire: Wire) => routes.value.find(r => r.wire === wire)
/** The number a cable carries right now: wire 0 is the lowest bit. */
function cableValue(r: Route): { dec: string; tip: string } | null {
if (!r.bits) return null
const from = r.wire.from.node
const bits = Array.from({ length: r.bits }, (_, i) => ed.val(from, `b${i}`) === 1)
const n = bits.reduce((v, on, i) => v + (on ? 2 ** i : 0), 0)
const hex = `0x${n.toString(16).toUpperCase().padStart(Math.ceil(r.bits / 4), '0')}`
const bin = bits.map(b => (b ? '1' : '0')).reverse().join('')
return { dec: r.bits > 4 ? `${n} · ${hex}` : String(n), tip: `${r.bits} wires: ${bin} = ${n} = ${hex} (wire 0 is the lowest bit)` }
}
/** What a wire carries, for its tooltip: where it comes from, where it goes, and its value. */
function wireTip(r: Route): string {
const v = cableValue(r)
if (v) return v.tip
const name = (ref: PinRef) => {
const n = nodeMap.value.get(ref.node)
if (!n) return '?'
const pin = pinName(n, ref.pin, ed.getDef.value)
const part = n.label?.trim() || (n.kind === 'chip' ? (n.chip && ed.getDef.value(n.chip)?.name) || 'Component' : n.kind.toUpperCase())
return pin ? `${part} ${pin}` : part
}
return `${name(r.wire.from)} → ${name(r.wire.to)}: ${srcVal(r.src)}`
}
/** Dots where a net branches, so crossings without a dot read as "not connected". */
const junctions = computed(() => {
const groups = new Map<string, Pt[][]>()
@ -281,7 +309,18 @@ type Drag =
/** Pins the moving parts land on: the step that lines them up and the wires dropping makes. */
snap?: { shift: Pt; links: Link[] } | null
}
| { kind: 'wire'; node: string; pin: string; dir: 'in' | 'out'; start: Pt; cur: Pt; moved: boolean; branch?: Pt[] }
| {
kind: 'wire'
node: string
pin: string
dir: 'in' | 'out'
start: Pt
cur: Pt
moved: boolean
branch?: Pt[]
/** Moving one end of this wire: the other end stays, the wire goes where it is dropped. */
replace?: string
}
| { kind: 'box'; start: Pt; cur: Pt; nodes: string[]; wires: string[] }
| { kind: 'segment'; wire: Wire; base: Pt[]; k: number; axis: 0 | 1; start: number; moved: boolean }
| { kind: 'corner'; wire: Wire; route: Pt[]; i: number; moved: boolean }
@ -354,6 +393,13 @@ function onPointerDown(e: PointerEvent) {
}
const target = e.target as Element
const widenEl = target.closest('[data-inputs]')
if (widenEl) {
// + or − under a selected gate: one input more or less.
const n = nodeMap.value.get(widenEl.closest('[data-node]')?.getAttribute('data-node') ?? '')
if (n) ed.setInputs(n, inputCount(n, ed.getDef.value) + Number(widenEl.getAttribute('data-inputs')))
return
}
const fitEl = target.closest('[data-fit]')
if (fitEl) {
// A green box: wire the selection to the pins pointed at.
@ -364,6 +410,11 @@ function onPointerDown(e: PointerEvent) {
return
}
const pinEl = target.closest('[data-pin]')
if (pinEl && e.altKey && pinEl.getAttribute('data-dir') === 'in') {
// Alt + click on an input: invert it (a bubble), or take the bubble off.
const n = nodeMap.value.get(pinEl.getAttribute('data-node')!)
if (n && INVERTIBLE.has(n.kind)) return ed.toggleInvert(n, pinEl.getAttribute('data-pin')!)
}
if (pinEl) {
drag.value = {
kind: 'wire',
@ -447,7 +498,7 @@ function onWireDown(e: PointerEvent, el: Element, w: Pt) {
return
}
const index = Number(el.getAttribute('data-seg'))
const index = el.hasAttribute('data-seg') ? Number(el.getAttribute('data-seg')) : Math.max(0, segmentAt(route.pts, w, 1))
if (e.ctrlKey || e.metaKey) {
// Branch: a new wire from the same signal, starting at this point.
drag.value = { kind: 'wire', node: wire.from.node, pin: wire.from.pin, dir: 'out', start: w, cur: w, moved: true, branch: branchCorners(route.pts, index, w) }
@ -462,6 +513,15 @@ function onWireDown(e: PointerEvent, el: Element, w: Pt) {
ed.selection.value = []
return
}
// Grabbing a wire by its end (the grip, or close to the pin) moves that end to another pin.
const end = (el.getAttribute('data-end') as 'from' | 'to' | null) ?? (e.altKey ? null : nearEnd(route.pts, w))
if (end && !isCable(wire)) {
const stay = end === 'to' ? wire.from : wire.to
drag.value = { kind: 'wire', node: stay.node, pin: stay.pin, dir: end === 'to' ? 'out' : 'in', start: w, cur: w, moved: false, replace: wire.id }
ed.wireSel.value = [wire.id]
ed.selection.value = []
return
}
if (!wireSelected.value.has(wire.id)) {
ed.wireSel.value = [wire.id]
ed.selection.value = []
@ -584,6 +644,24 @@ const hints = computed(() => {
}
return out
})
/** Inputs with no wire, marked like Loxone does: they read 0. */
const openPins = computed(() => {
const out = new Map<string, Set<string>>()
for (const n of def.value.nodes) {
if (!CHECKED_INPUTS.has(n.kind)) continue
const open = shapes.value.get(n.id)!.inputs.filter(p => !p.bus && !linked.value.in.has(`${n.id}:${p.key}`)).map(p => p.key)
if (open.length) out.set(n.id, new Set(open))
}
return out
})
/** The signal of the one selected tag or reference: all of its tags and references light up. */
const signalSel = computed(() => {
if (ed.selection.value.length !== 1) return ''
const n = nodeMap.value.get(ed.selection.value[0]!)
return n && (n.kind === 'tag' || n.kind === 'ref') ? (n.label?.trim() ?? '') : ''
})
const SOURCES = new Set(['input', 'button', 'clock'])
const SINKS = new Set(['output', 'lamp'])
@ -664,12 +742,28 @@ function onPointerUp(e: PointerEvent) {
case 'wire': {
const here = { node: d.node, pin: d.pin }
if (!d.moved) {
if (d.replace) break
// A click on a pin: the wire follows the mouse until the next click.
ed.linking.value = { queue: [{ ...here, dir: d.dir, label: '' }], at: 0 }
break
}
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir))
const onWire = wireDrop(d)
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir)) ?? onWire?.pin
if (!target) break
if (d.replace) {
ed.rewire(d.replace, d.dir === 'out' ? here : target, d.dir === 'out' ? target : here)
break
}
if (onWire && d.dir === 'in' && !d.branch) {
// Dropped on a wire from a pin that needs a signal: it taps that wire's signal where it was dropped.
const r = onWire.route
const fn = nodeMap.value.get(target.node)!
const tn = nodeMap.value.get(here.node)!
const a = pinPos(fn, shapes.value.get(fn.id)!, target.pin, 'out')!
const b = pinPos(tn, shapes.value.get(tn.id)!, here.pin, 'in')!
ed.connect(target, here, branchTo(branchCorners(r.pts, onWire.seg, d.cur), [a.x, a.y], [b.x, b.y]))
break
}
// Dragged from one of several selected parts to another part: wire them all, in order.
if (!d.branch && ed.selection.value.length > 1 && ed.selection.value.includes(d.node) && !ed.selection.value.includes(target.node)) {
ed.connectMany(seriesLinks(def.value, ed.getDef.value, ed.selection.value, { node: d.node, pin: d.pin, dir: d.dir }, target))
@ -699,7 +793,7 @@ function onPointerUp(e: PointerEvent) {
function onDoubleClick(node: CircuitNode) {
if (node.kind === 'chip' && node.chip) ed.open(node.chip)
else if (['input', 'output', 'lamp', 'button', 'note', 'hex', 'panel'].includes(node.kind)) {
else if (['input', 'output', 'lamp', 'button', 'note', 'hex', 'panel', 'tag', 'ref'].includes(node.kind)) {
ed.selection.value = [node.id]
ed.labelFocus.value++
}
@ -765,6 +859,16 @@ function onKey(e: KeyboardEvent) {
return
}
}
if (mod && key === 'p') {
e.preventDefault()
ed.exportSheet('print')
return
}
if (mod && key === 'f') {
e.preventDefault()
ed.dialog.value = 'search'
return
}
if (mod && key === 'z') {
e.preventDefault()
if (e.shiftKey) ed.redo()
@ -860,6 +964,52 @@ const tempWire = computed(() => {
return { d: toPath(pts), snapped: !!target, end }
})
const isCable = (w: Wire) => nodeMap.value.get(w.from.node)?.kind === 'bundle'
/**
* A wire being drawn and dropped on another wire (not on a pin): one that
* needs a signal takes that wire's signal; one that carries a signal feeds
* what that wire fed, in its place.
*/
function wireDrop(d: { node: string; pin: string; dir: 'in' | 'out'; cur: Pt; replace?: string }) {
if (targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir))) return null
const bus = ed.isBus(d.node, d.pin, d.dir)
for (let i = routes.value.length - 1; i >= 0; i--) {
const r = routes.value[i]!
if (r.wire.id === d.replace || !!r.bits !== bus) continue
if (d.dir === 'in' ? r.wire.to.node === d.node && r.wire.to.pin === d.pin : r.wire.from.node === d.node && r.wire.from.pin === d.pin) continue
const seg = segmentAt(r.pts, d.cur, 0.35)
if (seg < 0) continue
return { route: r, seg, pin: d.dir === 'in' ? r.wire.from : r.wire.to }
}
return null
}
/** The wire a wire being drawn would drop onto, shown highlighted. */
const dropWire = computed(() => {
const d = pending.value
return d ? (wireDrop({ ...d, replace: drag.value?.kind === 'wire' ? drag.value.replace : undefined })?.route.wire.id ?? null) : null
})
/** The wire whose end is being moved: drawn faint while it follows the mouse. */
const movingWire = computed(() => (drag.value?.kind === 'wire' && drag.value.moved ? (drag.value.replace ?? null) : null))
const hoverWire = ref<string | null>(null)
/** Grips on the ends of the wire under the mouse (or selected): drag one to move that end to another pin. */
const grips = computed(() => {
if (drag.value) return []
const ids = new Set([...ed.wireSel.value.slice(0, 8), ...(hoverWire.value ? [hoverWire.value] : [])])
return routes.value
.filter(r => ids.has(r.wire.id) && !r.bits)
.flatMap(r =>
(['from', 'to'] as const).flatMap(end => {
const p = endGrip(r.pts, end)
return p ? [{ wire: r.wire.id, end, x: p[0], y: p[1] }] : []
}),
)
})
/** Pins a wire being drawn can go to: free ones stand out, taken ones would be replaced. */
const targets = computed(() => {
const d = pending.value
@ -925,6 +1075,41 @@ const cableGhost = computed(() => {
return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) }
})
// ── Sheets ──────────────────────────────────────────────────────────
const content = ref<SVGGElement>()
/** The open circuit as a sheet with a title block: printed on white paper, or saved as SVG like on screen. */
watch(
() => ed.sheetRequest.value?.n,
() => {
const req = ed.sheetRequest.value
if (!req || !content.value) return
if (!def.value.nodes.length) return ed.notify('Nothing to print: the circuit is empty', 'error')
const b = bounds(def.value.nodes)
for (const r of routes.value) {
for (const [x, y] of r.pts) {
b.x0 = Math.min(b.x0, x)
b.x1 = Math.max(b.x1, x)
b.y0 = Math.min(b.y0, y)
b.y1 = Math.max(b.y1, y)
}
}
const m = 2
const box = { x: (b.x0 - m) * G, y: (b.y0 - m) * G, w: (b.x1 - b.x0 + 2 * m) * G, h: (b.y1 - b.y0 + 2 * m) * G }
// Without the selection, so the sheet shows the circuit as it is.
const keep = { nodes: ed.selection.value, wires: ed.wireSel.value }
ed.selection.value = []
ed.wireSel.value = []
nextTick(() => {
const info = { project: ed.meta.value?.name ?? ed.project.value.name ?? 'Project', circuit: def.value.name, date: new Date(), box }
if (req.mode === 'print') printSheet(sheetSvg(content.value!, { ...info, paper: true }), `${info.project} - ${info.circuit}`)
else downloadSheet(sheetSvg(content.value!, info), info.circuit)
ed.selection.value = keep.nodes
ed.wireSel.value = keep.wires
})
},
)
// ── Context menu ────────────────────────────────────────────────────
const menu = ref<{ x: number; y: number; entries: MenuEntry[]; keyboard?: boolean } | null>(null)
const { build } = useMenu()
@ -1059,7 +1244,7 @@ defineExpose({ fit, zoomAt })
<rect v-if="gridSize >= 5" width="100%" height="100%" fill="url(#grid-dots)" />
<rect v-if="gridSize * 8 >= 6" width="100%" height="100%" fill="url(#grid-major)" />
<g :transform="`translate(${view.x} ${view.y}) scale(${view.zoom})`">
<g ref="content" :transform="`translate(${view.x} ${view.y}) scale(${view.zoom})`">
<g class="wires">
<g
v-for="r in routes"
@ -1067,7 +1252,14 @@ defineExpose({ fit, zoomAt })
class="wire"
:class="[
r.wire.color ? `c-${r.wire.color}` : '',
{ on: srcVal(r.src) === 1, selected: wireSelected.has(r.wire.id), hover: hoverSrc === r.src, cable: !!r.bits },
{
on: srcVal(r.src) === 1,
selected: wireSelected.has(r.wire.id),
hover: hoverSrc === r.src,
cable: !!r.bits,
'drop-target': dropWire === r.wire.id,
moving: movingWire === r.wire.id,
},
]"
>
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="r.sleeve ? { strokeWidth: `${r.sleeve + 9}px` } : undefined" />
@ -1096,13 +1288,15 @@ defineExpose({ fit, zoomAt })
:style="r.sleeve ? { strokeWidth: `${Math.max(10, r.sleeve + 4)}px` } : undefined"
:data-wire="r.wire.id"
:data-seg="i"
@pointerenter="hoverSrc = r.src"
@pointerleave="hoverSrc = null"
@pointerenter="(hoverSrc = r.src), (hoverWire = r.wire.id)"
@pointerleave="(hoverSrc = null), (hoverWire = null)"
/>
<g v-if="r.bits && r.mark" class="cable-mark" :transform="`translate(${r.mark[0] * G} ${r.mark[1] * G})`">
<path :d="r.sleeve ? `M-4 ${r.sleeve / 2 + 3}L4 ${-r.sleeve / 2 - 3}` : 'M-4 6L4 -6'" />
<text x="6" :y="r.sleeve ? -r.sleeve / 2 - 4 : -6">{{ r.bits }}</text>
<text x="6" :y="r.sleeve ? r.sleeve / 2 + 11 : 14" class="cable-value">= {{ cableValue(r)?.dec }}</text>
</g>
<title v-if="hoverWire === r.wire.id">{{ wireTip(r) }}</title>
</g>
<g v-for="(j, i) in junctions" :key="`j${i}`" class="wire" :class="[j.color ? `c-${j.color}` : '', { on: srcVal(j.src) === 1 }]">
<circle :cx="j.x * G" :cy="j.y * G" r="3.2" class="junction" :data-junction="j.src" />
@ -1117,8 +1311,24 @@ defineExpose({ fit, zoomAt })
:selected="selected.has(n.id)"
:through="linked.out.has(`${n.id}:q`) && (n.kind === 'lamp' || n.kind === 'output')"
:hint="hints.get(n.id)"
:linked="!!signalSel && (n.kind === 'tag' || n.kind === 'ref') && n.label?.trim() === signalSel"
:open="openPins.get(n.id)"
/>
<circle
v-for="g in grips"
:key="`${g.wire}-${g.end}`"
:cx="g.x * G"
:cy="g.y * G"
r="4"
class="wire-grip"
:data-wire="g.wire"
:data-end="g.end"
@pointerenter="hoverWire = g.wire"
@pointerleave="hoverWire = null"
>
<title>Drag to move this end to another pin</title>
</circle>
<rect
v-for="h in handles"
:key="`${h.wire}-${h.i}`"

View File

@ -2,6 +2,7 @@
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
import { transistorBreakdown } from '~/lib/logic/bulk'
import { chipPins } from '~/lib/logic/geometry'
import { unusedComponents } from '~/lib/logic/check'
import { usages } from '~/lib/logic/ops'
import type { SymbolKind } from '~/lib/logic/types'
@ -44,11 +45,56 @@ function toggleFace(e: Event) {
ed.commit(false)
}
// ── Problems ────────────────────────────────────────────────────────
const LEVEL_ICON = { error: 'lucide:circle-x', warn: 'lucide:triangle-alert', info: 'lucide:info' } as const
const showInfo = ref(false)
const shownIssues = computed(() => ed.issues.value.filter(i => showInfo.value || i.level !== 'info'))
const infoCount = computed(() => ed.issues.value.filter(i => i.level === 'info').length)
const unused = computed(() => unusedComponents(ed.project.value).filter(d => d.id !== def.value.id))
const showUnused = ref(false)
const confirmRemove = ref<string | null>(null)
const confirmDelete = ref(false)
watch(() => def.value.id, () => (confirmDelete.value = false))
</script>
<template>
<section class="problems">
<div class="problems-head">
<h3>Check</h3>
<span v-if="!shownIssues.length" class="ok"><Icon name="lucide:circle-check" class="size-4" /> {{ infoCount ? 'No problems' : 'All good' }}</span>
<label v-if="infoCount" class="check ml-auto"><input v-model="showInfo" type="checkbox" /> Notes ({{ infoCount }})</label>
</div>
<ul v-if="shownIssues.length" class="issue-list">
<li v-for="(i, k) in shownIssues.slice(0, 40)" :key="k">
<button class="issue" :class="i.level" :disabled="!i.nodes.length" @click="ed.showIssue(i.nodes)">
<Icon :name="LEVEL_ICON[i.level]" class="issue-icon size-4 shrink-0" />
<span>{{ i.text }}</span>
</button>
</li>
</ul>
<p v-if="shownIssues.length > 40" class="hint">and {{ shownIssues.length - 40 }} more</p>
<template v-if="unused.length">
<button class="section-toggle mt-2" @click="showUnused = !showUnused">
<Icon :name="showUnused ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
Not used in another circuit ({{ unused.length }})
</button>
<template v-if="showUnused">
<p class="hint">Circuits you work in directly show up here too. Delete only what you don't need.</p>
<ul class="issue-list">
<li v-for="d in unused" :key="d.id" class="unused-row">
<a href="#" class="grow truncate" @click.prevent="ed.open(d.id)">{{ d.name }}</a>
<template v-if="confirmRemove === d.id">
<button class="btn-sm danger" @click="ed.removeComponent(d.id), (confirmRemove = null)">Delete</button>
<button class="btn-sm" @click="confirmRemove = null">Keep</button>
</template>
<button v-else class="icon-btn" title="Delete this component" @click="confirmRemove = d.id"><Icon name="lucide:trash-2" class="size-3.5" /></button>
</li>
</ul>
</template>
</template>
</section>
<section>
<h3>This circuit</h3>
<label class="field">
@ -101,6 +147,19 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</p>
</section>
<section>
<h3>Sheet</h3>
<p class="hint">The circuit as a wiring sheet with a title block: print it, save it as PDF, or keep it as an SVG.</p>
<div class="grid grid-cols-2 gap-2">
<button class="btn" :disabled="!def.nodes.length" title="On white paper (Ctrl+P); choose Save as PDF in the print dialog" @click="ed.exportSheet('print')">
<Icon name="lucide:printer" class="size-4" /> Print / PDF
</button>
<button class="btn" :disabled="!def.nodes.length" title="As on screen, to open in a browser or drawing program" @click="ed.exportSheet('svg')">
<Icon name="lucide:file-image" class="size-4" /> SVG file
</button>
</div>
</section>
<section>
<button class="section-toggle" @click="showBreakdown = !showBreakdown">
<Icon :name="showBreakdown ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />

View File

@ -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)'],

View File

@ -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(
>
<Icon :name="t.icon" class="size-4 shrink-0" />
<span class="label">{{ t.label }}</span>
<span v-if="t.badge" class="badge">{{ t.badge }}</span>
<span v-if="t.badge" class="badge" :class="{ warn: 'warn' in t && t.warn }">{{ t.badge }}</span>
</button>
</nav>
<div class="scroll">

View File

@ -2,6 +2,7 @@
import { stats } from '~/lib/logic/analyze'
import { compile } from '~/lib/logic/compile'
import { cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, cableOffsets, chipPins, MAX_BITS, panelOffsets, rowLabel } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
@ -29,6 +30,8 @@ const HINTS: Record<string, string> = {
bundle: 'Wire 0 (top) to the last on the left go into the cable on the right. Run the cable to a split, which gives them back in the same order. The wires are named after what drives them, or else what they drive.',
split: 'Takes a cable from a bundle and gives its wires back in the same order, top to bottom, with their names.',
pixel: 'Lights at 1. Inside a component, all its pixels show on the component box as one screen, without gaps: space them out inside to wire them, every column and row they sit on becomes a column and row of the screen.',
tag: 'Wire a signal into it and give it a name. Every "Use signal" with that name in this circuit carries the same signal, without a wire. Names stay inside this circuit.',
ref: 'Carries the signal of the "Send signal" with the same name in this circuit. Select it to see all places that signal goes.',
panel: 'Click a row on the canvas to flip its switch or hold its button, or press its key. Rows without a name take the name of the pin they are wired to. Open a row (the arrow) for its key, colour, spacing and order.',
}
@ -122,9 +125,16 @@ function setOn(on: boolean) {
/** A name typed by hand is kept from then on; clearing it lets connections name the part again. */
function onLabel() {
delete n.value.autoLabel
ed.commit(false)
// A signal's name decides what it connects to.
ed.commit(n.value.kind === 'tag' || n.value.kind === 'ref')
}
// ── Signals ─────────────────────────────────────────────────────────
const signal = computed(() => n.value.label?.trim() ?? '')
const signalNames = computed(() => [...new Set(ed.def.value.nodes.filter(x => x.kind === 'tag' && x.label?.trim()).map(x => x.label!.trim()))].sort())
const senders = computed(() => ed.def.value.nodes.filter(x => x.kind === 'tag' && !!signal.value && x.label?.trim() === signal.value))
const uses = computed(() => ed.def.value.nodes.filter(x => x.kind === 'ref' && !!signal.value && x.label?.trim() === signal.value))
const dock = computed(() => {
const id = n.value.attach
const chip = id ? ed.def.value.nodes.find(x => x.id === id) : undefined
@ -138,6 +148,13 @@ const widens = computed(() => {
})
const inputs = computed(() => inputCount(n.value, ed.getDef.value))
/** Inputs that can carry a bubble, with their names. */
const invertible = computed(() => {
if (!INVERTIBLE.has(n.value.kind)) return []
const inv = new Set(n.value.invert ?? [])
return ed.shape(n.value).inputs.map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
})
/** The bundle of the cable this bundle or split belongs to. */
const cableBundle = computed(() => {
if (n.value.kind === 'bundle') return n.value
@ -252,19 +269,62 @@ function setRowHz(row: PanelRow, e: Event) {
</label>
<p v-if="widens && inputs > 2" class="hint -mt-1">Built from {{ inputs - 1 }} two-input gates in a tree, so the transistors count honestly.</p>
<div v-if="invertible.length" class="field">
<span>Inverted inputs (Alt + click a pin)</span>
<div class="invert-pins">
<button
v-for="p in invertible"
:key="p.key"
class="invert-pin"
:class="{ on: p.on }"
:title="p.on ? 'Inverted: one NAND, 4 transistors. Click to take the bubble off.' : 'Invert this input'"
@click="ed.toggleInvert(n, p.key)"
>
<span class="dot" />{{ p.label }}
</button>
</div>
</div>
<label v-if="hasLabel" class="field">
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : 'Label' }}</span>
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : n.kind === 'tag' ? 'Signal name' : n.kind === 'ref' ? 'Signal' : 'Label' }}</span>
<textarea v-if="n.kind === 'note'" ref="labelInput" v-model="n.label" rows="3" @change="ed.commit(false)" />
<input
v-else
ref="labelInput"
v-model="n.label"
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : ''"
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : n.kind === 'tag' || n.kind === 'ref' ? 'e.g. CLK, RESET' : ''"
:list="n.kind === 'ref' ? 'signal-names' : undefined"
@change="onLabel"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
</label>
<p v-if="n.autoLabel && n.label" class="hint -mt-1">Named automatically. Typing a name keeps it.</p>
<datalist id="signal-names">
<option v-for="name in signalNames" :key="name" :value="name" />
</datalist>
<!-- Signals -->
<template v-if="n.kind === 'tag'">
<p v-if="senders.length > 1" class="result fail">
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
<span>{{ senders.length }} "Send signal" parts use this name: they all drive it, like a short.</span>
</p>
<p class="hint">{{ uses.length ? `Used in ${uses.length} place${uses.length === 1 ? '' : 's'}.` : 'Not used anywhere yet.' }}</p>
<div class="mb-2 grid grid-cols-2 gap-2">
<button class="btn" :disabled="!signal" title="A 'Use signal' for it, placed next to it" @click="ed.useSignal(n)"><Icon name="lucide:tag" class="size-4" /> Use it</button>
<button class="btn" :disabled="!uses.length" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
</div>
</template>
<template v-if="n.kind === 'ref'">
<p v-if="!senders.length" class="result fail">
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
<span>{{ signal ? `Nothing sends "${signal}" in this circuit, so it reads 0.` : 'Pick the signal it carries.' }}</span>
</p>
<div v-else class="mb-2 grid grid-cols-2 gap-2">
<button class="btn" @click="ed.focusNode(senders[0]!.id)"><Icon name="lucide:locate-fixed" class="size-4" /> Go to source</button>
<button class="btn" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
</div>
</template>
<!-- Input panel rows -->
<template v-if="n.kind === 'panel'">

View File

@ -1,6 +1,7 @@
<script setup lang="ts">
import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { GRID as G, noteLines, noteScale, PANEL_CONTROL_W, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode } from '~/lib/logic/types'
@ -13,6 +14,10 @@ const props = defineProps<{
through?: boolean
/** Name of the pin this part is wired to, shown dimmed while it has no name of its own. */
hint?: string
/** A signal tag or reference of the signal selected: shown highlighted. */
linked?: boolean
/** Inputs with no wire: a small orange marker says they read 0. */
open?: Set<string>
}>()
const ed = useEditor()
@ -77,6 +82,38 @@ function dot(key: string): boolean {
return key === 'q' || key === 'a' ? !c.bus : !c.linked.has(key)
}
/** A signal's flag: pointing right; a reference has a notch at its tail. */
function flag(x0: number, w: number, notch: boolean) {
const x1 = (x0 + w) * G
const a = x0 * G
return `M${a} ${-0.6 * G}H${x1 - 0.45 * G}L${x1} 0L${x1 - 0.45 * G} ${0.6 * G}H${a}${notch ? `L${a + 0.35 * G} 0` : ''}Z`
}
/** A reference whose name no tag in this circuit sends. */
const orphan = computed(() => {
if (props.node.kind !== 'ref' || props.ghost) return false
const name = props.node.label?.trim()
return !name || !ed.def.value.nodes.some(n => n.kind === 'tag' && n.label?.trim() === name)
})
/** A selected gate that can take more inputs gets + and − below it. */
const widen = computed(() => {
if (!props.selected || props.ghost || !props.shape.gate) return null
const get = ed.getDef.value
const base = baseOf(props.node, get)
if (!base || !gateFamily(get, base)) return null
const n = inputCount(props.node, get)
return { n, more: n < MAX_GATE_INPUTS, less: n > 2 }
})
/** Bubbles on inverted inputs: on the stub of a gate or lamp, just outside a component's box. */
const bubbles = computed(() => {
const inv = new Set(props.node.invert ?? [])
if (!inv.size) return []
const dx = props.node.kind === 'chip' && !props.shape.gate ? -0.3 : 0.28
return props.shape.inputs.filter(p => inv.has(p.key)).map(p => ({ key: p.key, x: (p.dx + dx) * G, y: p.dy * G }))
})
/** The edge a plugged cable end touches its part with. */
const seam = computed(() => (props.node.kind === 'bundle' ? 0 : G))
@ -238,6 +275,18 @@ const title = computed(() => {
</g>
</template>
<!-- Signals: a tag names the wire into it, a reference carries that signal anywhere -->
<template v-else-if="node.kind === 'tag'">
<path :d="`M0 0H${0.5 * G}`" class="stub" />
<path :d="flag(0.5, b.w, false)" class="signal-flag" :class="{ on: v('a') === 1, linked }" />
<text :x="(0.5 + (b.w - 0.45) / 2) * G" y="3.5" text-anchor="middle" class="signal-name">{{ node.label?.trim() || '?' }}</text>
</template>
<template v-else-if="node.kind === 'ref'">
<path :d="flag(0, b.w, true)" class="signal-flag use" :class="{ on: v('q') === 1, linked, orphan }" />
<text :x="(0.18 + (b.w - 0.45) / 2) * G" y="3.5" text-anchor="middle" class="signal-name">{{ node.label?.trim() || '?' }}</text>
<path :d="`M${b.w * G} 0H${(b.w + 0.5) * G}`" class="stub" />
</template>
<!-- Pixel: one square of a screen -->
<template v-else-if="node.kind === 'pixel'">
<rect x="1" :y="b.y * G + 1" :width="G - 2" :height="G - 2" rx="1" class="pixel" :class="[node.color ? `px-${node.color}` : '', { on: v('a') === 1 }]" />
@ -294,8 +343,24 @@ const title = computed(() => {
class="sel-outline"
/>
<circle v-for="bb in bubbles" :key="`inv-${bb.key}`" :cx="bb.x" :cy="bb.y" :r="0.24 * G" class="invert-bubble" />
<g v-if="widen" class="widen" :transform="`translate(${(b.x + b.w / 2) * G} ${(b.y + b.h) * G + 13})`">
<g v-if="widen.less" data-inputs="-1" class="widen-btn" transform="translate(-11 0)">
<title>One input less ({{ widen.n - 1 }})</title>
<circle r="7.5" />
<path d="M-3.5 0H3.5" />
</g>
<g v-if="widen.more" data-inputs="1" class="widen-btn" :transform="`translate(${widen.less ? 11 : 0} 0)`">
<title>One more input ({{ widen.n + 1 }})</title>
<circle r="7.5" />
<path d="M-3.5 0H3.5M0 -3.5V3.5" />
</g>
</g>
<template v-if="!ghost">
<g v-for="p in shape.inputs" :key="`i-${p.key}`">
<path v-if="open?.has(p.key)" :d="`M${p.dx * G - 8} ${p.dy * G - 3.5}L${p.dx * G - 3} ${p.dy * G}L${p.dx * G - 8} ${p.dy * G + 3.5}Z`" class="open-pin" />
<circle :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="in" />
<circle v-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
</g>

View File

@ -23,6 +23,8 @@ const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint:
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1. Pixels inside a component show on its box as one screen: build your own LCD.' },
{ kind: 'bundle', name: 'Cable bundle', icon: 'lucide:merge', hint: 'Gathers several wires into one cable. Or select wires and press "Bundle into cable".' },
{ kind: 'split', name: 'Cable split', icon: 'lucide:split', hint: 'Fans a cable out into its wires again.' },
{ kind: 'tag', name: 'Send signal', icon: 'lucide:flag', hint: 'Names the signal wired into it, like CLK or RESET. Every "Use signal" of that name in this circuit carries it, without a wire.' },
{ kind: 'ref', name: 'Use signal', icon: 'lucide:tag', hint: 'The signal of the "Send signal" with the same name, anywhere in this circuit: no long wires for clock, reset or control lines.' },
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
]

View File

@ -0,0 +1,120 @@
<script setup lang="ts">
// Find anything in the project (Ctrl+F): parts in every circuit, and
// components with every place they are used. Enter or a click goes there.
import { searchProject, type PartHit } from '~/lib/logic/search'
const ed = useEditor()
const query = ref('')
const at = ref(0)
const input = ref<HTMLInputElement>()
onMounted(() => input.value?.focus())
const found = computed(() => searchProject(ed.project.value, query.value))
/** Every result in list order, for the arrow keys. */
const flat = computed(() => [
...found.value.components.map(c => ({ go: () => ed.open(c.def.id) })),
...found.value.parts.map(p => ({ go: () => goPart(p) })),
])
watch(query, () => (at.value = 0))
function close() {
ed.dialog.value = null
}
/** Opens the circuit it is in (unless it is open) and centres on it. */
function goTo(defId: string, nodeId: string) {
close()
if (ed.def.value.id !== defId) ed.open(defId)
nextTick(() => ed.focusNode(nodeId))
}
function goPart(p: PartHit) {
goTo(p.def, p.node)
}
function onKey(e: KeyboardEvent) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
const n = flat.value.length
if (n) at.value = (at.value + (e.key === 'ArrowDown' ? 1 : -1) + n) % n
} else if (e.key === 'Enter') {
e.preventDefault()
const hit = flat.value[at.value]
if (hit) {
close()
hit.go()
}
} else if (e.key === 'Escape') close()
}
const ICONS: Record<string, string> = {
chip: 'lucide:cpu',
nand: 'lucide:square-function',
input: 'lucide:toggle-left',
output: 'lucide:log-out',
lamp: 'lucide:lightbulb',
button: 'lucide:circle-dot',
clock: 'lucide:audio-waveform',
panel: 'lucide:sliders-vertical',
hex: 'lucide:binary',
note: 'lucide:sticky-note',
bundle: 'lucide:merge',
split: 'lucide:split',
tag: 'lucide:flag',
ref: 'lucide:tag',
pixel: 'lucide:square',
}
</script>
<template>
<div class="modal-backdrop search-backdrop" @click.self="close">
<div class="modal search-modal" role="dialog" aria-label="Search the project" @keydown="onKey">
<div class="search-field">
<Icon name="lucide:search" class="size-4 shrink-0" />
<input ref="input" v-model="query" placeholder="Find a part, pin, signal or component…" />
<kbd>Esc</kbd>
</div>
<p v-if="!query.trim()" class="hint search-empty">Names, kinds (lamp, NAND), signals, panel rows and note text, in every circuit of this project.</p>
<p v-else-if="!flat.length" class="hint search-empty">Nothing called "{{ query.trim() }}".</p>
<div v-else class="search-results">
<template v-if="found.components.length">
<h3>Components</h3>
<div
v-for="(c, i) in found.components"
:key="c.def.id"
class="search-hit"
:class="{ active: at === i }"
@pointerenter="at = i"
>
<button class="search-main" @click="close(), ed.open(c.def.id)">
<Icon name="lucide:package" class="size-4 shrink-0" />
<span class="grow truncate">{{ c.def.name }}</span>
<span class="search-where">{{ c.usedIn.length ? `used in ${c.usedIn.length} circuit${c.usedIn.length === 1 ? '' : 's'}` : 'not used in another circuit' }}</span>
</button>
<div v-if="c.usedIn.length" class="search-uses">
<button v-for="u in c.usedIn" :key="u.def.id" class="btn-sm" :title="`Open ${u.def.name} at the first one`" @click="goTo(u.def.id, u.nodes[0]!)">
{{ u.def.name }}<span v-if="u.nodes.length > 1" class="muted"> ×{{ u.nodes.length }}</span>
</button>
</div>
</div>
</template>
<template v-if="found.parts.length">
<h3>Parts</h3>
<button
v-for="(p, i) in found.parts"
:key="`${p.def}/${p.node}`"
class="search-hit search-main"
:class="{ active: at === found.components.length + i }"
@pointerenter="at = found.components.length + i"
@click="goPart(p)"
>
<Icon :name="ICONS[p.kind] ?? 'lucide:box'" class="size-4 shrink-0" />
<span class="grow truncate">{{ p.text }}<span v-if="p.detail" class="muted"> · {{ p.detail }}</span></span>
<span class="search-where">{{ p.def === ed.def.value.id ? 'here' : p.defName }}</span>
</button>
</template>
</div>
</div>
</div>
</template>

View File

@ -82,6 +82,7 @@ const linkIcon = computed(() => {
</div>
<div class="flex items-center gap-1.5">
<button class="tb-btn" title="Find anything in the project (Ctrl+F)" @click="ed.dialog.value = 'search'"><Icon name="lucide:search" class="size-4" /></button>
<button class="tb-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
<button class="tb-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
<button

View File

@ -5,14 +5,15 @@
import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
import { bundleWires, cablePanel, dissolveCable, pluggedInto, plugInto, syncCables } from '~/lib/logic/cables'
import { fitLinks, fitSpots } from '~/lib/logic/fit'
import { checkCircuit } from '~/lib/logic/check'
import { loadSoundSettings, saveSoundSettings, sfx, type Sound, type SoundSettings } from '~/lib/audio'
import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUnlocked, NEEDS, unlockedBy } from '~/lib/logic/progress'
import { apiId, makePuzzle, scoreSolution } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile, rowSource } from '~/lib/logic/compile'
import { MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel } from '~/lib/logic/labels'
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 {
addExamples,
@ -144,7 +145,7 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings'>(null)
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search'>(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,

View File

@ -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() },

View File

@ -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<string, number> {
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)

View File

@ -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<string, number>, get: DefLookup): CostLine[] {
const lines = new Map<string, CostLine>()
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<string,
line.ids.push(n.id)
lines.set(key, line)
}
if (bubbles.count) lines.set('invert', bubbles)
return [...lines.values()].sort((a, b) => b.total - a.total || a.name.localeCompare(b.name))
}

108
app/lib/logic/check.ts Normal file
View File

@ -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<string, CircuitNode[]>()
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<string, CircuitNode[]>()
const refs = new Map<string, CircuitNode[]>()
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<IssueLevel, number> = { 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<string>()
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)
}

View File

@ -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<string, number>()
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<string, CircuitNode[]>()
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<string, number>()
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))
}
}

View File

@ -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
}

View File

@ -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)

View File

@ -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<NodeKind>(['input', 'button', 'output', 'lamp'])
const ADOPTERS = new Set<NodeKind>(['input', 'button', 'output', 'lamp', 'tag'])
/**
* After a new wire: a switch, button, output pin or lamp that has no name

View File

@ -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

View File

@ -23,6 +23,8 @@ export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
bundle: 'Cable bundle',
split: 'Cable split',
pixel: 'Pixel',
tag: 'Send signal',
ref: 'Use signal',
}
/** Challenges each one builds on. */

76
app/lib/logic/search.ts Normal file
View File

@ -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) }
}

View File

@ -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

View File

@ -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'
}

151
app/lib/sheet.ts Normal file
View File

@ -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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[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 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${x} ${y} ${W} ${H}" width="${W}" height="${H}">
<rect x="${x}" y="${y}" width="${W}" height="${H}" fill="${bg}"/>
${clone.outerHTML}
<rect x="${x + 0.5}" y="${y + 0.5}" width="${W - 1}" height="${H - 1}" fill="none" stroke="${line}"/>
<line x1="${x}" y1="${ty}" x2="${x + W}" y2="${ty}" stroke="${line}"/>
<g font-family="${font}" font-size="11">
<text x="${x + 12}" y="${ty + 21}" fill="${ink}" font-weight="700">${esc(info.project)} / ${esc(info.circuit)}</text>
<text x="${x + W / 2}" y="${ty + 21}" fill="${muted}" text-anchor="middle">${esc(when)}</text>
<text x="${x + W - 12}" y="${ty + 21}" fill="${muted}" text-anchor="end">Sheet 1 / 1 · logicate.blax.at</text>
</g>
</svg>`
}
/** 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(`<!doctype html><html><head><title>${esc(title)}</title><style>
@page { size: landscape; margin: 10mm; }
html, body { margin: 0; background: #fff; }
svg { display: block; width: 100%; height: auto; max-height: 100vh; }
</style></head><body>${svg}</body></html>`)
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)
}

73
tests/check.test.ts Normal file
View File

@ -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\)$/)
})
})

132
tests/signals.test.ts Normal file
View File

@ -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<string, boolean>) => {
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'))
})
})