Merge branch 'feat/drag'

This commit is contained in:
Fabian @ Blax Software 2026-10-26 18:54:28 +01:00
commit ef9a4a2a6b
6 changed files with 466 additions and 70 deletions

View File

@ -34,6 +34,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
- Tidy wiring (Settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
- Moving parts (drag one or several, or the arrow keys): wires between parts that move together go along with their bends. A wire to a part that stays keeps its hand-placed bends as long as the way through them stays clear (no part under it, a cable by its full width, no line of another signal, no pin it does not end on) and lets go of the others, which are laid out anew around the parts; a part put down on a wire's bends does the same to that wire. What shows while dragging is what stays, and one Ctrl+Z undoes the move.
- Saves are handled like a game: the main menu's "Load game" lists every save (open, rename, copy, delete, savegames, recently deleted, new, open a file), and in the editor Esc (with nothing selected) or the project button opens the pause menu: Resume, Save, Save as copy, Load, Settings, How to play, Main menu. Export a project file, open a file as a new project, or add the components of a file to the open project.
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). One save per project on every device: if two computers changed the same project, the newer save wins everywhere and the other one is kept as a savegame of that project (never as a second project). A new browser keeps its starter project unsaved until something changes in it, and while signed in the main menu waits for the account's saves before anything can be started, so a second device never makes a twin.
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
@ -52,7 +53,8 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
- `state.ts` finds the gates on feedback loops (strongly connected gates, Tarjan) and packs those that are 1 for the project: each node id once, each gate as the path levels it shares with the gate before plus the rest. Restoring runs the gates in the order signals flow, so the gates in front of a latch are right before the latch reads them; ids that no longer exist are ignored.
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout), and after a move keeps the hand-placed bends that still leave a clear way (`settleCorners`).
- `move.ts` moves parts for a drag and the arrow keys, always from where they started, with their wires.
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.

View File

@ -10,6 +10,7 @@ import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { latchLayout, latchSeam } from '~/lib/logic/latch'
import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move'
import { wirePath, type HopSpan } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
import { inputCount } from '~/lib/logic/wide'
@ -129,6 +130,12 @@ function cablePx(w: Wire | undefined): number | undefined {
if (conn) return Math.min(8, Math.max(2, ed.getDef.value.conn?.(conn)?.lines.length ?? 2)) * LANE * G + 6
}
/** Puts the parts of a move `dx`, `dy` squares from where they started, with their wires (cables as wide as drawn). */
function moveTo(start: MoveStart, dx: number, dy: number) {
const byId = new Map(def.value.wires.map(w => [w.id, w]))
moveParts(def.value, start, dx, dy, shapes.value, { widthOf: id => cablePx(byId.get(id)) })
}
const routes = computed<Route[]>(() => {
const byId = new Map(def.value.wires.map(w => [w.id, w]))
const routed = circuitRoutes(def.value, shapes.value, { tidy: !!ed.project.value.settings.tidy, widthOf: id => cablePx(byId.get(id)) })
@ -478,10 +485,10 @@ type Drag =
| {
kind: 'move'
start: Pt
orig: Map<string, Pt>
/** Docked panels moved without their component: they only slide sideways. */
lockY: Set<string>
wires: Map<Wire, Pt[]>
/** Where the moving parts and the corners were: every step moves from there. */
orig: MoveStart
/** Squares moved so far. */
at: Pt
moved: boolean
node: CircuitNode
toggle: boolean
@ -493,8 +500,8 @@ type Drag =
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
/** A cable end brought close to the part its wires run to: dropped, it plugs in. */
plug?: { part: string; rings: Pt[] } | null
/** A cable end brought close to the part its wires run to: dropped, it plugs in (at `at`). */
plug?: { part: string; rings: Pt[]; at: Pt } | null
}
| {
kind: 'wire'
@ -525,16 +532,6 @@ function isDoubleClick(id: string) {
return dbl
}
/** Wires whose corner points travel with the nodes being moved. */
function wiresToShift(moving: Set<string>): Map<Wire, Pt[]> {
const out = new Map<Wire, Pt[]>()
for (const wire of def.value.wires) {
const both = moving.has(wire.from.node) && moving.has(wire.to.node)
if (wire.pts && (both || wireSelected.value.has(wire.id))) out.set(wire, wire.pts.map(p => [...p] as Pt))
}
return out
}
function onPointerDown(e: PointerEvent) {
const w = toWorld(e)
const v = view.value
@ -653,20 +650,11 @@ function onPointerDown(e: PointerEvent) {
if (node.kind === 'button') ed.press(node, true)
if (row && !multi) ed.pressRow(node, row, true)
const ids = ed.withFollowers(selected.value.has(id) ? ed.selection.value : [id])
const orig = new Map<string, Pt>()
const lockY = new Set<string>()
for (const sid of ids) {
const n = nodeMap.value.get(sid)
if (!n) continue
orig.set(sid, [n.x, n.y])
if (n.attach && !ids.has(n.attach)) lockY.add(sid)
}
drag.value = {
kind: 'move',
start: w,
orig,
lockY,
wires: wiresToShift(ids),
orig: moveStart(def.value, ids, ed.wireSel.value),
at: [0, 0],
moved: false,
node,
toggle: (node.kind === 'input' || !!row) && !multi,
@ -741,24 +729,20 @@ function onPointerMove(e: PointerEvent) {
d.moved = true
if (d.node.kind === 'button') ed.press(d.node, 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)!)
const moving = def.value.nodes.filter(n => d.orig.nodes.has(n.id))
d.still = dropPins(def.value, def.value.nodes.filter(n => !d.orig.nodes.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 }))
const at = d.from.map(p => ({ ...p, x: p.x + dx, y: d.orig.lockY.has(p.node) ? p.y : p.y + dy }))
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) {
const n = nodeMap.value.get(id)
if (n) {
n.x = x + dx
n.y = d.lockY.has(id) ? y : y + dy
}
if (dx !== d.at[0] || dy !== d.at[1]) {
d.at = [dx, dy]
moveTo(d.orig, dx, dy)
}
for (const [wire, pts] of d.wires) wire.pts = pts.map(([x, y]) => [x + dx, y + dy])
d.plug = d.moved && d.grabbed === 1 && !e.altKey ? plugNear(d.node) : null
break
}
case 'wire':
@ -946,23 +930,20 @@ function onPointerUp(e: PointerEvent) {
if (d.node.kind === 'button') ed.press(d.node, false)
if (d.row && !d.moved) ed.pressRow(d.node, d.row, false)
if (d.moved && d.plug) {
ed.unplugMoved(new Set(d.orig.keys()))
// Onto the pins it plugs into, its wires settled there as for any move.
const [ox, oy] = d.orig.nodes.get(d.node.id)!
moveTo(d.orig, d.plug.at[0] - ox, d.plug.at[1] - oy)
ed.unplugMoved(new Set(d.orig.nodes.keys()))
if (d.node.kind === 'bundle' || d.node.kind === 'split') ed.plugEnd(d.node)
else ed.latchPart(d.node)
} else 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()))
moveTo(d.orig, d.at[0] + sx, d.at[1] + sy)
ed.unplugMoved(new Set(d.orig.nodes.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.nodes.keys()))
ed.commit(false)
} else if (d.toggle && d.row) ed.toggleRow(d.node, d.row)
else if (d.toggle) ed.toggleInput(d.node)
@ -1053,20 +1034,11 @@ function nudge(dx: number, dy: number) {
const ids = ed.withFollowers(ed.selection.value)
if (!ids.size && !ed.wireSel.value.length) return
ed.unplugMoved(ids)
for (const n of def.value.nodes) {
if (!ids.has(n.id)) continue
n.x += dx
if (!n.attach || ids.has(n.attach)) n.y += dy
}
// A wire moved on its own keeps the shape it has.
for (const r of routes.value) {
const both = ids.has(r.wire.from.node) && ids.has(r.wire.to.node)
if (wireSelected.value.has(r.wire.id)) {
const pts = r.wire.pts ?? r.pts.slice(1, -1)
r.wire.pts = pts.map(([x, y]) => [x + dx, y + dy])
} else if (both && r.wire.pts) {
r.wire.pts = r.wire.pts.map(([x, y]) => [x + dx, y + dy])
}
if (wireSelected.value.has(r.wire.id) && !r.wire.pts && !ids.has(r.wire.from.node) && !ids.has(r.wire.to.node)) r.wire.pts = r.pts.slice(1, -1)
}
moveTo(moveStart(def.value, ids, ed.wireSel.value), dx, dy)
ed.commit(false)
}
@ -1470,7 +1442,7 @@ function openMenuForSelection() {
* close to where it would latch onto the part it is wired to: the pins it
* would latch onto.
*/
function plugNear(n: CircuitNode): { part: string; rings: Pt[] } | null {
function plugNear(n: CircuitNode): { part: string; rings: Pt[]; at: Pt } | null {
if (n.kind !== 'bundle' && n.kind !== 'split') {
const host = ed.latchTargetOf({ ...n, latch: undefined })
const lay = host && latchLayout(def.value, n, host, ed.getDef.value)
@ -1482,14 +1454,14 @@ function plugNear(n: CircuitNode): { part: string; rings: Pt[] } | null {
.map(w => (w.to.node === n.id ? s.inputs.find(p => p.key === w.to.pin) : s.outputs.find(p => p.key === w.from.pin)))
.filter(p => !!p)
.map(p => [lay.x + p.dx, lay.y + p.dy] as Pt)
return { part: host.id, rings }
return { part: host.id, rings, at: [lay.x, lay.y] }
}
if (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) }
return { part: part.id, rings: lay.offsets.map(o => [x, lay.y + o] as Pt), at: [lay.x, lay.y] }
}
/** Where latched parts touch their part: a contact strip along the joint, held by a clamp at each end. */
@ -1512,7 +1484,7 @@ const dropRings = computed(() => {
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 []
const moving = new Set(d.orig.keys())
const moving = new Set(d.orig.nodes.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)!

View File

@ -17,6 +17,7 @@ const SHORTCUTS: [string, string][] = [
['Double-click a wire', 'Select the whole signal'],
['Shift + click', 'Add parts or wires to the selection'],
['Arrow keys', 'Move the selection one step (Shift: four)'],
['Drag several parts', 'Wires between them keep their shape; a wire to a part that stays keeps its bends while they stay clear of parts and other wires'],
['Double-click a component', 'Open it and see inside'],
['Drag on empty space', 'Select parts; across wires (no parts in the box) it selects every wire it crosses'],
['Drag right to left', 'Select everything the box touches, parts and wires (green box)'],

69
app/lib/logic/move.ts Normal file
View File

@ -0,0 +1,69 @@
// Moving parts by whole squares, the same way for a drag and for the arrow
// keys. A drag moves from where the parts started on every step, so what
// shows while dragging is what stays when the parts are let go. Wires come
// along: one between two moved parts keeps its shape, the hand-placed
// corners of the others are looked at again (routing.ts, settleCorners).
import type { Pt, Shape } from './geometry'
import { settleCorners, type RouteOptions } from './routing'
import type { ComponentDef } from './types'
/** Where the moving parts and the wires' corners were when the move started. */
export interface MoveStart {
/** Parts that move (followers included), where they were. */
nodes: Map<string, Pt>
/** Panels docked to a part that stays: they only slide sideways. */
lockY: Set<string>
/** Corners of every wire that has hand-placed ones. */
pts: Map<string, Pt[]>
/** Wires picked along with the parts. */
wires: Set<string>
}
export function moveStart(def: ComponentDef, ids: Set<string>, wires: Iterable<string> = []): MoveStart {
const nodes = new Map<string, Pt>()
const lockY = new Set<string>()
for (const n of def.nodes) {
if (!ids.has(n.id)) continue
nodes.set(n.id, [n.x, n.y])
if (n.attach && !ids.has(n.attach)) lockY.add(n.id)
}
const pts = new Map<string, Pt[]>()
for (const w of def.wires) if (w.pts) pts.set(w.id, w.pts.map(p => [p[0], p[1]] as Pt))
return { nodes, lockY, pts, wires: new Set(wires) }
}
/**
* Puts the moving parts `dx`, `dy` squares from where they started. A wire
* whose ends both moved the same way takes its corners along, and so does a
* picked wire whose ends both stay (a wire moved on its own goes where it is
* put). Every other wire starts again from the corners it had, and keeps
* those that still leave it a clear way.
*/
export function moveParts(def: ComponentDef, start: MoveStart, dx: number, dy: number, shapes: Map<string, Shape>, opts: RouteOptions = {}) {
const by = new Map<string, Pt>()
for (const n of def.nodes) {
const at = start.nodes.get(n.id)
if (!at) continue
const step: Pt = [dx, start.lockY.has(n.id) ? 0 : dy]
n.x = at[0] + step[0]
n.y = at[1] + step[1]
if (step[0] || step[1]) by.set(n.id, step)
}
const carried = new Set<string>()
for (const w of def.wires) {
const pts = start.pts.get(w.id)
if (!pts) continue
const a = by.get(w.from.node)
const b = by.get(w.to.node)
const step = a && b && a[0] === b[0] && a[1] === b[1] ? a : !a && !b && start.wires.has(w.id) ? ([dx, dy] as Pt) : undefined
w.pts = pts.map(([x, y]) => (step ? [x + step[0], y + step[1]] : [x, y]))
if (step) carried.add(w.id)
}
const byId = new Map(def.wires.map(w => [w.id, w]))
for (const [id, pts] of settleCorners(def, shapes, { by, carried }, opts)) {
const w = byId.get(id)!
if (pts) w.pts = pts
else delete w.pts
}
}

View File

@ -201,6 +201,7 @@ class BodyIndex {
}
const pinKey = (x: number, y: number) => (x + 50_000) * 100_000 + y + 50_000
const pinKeys = (pins: Pt[]) => new Set(pins.map(([x, y]) => pinKey(x, y)))
/**
* Cost of a route; stops counting once it is above `limit`. `fromPin`: it
@ -979,14 +980,20 @@ export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[], opts:
/** Routes every wire of a circuit, given the shapes of its parts. */
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions = {}): Routed[] {
const c = circuitOf(def, shapes, opts)
return routeAll(c.inputs, [...c.bodies.values()], [...c.pins.values()].flat(), opts)
}
/** A circuit's wires to route, and the body and pins of each of its parts (by part id). */
function circuitOf(def: ComponentDef, shapes: Map<string, Shape>, opts: RouteOptions) {
const nodes = new Map(def.nodes.map(n => [n.id, n]))
const bodies: Box[] = []
const pins: Pt[] = []
const bodies = new Map<string, Box>()
const pins = new Map<string, Pt[]>()
for (const n of def.nodes) {
const s = shapes.get(n.id)
if (!s) continue
if (n.kind !== 'note') bodies.push({ x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
for (const p of [...s.inputs, ...s.outputs]) pins.push([n.x + p.dx, n.y + p.dy])
if (n.kind !== 'note') bodies.set(n.id, { x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
pins.set(n.id, [...s.inputs, ...s.outputs].map(p => [n.x + p.dx, n.y + p.dy] as Pt))
}
const inputs: RouteInput[] = []
for (const w of def.wires) {
@ -1008,5 +1015,106 @@ export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opt
...(px ? { h: px / 2 / GRID } : {}),
})
}
return routeAll(inputs, bodies, pins, opts)
return { inputs, bodies, pins }
}
// ── Corners after a move ────────────────────────────────────────────
// Hand-placed corners are fixed lines the router routes around, so after
// parts move they are looked at again by the router's own rules: a route
// through them must not run over or under a part (by its full width), along
// a line of another signal or over someone else's pin. Only wires that
// moved or that a moved part now lies on are looked at.
export interface Moved {
/** How far each part that moved went. */
by: Map<string, Pt>
/** Wires whose corners went along with the parts. */
carried: Set<string>
}
type Side = 'a' | 'b' | ''
/**
* Hand-placed corners after parts moved. A wire carried along whole keeps
* its corners unless something that did not come along is now in its way.
* A wire with a moved end keeps the corners on the side that stayed for as
* long as the route through them is clear, and lets go of the others; a
* wire that a moved part now lies on does the same from either side. What
* is let go the router lays out. Returns the corners of every wire looked
* at again; null where none are left.
*/
export function settleCorners(def: ComponentDef, shapes: Map<string, Shape>, moved: Moved, opts: RouteOptions = {}): Map<string, Pt[] | null> {
const out = new Map<string, Pt[] | null>()
if (!moved.by.size) return out
const { inputs, bodies, pins } = circuitOf(def, shapes, opts)
const wires = new Map(def.wires.map(w => [w.id, w]))
// How far a part went, as a key: parts with the same one moved together.
const went = (id: string) => `${moved.by.get(id) ?? [0, 0]}`
// The parts that did not go the same way, with their pins: what can be in the way of a wire that came along.
const apart = new Map<string, { bodies: BodyIndex; pins: Set<number> }>()
const apartFrom = (k: string) => {
let s = apart.get(k)
if (!s) {
const ids = new Set(def.nodes.filter(n => went(n.id) !== k).map(n => n.id))
const of = <T>(m: Map<string, T>) => [...m].filter(([id]) => ids.has(id)).map(([, v]) => v)
s = { bodies: new BodyIndex(of(bodies)), pins: pinKeys(of(pins).flat()) }
apart.set(k, s)
}
return s
}
const hand = inputs.filter(w => w.pts?.length && (w.a[0] !== w.b[0] || w.a[1] !== w.b[1]))
const occ = new Occupancy()
const look = new Map<RouteInput, Side>()
const whole: RouteInput[] = []
// The parts that did not stay where they were.
const moving = apartFrom('0,0')
const none = new Occupancy()
for (const w of hand) {
const { from, to } = wires.get(w.id)!
const a = moved.by.has(from.node)
const b = moved.by.has(to.node)
if (moved.carried.has(w.id)) {
if (a && b && went(from.node) === went(to.node)) whole.push(w)
else look.set(w, '')
} else if (a || b) look.set(w, a && b ? '' : a ? 'b' : 'a')
else {
// Its ends stayed: looked at when a moved part, or a pin of one, now lies on it.
const r = routeWire(w.a, w.b, w.pts)
if (cost(r, w.net, none, moving.bodies, moving.pins, Infinity, w.h).penalty > 0) look.set(w, '')
else occ.add(r, w.net, w.h)
}
}
// Carried along whole: only what did not come along, and the lines that stay, can be in the way.
const clear = whole.filter(w => {
const s = apartFrom(went(wires.get(w.id)!.from.node))
const ok = cost(routeWire(w.a, w.b, w.pts), w.net, occ, s.bodies, s.pins, Infinity, w.h).penalty === 0
if (!ok) look.set(w, '')
return ok
})
for (const w of clear) occ.add(routeWire(w.a, w.b, w.pts), w.net, w.h)
const all = { bodies: new BodyIndex([...bodies.values()]), pins: pinKeys([...pins.values()].flat()) }
for (const w of hand) {
const side = look.get(w)
if (side === undefined) continue
const kept = keepCorners(w, side, occ, all.bodies, all.pins)
out.set(w.id, kept)
if (kept) occ.add(routeWire(w.a, w.b, kept), w.net, w.h)
}
return out
}
/**
* The most hand-placed corners of a wire that still make a clear route,
* counted from its source ('a'), its target ('b') or either end (''), given
* as the corners of that route. Null when no corners do.
*/
function keepCorners(w: RouteInput, side: Side, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] | null {
const pts = w.pts!
for (let k = pts.length; k > 0; k--) {
for (const from of side ? [side] : k === pts.length ? ['a'] : ['a', 'b']) {
const route = routeWire(w.a, w.b, from === 'a' ? pts.slice(0, k) : pts.slice(pts.length - k))
if (route.length > 2 && cost(route, w.net, occ, bodies, pins, Infinity, w.h).penalty === 0) return route.slice(1, -1)
}
}
return null
}

244
tests/drag.test.ts Normal file
View File

@ -0,0 +1,244 @@
import { describe, expect, it } from 'vitest'
import { LANE } from '../app/lib/logic/cables'
import { cableBits, GRID, shapeOf, type Pt, type Shape } from '../app/lib/logic/geometry'
import { latchedTo } from '../app/lib/logic/latch'
import { moveParts, moveStart } from '../app/lib/logic/move'
import { createProject, lookup } from '../app/lib/logic/ops'
import { circuitRoutes, type Routed } from '../app/lib/logic/routing'
import type { CircuitNode, ComponentDef, Wire } from '../app/lib/logic/types'
interface Circuit {
def: ComponentDef
shapes: Map<string, Shape>
}
function circuit(nodes: CircuitNode[], wires: Wire[]): Circuit {
const p = createProject({ examples: false })
const def: ComponentDef = { id: 'root', name: 'Root', symbol: 'box', nodes, wires }
p.components.push(def)
const get = lookup(p)
return { def, shapes: new Map(nodes.map(n => [n.id, shapeOf(n, get)])) }
}
const part = (id: string, kind: CircuitNode['kind'], x: number, y: number, more: Partial<CircuitNode> = {}): CircuitNode => ({ id, kind, x, y, ...more })
const wire = (id: string, from: string, to: string, pts?: Pt[]): Wire => {
const [fn, fp] = from.split('.')
const [tn, tp] = to.split('.')
return { id, from: { node: fn!, pin: fp! }, to: { node: tn!, pin: tp! }, ...(pts ? { pts } : {}) }
}
/** Drawn width of a cable in pixels, as the canvas draws it: a ribbon's sleeve with its outline. */
const widthOf = (c: Circuit) => (id: string) => {
const w = c.def.wires.find(x => x.id === id)
const from = w && c.def.nodes.find(n => n.id === w.from.node)
return from?.kind === 'bundle' ? cableBits(from) * LANE * GRID + 6 : undefined
}
/** Moves parts the way the canvas does: in steps from where they started, as a drag goes. */
function drag(c: Circuit, ids: string[], steps: Pt[], picked: string[] = []) {
const start = moveStart(c.def, new Set(ids), picked)
for (const [dx, dy] of steps) moveParts(c.def, start, dx, dy, c.shapes, { widthOf: widthOf(c) })
}
const routes = (c: Circuit) => circuitRoutes(c.def, c.shapes, { widthOf: widthOf(c) })
/**
* Lines drawn over or under a part, as "wire>part": a line counts as wide
* as it is drawn, and only its ends may touch a part, on their own pins.
*/
function underParts(c: Circuit, rs: Routed[]): string[] {
const out: string[] = []
for (const r of rs) {
const p = r.draw
for (let i = 0; i < p.length - 1; i++) {
let [ax, ay] = p[i]!
let [bx, by] = p[i + 1]!
// Pins that touch (a latched part): nothing is drawn.
if (ax === bx && ay === by) continue
const dx = Math.sign(bx - ax)
const dy = Math.sign(by - ay)
// The ends on the wire's own pins touch their parts.
if (i === 0) [ax, ay] = [ax + dx * r.h, ay + dy * r.h]
if (i === p.length - 2) [bx, by] = [bx - dx * r.h, by - dy * r.h]
if ((bx - ax) * dx < 0 || (by - ay) * dy < 0) continue
const m = r.h - 1e-6
for (const n of c.def.nodes) {
if (n.kind === 'note') continue
const b = c.shapes.get(n.id)!.body
const x0 = n.x + b.x - m
const x1 = n.x + b.x + b.w + m
const y0 = n.y + b.y - m
const y1 = n.y + b.y + b.h + m
const lx = Math.min(ax, bx)
const hx = Math.max(ax, bx)
const ly = Math.min(ay, by)
const hy = Math.max(ay, by)
if (ly < y1 && hy > y0 && lx < x1 && hx > x0) out.push(`${r.id}>${n.id}`)
}
}
}
return out
}
/** Lines of different signals drawn on or against each other (or routed so, `grid`), as "wire/wire". */
function touching(rs: Routed[], grid = false): string[] {
const segs: { id: string; net: string; h: number; horizontal: boolean; c: number; lo: number; hi: number }[] = []
for (const r of rs) {
const p = grid ? r.grid : r.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ax === bx && ay === by) continue
const horizontal = ay === by
segs.push({ id: r.id, net: r.net, h: r.h, horizontal, c: horizontal ? ay : ax, lo: horizontal ? Math.min(ax, bx) : Math.min(ay, by), hi: horizontal ? Math.max(ax, bx) : Math.max(ay, by) })
}
}
const out: string[] = []
for (let i = 0; i < segs.length; i++) {
for (let j = i + 1; j < segs.length; j++) {
const s = segs[i]!
const t = segs[j]!
if (s.net === t.net || s.horizontal !== t.horizontal || Math.abs(s.c - t.c) >= s.h + t.h - 1e-9) continue
if (Math.min(s.hi, t.hi) - Math.max(s.lo, t.lo) > 1e-9) out.push(`${s.id}/${t.id}`)
}
}
return out
}
const shifted = (route: Pt[], dx: number, dy: number) => route.map(([x, y]) => [x + dx, y + dy])
const routeOf = (rs: Routed[], id: string) => rs.find(r => r.id === id)!.grid
describe('dragging parts', () => {
it('a wire to a part that moves a little keeps its hand-placed corners, stretched to the pin', () => {
const c = circuit([part('s', 'input', 0, 0), part('l', 'output', 12, 6)], [wire('w', 's.q', 'l.a', [[5, 0], [5, 6]])])
drag(c, ['l'], [[0, -2]])
expect(c.def.wires[0]!.pts).toEqual([[5, 0], [5, 4]])
expect(routeOf(routes(c), 'w')).toEqual([[2, 0], [5, 0], [5, 4], [12, 4]])
})
it('a wire whose part moves past its hand-placed corners comes into the pin from the left, not through the part', () => {
const c = circuit([part('s', 'input', 0, 0), part('g', 'nand', 14, 0)], [wire('w', 's.q', 'g.a', [[6, 0], [6, 4], [11, 4], [11, 0]])])
drag(c, ['g'], [[-2, 0], [-5, 0]])
const rs = routes(c)
expect(underParts(c, rs)).toEqual([])
expect(routeOf(rs, 'w').at(-1)).toEqual([9, 0])
})
it('parts moved together keep the wires between them; wires to parts that stay go around what is in the way', () => {
const c = circuit(
[
part('i1', 'input', 0, 0),
part('i2', 'input', 0, 4),
part('g1', 'nand', 10, 0),
part('g2', 'nand', 20, 3),
part('o', 'output', 32, 4),
// A part that stays, beside where the moved parts go.
part('x', 'nand', 3, 7),
],
[
wire('w1', 'i1.q', 'g1.a'),
wire('w2', 'i2.q', 'g1.b', [[5, 4], [5, 2]]),
wire('w3', 'g1.q', 'g2.a', [[17, 1], [17, 3]]),
wire('w4', 'g1.q', 'g2.b'),
wire('w5', 'g2.q', 'o.a'),
],
)
const before = routes(c)
drag(c, ['g1', 'g2'], [[0, 3], [1, 6], [0, 8]])
const rs = routes(c)
expect(underParts(c, rs)).toEqual([])
expect(touching(rs)).toEqual([])
// Between the two moved parts: the same shape, moved along.
expect(routeOf(rs, 'w3')).toEqual(shifted(routeOf(before, 'w3'), 0, 8))
expect(routeOf(rs, 'w4')).toEqual(shifted(routeOf(before, 'w4'), 0, 8))
expect(c.def.wires.find(w => w.id === 'w3')!.pts).toEqual([[17, 9], [17, 11]])
})
it('a wire whose stretched corners would run along another signal lets go of them', () => {
const c = circuit(
[part('s1', 'input', -2, 0), part('l1', 'output', 30, 0), part('s2', 'input', 0, 12), part('l2', 'output', 30, 9)],
[wire('w1', 's1.q', 'l1.a', [[10, 0], [10, 6], [20, 6], [20, 0]]), wire('w2', 's2.q', 'l2.a', [[4, 12], [4, 9], [16, 9]])],
)
drag(c, ['l2'], [[0, -3]])
const rs = routes(c)
expect(touching(rs, true)).toEqual([])
expect(underParts(c, rs)).toEqual([])
// The other wire is left as it was.
expect(c.def.wires[0]!.pts).toEqual([[10, 0], [10, 6], [20, 6], [20, 0]])
})
it('everything moved at once keeps every corner, even of wires that already shared a line', () => {
const c = circuit(
[part('s1', 'input', -2, 0), part('l1', 'output', 10, 0), part('s2', 'input', -2, 4), part('l2', 'output', 10, 4)],
[wire('a', 's1.q', 'l1.a', [[2, 0], [2, 4], [8, 4], [8, 0]]), wire('b', 's2.q', 'l2.a', [[1, 4], [9, 4]])],
)
drag(c, ['s1', 'l1', 's2', 'l2'], [[3, 5]], ['a', 'b'])
expect(c.def.wires.map(w => w.pts)).toEqual([shifted([[2, 0], [2, 4], [8, 4], [8, 0]], 3, 5), shifted([[1, 4], [9, 4]], 3, 5)])
})
it('a wire moved on its own goes where it is put', () => {
const c = circuit([part('s', 'input', 0, 0), part('l', 'output', 12, 6)], [wire('w', 's.q', 'l.a', [[5, 0], [5, 6]])])
drag(c, [], [[1, 0]], ['w'])
expect(c.def.wires[0]!.pts).toEqual([[6, 0], [6, 6]])
})
it('a part moved onto a wire that stays: the wire lets go of the corners under it', () => {
const c = circuit(
[part('a', 'input', 0, 0), part('b', 'output', 30, 0), part('p', 'nand', 12, -10)],
[wire('w', 'a.q', 'b.a', [[8, 0], [8, 6], [20, 6], [20, 0]])],
)
drag(c, ['p'], [[0, 15]])
const rs = routes(c)
expect(underParts(c, rs)).toEqual([])
expect(touching(rs)).toEqual([])
})
it('what shows while dragging is what stays: corners let go on the way come back', () => {
const make = () =>
circuit([part('a', 'input', 0, 0), part('b', 'output', 30, 0), part('p', 'nand', 12, -10)], [wire('w', 'a.q', 'b.a', [[8, 0], [8, 6], [20, 6], [20, 0]])])
const c = make()
// Down over the wire's dip and on below it.
drag(c, ['p'], [[0, 5], [0, 15], [0, 16], [0, 20]])
const once = make()
drag(once, ['p'], [[0, 20]])
expect(c.def).toEqual(once.def)
expect(c.def.wires[0]!.pts).toEqual([[8, 0], [8, 6], [20, 6], [20, 0]])
expect(underParts(c, routes(c))).toEqual([])
})
it('a cable keeps clear of parts by its full width', () => {
// An 8-wire cable with a hand-placed hump; a part sits below where its end goes.
const c = circuit(
[part('bu', 'bundle', 0, 0, { bits: 8 }), part('sp', 'split', 30, 0, { bits: 8 }), part('x', 'nand', 18, 12)],
[wire('c', 'bu.q', 'sp.a', [[5, 3], [5, 10], [14, 10], [14, 3]])],
)
drag(c, ['sp'], [[0, 8]])
const rs = routes(c)
expect(rs[0]!.h).toBeGreaterThan(0.5)
expect(underParts(c, rs)).toEqual([])
// A plain wire there passes the part with room to spare and keeps its corners.
const plain = circuit(
[part('s', 'input', -1, 3), part('l', 'output', 30, 3), part('x', 'nand', 18, 12)],
[wire('w', 's.q', 'l.a', [[5, 3], [5, 10], [14, 10], [14, 3]])],
)
drag(plain, ['l'], [[0, 8]])
expect(plain.def.wires[0]!.pts?.length).toBeGreaterThan(1)
expect(underParts(plain, routes(plain))).toEqual([])
})
it('a part latched onto another moves with it, and its wires to parts that stay settle the same way', () => {
const c = circuit(
[part('g', 'nand', 10, 0), part('o', 'output', 14, 1, { latch: 'g' }), part('l', 'lamp', 30, 1), part('x', 'nand', 18, 3)],
[wire('in', 'g.q', 'o.a'), wire('w', 'o.q', 'l.a', [[20, 1], [20, -4], [26, -4], [26, 1]])],
)
const ids = new Set(['g'])
for (const n of latchedTo(c.def, ids)) ids.add(n.id)
drag(c, [...ids], [[0, 6]])
const o = c.def.nodes.find(n => n.id === 'o')!
expect([o.x, o.y]).toEqual([14, 7])
const rs = routes(c)
expect(routeOf(rs, 'in')).toEqual([[14, 7], [14, 7]])
expect(underParts(c, rs)).toEqual([])
expect(touching(rs)).toEqual([])
})
})