BF input panels are component inputs, cable ends plug in more reliably; A merge panels, hex pass-through, design a component's box

- Inside a component, the switch and button rows of its input panels are now input pins (in order with the other inputs, named after the rows); "Rows are component inputs" can be turned off per panel to keep the old fixed switches
- Select input panels, Merge: one panel with all rows, spacing and wires kept; circuits that place this one keep their wires
- Cable ends plug in more often: bundling orders the wires by the part a side runs to, an end with only some wires on a part still plugs, an end placed by hand next to the pins plugs, and dragging an end near its part shows green rings and plugs it on drop
- Hex displays pass their four bits on (outputs on the right), so they can sit in the middle of a bus
- Design the box: move lamps, displays, the screen and the name on a component's box, draw lines, boxes, circles and text in six colours, size it, leave things off; every placed copy shows it

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-21 13:49:29 +02:00
parent 4d0e32d678
commit deb94b9d61
25 changed files with 1151 additions and 38 deletions

View File

@ -915,6 +915,38 @@ kbd {
border-color: var(--accent); border-color: var(--accent);
} }
/* Drawings on a hand-drawn component box. */
.node .face-ink {
fill: none;
stroke-width: 1.5;
stroke-linecap: round;
}
.node .face-text {
font-family: var(--font-sans);
font-weight: 600;
pointer-events: none;
}
.node .face-ink.ink-muted { stroke: #6b778a; }
.node .face-ink.ink-text { stroke: var(--text); }
.node .face-ink.ink-red { stroke: #ff5c5c; }
.node .face-ink.ink-yellow { stroke: #ffd34d; }
.node .face-ink.ink-green { stroke: #3ddc84; }
.node .face-ink.ink-blue { stroke: #4dabff; }
.node .face-ink.filled.ink-muted { fill: rgb(107 119 138 / 0.25); }
.node .face-ink.filled.ink-text { fill: rgb(219 226 234 / 0.18); }
.node .face-ink.filled.ink-red { fill: rgb(255 92 92 / 0.22); }
.node .face-ink.filled.ink-yellow { fill: rgb(255 211 77 / 0.22); }
.node .face-ink.filled.ink-green { fill: rgb(61 220 132 / 0.22); }
.node .face-ink.filled.ink-blue { fill: rgb(77 171 255 / 0.22); }
.node .face-text.ink-muted { fill: #8592a3; }
.node .face-text.ink-text { fill: var(--text); }
.node .face-text.ink-red { fill: #ff5c5c; }
.node .face-text.ink-yellow { fill: #ffd34d; }
.node .face-text.ink-green { fill: #3ddc84; }
.node .face-text.ink-blue { fill: #4dabff; }
/* + and − under a selected gate. */ /* + and − under a selected gate. */
.widen-btn { .widen-btn {
cursor: pointer; cursor: pointer;
@ -3003,3 +3035,128 @@ kbd {
.search-results .muted { .search-results .muted {
color: var(--muted); color: var(--muted);
} }
/* ── Face designer ──────────────────────────────────────────────── */
.modal.face-modal {
width: min(760px, 100%);
}
.face-tools {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
margin: 14px 0 10px;
}
.face-tools .seg button {
padding: 0 9px;
}
.face-inks {
display: flex;
gap: 5px;
}
.face-size {
display: flex;
align-items: center;
gap: 5px;
color: var(--muted);
font-size: 12px;
}
.face-size input {
width: 56px;
height: 26px;
padding: 0 6px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
}
.btn-sm.on {
border-color: var(--accent);
color: var(--accent);
}
.face-canvas {
display: block;
user-select: none;
-webkit-user-select: none;
max-width: 100%;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
touch-action: none;
}
.face-canvas.drawing {
cursor: crosshair;
}
.face-thing {
fill: transparent;
stroke: rgb(76 194 255 / 0.25);
stroke-dasharray: 3 3;
cursor: move;
}
.face-thing.shape {
stroke: transparent;
}
.face-thing:hover,
.face-thing.shape:hover {
stroke: rgb(76 194 255 / 0.6);
}
.face-thing.sel,
.face-thing.shape.sel {
stroke: var(--accent);
stroke-dasharray: none;
stroke-width: 1.5;
}
.face-canvas.drawing .face-thing,
.face-canvas.drawing .face-hit {
pointer-events: none;
}
.face-hit {
stroke: transparent;
stroke-width: 9;
stroke-linecap: round;
cursor: move;
}
.face-hit:hover {
stroke: rgb(76 194 255 / 0.3);
}
.face-hit.sel {
stroke: rgb(76 194 255 / 0.45);
}
.face-grip {
fill: var(--bg);
stroke: var(--accent);
stroke-width: 1.5;
cursor: nwse-resize;
}
.face-props,
.face-hidden {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
min-height: 34px;
margin-top: 10px;
}
.face-props .text-input {
flex: 1;
min-width: 120px;
}

View File

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

View File

@ -341,6 +341,13 @@ function pack() {
<p class="hint mt-2">Or drag one wire from a selected part to a pin: the others follow onto the next pins.</p> <p class="hint mt-2">Or drag one wire from a selected part to a pin: the others follow onto the next pins.</p>
</section> </section>
<section v-if="only('panel') && nodes.length > 1">
<h3>Input panels</h3>
<button class="btn w-full" title="One panel with all their rows, top panel first; wires stay on their rows" @click="ed.mergeSelectedPanels()">
<Icon name="lucide:combine" class="size-4" /> Merge into one panel
</button>
</section>
<section> <section>
<h3>Make a component</h3> <h3>Make a component</h3>
<p class="hint">Wires that cross the selection border become its pins.</p> <p class="hint">Wires that cross the selection border become its pins.</p>

View File

@ -8,7 +8,7 @@ import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { seriesLinks, type Link } from '~/lib/logic/bulk' import { seriesLinks, type Link } from '~/lib/logic/bulk'
import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit' import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu' import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { wirePath } from '~/lib/draw' import { wirePath } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet' import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
import { inputCount } from '~/lib/logic/wide' import { inputCount } from '~/lib/logic/wide'
@ -308,6 +308,8 @@ type Drag =
from?: DropPin[] from?: DropPin[]
/** Pins the moving parts land on: the step that lines them up and the wires dropping makes. */ /** Pins the moving parts land on: the step that lines them up and the wires dropping makes. */
snap?: { shift: Pt; links: Link[] } | null snap?: { shift: Pt; links: Link[] } | null
/** A cable end brought close to the part its wires run to: dropped, it plugs in. */
plug?: { part: string; rings: Pt[] } | null
} }
| { | {
kind: 'wire' kind: 'wire'
@ -555,6 +557,7 @@ function onPointerMove(e: PointerEvent) {
const at = d.from.map(p => ({ ...p, x: p.x + dx, y: d.lockY.has(p.node) ? p.y : p.y + dy })) const at = d.from.map(p => ({ ...p, x: p.x + dx, y: d.lockY.has(p.node) ? p.y : p.y + dy }))
d.snap = e.altKey ? null : dropLinks(at, d.still, d.grabbed === 1 ? 1 : 0) d.snap = e.altKey ? null : dropLinks(at, d.still, d.grabbed === 1 ? 1 : 0)
} }
d.plug = d.moved && d.grabbed === 1 && !e.altKey ? plugNear(d.node) : null
for (const [id, [x, y]] of d.orig) { for (const [id, [x, y]] of d.orig) {
const n = nodeMap.value.get(id) const n = nodeMap.value.get(id)
if (n) { if (n) {
@ -721,7 +724,10 @@ function onPointerUp(e: PointerEvent) {
case 'move': case 'move':
if (d.node.kind === 'button') ed.press(d.node, false) if (d.node.kind === 'button') ed.press(d.node, false)
if (d.row && !d.moved) ed.pressRow(d.node, d.row, false) if (d.row && !d.moved) ed.pressRow(d.node, d.row, false)
if (d.moved && d.snap?.links.length) { if (d.moved && d.plug) {
ed.unplugMoved(new Set(d.orig.keys()))
ed.plugEnd(d.node)
} else if (d.moved && d.snap?.links.length) {
const [sx, sy] = d.snap.shift const [sx, sy] = d.snap.shift
for (const id of d.orig.keys()) { for (const id of d.orig.keys()) {
const n = nodeMap.value.get(id) const n = nodeMap.value.get(id)
@ -1166,9 +1172,23 @@ function openMenuForSelection() {
menu.value = entries.length ? { x, y, entries, keyboard: true } : null menu.value = entries.length ? { x, y, entries, keyboard: true } : null
} }
/**
* A free cable end dragged to within a square or so of where it would sit
* on its part's pins: the pins it would plug into.
*/
function plugNear(n: CircuitNode): { part: string; rings: Pt[] } | null {
if ((n.kind !== 'bundle' && n.kind !== 'split') || n.plug) return null
const part = ed.plugTarget(n)
const lay = part && plugLayout(def.value, n, part, ed.getDef.value)
if (!part || !lay || Math.hypot(n.x - lay.x, n.y - lay.y) > 1.6) return null
const x = n.kind === 'split' ? lay.x + 1 : lay.x
return { part: part.id, rings: lay.offsets.map(o => [x, lay.y + o] as Pt) }
}
/** Pins a dragged part will connect to when dropped, shown as green rings. */ /** Pins a dragged part will connect to when dropped, shown as green rings. */
const dropRings = computed(() => { const dropRings = computed(() => {
const d = drag.value const d = drag.value
if (d?.kind === 'move' && d.plug) return d.plug.rings.map(([x, y]) => ({ x, y }))
if (d?.kind !== 'move' || !d.snap || !d.still) return [] if (d?.kind !== 'move' || !d.snap || !d.still) return []
const moving = new Set(d.orig.keys()) const moving = new Set(d.orig.keys())
return d.snap.links.map(l => { return d.snap.links.map(l => {

View File

@ -147,6 +147,14 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</p> </p>
</section> </section>
<section>
<h3>Its box</h3>
<p class="hint">How it looks when placed: {{ def.design ? 'drawn by hand' : 'laid out automatically' }}.</p>
<button class="btn w-full" title="Move lamps, displays and the name, draw lines, boxes and text, size the box" @click="ed.designFace(def.id)">
<Icon name="lucide:pen-tool" class="size-4" /> Design the box
</button>
</section>
<section> <section>
<h3>Sheet</h3> <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> <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>

View File

@ -0,0 +1,399 @@
<script setup lang="ts">
// Drawing a component's box by hand: drag its lamps, displays, screen and
// name where they belong, draw lines, boxes, circles and text on it, size
// it. Everything shows live on the box, and on every copy placed.
import { GRID as G } from '~/lib/logic/geometry'
import { uid } from '~/lib/logic/ops'
import { FACE_INKS, type CircuitNode, type FaceDesign, type FaceInk, type FaceShape } from '~/lib/logic/types'
const ed = useEditor()
const def = computed(() => (ed.faceFor.value ? ed.getDef.value(ed.faceFor.value) : undefined))
const preview = computed<CircuitNode>(() => ({ id: 'face-preview', kind: 'chip', chip: def.value?.id, x: 0, y: 0 }))
const shape = computed(() => ed.shape(preview.value))
const body = computed(() => shape.value.body)
type Tool = 'move' | 'line' | 'rect' | 'ellipse' | 'text'
const TOOLS: { id: Tool; icon: string; title: string }[] = [
{ id: 'move', icon: 'lucide:mouse-pointer-2', title: 'Move and resize' },
{ id: 'line', icon: 'lucide:minus', title: 'Line' },
{ id: 'rect', icon: 'lucide:square', title: 'Box' },
{ id: 'ellipse', icon: 'lucide:circle', title: 'Circle' },
{ id: 'text', icon: 'lucide:type', title: 'Text' },
]
const INK_HEX: Record<FaceInk, string> = { muted: '#6b778a', text: '#dbe2ea', red: '#ff5c5c', yellow: '#ffd34d', green: '#3ddc84', blue: '#4dabff' }
const tool = ref<Tool>('move')
const ink = ref<FaceInk>('muted')
const fill = ref(false)
/** What is selected: a drawing's id, a lamp or display node id, 'screen' or 'name'. */
const sel = ref<string | null>(null)
const VIEW_W = 700
const VIEW_H = 420
const PAD = 30
const k = computed(() => Math.min(3, (VIEW_W - 2 * PAD) / (Math.max(body.value.w, 4) * G), (VIEW_H - 2 * PAD) / (Math.max(body.value.h, 3) * G)))
const svg = ref<SVGSVGElement>()
/** The design being edited, made from the automatic layout on the first change, so nothing jumps. */
function design(): FaceDesign {
const d = def.value!
if (!d.design) {
const s = shape.value
const place: Record<string, { x: number; y: number }> = {}
for (const it of s.face ?? []) place[it.kind === 'screen' ? 'screen' : it.id] = { x: it.x, y: it.y - s.body.y }
d.design = { w: s.body.w, h: s.body.h, place, shapes: [] }
}
d.design.place ??= {}
d.design.shapes ??= []
return d.design
}
const snap = (v: number) => Math.round(v * 4) / 4
/** Pointer position in grid units from the box's top left corner. */
function at(e: PointerEvent) {
const r = svg.value!.getBoundingClientRect()
return { x: (e.clientX - r.left - PAD) / (G * k.value), y: (e.clientY - r.top - PAD) / (G * k.value) }
}
const nameText = computed(() => def.value?.name ?? '')
/** Everything that can be grabbed on the box, in grid units from its top left corner. */
const things = computed(() => {
const top = body.value.y
const out: { id: string; label: string; x: number; y: number; w: number; h: number }[] = []
for (const it of shape.value.face ?? []) {
out.push({ id: it.kind === 'screen' ? 'screen' : it.id, label: it.label || it.kind, x: it.x, y: it.y - top, w: it.w, h: it.h })
}
if (shape.value.nameAt !== null) {
const c = shape.value.nameAt ?? { x: body.value.w / 2, y: shape.value.nameY ?? 0 }
const w = nameText.value.length * 0.5 + 0.6
out.push({ id: 'name', label: 'name', x: c.x - w / 2, y: c.y - top - 0.55, w, h: 1.1 })
}
return out
})
const shapes = computed(() => def.value?.design?.shapes ?? [])
const selShape = computed(() => shapes.value.find(s => s.id === sel.value))
const selThing = computed(() => things.value.find(t => t.id === sel.value))
/** Things left off the box, to put back. */
const hidden = computed(() => {
const d = def.value
return (d?.design?.hide ?? []).map(id => ({
id,
label: id === 'name' ? 'Name' : id === 'screen' ? 'Screen' : d?.nodes.find(n => n.id === id)?.label?.trim() || (d?.nodes.find(n => n.id === id)?.kind ?? id),
}))
})
type Drag =
| { type: 'create'; id: string }
| { type: 'move'; id: string; start: { x: number; y: number }; orig: { x: number; y: number } }
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
const drag = ref<Drag | null>(null)
function onDown(e: PointerEvent) {
if (!def.value || e.button !== 0) return
// No text selection: a later drag over selected text would turn into the browser's drag and drop.
e.preventDefault()
const p = at(e)
svg.value!.setPointerCapture(e.pointerId)
if (tool.value === 'text') {
const s: FaceShape = { id: uid('f'), kind: 'text', x: snap(p.x), y: snap(p.y - 0.5), w: 3, h: 1, text: 'Text', ink: ink.value === 'muted' ? 'text' : ink.value }
design().shapes!.push(s)
sel.value = s.id
tool.value = 'move'
ed.commit(false)
nextTick(() => textInput.value?.select())
return
}
if (tool.value !== 'move') {
const s: FaceShape = { id: uid('f'), kind: tool.value, x: snap(p.x), y: snap(p.y), w: 0, h: 0, ink: ink.value, ...(fill.value && tool.value !== 'line' ? { fill: true } : {}) }
design().shapes!.push(s)
sel.value = s.id
drag.value = { type: 'create', id: s.id }
return
}
const el = (e.target as Element).closest('[data-face]')
const id = el?.getAttribute('data-face')
if (!id) {
sel.value = null
return
}
sel.value = id
const handle = el!.getAttribute('data-handle') as 'a' | 'b' | null
const sh = shapes.value.find(s => s.id === id)
if (handle && sh) {
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
return
}
const t = things.value.find(x => x.id === id)
const orig = sh ? { x: sh.x, y: sh.y } : t ? { x: t.x, y: t.y } : null
if (orig) drag.value = { type: 'move', id, start: p, orig }
}
function onMove(e: PointerEvent) {
const d = drag.value
if (!d) return
const p = at(e)
if (d.type === 'create') {
const s = shapes.value.find(x => x.id === d.id)
if (!s) return
s.w = snap(p.x) - s.x
s.h = snap(p.y) - s.y
if (e.shiftKey && s.kind === 'line') {
// Shift: straight across or straight down.
if (Math.abs(s.w) > Math.abs(s.h)) s.h = 0
else s.w = 0
}
return
}
if (d.type === 'move') {
const x = snap(d.orig.x + p.x - d.start.x)
const y = snap(d.orig.y + p.y - d.start.y)
const s = shapes.value.find(sh => sh.id === d.id)
if (s) {
s.x = x
s.y = y
} else if (d.id === 'name') {
const w = nameText.value.length * 0.5 + 0.6
design().place!.name = { x: x + w / 2, y: y + 0.55 }
} else design().place![d.id] = { x, y }
return
}
const s = shapes.value.find(sh => sh.id === d.id)
if (!s) return
const o = d.orig
if (d.handle === 'b') {
s.w = snap(p.x) - o.x
s.h = snap(p.y) - o.y
} else {
s.x = snap(p.x)
s.y = snap(p.y)
s.w = o.x + o.w - s.x
s.h = o.y + o.h - s.y
}
}
function onUp() {
const d = drag.value
drag.value = null
if (!d) return
if (d.type === 'create') {
const s = shapes.value.find(x => x.id === d.id)
// A click without dragging draws nothing.
if (s && Math.abs(s.w) < 0.25 && Math.abs(s.h) < 0.25) {
design().shapes = shapes.value.filter(x => x !== s)
sel.value = null
return
}
tool.value = 'move'
}
ed.commit(false)
}
function remove() {
if (!selShape.value) return
design().shapes = shapes.value.filter(s => s !== selShape.value)
sel.value = null
ed.commit(false)
}
function hide(id: string) {
const d = design()
d.hide = [...new Set([...(d.hide ?? []), id])]
sel.value = null
ed.commit(false)
}
function show(id: string) {
const d = design()
d.hide = (d.hide ?? []).filter(x => x !== id)
if (!d.hide.length) delete d.hide
ed.commit(false)
}
function setInk(i: FaceInk) {
ink.value = i
if (selShape.value) {
selShape.value.ink = i
ed.commit(false)
}
}
function toggleFill() {
fill.value = !fill.value
const s = selShape.value
if (s && s.kind !== 'line' && s.kind !== 'text') {
if (fill.value) s.fill = true
else delete s.fill
ed.commit(false)
}
}
function setSize(axis: 'w' | 'h', e: Event) {
const v = Number((e.target as HTMLInputElement).value)
if (!(v > 0)) return
design()[axis] = Math.min(80, Math.max(2, Math.round(v * 2) / 2))
ed.commit(false)
}
function reset() {
if (!def.value) return
delete def.value.design
sel.value = null
ed.commit(false)
}
const textInput = ref<HTMLInputElement>()
function onKey(e: KeyboardEvent) {
if ((e.target as HTMLElement).closest('input, textarea, select')) return
if ((e.key === 'Delete' || e.key === 'Backspace') && selShape.value) {
e.preventDefault()
remove()
}
}
function close() {
ed.dialog.value = null
ed.faceFor.value = null
}
/** Ends of a line, or opposite corners of anything else, to drag. */
const grips = computed(() => {
const s = selShape.value
if (!s || s.kind === 'text') return []
return [
{ h: 'a', x: s.x, y: s.y },
{ h: 'b', x: s.x + s.w, y: s.y + s.h },
]
})
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div v-if="def" class="modal face-modal" role="dialog" aria-labelledby="face-title" tabindex="-1" @keydown="onKey">
<div class="flex items-start justify-between gap-4">
<div>
<h2 id="face-title">The box of "{{ def.name }}"</h2>
<p class="hint mt-1">Drag lamps, displays and the name where you want them, draw on it, size it. Every placed copy shows it.</p>
</div>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<div class="face-tools">
<div class="seg">
<button v-for="t in TOOLS" :key="t.id" :class="{ active: tool === t.id }" :title="t.title" @click="tool = t.id">
<Icon :name="t.icon" class="size-4" />
</button>
</div>
<div class="face-inks" title="Colour">
<button
v-for="i in FACE_INKS"
:key="i"
class="ctx-dot"
:class="{ active: (selShape?.ink ?? ink) === i }"
:style="{ background: INK_HEX[i] }"
:title="i"
@click="setInk(i)"
/>
</div>
<button class="btn-sm" :class="{ on: selShape?.fill ?? fill }" title="Fill boxes and circles lightly" @click="toggleFill">
<Icon name="lucide:paint-bucket" class="size-3.5" /> Fill
</button>
<label class="face-size">W <input type="number" min="2" max="80" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
<label class="face-size">H <input type="number" min="2" max="80" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
<button class="btn-sm ml-auto" :disabled="!def.design" title="Back to the automatic layout; drawings are removed" @click="reset">
<Icon name="lucide:rotate-ccw" class="size-3.5" /> Automatic
</button>
</div>
<svg
ref="svg"
class="face-canvas"
:class="{ drawing: tool !== 'move' }"
:width="VIEW_W"
:height="VIEW_H"
@pointerdown="onDown"
@pointermove="onMove"
@pointerup="onUp"
@pointercancel="onUp"
>
<defs>
<pattern id="face-grid" :width="G * k / 2" :height="G * k / 2" patternUnits="userSpaceOnUse" :x="PAD" :y="PAD">
<circle cx="0.6" cy="0.6" r="0.6" fill="#2a3442" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#face-grid)" />
<g :transform="`translate(${PAD} ${PAD - body.y * G * k}) scale(${k})`">
<EditorNodeView :node="preview" :shape="shape" :selected="false" />
<g :transform="`translate(0 ${body.y * G})`">
<rect
v-for="t in things"
:key="t.id"
:x="t.x * G - 2"
:y="t.y * G - 2"
:width="t.w * G + 4"
:height="t.h * G + 4"
rx="3"
class="face-thing"
:class="{ sel: sel === t.id }"
:data-face="t.id"
/>
<template v-for="s in shapes" :key="s.id">
<line
v-if="s.kind === 'line'"
:x1="s.x * G"
:y1="s.y * G"
:x2="(s.x + s.w) * G"
:y2="(s.y + s.h) * G"
class="face-hit"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
<rect
v-else
:x="Math.min(s.x, s.x + s.w) * G - 2"
:y="Math.min(s.y, s.y + s.h) * G - 2"
:width="Math.max(Math.abs(s.w) * G, s.kind === 'text' ? (s.text?.length ?? 1) * 6.6 * (s.size ?? 1) : 0) + 4"
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
rx="2"
class="face-thing shape"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
</template>
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
</g>
</g>
</svg>
<div class="face-props">
<template v-if="selShape">
<template v-if="selShape.kind === 'text'">
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
<select :value="selShape.size ?? 1" class="text-input w-28" @change="(selShape.size = Number(($event.target as HTMLSelectElement).value)), ed.commit(false)">
<option :value="0.75">Small</option>
<option :value="1">Normal</option>
<option :value="1.5">Large</option>
<option :value="2">Huge</option>
</select>
</template>
<span v-else class="hint">{{ { line: 'Line', rect: 'Box', ellipse: 'Circle' }[selShape.kind] }}: drag it, or its dots to resize. Shift keeps a new line straight.</span>
<button class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
</template>
<template v-else-if="selThing">
<span class="hint">{{ selThing.id === 'name' ? 'The name' : selThing.label }}: drag it where it belongs.</span>
<button class="btn-sm ml-auto" @click="hide(selThing.id)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off the box</button>
</template>
<span v-else class="hint">Pick a tool to draw, or drag things on the box. Delete removes a drawing.</span>
</div>
<div v-if="hidden.length" class="face-hidden">
<span class="hint">Left off:</span>
<button v-for="h in hidden" :key="h.id" class="btn-sm" title="Put it back on the box" @click="show(h.id)">
<Icon name="lucide:eye" class="size-3.5" /> {{ h.label }}
</button>
</div>
</div>
</div>
</template>

View File

@ -31,6 +31,8 @@ const SHORTCUTS: [string, string][] = [
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'], ['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+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'], ['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
['Select input panels, Merge', 'One panel with all their rows; inside a component its rows are input pins'],
['Design the box (Circuit tab)', 'Move lamps, displays and the name on a component\'s box, draw lines, boxes, circles and text'],
['Select several lamps, pins or switches', 'Green boxes show free pins in a row they fit; point along one, click to wire them all'], ['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'], ['Shift + click on canvas', 'Keep placing the same part'],
['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'], ['Ctrl+C, Ctrl+V, Ctrl+D', 'Copy, paste, duplicate; names continue their series (D0 → D1)'],

View File

@ -219,6 +219,12 @@ const undriven = computed(() => {
return cableBits(n.value) - fed.size return cableBits(n.value) - fed.size
}) })
function setInner(inner: boolean) {
if (inner) n.value.inner = true
else delete n.value.inner
ed.commit()
}
function setRowHz(row: PanelRow, e: Event) { function setRowHz(row: PanelRow, e: Event) {
const v = Number((e.target as HTMLInputElement).value) const v = Number((e.target as HTMLInputElement).value)
if (v > 0 && v <= 1000) row.hz = v if (v > 0 && v <= 1000) row.hz = v
@ -394,6 +400,11 @@ function setRowHz(row: PanelRow, e: Event) {
<button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id])"> <button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id])">
<Icon name="lucide:cable" class="size-4" /> Wire rows one by one <Icon name="lucide:cable" class="size-4" /> Wire rows one by one
</button> </button>
<label class="check mt-2" title="Used as a component, its switch and button rows are its input pins (top to bottom, with the other inputs). Clock rows stay inside.">
<input type="checkbox" :checked="!n.inner" @change="setInner(!($event.target as HTMLInputElement).checked)" />
Rows are component inputs
</label>
<p v-if="n.inner" class="hint">Kept inside: in a component the switches stay as set here, buttons read 0.</p>
</template> </template>
<!-- Kind-specific settings --> <!-- Kind-specific settings -->
@ -522,6 +533,9 @@ function setRowHz(row: PanelRow, e: Event) {
</dl> </dl>
<div class="grid gap-2"> <div class="grid gap-2">
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button> <button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
<button class="btn w-full" title="Move its lamps and displays, draw on it, size it: for every copy" @click="ed.designFace(chipDef.id)">
<Icon name="lucide:pen-tool" class="size-4" /> Design its box
</button>
<button <button
v-if="chipInputs && !hasPanel" v-if="chipInputs && !hasPanel"
class="btn w-full" class="btn w-full"

View File

@ -153,7 +153,44 @@ const title = computed(() => {
<template v-else-if="node.kind === 'chip'"> <template v-else-if="node.kind === 'chip'">
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text> <text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" /> <rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
<text :x="(b.w * G) / 2" :y="(shape.nameY ?? b.y + b.h / 2) * G + 4" text-anchor="middle" class="chip-name">{{ chipDef?.name ?? 'Missing' }}</text> <!-- Drawings on a hand-drawn box, under its lamps and displays -->
<template v-for="d in shape.drawing" :key="d.id">
<line v-if="d.kind === 'line'" :x1="d.x * G" :y1="d.y * G" :x2="(d.x + d.w) * G" :y2="(d.y + d.h) * G" class="face-ink" :class="`ink-${d.ink ?? 'muted'}`" />
<rect
v-else-if="d.kind === 'rect'"
:x="Math.min(d.x, d.x + d.w) * G"
:y="Math.min(d.y, d.y + d.h) * G"
:width="Math.abs(d.w) * G"
:height="Math.abs(d.h) * G"
rx="2"
class="face-ink"
:class="[`ink-${d.ink ?? 'muted'}`, { filled: d.fill }]"
/>
<ellipse
v-else-if="d.kind === 'ellipse'"
:cx="(d.x + d.w / 2) * G"
:cy="(d.y + d.h / 2) * G"
:rx="(Math.abs(d.w) / 2) * G"
:ry="(Math.abs(d.h) / 2) * G"
class="face-ink"
:class="[`ink-${d.ink ?? 'muted'}`, { filled: d.fill }]"
/>
<text
v-else
:x="d.x * G"
:y="(d.y + 0.75 * (d.size ?? 1)) * G"
class="face-text"
:class="`ink-${d.ink ?? 'text'}`"
:style="{ fontSize: `${11 * (d.size ?? 1)}px` }"
>{{ d.text }}</text>
</template>
<text
v-if="shape.nameAt !== null"
:x="(shape.nameAt?.x ?? b.w / 2) * G"
:y="(shape.nameAt?.y ?? shape.nameY ?? b.y + b.h / 2) * G + 4"
text-anchor="middle"
class="chip-name"
>{{ chipDef?.name ?? 'Missing' }}</text>
<template v-for="f in shape.face" :key="f.id"> <template v-for="f in shape.face" :key="f.id">
<template v-if="f.kind === 'screen'"> <template v-if="f.kind === 'screen'">
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" /> <rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />

View File

@ -33,6 +33,7 @@ function pinNumber(e: IoEntry, entries: IoEntry[]) {
} }
function kindText(e: IoEntry, entries: IoEntry[]): string { function kindText(e: IoEntry, entries: IoEntry[]): string {
if (e.row && e.pin) return `pin ${pinNumber(e, entries)} · ${e.row.type}`
if (e.row) return e.row.type === 'clock' && e.row.hz ? `clock ${e.row.hz} Hz` : e.row.type if (e.row) return e.row.type === 'clock' && e.row.hz ? `clock ${e.row.hz} Hz` : e.row.type
if (e.pin) return `pin ${pinNumber(e, entries)}` if (e.pin) return `pin ${pinNumber(e, entries)}`
if (e.node.kind === 'clock') return e.node.hz ? `clock ${e.node.hz} Hz` : 'clock' if (e.node.kind === 'clock') return e.node.hz ? `clock ${e.node.hz} Hz` : 'clock'

View File

@ -14,7 +14,7 @@ import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challeng
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile' import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry' import { chipPins, MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels' import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
import { attachPanel, detachPanel, dockedPanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels' import { attachPanel, detachPanel, dockedPanels, mergePanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
import { import {
addExamples, addExamples,
containsDef, containsDef,
@ -145,7 +145,13 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null) const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0) const labelFocus = ref(0)
const showHelp = ref(false) const showHelp = ref(false)
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search'>(null) const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
/** The component whose box is being drawn in the face designer. */
const faceFor = ref<string | null>(null)
function designFace(defId: string) {
faceFor.value = defId
dialog.value = 'face'
}
/** Tab shown in the right panel. */ /** Tab shown in the right panel. */
const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit') const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit')
/** Which side panels are open; remembered in this browser. */ /** Which side panels are open; remembered in this browser. */
@ -720,6 +726,25 @@ function create() {
notify(`Input panel with ${panel.rows!.length} switch${panel.rows!.length === 1 ? '' : 'es'} attached`) notify(`Input panel with ${panel.rows!.length} switch${panel.rows!.length === 1 ? '' : 'es'} attached`)
} }
/** Joins the selected panels into one; circuits that place this one keep their wires to the rows. */
function mergeSelectedPanels() {
const res = mergePanels(def.value, selection.value)
if (!res) return notify('Select at least two input panels', 'error')
const id = def.value.id
for (const d of project.value.components) {
const chips = new Set(d.nodes.filter(n => n.kind === 'chip' && n.chip === id).map(n => n.id))
if (!chips.size) continue
for (const w of d.wires) {
const to = chips.has(w.to.node) ? res.renamed.get(w.to.pin) : undefined
if (to) w.to = { node: w.to.node, pin: to }
}
}
selection.value = [res.panel.id]
wireSel.value = []
commit()
notify(`One panel with ${res.panel.rows?.length ?? 0} rows`)
}
function undock(panel: CircuitNode) { function undock(panel: CircuitNode) {
detachPanel(panel) detachPanel(panel)
commit() commit()
@ -1879,6 +1904,7 @@ function create() {
pressRow, pressRow,
addPanel, addPanel,
undock, undock,
mergeSelectedPanels,
setRowType, setRowType,
addRow, addRow,
dropRow, dropRow,
@ -1888,6 +1914,8 @@ function create() {
showIssue, showIssue,
sheetRequest, sheetRequest,
exportSheet, exportSheet,
faceFor,
designFace,
fits, fits,
fitHover, fitHover,
connectFit, connectFit,

View File

@ -138,7 +138,12 @@ export function useMenu() {
function oneNode(n: CircuitNode): MenuEntry[] { function oneNode(n: CircuitNode): MenuEntry[] {
const get = ed.getDef.value const get = ed.getDef.value
const out: MenuEntry[] = [{ head: n.label?.trim() && !n.autoLabel ? `${partName(n)} · ${n.label.trim()}` : partName(n) }] const out: MenuEntry[] = [{ head: n.label?.trim() && !n.autoLabel ? `${partName(n)} · ${n.label.trim()}` : partName(n) }]
if (n.kind === 'chip' && n.chip) out.push({ label: 'Open component', icon: 'lucide:log-in', keys: 'Enter', run: () => ed.open(n.chip!) }) if (n.kind === 'chip' && n.chip) {
out.push(
{ label: 'Open component', icon: 'lucide:log-in', keys: 'Enter', run: () => ed.open(n.chip!) },
{ label: 'Design its box', icon: 'lucide:pen-tool', run: () => ed.designFace(n.chip!) },
)
}
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) }) if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) }) if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
const swaps = swapChoices([n]) const swaps = swapChoices([n])
@ -270,6 +275,7 @@ export function useMenu() {
const fits = fitItems() const fits = fitItems()
if (fits.length) out.push({ label: 'Wire them all to', icon: 'lucide:cable', children: fits }) if (fits.length) out.push({ label: 'Wire them all to', icon: 'lucide:cable', children: fits })
out.push({ label: 'Connect one by one', icon: 'lucide:list-ordered', run: () => ed.startLinking() }) out.push({ label: 'Connect one by one', icon: 'lucide:list-ordered', run: () => ed.startLinking() })
if (nodes.every(n => n.kind === 'panel')) out.push({ label: 'Merge into one panel', icon: 'lucide:combine', run: () => ed.mergeSelectedPanels() })
if (nodes.every(n => n.kind === 'input')) { if (nodes.every(n => n.kind === 'input')) {
out.push({ out.push({
label: 'Switches', label: 'Switches',

View File

@ -4,7 +4,7 @@
import { TRANSISTORS_PER_NAND } from './analyze' import { TRANSISTORS_PER_NAND } from './analyze'
import { invertedPins } from './compile' import { invertedPins } from './compile'
import { chipPins } from './geometry' import { chipPins, isPinRow, rowPin } from './geometry'
import type { DefLookup } from './geometry' import type { DefLookup } from './geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from './ops' import { pinKeys, SINK_KINDS, SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PanelRow } from './types' import type { CircuitNode, ComponentDef, PanelRow } from './types'
@ -54,10 +54,20 @@ export interface IoEntry {
*/ */
export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } { export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } {
const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition) const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition)
// Pins in pin order: input switches and panel rows by where they sit.
const at = new Map<string, IoEntry>()
for (const node of of(['input'])) at.set(node.id, { node, pin: true })
const inside: IoEntry[] = []
for (const node of of(['panel'])) {
for (const row of node.rows ?? []) {
if (isPinRow(node, row)) at.set(rowPin(node.id, row.id), { node, row, pin: true })
else inside.push({ node, row, pin: false })
}
}
const inputs: IoEntry[] = [ const inputs: IoEntry[] = [
...of(['input']).map(node => ({ node, pin: true })), ...chipPins(def).inputs.map(p => at.get(p.key)!).filter(Boolean),
...of(['button', 'clock']).map(node => ({ node, pin: false })), ...of(['button', 'clock']).map(node => ({ node, pin: false })),
...of(['panel']).flatMap(node => (node.rows ?? []).map(row => ({ node, row, pin: false }))), ...inside,
] ]
const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))] const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))]
return { inputs, outputs } return { inputs, outputs }

View File

@ -55,7 +55,14 @@ export function bundleWires(
return { w, a: pinPos(fn, shapeOf(fn, get), w.from.pin, 'out')!, b: pinPos(tn, shapeOf(tn, get), w.to.pin, 'in')! } return { w, a: pinPos(fn, shapeOf(fn, get), w.from.pin, 'out')!, b: pinPos(tn, shapeOf(tn, get), w.to.pin, 'in')! }
}) })
if (ends.some(e => !e.a || !e.b)) return { ok: false, error: 'Some wires have no pins' } if (ends.some(e => !e.a || !e.b)) return { ok: false, error: 'Some wires have no pins' }
ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y) // Wire order: top to bottom at the targets, so the split can plug into them;
// when only the sources are all on one part, top to bottom there instead,
// so the bundle can plug into that part.
const one = (ids: Set<string>) => ids.size === 1 && !CABLE_ENDS.has(nodes.get([...ids][0]!)!.kind)
const fromOne = one(new Set(wires.map(w => w.from.node)))
const toOne = one(new Set(wires.map(w => w.to.node)))
if (fromOne && !toOne) ends.sort((p, q) => p.a.y - q.a.y || p.b.y - q.b.y)
else ends.sort((p, q) => p.b.y - q.b.y || p.a.y - q.a.y)
const n = ends.length const n = ends.length
const mid = Math.floor((n - 1) / 2) const mid = Math.floor((n - 1) / 2)
@ -89,9 +96,10 @@ export function bundleWires(
}) })
// The sleeve starts neutral: the wires inside show their own colours. // The sleeve starts neutral: the wires inside show their own colours.
def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } }) def.wires.push({ id: uid('w'), from: { node: bundle.id, pin: 'q' }, to: { node: split.id, pin: 'a' } })
if (!at) { {
// All the wires leave one part (or reach one part) in cable order: that end plugs straight in, // All the wires leave one part (or reach one part) in cable order: that end plugs straight in,
// unless another part sits where it would go. // unless another part sits where it would go. An end placed by hand plugs in when it was
// put right by those pins.
for (const [end, side] of [ for (const [end, side] of [
[bundle, new Set(ends.map(e => e.w.from.node))], [bundle, new Set(ends.map(e => e.w.from.node))],
[split, new Set(ends.map(e => e.w.to.node))], [split, new Set(ends.map(e => e.w.to.node))],
@ -99,6 +107,7 @@ export function bundleWires(
const part = side.size === 1 ? nodes.get([...side][0]!) : undefined const part = side.size === 1 ? nodes.get([...side][0]!) : undefined
const lay = part && !CABLE_ENDS.has(part.kind) ? plugLayout(def, end, part, get) : null const lay = part && !CABLE_ENDS.has(part.kind) ? plugLayout(def, end, part, get) : null
if (!part || !lay) continue if (!part || !lay) continue
if (at && Math.hypot(end.x - lay.x, end.y - lay.y) > 2.5) continue
const box = { x: lay.x, y: lay.y - 0.5, w: 1, h: lay.offsets[n - 1]! + 1 } const box = { x: lay.x, y: lay.y - 0.5, w: 1, h: lay.offsets[n - 1]! + 1 }
const clash = def.nodes.some(nd => { const clash = def.nodes.some(nd => {
if (nd === part || nd === bundle || nd === split || nd.kind === 'note') return false if (nd === part || nd === bundle || nd === split || nd.kind === 'note') return false
@ -170,13 +179,13 @@ export function plugInto(def: ComponentDef, end: CircuitNode, partId: string, ge
} }
/** /**
* The part a free cable end touches with all its wires, every one wired to * The part a free cable end touches with all its wires (at least two), every
* it, so it counts as plugged in. One wire landing on a lamp doesn't make * one wired to it, so it counts as plugged in. One wire landing on a lamp
* the whole end a plug. * doesn't make the whole end a plug.
*/ */
function touching(def: ComponentDef, end: CircuitNode, nodes: Map<string, CircuitNode>, get: DefLookup): string | null { function touching(def: ComponentDef, end: CircuitNode, nodes: Map<string, CircuitNode>, get: DefLookup): string | null {
const wires = singleWires(def, end) const wires = singleWires(def, end)
if (new Set(wires.map(w => bitOf(end, w))).size < cableBits(end)) return null if (new Set(wires.map(w => bitOf(end, w))).size < 2) return null
const ids = new Set(wires.map(w => farEnd(end, w).node)) const ids = new Set(wires.map(w => farEnd(end, w).node))
const part = ids.size === 1 ? nodes.get([...ids][0]!) : undefined const part = ids.size === 1 ? nodes.get([...ids][0]!) : undefined
if (!part || CABLE_ENDS.has(part.kind)) return null if (!part || CABLE_ENDS.has(part.kind)) return null

View File

@ -2,7 +2,7 @@
// nets. Chip boundaries and input/output pins disappear: they are aliases, // nets. Chip boundaries and input/output pins disappear: they are aliases,
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH. // merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
import { cableBits, chipPins, type ChipPins, type DefLookup } from './geometry' import { cableBits, chipPins, isPinRow, rowPin, type ChipPins, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Wire } from './types' import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0 export const LOW = 0
@ -70,6 +70,8 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
return ['q'] return ['q']
case 'chip': case 'chip':
return pins ? pins.outputs.map(p => p.key) : [] return pins ? pins.outputs.map(p => p.key) : []
case 'hex':
return ['q0', 'q1', 'q2', 'q3']
case 'panel': case 'panel':
return (node.rows ?? []).map(r => r.id) return (node.rows ?? []).map(r => r.id)
case 'bundle': case 'bundle':
@ -97,7 +99,7 @@ export function cableKeys(node: CircuitNode): string[] {
} }
/** Key of a panel row in the simulator's sources, like a switch's node id. */ /** Key of a panel row in the simulator's sources, like a switch's node id. */
export const rowSource = (nodeId: string, rowId: string) => `${nodeId}:${rowId}` export const rowSource = rowPin
const MAX_DEPTH = 64 const MAX_DEPTH = 64
@ -234,11 +236,13 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
} }
case 'panel': case 'panel':
// In the open circuit the rows are switches and buttons you use; // In the open circuit the rows are switches and buttons you use;
// inside a component a switch row keeps its position, a button is 0. // inside a component they are its input pins. A panel kept inside
// has fixed switches there (a button is 0).
for (const r of n.rows ?? []) { for (const r of n.rows ?? []) {
const net = outNet.get(`${n.id}:${r.id}`)! const net = outNet.get(`${n.id}:${r.id}`)!
if (r.type === 'clock') clocks.push({ net, hz: r.hz ?? 0, key: `${path}${n.id}:${r.id}` }) if (r.type === 'clock') clocks.push({ net, hz: r.hz ?? 0, key: `${path}${n.id}:${r.id}` })
else if (!inNets) sources.set(rowSource(n.id, r.id), net) else if (!inNets) sources.set(rowSource(n.id, r.id), net)
else if (isPinRow(n, r)) union(net, inNets.get(rowPin(n.id, r.id)) ?? LOW)
else if (r.type === 'switch' && r.on) union(net, HIGH) else if (r.type === 'switch' && r.on) union(net, HIGH)
} }
break break
@ -254,6 +258,9 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
// A lamp passes its signal on to whatever its right pin feeds. // A lamp passes its signal on to whatever its right pin feeds.
union(q, pinIn(n, 'a')) union(q, pinIn(n, 'a'))
break break
case 'hex':
for (let i = 0; i < 4; i++) union(outNet.get(`${n.id}:q${i}`)!, inNet(n.id, `b${i}`))
break
case 'chip': { case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined const child = n.chip ? getDef(n.chip) : undefined
const pins = pinsOf(n) const pins = pinsOf(n)

View File

@ -1,7 +1,7 @@
// Node shapes and pin positions, all in grid units relative to the node's // Node shapes and pin positions, all in grid units relative to the node's
// (x, y). Pins always sit on whole grid points so straight wires line up. // (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, LampColor, PanelRow, SymbolKind } from './types' import type { CircuitNode, ComponentDef, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
export const GRID = 16 export const GRID = 16
@ -24,6 +24,10 @@ export interface Shape {
nameY?: number nameY?: number
/** Lamps and displays from inside the component, shown on its box. */ /** Lamps and displays from inside the component, shown on its box. */
face?: FaceItem[] face?: FaceItem[]
/** Where a box prints its name (its middle), or null when it is left off; empty: centred. */
nameAt?: { x: number; y: number } | null
/** Drawings on a hand-drawn box, in grid units relative to the chip node. */
drawing?: FaceShape[]
} }
export interface ScreenPixel { export interface ScreenPixel {
@ -61,15 +65,34 @@ export interface ChipPins {
outputs: { key: string; label: string }[] outputs: { key: string; label: string }[]
} }
/** A component's pins are its input/output nodes, ordered top to bottom. */ /** Pin key of a panel row: the same key the row has as a switch in the simulator. */
export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
/** Panel rows that are input pins of their component: switches and buttons, unless the panel keeps them inside. */
export const isPinRow = (panel: CircuitNode, row: PanelRow) => !panel.inner && row.type !== 'clock'
/**
* A component's pins, ordered top to bottom: its input and output nodes,
* and the switch and button rows of its input panels, which count as inputs.
*/
export function chipPins(def: ComponentDef): ChipPins { export function chipPins(def: ComponentDef): ChipPins {
const byPos = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x const inputs: { key: string; label: string; x: number; y: number }[] = []
const pins = (kind: 'input' | 'output', fallback: string) => for (const n of def.nodes) {
def.nodes if (n.kind === 'input') inputs.push({ key: n.id, label: n.label?.trim() ?? '', x: n.x, y: n.y })
.filter(n => n.kind === kind) else if (n.kind === 'panel') {
.sort(byPos) const rows = n.rows ?? []
.map((n, i) => ({ key: n.id, label: n.label?.trim() || `${fallback}${i + 1}` })) const at = panelOffsets(rows)
return { inputs: pins('input', 'in'), outputs: pins('output', 'out') } rows.forEach((r, i) => {
if (isPinRow(n, r)) inputs.push({ key: rowPin(n.id, r.id), label: r.label?.trim() || r.name?.trim() || '', x: n.x, y: n.y + at[i]! })
})
}
}
inputs.sort((a, b) => a.y - b.y || a.x - b.x)
const outputs = def.nodes.filter(n => n.kind === 'output').sort((a, b) => a.y - b.y || a.x - b.x)
return {
inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })),
outputs: outputs.map((n, i) => ({ key: n.id, label: n.label?.trim() || `out${i + 1}` })),
}
} }
/** /**
@ -167,6 +190,35 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
} }
} }
/**
* A box drawn by hand: the size it was given (never shorter than its pins
* need), everything placed where it was put, the rest where it would go
* anyway, and its drawings.
*/
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
const auto = boxShape(def.name, pins, face)
const d = def.design!
const top = auto.body.y
const pinH = Math.max(pins.inputs.length, pins.outputs.length, 1)
const w = Math.max(2, d.w)
const h = Math.max(pinH === 1 ? 2 : pinH, d.h)
const hide = new Set(d.hide ?? [])
const place = d.place ?? {}
return {
...auto,
body: { x: 0, y: top, w, h },
outputs: auto.outputs.map(p => ({ ...p, dx: w })),
face: (auto.face ?? [])
.filter(it => !hide.has(it.kind === 'screen' ? 'screen' : it.id))
.map(it => {
const at = place[it.kind === 'screen' ? 'screen' : it.id]
return at ? { ...it, x: at.x, y: top + at.y } : it
}),
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
drawing: (d.shapes ?? []).map(sh => ({ ...sh, y: top + sh.y })),
}
}
function boxShape(name: string, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape { function boxShape(name: string, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
const nIn = pins.inputs.length const nIn = pins.inputs.length
const nOut = pins.outputs.length const nOut = pins.outputs.length
@ -227,10 +279,11 @@ function refShape(node: CircuitNode): Shape {
return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] } return { body: { x: 0, y: -0.6, w, h: 1.2 }, inputs: [], outputs: [{ key: 'q', label: '', dx: w + 0.5, dy: 0 }] }
} }
// A hex display passes its four bits on, so it can sit in the middle of a bus.
const HEX_SHAPE: Shape = { const HEX_SHAPE: Shape = {
body: { x: 0, y: -0.5, w: 3, h: 4 }, 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 })), inputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `b${i}`, label, dx: 0, dy: i })),
outputs: [], outputs: ['1', '2', '4', '8'].map((label, i) => ({ key: `q${i}`, label, dx: 3, dy: i })),
} }
const CLOCK_SHAPE: Shape = { const CLOCK_SHAPE: Shape = {
@ -355,6 +408,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
if (!def) return MISSING_SHAPE if (!def) return MISSING_SHAPE
const pins = chipPins(def) const pins = chipPins(def)
const face = faceLayout(def) const face = faceLayout(def)
if (def.design) return designedShape(def, pins, face)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) { if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!) return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
} }

View File

@ -84,6 +84,12 @@ export function pinName(node: CircuitNode, pin: string, get: DefLookup): string
if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined if (node.kind === 'bundle' || node.kind === 'split') return /^b\d+$/.test(pin) ? node.names?.[Number(pin.slice(1))]?.trim() || undefined : undefined
if (node.kind !== 'chip' || !node.chip) return undefined if (node.kind !== 'chip' || !node.chip) return undefined
const def = get(node.chip) const def = get(node.chip)
// A pin made from a panel row: panel:row.
const at = pin.indexOf(':')
if (at > 0) {
const row = def?.nodes.find(n => n.id === pin.slice(0, at))?.rows?.find(r => r.id === pin.slice(at + 1))
return row?.label?.trim() || row?.name?.trim() || undefined
}
return def?.nodes.find(n => n.id === pin)?.label?.trim() || undefined return def?.nodes.find(n => n.id === pin)?.label?.trim() || undefined
} }

View File

@ -3,7 +3,7 @@
// it gets one row per free input pin. A docked panel moves with its // it gets one row per free input pin. A docked panel moves with its
// component and follows it when the component gains or loses pins. // component and follows it when the component gains or loses pins.
import { chipPins, shapeOf, type DefLookup } from './geometry' import { chipPins, panelOffsets, rowPin, shapeOf, type DefLookup } from './geometry'
import { lookup, uid } from './ops' import { lookup, uid } from './ops'
import type { CircuitNode, ComponentDef, PanelRow, Project } from './types' import type { CircuitNode, ComponentDef, PanelRow, Project } from './types'
@ -132,3 +132,42 @@ export function detachPanel(panel: CircuitNode) {
delete panel.attach delete panel.attach
delete panel.skip delete panel.skip
} }
/**
* Joins panels into one: the top one keeps its rows, the others' rows follow
* below in order, keeping their spacing, with their wires. The joined panel
* is free (no longer docked). Returns it with the pin keys that changed
* (old → new), so circuits that place this one can keep their wires; null
* for fewer than two panels.
*/
export function mergePanels(def: ComponentDef, ids: string[]): { panel: CircuitNode; renamed: Map<string, string> } | null {
const panels = def.nodes.filter(n => n.kind === 'panel' && ids.includes(n.id)).sort((a, b) => a.y - b.y || a.x - b.x)
if (panels.length < 2) return null
const [target, ...rest] = panels as [CircuitNode, ...CircuitNode[]]
const rows = target.rows ?? []
const at = panelOffsets(rows)
rows.forEach((r, i) => (r.dy = at[i]!))
let bottom = at.length ? at[at.length - 1]! : -1
const used = new Set(rows.map(r => r.id))
const renamed = new Map<string, string>()
for (const p of rest) {
const theirs = p.rows ?? []
const off = panelOffsets(theirs)
const shift = bottom + 1 - (off[0] ?? 0)
theirs.forEach((r, i) => {
const id = used.has(r.id) ? uid('r') : r.id
used.add(id)
for (const w of def.wires) if (w.from.node === p.id && w.from.pin === r.id) w.from = { node: target.id, pin: id }
renamed.set(rowPin(p.id, r.id), rowPin(target.id, id))
rows.push({ ...r, id, dy: off[i]! + shift })
})
if (theirs.length) bottom = rows[rows.length - 1]!.dy!
}
target.rows = rows
delete target.attach
delete target.skip
const gone = new Set(rest.map(p => p.id))
def.nodes = def.nodes.filter(n => !gone.has(n.id))
def.wires = def.wires.filter(w => !gone.has(w.from.node) && !gone.has(w.to.node))
return { panel: target, renamed }
}

View File

@ -2,7 +2,19 @@
// and the share-link server, so it must stay free of browser APIs. // and the share-link server, so it must stay free of browser APIs.
import { cleanPuzzle } from './puzzles' import { cleanPuzzle } from './puzzles'
import { CROSSING_STYLES, LAMP_COLORS, PANEL_CONTROLS, WIRE_COLORS, type CircuitNode, type PanelRow, type Project, type PuzzleSpec } from './types' import {
CROSSING_STYLES,
FACE_INKS,
LAMP_COLORS,
PANEL_CONTROLS,
WIRE_COLORS,
type CircuitNode,
type ComponentDef,
type FaceDesign,
type PanelRow,
type Project,
type PuzzleSpec,
} from './types'
/** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */ /** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */
function cleanNode(n: CircuitNode) { function cleanNode(n: CircuitNode) {
@ -21,6 +33,13 @@ function cleanNode(n: CircuitNode) {
if (!Array.isArray(n.rows)) delete n.rows if (!Array.isArray(n.rows)) delete n.rows
else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS) else n.rows = n.rows.filter(cleanRow).slice(0, MAX_ROWS)
} }
if (n.plug !== undefined && typeof n.plug !== 'string') delete n.plug
if (n.pitch !== undefined && !(Number.isInteger(n.pitch) && n.pitch >= 1 && n.pitch <= 8)) delete n.pitch
if (n.offsets !== undefined && !(Array.isArray(n.offsets) && n.offsets.every(v => Number.isInteger(v) && v >= 0 && v <= 10_000))) delete n.offsets
for (const k of ['names', 'invert'] as const) {
if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
}
if (n.inner !== undefined && n.inner !== true) delete n.inner
} }
const MAX_ROWS = 256 const MAX_ROWS = 256
@ -32,9 +51,46 @@ function cleanRow(r: PanelRow): boolean {
if (r.on !== undefined && typeof r.on !== 'boolean') delete r.on if (r.on !== undefined && typeof r.on !== 'boolean') delete r.on
if (r.hz !== undefined && !(typeof r.hz === 'number' && r.hz > 0 && r.hz <= 1000)) delete r.hz if (r.hz !== undefined && !(typeof r.hz === 'number' && r.hz > 0 && r.hz <= 1000)) delete r.hz
if (r.dy !== undefined && !(Number.isInteger(r.dy) && r.dy >= 0 && r.dy <= 10_000)) delete r.dy if (r.dy !== undefined && !(Number.isInteger(r.dy) && r.dy >= 0 && r.dy <= 10_000)) delete r.dy
if (r.key !== undefined && !(typeof r.key === 'string' && r.key.length === 1)) delete r.key
if (r.color !== undefined && !LAMP_COLORS.includes(r.color)) delete r.color
return true return true
} }
const num = (v: unknown, lo: number, hi: number) => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi
/** A hand-drawn box: sizes and places in range, drawings of known kinds; a broken one is dropped. */
function cleanDesign(d: ComponentDef) {
const f = d.design as FaceDesign | undefined
if (!f || typeof f !== 'object' || !num(f.w, 1, 200) || !num(f.h, 1, 200)) {
delete d.design
return
}
if (f.place !== undefined) {
if (!f.place || typeof f.place !== 'object' || Array.isArray(f.place)) delete f.place
else for (const [k, v] of Object.entries(f.place)) if (!v || !num(v.x, -200, 400) || !num(v.y, -200, 400)) delete f.place[k]
}
if (f.hide !== undefined && !(Array.isArray(f.hide) && f.hide.every(v => typeof v === 'string'))) delete f.hide
if (f.shapes !== undefined) {
f.shapes = Array.isArray(f.shapes)
? f.shapes
.filter(
sh =>
sh &&
typeof sh.id === 'string' &&
['line', 'rect', 'ellipse', 'text'].includes(sh.kind) &&
[sh.x, sh.y, sh.w, sh.h].every(v => num(v, -400, 400)),
)
.slice(0, 500)
: []
for (const sh of f.shapes) {
if (sh.ink !== undefined && !FACE_INKS.includes(sh.ink)) delete sh.ink
if (sh.text !== undefined && typeof sh.text !== 'string') delete sh.text
if (sh.size !== undefined && !num(sh.size, 0.25, 4)) delete sh.size
if (sh.fill !== undefined && sh.fill !== true) delete sh.fill
}
}
}
/** Upper bounds for a project that comes from outside. */ /** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 } export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
@ -53,6 +109,7 @@ export function toProject(data: unknown): Project {
nodes += d.nodes.length nodes += d.nodes.length
d.symbol ??= 'box' d.symbol ??= 'box'
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
if (d.design !== undefined) cleanDesign(d)
for (const n of d.nodes) cleanNode(n) for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
} }

View File

@ -63,6 +63,8 @@ export interface CircuitNode {
names?: string[] names?: string[]
/** Input pins with a bubble: the signal comes in inverted, through one NAND (counted like any other). */ /** Input pins with a bubble: the signal comes in inverted, through one NAND (counted like any other). */
invert?: string[] invert?: string[]
/** Panel whose rows stay inside a component (as fixed switches) instead of becoming its input pins. */
inner?: boolean
} }
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
@ -127,6 +129,43 @@ export interface ComponentDef {
challenge?: string challenge?: string
/** A gate with more inputs, built from a two-input gate (a component id, or "nand"). */ /** A gate with more inputs, built from a two-input gate (a component id, or "nand"). */
wide?: { base: string; n: number } wide?: { base: string; n: number }
/** The component's box drawn by hand; empty: laid out automatically. */
design?: FaceDesign
}
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
export type FaceInk = (typeof FACE_INKS)[number]
/**
* A component box drawn by hand: its size, where its lamps, displays,
* screen and name sit, what is left off, and drawings of its own. All in
* grid units from the box's top left corner; pins stay on the left and
* right edges.
*/
export interface FaceDesign {
w: number
h: number
/** Top left corner of lamps and displays (by node id), the pixel screen ('screen') and the name ('name'). */
place?: Record<string, { x: number; y: number }>
/** Left off the box: lamp and display node ids, 'screen', 'name'. */
hide?: string[]
shapes?: FaceShape[]
}
export interface FaceShape {
id: string
kind: 'line' | 'rect' | 'ellipse' | 'text'
/** Top left corner and size; for a line, its start and the step to its end (w, h may be negative). */
x: number
y: number
w: number
h: number
text?: string
ink?: FaceInk
/** Rectangles and ellipses: filled lightly instead of only outlined. */
fill?: boolean
/** Text size: 1 is normal. */
size?: number
} }
export interface Settings { export interface Settings {

View File

@ -38,11 +38,17 @@ describe('the list of inputs and outputs', () => {
wires: [], wires: [],
} }
it('lists pins first in pin order, then the parts that stay inside, with panel rows', () => { it('lists pins first in pin order (panel rows are pins too), then the parts that stay inside', () => {
const { inputs, outputs } = ioList(def) const { inputs, outputs } = ioList(def)
expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'clk:false', 'p/r1:false', 'p/r2:false']) expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'p/r1:true', 'p/r2:true', 'clk:false'])
expect(outputs.map(e => e.node.id)).toEqual(['q', 'l']) expect(outputs.map(e => e.node.id)).toEqual(['q', 'l'])
expect(inputs.map(entryLabel)).toEqual(['A', 'B', '', 'EN', '']) expect(inputs.map(entryLabel)).toEqual(['A', 'B', 'EN', '', ''])
})
it('a panel kept inside lists its rows after the pins', () => {
const inside = { ...def, nodes: def.nodes.map(n => (n.kind === 'panel' ? { ...n, inner: true } : n)) }
const { inputs } = ioList(inside)
expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'clk:false', 'p/r1:false', 'p/r2:false'])
}) })
it('flags names used twice on the same side only', () => { it('flags names used twice on the same side only', () => {

88
tests/face.test.ts Normal file
View File

@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
function shown(): { p: ReturnType<typeof createProject>; inner: ComponentDef } {
const p = createProject({ examples: false })
const inner: ComponentDef = {
id: 'inner',
name: 'Show',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 1, label: 'B' },
{ id: 'l', kind: 'lamp', x: 6, y: 0, label: 'L' },
{ id: 'h', kind: 'hex', x: 6, y: 4 },
{ id: 'q', kind: 'output', x: 12, y: 0, label: 'Q' },
],
wires: [{ id: 'w', from: { node: 'a', pin: 'q' }, to: { node: 'l', pin: 'a' } }],
}
p.components.push(inner)
return { p, inner }
}
describe('hex display', () => {
it('passes its four bits on, so it can sit in the middle of a bus', () => {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: 0, y: 0 },
{ id: 'h', kind: 'hex', x: 4, y: 0 },
{ id: 'l', kind: 'lamp', x: 10, y: 0 },
],
wires: [
{ id: 'a', from: { node: 's', pin: 'q' }, to: { node: 'h', pin: 'b0' } },
{ id: 'b', from: { node: 'h', pin: 'q0' }, to: { node: 'l', pin: 'a' } },
],
}
p.components.push(def)
expect(shapeOf(def.nodes[1]!, lookup(p)).outputs.map(o => o.key)).toEqual(['q0', 'q1', 'q2', 'q3'])
const sim = new Simulator(compile(lookup(p), 'root'))
sim.setSource('s', true)
sim.run()
expect(sim.pin('l', 'a')).toBe(1)
})
})
describe('a box drawn by hand', () => {
it('takes its size, places things where they were put, leaves hidden ones off, carries drawings', () => {
const { p, inner } = shown()
const chip = { id: 'c', kind: 'chip' as const, chip: 'inner', x: 0, y: 0 }
const auto = shapeOf(chip, lookup(p))
expect(auto.face?.map(f => f.id)).toEqual(['l', 'h'])
inner.design = {
w: 9,
h: 7,
place: { l: { x: 5, y: 1 }, name: { x: 3, y: 5 } },
hide: ['h'],
shapes: [{ id: 's1', kind: 'rect', x: 1, y: 1, w: 2, h: 2, ink: 'red' }],
}
const s = shapeOf(chip, lookup(p))
expect(s.body.w).toBe(9)
expect(s.body.h).toBe(7)
// Outputs move to the new right edge; inputs stay on the left.
expect(s.outputs.every(o => o.dx === 9)).toBe(true)
expect(s.face).toEqual([expect.objectContaining({ id: 'l', x: 5, y: s.body.y + 1 })])
expect(s.nameAt).toEqual({ x: 3, y: s.body.y + 5 })
expect(s.drawing?.[0]).toMatchObject({ id: 's1', y: s.body.y + 1 })
// Never shorter than its pins need.
inner.design.h = 1
expect(shapeOf(chip, lookup(p)).body.h).toBeGreaterThanOrEqual(2)
})
it('a broken design from a file is dropped, a broken drawing too', () => {
const { p, inner } = shown()
inner.design = { w: 6, h: 4, shapes: [{ id: 'x', kind: 'rect', x: 0, y: 0, w: 1, h: 1 }, { id: 'y', kind: 'laser' as 'rect', x: 0, y: 0, w: 1, h: 1 }] }
const back = toProject(JSON.parse(JSON.stringify(p)))
expect(back.components.find(d => d.id === 'inner')!.design!.shapes!.map(s => s.id)).toEqual(['x'])
;(inner as { design: unknown }).design = { w: 'big' }
expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'inner')!.design).toBeUndefined()
})
})

75
tests/panels.test.ts Normal file
View File

@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { chipPins, panelOffsets } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { mergePanels } from '../app/lib/logic/panels'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
describe('merging input panels', () => {
it('rows of the lower panel follow below, with their wires, as one panel', () => {
const def: ComponentDef = {
id: 'd',
name: 'D',
symbol: 'box',
nodes: [
{ id: 'p2', kind: 'panel', x: 0, y: 10, rows: [{ id: 'r1', type: 'switch', label: 'B0' }, { id: 'r2', type: 'button', label: 'B1', dy: 2 }] },
{ id: 'p1', kind: 'panel', x: 0, y: 0, attach: 'x', rows: [{ id: 'r1', type: 'switch', label: 'A0' }] },
{ id: 'l', kind: 'lamp', x: 10, y: 0 },
{ id: 'm', kind: 'lamp', x: 10, y: 4 },
],
wires: [
{ id: 'w1', from: { node: 'p1', pin: 'r1' }, to: { node: 'l', pin: 'a' } },
{ id: 'w2', from: { node: 'p2', pin: 'r2' }, to: { node: 'm', pin: 'a' } },
],
}
const res = mergePanels(def, ['p1', 'p2'])!
expect(res.panel.id).toBe('p1')
expect(def.nodes.some(n => n.id === 'p2')).toBe(false)
expect(res.panel.attach).toBeUndefined()
const rows = res.panel.rows!
expect(rows.map(r => r.label)).toEqual(['A0', 'B0', 'B1'])
// Spacing kept: B1 was two rows under B0.
expect(panelOffsets(rows)).toEqual([0, 1, 3])
// The wire from B1 now leaves the merged panel; the clashing row id got a new one.
const w2 = def.wires.find(w => w.id === 'w2')!
expect(w2.from.node).toBe('p1')
expect(rows.find(r => r.label === 'B1')!.id).toBe(w2.from.pin)
expect(new Set(rows.map(r => r.id)).size).toBe(3)
expect(res.renamed.get('p2:r2')).toBe(`p1:${w2.from.pin}`)
})
it('a merged panel inside a component gives one pin per row, in order', () => {
const p = createProject({ examples: false })
const inner: ComponentDef = {
id: 'inner',
name: 'Inner',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r', type: 'switch', label: 'X' }] },
{ id: 'b', kind: 'panel', x: 0, y: 5, rows: [{ id: 'r', type: 'switch', label: 'Y' }] },
{ id: 'q', kind: 'output', x: 10, y: 5, label: 'Q' },
],
wires: [{ id: 'w', from: { node: 'b', pin: 'r' }, to: { node: 'q', pin: 'a' } }],
}
p.components.push(inner)
mergePanels(inner, ['a', 'b'])
const pins = chipPins(inner).inputs
expect(pins.map(x => x.label)).toEqual(['X', 'Y'])
const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: -5, y: 0 },
{ id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 },
],
wires: [{ id: 'x', from: { node: 's', pin: 'q' }, to: { node: 'u', pin: pins[1]!.key } }],
}
p.components.push(root)
const sim = new Simulator(compile(lookup(p), 'root'))
sim.setSource('s', true)
sim.run()
expect(sim.pin('u', 'q')).toBe(1)
})
})

View File

@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { bundleWires, cablePanel, nameTags, plugInto, syncCables } from '../app/lib/logic/cables' import { bundleWires, cablePanel, nameTags, plugInto, plugLayout, syncCables } from '../app/lib/logic/cables'
import { compile, rowSource } from '../app/lib/logic/compile' import { compile, rowSource } from '../app/lib/logic/compile'
import { chipPins, panelOffsets, pinPos, shapeOf } from '../app/lib/logic/geometry' import { chipPins, panelOffsets, pinPos, shapeOf } from '../app/lib/logic/geometry'
import { copySelection, createProject, lookup, pasteClip } from '../app/lib/logic/ops' import { copySelection, createProject, lookup, pasteClip } from '../app/lib/logic/ops'
@ -269,3 +269,27 @@ describe('cables saved before plugs existed', () => {
expect(sums(p, def)).toEqual(before) expect(sums(p, def)).toEqual(before)
}) })
}) })
describe('plugging in more often', () => {
it('outputs of one part bundled to scattered targets: the bundle plugs into the part', () => {
const { p, def, outs } = adder()
// Lamps in reverse order: wire order follows the Adder's pins, not the lamps.
for (const i of [0, 1, 2, 3, 4]) node(def, `l${i}`).y = 40 - i * 3
const res = bundleWires(def, outs.map((_, i) => `wo${i}`), lookup(p))
if (!res.ok) throw new Error(res.error)
expect(res.bundle.plug).toBe('add')
expect(touches(p, def, res.bundle)).toBe(true)
})
it('an end with only some of its wires on a part still plugs in', () => {
const { p, def, ins } = adder()
def.nodes.push({ id: 'sp', kind: 'split', bits: 5, x: 0, y: 30 })
for (const i of [0, 1, 2, 3]) def.wires.push({ id: `t${i}`, from: { node: 'sp', pin: `b${i}` }, to: { node: 'add', pin: ins[i]! } })
const sp = node(def, 'sp')
const lay = plugLayout(def, sp, node(def, 'add'), lookup(p))!
sp.x = lay.x
sp.y = lay.y
syncCables(p)
expect(sp.plug).toBe('add')
})
})

View File

@ -196,25 +196,44 @@ describe('input panels', () => {
expect(panel.attach).toBeUndefined() expect(panel.attach).toBeUndefined()
}) })
it('works as a source inside a component: a switch row keeps its position, a clock row is a clock', () => { it('inside a component its switch rows are input pins, a clock row is a clock; kept inside, a switch keeps its position', () => {
const p = createProject({ examples: false }) const p = createProject({ examples: false })
const inner: ComponentDef = { const inner: ComponentDef = {
id: 'inner', id: 'inner',
name: 'Inner', name: 'Inner',
symbol: 'box', symbol: 'box',
nodes: [ nodes: [
{ id: 'pn', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r1', type: 'switch', on: true }, { id: 'r2', type: 'clock' }] }, { id: 'pn', kind: 'panel', x: 0, y: 0, rows: [{ id: 'r1', type: 'switch', on: true, label: 'EN' }, { id: 'r2', type: 'clock' }] },
{ id: 'q', kind: 'output', x: 10, y: 0, label: 'Q' }, { id: 'q', kind: 'output', x: 10, y: 0, label: 'Q' },
], ],
wires: [{ id: 'w', from: { node: 'pn', pin: 'r1' }, to: { node: 'q', pin: 'a' } }], wires: [{ id: 'w', from: { node: 'pn', pin: 'r1' }, to: { node: 'q', pin: 'a' } }],
} }
const root: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes: [{ id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 }], wires: [] } const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 'sw', kind: 'input', x: -6, y: 0 },
{ id: 'u', kind: 'chip', chip: 'inner', x: 0, y: 0 },
],
wires: [{ id: 'x', from: { node: 'sw', pin: 'q' }, to: { node: 'u', pin: 'pn:r1' } }],
}
p.components.push(inner, root) p.components.push(inner, root)
expect(chipPins(inner).inputs).toEqual([{ key: 'pn:r1', label: 'EN' }])
const nl = compile(lookup(p), 'root') const nl = compile(lookup(p), 'root')
expect(nl.clocks.length).toBe(1) expect(nl.clocks.length).toBe(1)
const s = new Simulator(nl) const s = new Simulator(nl)
s.run() s.run()
expect(s.pin('u', 'q')).toBe(0)
s.setSource('sw', true)
s.run()
expect(s.pin('u', 'q')).toBe(1) expect(s.pin('u', 'q')).toBe(1)
// Kept inside: no pin, and the switch stays as it was set.
inner.nodes[0]!.inner = true
expect(chipPins(inner).inputs).toEqual([])
const kept = new Simulator(compile(lookup(p), 'root'))
kept.run()
expect(kept.pin('u', 'q')).toBe(1)
}) })
it('survives a round trip through project validation, and bad rows are dropped', () => { it('survives a round trip through project validation, and bad rows are dropped', () => {