logigate/app/lib/logic/move.ts

66 lines
2.6 KiB
TypeScript
Raw Normal View History

// 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>
/** 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>()
for (const n of def.nodes) {
if (!ids.has(n.id)) continue
nodes.set(n.id, [n.x, n.y])
}
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, 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, 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
}
}