A wire a selection where it fits: green boxes over free pins in a row, and parts dropped onto a pin connect

- Select several lamps, output pins, switches or gates: every run of free pins they fit on (nearest parts first) shows as a green box; pointing along it picks the pins (S0+S1, S1+S2, ...) with a preview, a click wires them all top to bottom
- "Wire them all to" lists those fits, nearest first; the old pick-any-part stays under "Any part"
- Dragging a part so a free pin lands on (or a square from) a pin it can join shows a green ring and connects on drop; Alt places it without connecting
- A cable end only plugs in by itself when all its wires sit on the part; a name a part covers is hidden

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-21 12:16:26 +02:00
parent 81a33b9b4b
commit 7ce8ffb9bc
9 changed files with 578 additions and 15 deletions

View File

@ -2358,6 +2358,64 @@ kbd {
.lane.c-purple { --w-on: #b388ff; --w-off: #463768; } .lane.c-purple { --w-on: #b388ff; --w-off: #463768; }
.lane.c-pink { --w-on: #ff7ac6; --w-off: #673657; } .lane.c-pink { --w-on: #ff7ac6; --w-off: #673657; }
/* Where the selection fits: green boxes over runs of free pins, and pins a dragged part lands on. */
.fit-strip {
fill: rgb(61 220 132 / 0.16);
stroke: rgb(61 220 132 / 0.75);
stroke-width: 1.5;
cursor: pointer;
}
.fit-strip.active {
fill: rgb(61 220 132 / 0.06);
stroke-dasharray: 3 3;
}
.fit-window {
fill: rgb(61 220 132 / 0.32);
stroke: var(--on);
stroke-width: 2;
pointer-events: none;
}
.fit-line {
fill: none;
stroke: var(--on);
stroke-width: 1.5;
stroke-dasharray: 4 4;
opacity: 0.85;
pointer-events: none;
}
.fit-pin {
fill: none;
stroke: var(--on);
stroke-width: 2;
pointer-events: none;
}
.drop-ring {
fill: rgb(61 220 132 / 0.25);
stroke: var(--on);
stroke-width: 2;
pointer-events: none;
}
.fit-list {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.fit-list .btn-sm.active {
border-color: var(--on);
color: var(--on);
}
.fit-list .muted {
color: var(--muted);
}
.box-select.crossing { .box-select.crossing {
fill: rgb(61 220 132 / 0.08); fill: rgb(61 220 132 / 0.08);
stroke: var(--on); stroke: var(--on);

View File

@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
// Settings for several selected parts at once: one change, all of them. // Settings for several selected parts at once: one change, all of them.
import { byPosition, numberedNames, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk' import { byPosition, numberedNames, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
import { canFit } from '~/lib/logic/fit'
import { chipPins } from '~/lib/logic/geometry' import { chipPins } from '~/lib/logic/geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' import { pinKeys, SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress' import { KIND_NAMES } from '~/lib/logic/progress'
@ -117,6 +118,27 @@ const others = computed(() => {
const target = ref('') const target = ref('')
const chosen = computed(() => others.value.find(o => o.id === target.value) ?? others.value[0]) const chosen = computed(() => others.value.find(o => o.id === target.value) ?? others.value[0])
const targetId = computed({ get: () => chosen.value?.id ?? '', set: v => (target.value = v) }) const targetId = computed({ get: () => chosen.value?.id ?? '', set: v => (target.value = v) })
/** Where they fit, nearest first: every way to put them on a run of free pins. */
const fitChoices = computed(() => {
const out: { spot: number; start: number; part: string; pins: string; dist: number }[] = []
ed.fits.value.forEach((f, spot) => {
const node = ed.def.value.nodes.find(n => n.id === f.part)
const part = node ? partName(node) : 'part'
const k = f.mine.length
for (let start = 0; start + k <= f.pins.length; start++) {
const a = f.pins[start]!
const b = f.pins[start + k - 1]!
const name = (p: typeof a, i: number) => p.label || String(i + 1)
out.push({ spot, start, part, pins: `${name(a, start)}–${name(b, start + k - 1)}`, dist: Math.hypot(a.x - f.from[0], (a.y + b.y) / 2 - f.from[1]) })
}
})
return out.sort((a, b) => a.dist - b.dist).slice(0, 8)
})
function partName(n: { label?: string; chip?: string; kind: NodeKind; autoLabel?: boolean }) {
return (!n.autoLabel && n.label?.trim()) || (n.chip && ed.getDef.value(n.chip)?.name) || KIND_NAMES[n.kind] || n.kind
}
const mineIn = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).ins.length)) const mineIn = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).ins.length))
const mineOut = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).outs.length)) const mineOut = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).outs.length))
@ -236,17 +258,37 @@ function pack() {
<section v-if="others.length && chosen"> <section v-if="others.length && chosen">
<h3>Wire them all to</h3> <h3>Wire them all to</h3>
<select v-model="targetId" class="text-input"> <template v-if="fitChoices.length">
<option v-for="o in others" :key="o.id" :value="o.id">{{ o.name }} ({{ o.pins.ins.length }} in, {{ o.pins.outs.length }} out)</option> <p class="hint">The green boxes on the canvas show where they fit. Point along one to pick the pins, click to wire.</p>
</select> <div class="fit-list">
<div class="mt-2 grid gap-2"> <button
<button v-if="mineIn && chosen.pins.outs.length" class="btn w-full" title="Its outputs, in order, into the selected parts, top to bottom" @click="ed.connectSelectionTo(chosen.id, 'in')"> v-for="c in fitChoices"
<Icon name="lucide:arrow-right-to-line" class="size-4" /> From {{ chosen.name }}'s outputs :key="`${c.spot}-${c.start}`"
</button> class="btn-sm"
<button v-if="mineOut && chosen.pins.ins.length" class="btn w-full" title="The selected parts, top to bottom, into its inputs in order" @click="ed.connectSelectionTo(chosen.id, 'out')"> :class="{ active: ed.fitHover.value?.spot === c.spot && ed.fitHover.value?.start === c.start }"
<Icon name="lucide:arrow-left-from-line" class="size-4" /> Into {{ chosen.name }}'s inputs @pointerenter="ed.fitHover.value = { spot: c.spot, start: c.start }"
</button> @pointerleave="ed.fitHover.value = null"
</div> @click="ed.connectFit(c.spot, c.start)"
>
<span class="font-mono">{{ c.pins }}</span> <span class="muted">{{ c.part }}</span>
</button>
</div>
</template>
<p v-else-if="canFit(ed.def.value, ed.getDef.value, ids)" class="hint">No part nearby has {{ nodes.length }} free pins in a row for them.</p>
<details class="mt-2">
<summary class="hint cursor-pointer">Any part, from its first pin</summary>
<select v-model="targetId" class="text-input mt-2">
<option v-for="o in others" :key="o.id" :value="o.id">{{ o.name }} ({{ o.pins.ins.length }} in, {{ o.pins.outs.length }} out)</option>
</select>
<div class="mt-2 grid gap-2">
<button v-if="mineIn && chosen.pins.outs.length" class="btn w-full" title="Its outputs, in order, into the selected parts, top to bottom" @click="ed.connectSelectionTo(chosen.id, 'in')">
<Icon name="lucide:arrow-right-to-line" class="size-4" /> From {{ chosen.name }}'s outputs
</button>
<button v-if="mineOut && chosen.pins.ins.length" class="btn w-full" title="The selected parts, top to bottom, into its inputs in order" @click="ed.connectSelectionTo(chosen.id, 'out')">
<Icon name="lucide:arrow-left-from-line" class="size-4" /> Into {{ chosen.name }}'s inputs
</button>
</div>
</details>
<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>

View File

@ -4,7 +4,8 @@ import { cableBits, GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types' 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, moveCorner, moveSegment, routeTouchesBox, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing' import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { seriesLinks } from '~/lib/logic/bulk' import { seriesLinks, type Link } from '~/lib/logic/bulk'
import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { wirePath } from '~/lib/draw' import { wirePath } from '~/lib/draw'
import { pinName } from '~/lib/logic/labels' import { pinName } from '~/lib/logic/labels'
@ -263,6 +264,13 @@ type Drag =
node: CircuitNode node: CircuitNode
toggle: boolean toggle: boolean
row?: PanelRow row?: PanelRow
/** How many parts were picked up (followers not counted): one part may snap to a pin a square away. */
grabbed: number
/** Pins of the parts staying put, and of the moving parts where they started; filled once the drag moves. */
still?: DropPin[]
from?: DropPin[]
/** 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[] }
| { kind: 'box'; start: Pt; cur: Pt; nodes: string[]; wires: string[] } | { kind: 'box'; start: Pt; cur: Pt; nodes: string[]; wires: string[] }
@ -336,6 +344,15 @@ function onPointerDown(e: PointerEvent) {
} }
const target = e.target as Element const target = e.target as Element
const fitEl = target.closest('[data-fit]')
if (fitEl) {
// A green box: wire the selection to the pins pointed at.
const i = Number(fitEl.getAttribute('data-fit'))
const spot = ed.fits.value[i]
const h = ed.fitHover.value
if (spot) ed.connectFit(i, h?.spot === i ? h.start : fitStart(spot, w[1]))
return
}
const pinEl = target.closest('[data-pin]') const pinEl = target.closest('[data-pin]')
if (pinEl) { if (pinEl) {
drag.value = { drag.value = {
@ -400,6 +417,7 @@ function onPointerDown(e: PointerEvent) {
node, node,
toggle: (node.kind === 'input' || !!row) && !multi, toggle: (node.kind === 'input' || !!row) && !multi,
row, row,
grabbed: selected.value.has(id) ? ed.selection.value.length : 1,
} }
return return
} }
@ -458,6 +476,14 @@ function onPointerMove(e: PointerEvent) {
d.moved = true d.moved = true
if (d.node.kind === 'button') ed.press(d.node, false) if (d.node.kind === 'button') ed.press(d.node, false)
if (d.row) ed.pressRow(d.node, d.row, false) if (d.row) ed.pressRow(d.node, d.row, false)
const moving = def.value.nodes.filter(n => d.orig.has(n.id))
d.still = dropPins(def.value, def.value.nodes.filter(n => !d.orig.has(n.id)), n => shapes.value.get(n.id)!)
d.from = dropPins(def.value, moving, n => shapes.value.get(n.id)!)
}
if (d.still && d.from) {
// Dropped onto pins it can join, it connects there (Alt: just place it).
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)
} }
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)
@ -604,7 +630,19 @@ function onPointerUp() {
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) { if (d.moved && d.snap?.links.length) {
const [sx, sy] = d.snap.shift
for (const id of d.orig.keys()) {
const n = nodeMap.value.get(id)
if (!n) continue
n.x += sx
if (!d.lockY.has(id)) n.y += sy
}
for (const wire of d.wires.keys()) wire.pts = wire.pts?.map(([x, y]) => [x + sx, y + sy])
ed.unplugMoved(new Set(d.orig.keys()))
ed.connectMany(d.snap.links)
ed.commit(false)
} else if (d.moved) {
ed.unplugMoved(new Set(d.orig.keys())) ed.unplugMoved(new Set(d.orig.keys()))
ed.commit(false) ed.commit(false)
} else if (d.toggle && d.row) ed.toggleRow(d.node, d.row) } else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
@ -870,6 +908,46 @@ const cableGhost = computed(() => {
return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) } return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) }
}) })
/** Pins a dragged part will connect to when dropped, shown as green rings. */
const dropRings = computed(() => {
const d = drag.value
if (d?.kind !== 'move' || !d.snap || !d.still) return []
const moving = new Set(d.orig.keys())
return d.snap.links.map(l => {
const end = moving.has(l.from.node) ? { ...l.to, dir: 'in' } : { ...l.from, dir: 'out' }
return d.still!.find(p => p.node === end.node && p.pin === end.pin && p.dir === end.dir)!
}).filter(Boolean)
})
/** Green boxes over the runs of pins the selection fits onto; hidden while dragging, wiring or placing. */
const fitShown = computed(() => (drag.value || ed.linking.value || ed.placing.value || ed.cabling.value ? [] : ed.fits.value))
function pinAt(ref: PinRef, dir: 'in' | 'out'): Pt | null {
const n = nodeMap.value.get(ref.node)
const p = n && pinPos(n, shapes.value.get(n.id)!, ref.pin, dir)
return p ? [p.x, p.y] : null
}
/** The fit pointed at: its box and a line from each selected part to the pin it would get. */
const fitPreview = computed(() => {
const h = ed.fitHover.value
const spot = h && fitShown.value[h.spot]
if (!h || !spot) return null
const k = spot.mine.length
const pins = spot.pins.slice(h.start, h.start + k)
const lines = spot.mine.map((m, i) => {
const a = pinAt(m, spot.side === 'out' ? 'in' : 'out')
const b = pins[i]!
return a ? `M${a[0] * G} ${a[1] * G}L${b.x * G} ${b.y * G}` : ''
})
return { x: pins[0]!.x, y0: pins[0]!.y, y1: pins[k - 1]!.y, lines, pins }
})
function onFitMove(i: number, e: PointerEvent) {
const spot = fitShown.value[i]
if (spot) ed.fitHover.value = { spot: i, start: fitStart(spot, toWorld(e)[1]) }
}
const cursorStyle = computed(() => { const cursorStyle = computed(() => {
if (drag.value?.kind === 'pan') return 'grabbing' if (drag.value?.kind === 'pan') return 'grabbing'
if (spaceDown.value) return 'grab' if (spaceDown.value) return 'grab'
@ -981,6 +1059,36 @@ defineExpose({ fit, zoomAt })
:data-corner="h.i" :data-corner="h.i"
/> />
<g v-if="fitShown.length" class="fits">
<rect
v-for="(f, i) in fitShown"
:key="`f${i}`"
:x="(f.pins[0]!.x - 0.45) * G"
:y="(f.pins[0]!.y - 0.5) * G"
:width="0.9 * G"
:height="(f.pins[f.pins.length - 1]!.y - f.pins[0]!.y + 1) * G"
rx="4"
class="fit-strip"
:class="{ active: ed.fitHover.value?.spot === i }"
:data-fit="i"
@pointermove="onFitMove(i, $event)"
@pointerleave="ed.fitHover.value = null"
/>
<template v-if="fitPreview">
<path v-for="(l, i) in fitPreview.lines" :key="`fl${i}`" :d="l" class="fit-line" />
<rect
:x="(fitPreview.x - 0.55) * G"
:y="(fitPreview.y0 - 0.55) * G"
:width="1.1 * G"
:height="(fitPreview.y1 - fitPreview.y0 + 1.1) * G"
rx="5"
class="fit-window"
/>
<circle v-for="(p, i) in fitPreview.pins" :key="`fp${i}`" :cx="p.x * G" :cy="p.y * G" r="4.5" class="fit-pin" />
</template>
</g>
<circle v-for="(p, i) in dropRings" :key="`d${i}`" :cx="p.x * G" :cy="p.y * G" r="7" class="drop-ring" />
<g class="targets"> <g class="targets">
<circle v-for="(t, i) in targets" :key="`t${i}`" :cx="t.x * G" :cy="t.y * G" r="5.5" class="pin-target" :class="{ taken: !t.free }" /> <circle v-for="(t, i) in targets" :key="`t${i}`" :cx="t.x * G" :cy="t.y * G" r="5.5" class="pin-target" :class="{ taken: !t.free }" />
</g> </g>

View File

@ -23,6 +23,8 @@ const SHORTCUTS: [string, string][] = [
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'], ['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'], ['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 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'],
['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)'],
['Delete', 'Remove the selection'], ['Delete', 'Remove the selection'],

View File

@ -4,6 +4,7 @@
import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze' 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 { bundleWires, cablePanel, dissolveCable, pluggedInto, plugInto, syncCables } from '~/lib/logic/cables'
import { fitLinks, fitSpots } from '~/lib/logic/fit'
import { loadSoundSettings, saveSoundSettings, sfx, type Sound, type SoundSettings } from '~/lib/audio' 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 { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUnlocked, NEEDS, unlockedBy } from '~/lib/logic/progress'
import { apiId, makePuzzle, scoreSolution } from '~/lib/logic/puzzles' import { apiId, makePuzzle, scoreSolution } from '~/lib/logic/puzzles'
@ -507,6 +508,19 @@ function create() {
if (made > 1) notify(`Connected ${made} wires`) if (made > 1) notify(`Connected ${made} wires`)
} }
/** 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. */
const fitHover = ref<{ spot: number; start: number } | null>(null)
watch(fits, () => (fitHover.value = null))
function connectFit(spot: number, start: number) {
const s = fits.value[spot]
if (!s) return
fitHover.value = null
connectMany(fitLinks(s, start))
}
/** /**
* The selected parts to another part's pins, in order: their outputs to * The selected parts to another part's pins, in order: their outputs to
* its inputs (dir 'out'), or its outputs to their inputs (dir 'in'). * its inputs (dir 'out'), or its outputs to their inputs (dir 'in').
@ -1780,6 +1794,9 @@ function create() {
dropRow, dropRow,
withDocked, withDocked,
withFollowers, withFollowers,
fits,
fitHover,
connectFit,
unplugMoved, unplugMoved,
moveRow, moveRow,
setRowGap, setRowGap,

View File

@ -169,9 +169,14 @@ export function plugInto(def: ComponentDef, end: CircuitNode, partId: string, ge
return true return true
} }
/** The part a free cable end touches with every wire of its single-wire side, so it counts as plugged in. */ /**
* The part a free cable end touches with all its wires, every one wired to
* it, so it counts as plugged in. One wire landing on a lamp doesn't make
* the whole end a plug.
*/
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
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
@ -298,13 +303,19 @@ export function nameTags(def: ComponentDef, end: CircuitNode, get: DefLookup): s
if (end.plug || !end.names?.some(Boolean)) return [] if (end.plug || !end.names?.some(Boolean)) return []
const nodes = new Map(def.nodes.map(n => [n.id, n])) const nodes = new Map(def.nodes.map(n => [n.id, n]))
const wires = singleWires(def, end) const wires = singleWires(def, end)
const mine = shapeOf(end, get)
const inward = end.kind === 'bundle'
return Array.from({ length: cableBits(end) }, (_, i) => { return Array.from({ length: cableBits(end) }, (_, i) => {
const name = end.names![i]?.trim() ?? '' const name = end.names![i]?.trim() ?? ''
const links = wires.filter(w => bitOf(end, w) === i) const links = wires.filter(w => bitOf(end, w) === i)
const known = links.length > 0 && links.every(w => { const known = links.length > 0 && links.every(w => {
const far = farEnd(end, w) const far = farEnd(end, w)
const other = nodes.get(far.node) const other = nodes.get(far.node)
return !!other && showsName(other, far.pin, name, get) if (!other) return false
// A part sitting right on the pin covers the name anyway.
const a = pinPos(end, mine, inward ? w.to.pin : w.from.pin, inward ? 'in' : 'out')
const b = pinPos(other, shapeOf(other, get), far.pin, inward ? 'out' : 'in')
return (a && b && a.x === b.x && a.y === b.y) || showsName(other, far.pin, name, get)
}) })
return known ? '' : name return known ? '' : name
}) })

207
app/lib/logic/fit.ts Normal file
View File

@ -0,0 +1,207 @@
// Where selected parts fit: runs of free pins on other parts that the whole
// selection can be wired to in one go (shown as green boxes to pick from),
// and the pins a part being dragged lands on (connected when it is dropped).
import { byPosition, type Link } from './bulk'
import { shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
import { SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PinRef } from './types'
export interface FitPin {
key: string
label: string
/** Place on the canvas, in grid units. */
x: number
y: number
}
export interface FitSpot {
/** The part whose pins the selection fits onto. */
part: string
/** Which of its pins: its outputs (they feed the selected parts) or its inputs (the selected parts feed them). */
side: 'in' | 'out'
/** Free pins next to each other on one edge, top to bottom. */
pins: FitPin[]
/** The selected parts' pins, top to bottom: one per pin of a fit. */
mine: PinRef[]
/** Middle of the selected parts' pins. */
from: Pt
/** Distance from there to the middle of the run. */
dist: number
}
type ShapeOf = (n: CircuitNode) => Shape
function wiredPins(def: ComponentDef) {
return {
in: new Set(def.wires.map(w => `${w.to.node}:${w.to.pin}`)),
out: new Set(def.wires.map(w => `${w.from.node}:${w.from.pin}`)),
}
}
/**
* The pin a fit wires on a selected part: its one free input (a lamp, an
* output pin, a gate with one input left), or the one unwired output of a
* switch, button, clock or gate. Null when it has none, or several.
*/
function plugPin(n: CircuitNode, dir: 'in' | 'out', shape: Shape, wired: ReturnType<typeof wiredPins>): string | null {
if (dir === 'in') {
if (['note', 'panel', 'bundle', 'split', 'hex'].includes(n.kind)) return null
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
const outs = shape.outputs.filter(p => !p.bus)
return outs.length === 1 && !wired.out.has(`${n.id}:${outs[0]!.key}`) ? outs[0]!.key : null
}
/** Whether the selected parts could be wired as a group at all: each has one free input, or each one unwired output. */
export function canFit(def: ComponentDef, get: DefLookup, selected: string[]): boolean {
const ids = new Set(selected)
const sel = def.nodes.filter(n => ids.has(n.id))
const wired = wiredPins(def)
return sel.length > 1 && (['in', 'out'] as const).some(dir => sel.every(n => plugPin(n, dir, shapeOf(n, get), wired)))
}
/**
* Places the selected parts fit as a group: on another part, a run of free
* pins on one edge at least as long as the selection, that their one free
* input each (or one unwired output each) can be wired to in order. The
* nearest `limit` runs, nearest first; none for fewer than two parts.
*/
export function fitSpots(def: ComponentDef, get: DefLookup, selected: string[], limit = 6, shapeFn?: ShapeOf): FitSpot[] {
const shape = shapeFn ?? ((n: CircuitNode) => shapeOf(n, get))
const ids = new Set(selected)
const sel = def.nodes.filter(n => ids.has(n.id)).sort(byPosition)
if (sel.length < 2) return []
const wired = wiredPins(def)
const spots: FitSpot[] = []
for (const side of ['out', 'in'] as const) {
const mineDir = side === 'out' ? 'in' : 'out'
const plugs = sel.map(n => plugPin(n, mineDir, shape(n), wired))
if (plugs.some(p => !p)) continue
const mine = sel.map((n, i) => ({ node: n.id, pin: plugs[i]! }))
const at = sel.map((n, i) => {
const s = shape(n)
const p = (mineDir === 'in' ? s.inputs : s.outputs).find(x => x.key === plugs[i])!
return [n.x + p.dx, n.y + p.dy] as Pt
})
const cx = at.reduce((s, p) => s + p[0], 0) / at.length
const cy = at.reduce((s, p) => s + p[1], 0) / at.length
const k = sel.length
for (const n of def.nodes) {
if (ids.has(n.id) || n.kind === 'note') continue
const s = shape(n)
const pins = (side === 'out' ? s.outputs : s.inputs).filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
let run: FitPin[] = []
const flush = () => {
if (run.length >= k) {
const mx = run[0]!.x
const my = (run[0]!.y + run[run.length - 1]!.y) / 2
spots.push({ part: n.id, side, pins: run, mine, from: [cx, cy], dist: Math.hypot(mx - cx, my - cy) })
}
run = []
}
for (const p of pins) {
const free = !(side === 'out' ? wired.out : wired.in).has(`${n.id}:${p.key}`)
const x = n.x + p.dx
if (!free || (run.length && run[0]!.x !== x)) flush()
if (free) run.push({ key: p.key, label: p.label, x, y: n.y + p.dy })
}
flush()
}
}
return spots.sort((a, b) => a.dist - b.dist).slice(0, limit)
}
/** The fit of a spot whose middle is nearest to row `y`: index of its first pin. */
export function fitStart(spot: FitSpot, y: number): number {
const k = spot.mine.length
let best = 0
let bestD = Infinity
for (let s = 0; s + k <= spot.pins.length; s++) {
const d = Math.abs((spot.pins[s]!.y + spot.pins[s + k - 1]!.y) / 2 - y)
if (d < bestD) {
bestD = d
best = s
}
}
return best
}
/** The wires a fit makes: the selected parts, top to bottom, to the spot's pins from `start` on. */
export function fitLinks(spot: FitSpot, start: number): Link[] {
return spot.mine.map((m, i) => {
const theirs = { node: spot.part, pin: spot.pins[start + i]!.key }
return spot.side === 'out' ? { from: theirs, to: m } : { from: m, to: theirs }
})
}
export interface DropPin {
node: string
pin: string
dir: 'in' | 'out'
bus: boolean
/** Wired already: an input can't take a second wire. */
wired: boolean
x: number
y: number
}
/** Every pin of the given parts, where it is now. */
export function dropPins(def: ComponentDef, nodes: CircuitNode[], shape: ShapeOf): DropPin[] {
const wired = wiredPins(def)
const out: DropPin[] = []
for (const n of nodes) {
const s = shape(n)
for (const p of s.inputs) out.push({ node: n.id, pin: p.key, dir: 'in', bus: !!p.bus, wired: wired.in.has(`${n.id}:${p.key}`), x: n.x + p.dx, y: n.y + p.dy })
for (const p of s.outputs) out.push({ node: n.id, pin: p.key, dir: 'out', bus: !!p.bus, wired: wired.out.has(`${n.id}:${p.key}`), x: n.x + p.dx, y: n.y + p.dy })
}
return out
}
/** A free pin of a moved part meeting a pin it can join: an output and an input that has no wire yet. */
const fits = (m: DropPin, s: DropPin) => m.dir !== s.dir && m.bus === s.bus && !m.wired && !(s.dir === 'in' && s.wired)
/**
* Parts being dragged onto other parts' pins: where a free pin of theirs
* lands on a pin it can join, or (`reach` 1) within a square of one.
* Returns the step that puts the nearest pair exactly on top of each other,
* and every wire that makes; null when nothing is in reach.
*/
export function dropLinks(moving: DropPin[], still: DropPin[], reach: 0 | 1 = 1): { shift: Pt; links: Link[] } | null {
const at = new Map<string, DropPin[]>()
for (const p of still) {
const key = `${p.x},${p.y}`
const list = at.get(key)
if (list) list.push(p)
else at.set(key, [p])
}
let best: { d: number; shift: Pt } | null = null
for (const m of moving) {
for (let dx = -reach; dx <= reach; dx++) {
for (let dy = -reach; dy <= reach; dy++) {
for (const s of at.get(`${m.x + dx},${m.y + dy}`) ?? []) {
const d = Math.hypot(dx, dy)
if (fits(m, s) && (!best || d < best.d)) best = { d, shift: [dx, dy] }
}
}
}
}
if (!best) return null
const [sx, sy] = best.shift
const links: Link[] = []
const taken = new Set<string>()
for (const m of moving) {
for (const s of at.get(`${m.x + sx},${m.y + sy}`) ?? []) {
const into = m.dir === 'in' ? m : s
const key = `${into.node}:${into.pin}`
if (!fits(m, s) || taken.has(key)) continue
taken.add(key)
const from = m.dir === 'out' ? m : s
links.push({ from: { node: from.node, pin: from.pin }, to: { node: into.node, pin: into.pin } })
break
}
}
return { shift: best.shift, links }
}

103
tests/fit.test.ts Normal file
View File

@ -0,0 +1,103 @@
import { describe, expect, it } from 'vitest'
import { dropLinks, dropPins, fitLinks, fitSpots, fitStart } from '../app/lib/logic/fit'
import { chipPins, shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import type { CircuitNode, ComponentDef, Project } from '../app/lib/logic/types'
/** An Adder 4 with nothing wired, two lamps and two switches next to it. */
function bench(): { p: Project; def: ComponentDef; ins: string[]; outs: string[] } {
const p = createProject({ examples: true })
const pins = chipPins(lookup(p)('ex-add4')!)
const def: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 'add', kind: 'chip', chip: 'ex-add4', x: 20, y: 0 },
{ id: 'l0', kind: 'lamp', x: 40, y: 2 },
{ id: 'l1', kind: 'lamp', x: 40, y: 5 },
{ id: 's0', kind: 'input', x: 5, y: 0 },
{ id: 's1', kind: 'input', x: 5, y: 3 },
],
wires: [],
}
p.components.push(def)
return { p, def, ins: pins.inputs.map(x => x.key), outs: pins.outputs.map(x => x.key) }
}
describe('where a selection fits', () => {
it('two lamps fit on any two outputs in a row, nearest first', () => {
const { p, def, outs } = bench()
const spots = fitSpots(def, lookup(p), ['l0', 'l1'])
expect(spots).toHaveLength(1)
const [spot] = spots
expect(spot!.side).toBe('out')
expect(spot!.pins.map(x => x.label)).toEqual(['S0', 'S1', 'S2', 'S3', 'Cout'])
// Pointing between S2 and S3 picks that pair; it wires top to bottom.
const start = fitStart(spot!, (spot!.pins[2]!.y + spot!.pins[3]!.y) / 2)
expect(start).toBe(2)
expect(fitLinks(spot!, start)).toEqual([
{ from: { node: 'add', pin: outs[2] }, to: { node: 'l0', pin: 'a' } },
{ from: { node: 'add', pin: outs[3] }, to: { node: 'l1', pin: 'a' } },
])
})
it('a wired pin splits the run', () => {
const { p, def, outs } = bench()
def.nodes.push({ id: 'x', kind: 'lamp', x: 40, y: 20 })
def.wires.push({ id: 'w', from: { node: 'add', pin: outs[2]! }, to: { node: 'x', pin: 'a' } })
const spots = fitSpots(def, lookup(p), ['l0', 'l1'])
expect(spots.map(s => s.pins.map(x => x.label))).toEqual(expect.arrayContaining([['S0', 'S1'], ['S3', 'Cout']]))
})
it('two switches fit on free inputs in a row', () => {
const { p, def, ins } = bench()
def.wires.push({ id: 'w', from: { node: 's0', pin: 'q' }, to: { node: 'add', pin: ins[4]! } })
def.nodes.push({ id: 's2', kind: 'input', x: 5, y: 6 })
const spots = fitSpots(def, lookup(p), ['s1', 's2'])
const runs = spots.filter(s => s.part === 'add').map(s => s.pins.map(x => x.label))
expect(runs).toEqual(expect.arrayContaining([['A0', 'A1', 'A2', 'A3'], ['B1', 'B2', 'B3', 'Cin']]))
expect(spots.every(s => s.side === 'in')).toBe(true)
})
it('parts with no single free pin to wire fit nowhere', () => {
const { p, def } = bench()
def.nodes.push({ id: 'n0', kind: 'nand', x: 5, y: 10 }, { id: 'n1', kind: 'nand', x: 5, y: 14 })
// Two free inputs each: no input side; their one free output each fits onto inputs.
const spots = fitSpots(def, lookup(p), ['n0', 'n1'])
expect(spots.length).toBeGreaterThan(0)
expect(spots.every(s => s.side === 'in')).toBe(true)
expect(fitSpots(def, lookup(p), ['l0'])).toEqual([])
})
})
describe('dropping a part onto pins', () => {
const pinsOf = (p: Project, def: ComponentDef, nodes: CircuitNode[]) => dropPins(def, nodes, n => shapeOf(n, lookup(p)))
it('an output dropped a square away from a free output joins it, lined up exactly', () => {
const { p, def, outs } = bench()
const add = def.nodes.find(n => n.id === 'add')!
const s1 = shapeOf(add, lookup(p)).outputs[1]!
const lamp = def.nodes.find(n => n.id === 'l0')!
lamp.x = add.x + s1.dx + 1
lamp.y = add.y + s1.dy
const res = dropLinks(pinsOf(p, def, [lamp]), pinsOf(p, def, def.nodes.filter(n => n !== lamp)))!
expect(res.shift).toEqual([-1, 0])
expect(res.links).toEqual([{ from: { node: 'add', pin: outs[1] }, to: { node: 'l0', pin: 'a' } }])
// A group only joins where pins land exactly.
expect(dropLinks(pinsOf(p, def, [lamp]), pinsOf(p, def, def.nodes.filter(n => n !== lamp)), 0)).toBeNull()
})
it('an input that has a wire takes no second one', () => {
const { p, def, ins } = bench()
const add = def.nodes.find(n => n.id === 'add')!
def.wires.push({ id: 'w', from: { node: 's0', pin: 'q' }, to: { node: 'add', pin: ins[0]! } })
const a0 = shapeOf(add, lookup(p)).inputs[0]!
const sw = def.nodes.find(n => n.id === 's1')!
const q = shapeOf(sw, lookup(p)).outputs[0]!
sw.x = add.x + a0.dx - q.dx
sw.y = add.y + a0.dy - q.dy
const res = dropLinks(pinsOf(p, def, [sw]), pinsOf(p, def, def.nodes.filter(n => n !== sw)))
expect(res?.links.some(l => l.to.pin === ins[0])).not.toBe(true)
})
})

View File

@ -159,6 +159,21 @@ describe('plugged cable ends', () => {
expect(res.bundle.plug).toBe('add') expect(res.bundle.plug).toBe('add')
}) })
it('one wire landing on a part does not plug the whole end in', () => {
const { p, def } = adder()
const res = bundleWires(def, ['wo0', 'wo1', 'wo2', 'wo3', 'wo4'], lookup(p))
if (!res.ok) throw new Error(res.error)
// Only the last wire runs on, to a lamp sitting right on its pin.
def.wires = def.wires.filter(w => w.from.node !== res.split.id || w.from.pin === 'b4')
const lamp = node(def, 'l4')
const pin = shapeOf(res.split, lookup(p)).outputs[4]!
lamp.x = res.split.x + pin.dx
lamp.y = res.split.y + pin.dy
syncCables(p)
expect(touches(p, def, res.split)).toBe(true)
expect(res.split.plug).toBeUndefined()
})
it('takes the spacing of pins further apart', () => { it('takes the spacing of pins further apart', () => {
const p = createProject({ examples: true }) const p = createProject({ examples: true })
const get = lookup(p) const get = lookup(p)