// Project operations that don't depend on the UI: creating, packaging, // copying and cleaning up components. They mutate the project in place. import type { Challenge } from './challenges' import { inputKeys, outputKeys } from './compile' import { exampleLibrary, starterCircuit } from './examples' import { chipPins, shapeOf, type DefLookup } from './geometry' import type { CircuitNode, ComponentDef, NodeKind, Project, Wire } from './types' export function uid(prefix = ''): string { return prefix + Math.random().toString(36).slice(2, 10) } /** Deep copy that also works on Vue reactive proxies (structuredClone does not). */ function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T } export function lookup(project: Project): DefLookup { const map = new Map(project.components.map(d => [d.id, d])) return id => map.get(id) } export function createProject(opts: { examples: boolean; name?: string }): Project { return { version: 1, name: opts.name ?? (opts.examples ? 'NAND to computer' : 'New project'), components: [starterCircuit(), ...(opts.examples ? exampleLibrary() : [])], openId: 'main', settings: { symbols: 'iec', flow: true }, solved: [], } } /** Adds the example parts that are missing. Returns how many were added. */ export function addExamples(project: Project): number { const have = new Set(project.components.map(d => d.id)) const missing = exampleLibrary().filter(d => !have.has(d.id)) project.components.push(...missing) return missing.length } /** * Adds components from another project. Identical ones are skipped; a * different component with a clashing id gets a new id (and references to it * inside the imported set follow). Returns how many were added. */ export function mergeComponents(project: Project, incoming: ComponentDef[]): number { const existing = new Map(project.components.map(d => [d.id, d])) const remap = new Map() const added: ComponentDef[] = [] for (const d of incoming) { const have = existing.get(d.id) if (have && JSON.stringify(have) === JSON.stringify(d)) continue const copy = clone(d) if (have) { copy.id = uid('c') remap.set(d.id, copy.id) copy.name = uniqueName({ ...project, components: [...project.components, ...added] }, copy.name) } added.push(copy) } for (const d of added) { for (const n of d.nodes) if (n.kind === 'chip' && n.chip && remap.has(n.chip)) n.chip = remap.get(n.chip) } project.components.push(...added) return added.length } /** True when `defId` is `targetId` or has it somewhere inside. */ export function containsDef(project: Project, defId: string, targetId: string): boolean { const get = lookup(project) const seen = new Set() const walk = (id: string): boolean => { if (id === targetId) return true if (seen.has(id)) return false seen.add(id) const def = get(id) return !!def && def.nodes.some(n => n.kind === 'chip' && !!n.chip && walk(n.chip)) } return walk(defId) } /** Components that can go into `openId` without making it contain itself. */ export function placeable(project: Project, openId: string): ComponentDef[] { return project.components.filter(d => !containsDef(project, d.id, openId)) } export function usages(project: Project, defId: string): ComponentDef[] { return project.components.filter(d => d.id !== defId && d.nodes.some(n => n.kind === 'chip' && n.chip === defId)) } export function uniqueName(project: Project, base: string): string { const names = new Set(project.components.map(d => d.name.toLowerCase())) if (!names.has(base.toLowerCase())) return base for (let i = 2; ; i++) if (!names.has(`${base} ${i}`.toLowerCase())) return `${base} ${i}` } export function newComponent(project: Project, name: string): ComponentDef { const def: ComponentDef = { id: uid('c'), name: uniqueName(project, name), symbol: 'box', nodes: [ { id: uid('n'), kind: 'input', x: 0, y: 0, label: 'A' }, { id: uid('n'), kind: 'output', x: 16, y: 0, label: 'Q' }, ], wires: [], } project.components.push(def) return def } export function startChallenge(project: Project, c: Challenge): ComponentDef { const def: ComponentDef = { id: uid('c'), name: uniqueName(project, project.components.some(d => d.name.toLowerCase() === c.name.toLowerCase()) ? `My ${c.name}` : c.name), symbol: c.symbol ?? 'box', description: c.goal, challenge: c.id, nodes: [ ...c.inputs.map((label, i) => ({ id: uid('n'), kind: 'input' as const, x: 0, y: i * 3, label })), ...c.outputs.map((label, i) => ({ id: uid('n'), kind: 'output' as const, x: 24, y: i * 3, label })), ], wires: [], } project.components.push(def) return def } export function duplicateComponent(project: Project, id: string): ComponentDef | undefined { const src = project.components.find(d => d.id === id) if (!src) return undefined const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) } delete copy.challenge project.components.push(copy) return copy } /** Deletes a component. Refuses when other components still use it. */ export function deleteComponent(project: Project, id: string): string | null { const users = usages(project, id) if (users.length) return `Still used in ${users.map(u => u.name).join(', ')}` if (project.components.length <= 1) return 'The last circuit cannot be deleted' project.components = project.components.filter(d => d.id !== id) if (project.openId === id) project.openId = project.components[0]!.id return null } /** * Removes wires whose pins no longer exist (a component lost a pin) and * keeps one wire per input pin. Returns true if anything changed. */ export function pruneWires(project: Project): boolean { const get = lookup(project) let changed = false for (const def of project.components) { const ins = new Set() const outs = new Set() for (const n of def.nodes) { const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined for (const k of inputKeys(n, pins)) ins.add(`${n.id}:${k}`) for (const k of outputKeys(n, pins)) outs.add(`${n.id}:${k}`) } const taken = new Set() const kept: Wire[] = [] for (let i = def.wires.length - 1; i >= 0; i--) { const w = def.wires[i]! const to = `${w.to.node}:${w.to.pin}` if (!ins.has(to) || !outs.has(`${w.from.node}:${w.from.pin}`) || taken.has(to)) continue taken.add(to) kept.push(w) } if (kept.length !== def.wires.length) { def.wires = kept.reverse() changed = true } } return changed } export interface Clip { nodes: CircuitNode[] wires: Wire[] } export function copySelection(def: ComponentDef, ids: Set): Clip { return clone({ nodes: def.nodes.filter(n => ids.has(n.id)), wires: def.wires.filter(w => ids.has(w.from.node) && ids.has(w.to.node)), }) } /** Pastes a clip shifted by (dx, dy). Returns the new node ids. */ export function pasteClip(def: ComponentDef, clip: Clip, dx: number, dy: number): string[] { const ids = new Map() for (const n of clip.nodes) { const id = uid('n') ids.set(n.id, id) def.nodes.push({ ...clone(n), id, x: n.x + dx, y: n.y + dy }) } for (const w of clip.wires) { const from = ids.get(w.from.node) const to = ids.get(w.to.node) if (!from || !to) continue const wire: Wire = { id: uid('w'), from: { node: from, pin: w.from.pin }, to: { node: to, pin: w.to.pin } } if (w.pts) wire.pts = w.pts.map(([x, y]) => [x + dx, y + dy]) def.wires.push(wire) } return [...ids.values()] } /** * Turns the selected parts into a new component and puts one instance of it * in their place. Wires that crossed the selection border become pins. */ export function packageSelection( project: Project, defId: string, ids: Set, name: string, ): { ok: true; def: ComponentDef; chipNode: string } | { ok: false; error: string } { const get = lookup(project) const def = get(defId) if (!def) return { ok: false, error: 'Circuit not found' } const sel = def.nodes.filter(n => ids.has(n.id)) if (sel.some(n => n.kind === 'input' || n.kind === 'output')) { return { ok: false, error: 'Leave the circuit’s own input/output pins out of the selection' } } if (!sel.some(n => n.kind !== 'note')) return { ok: false, error: 'Select some parts first' } const inside = (id: string) => ids.has(id) const incoming = def.wires.filter(w => !inside(w.from.node) && inside(w.to.node)) const outgoing = def.wires.filter(w => inside(w.from.node) && !inside(w.to.node)) const internal = def.wires.filter(w => inside(w.from.node) && inside(w.to.node)) const minX = Math.min(...sel.map(n => n.x)) const minY = Math.min(...sel.map(n => n.y)) const maxX = Math.max(...sel.map(n => n.x + shapeOf(n, get).body.w)) const ox = 6 - minX const oy = -minY const nodeById = new Map(def.nodes.map(n => [n.id, n])) const pinY = (ref: { node: string; pin: string }, dir: 'in' | 'out') => { const n = nodeById.get(ref.node)! const s = shapeOf(n, get) const p = (dir === 'in' ? s.inputs : s.outputs).find(p => p.key === ref.pin) return n.y + (p?.dy ?? 0) } const labelOf = (nodeId: string) => { const n = nodeById.get(nodeId) return n && ['input', 'output', 'lamp', 'button', 'clock'].includes(n.kind) ? n.label?.trim() : undefined } // One input pin per distinct outside source, one output pin per distinct inside source. const group = (wires: Wire[], dir: 'in' | 'out') => { const map = new Map() for (const w of wires) { const key = `${w.from.node}:${w.from.pin}` const y = dir === 'in' ? pinY(w.to, 'in') : pinY(w.from, 'out') const g = map.get(key) if (g) { g.wires.push(w) g.y = Math.min(g.y, y) } else map.set(key, { src: w.from, wires: [w], y }) } return [...map.values()].sort((a, b) => a.y - b.y) } const ins = group(incoming, 'in') const outs = group(outgoing, 'out') const child: ComponentDef = { id: uid('c'), name: uniqueName(project, name.trim() || 'Part'), symbol: 'box', nodes: [], wires: [] } for (const n of sel) child.nodes.push({ ...clone(n), x: n.x + ox, y: n.y + oy }) for (const w of internal) { const copy = clone(w) if (copy.pts) copy.pts = copy.pts.map(([x, y]) => [x + ox, y + oy]) child.wires.push(copy) } const used = new Set() const pinLabel = (preferred: string | undefined, fallback: string) => { let label = preferred || fallback for (let i = 2; used.has(label); i++) label = `${preferred || fallback}${i}` used.add(label) return label } let nextY = -Infinity const inPins = ins.map((g, i) => { const y = Math.max(nextY, g.y + oy) nextY = y + 2 const node: CircuitNode = { id: uid('n'), kind: 'input', x: 0, y, label: pinLabel(labelOf(g.src.node), `I${i + 1}`) } child.nodes.push(node) for (const w of g.wires) child.wires.push({ id: uid('w'), from: { node: node.id, pin: 'q' }, to: w.to }) return { group: g, node } }) nextY = -Infinity const outPins = outs.map((g, i) => { const y = Math.max(nextY, g.y + oy) nextY = y + 2 const node: CircuitNode = { id: uid('n'), kind: 'output', x: maxX + ox + 4, y, label: pinLabel(labelOf(g.wires[0]!.to.node), `O${i + 1}`) } child.nodes.push(node) child.wires.push({ id: uid('w'), from: g.src, to: { node: node.id, pin: 'a' } }) return { group: g, node } }) project.components.push(child) // Replace the selection with one chip. const chipNode: CircuitNode = { id: uid('n'), kind: 'chip', chip: child.id, x: minX, y: minY } def.nodes = def.nodes.filter(n => !inside(n.id)) def.nodes.push(chipNode) def.wires = def.wires.filter(w => !inside(w.from.node) && !inside(w.to.node)) for (const { group: g, node } of inPins) { def.wires.push({ id: uid('w'), from: g.src, to: { node: chipNode.id, pin: node.id } }) } for (const { group: g, node } of outPins) { for (const w of g.wires) def.wires.push({ id: uid('w'), from: { node: chipNode.id, pin: node.id }, to: w.to }) } return { ok: true, def: child, chipNode: chipNode.id } } // ── Changing placed parts ─────────────────────────────────────────── export type SwapTarget = { kind: NodeKind; chip?: string } /** Kinds that can replace each other because they play the same role. */ export const SOURCE_KINDS: NodeKind[] = ['input', 'button', 'clock', 'high', 'low'] export const SINK_KINDS: NodeKind[] = ['output', 'lamp', 'hex'] /** Pin keys of a node, in pin order. */ export function pinKeys(node: CircuitNode, get: DefLookup): { ins: string[]; outs: string[] } { const def = node.kind === 'chip' && node.chip ? get(node.chip) : undefined const pins = def ? chipPins(def) : undefined return { ins: inputKeys(node, pins), outs: outputKeys(node, pins) } } /** * Replaces a placed part with another one without unwiring it: wires stay on * the pin in the same position (first input to first input, and so on). * Wires on pins the new part doesn't have are removed; returns how many. */ export function swapNode(project: Project, def: ComponentDef, nodeId: string, target: SwapTarget): number { const get = lookup(project) const node = def.nodes.find(n => n.id === nodeId) if (!node) return 0 const before = pinKeys(node, get) const after = pinKeys({ ...node, kind: target.kind, chip: target.chip }, get) const map = (pin: string, from: string[], to: string[]) => { const i = from.indexOf(pin) return i >= 0 && i < to.length ? to[i] : undefined } let removed = 0 def.wires = def.wires.filter(w => { const to = w.to.node === nodeId ? map(w.to.pin, before.ins, after.ins) : w.to.pin const from = w.from.node === nodeId ? map(w.from.pin, before.outs, after.outs) : w.from.pin if (!to || !from) { removed++ return false } w.to = { node: w.to.node, pin: to } w.from = { node: w.from.node, pin: from } return true }) node.kind = target.kind if (target.chip) node.chip = target.chip else delete node.chip // Drop settings the new kind doesn't use. if (target.kind !== 'clock') delete node.hz if (target.kind !== 'input') delete node.on if (target.kind !== 'input' && target.kind !== 'button') delete node.key if (target.kind !== 'lamp' && target.kind !== 'hex') delete node.color if (target.kind !== 'note') delete node.size return removed } /** Removes every wire attached to the given parts. Returns how many. */ export function unlinkWires(def: ComponentDef, ids: Set): number { const before = def.wires.length def.wires = def.wires.filter(w => !ids.has(w.from.node) && !ids.has(w.to.node)) return before - def.wires.length } /** * Replaces a placed component with the parts inside it (the reverse of * "Make component"). Its pins disappear: outside wires are joined straight * to the parts they reached inside. Returns the ids of the new parts. */ export function unpackChip(project: Project, defId: string, nodeId: string): { ok: true; nodes: string[] } | { ok: false; error: string } { const get = lookup(project) const def = get(defId) const chip = def?.nodes.find(n => n.id === nodeId) const child = chip?.chip ? get(chip.chip) : undefined if (!def || !chip || chip.kind !== 'chip' || !child) return { ok: false, error: 'Not a component' } const inner = child.nodes.filter(n => n.kind !== 'input' && n.kind !== 'output') const minX = inner.length ? Math.min(...inner.map(n => n.x)) : 0 const minY = inner.length ? Math.min(...inner.map(n => n.y)) : 0 const ox = chip.x - minX const oy = chip.y - minY const ids = new Map() for (const n of inner) { const id = uid('n') ids.set(n.id, id) def.nodes.push({ ...clone(n), id, x: n.x + ox, y: n.y + oy }) } const kindOf = new Map(child.nodes.map(n => [n.id, n.kind])) const feed = new Map() for (const w of def.wires) if (w.to.node === chip.id) feed.set(w.to.pin, w.from) const resolve = (ref: Wire['from']): Wire['from'] | undefined => kindOf.get(ref.node) === 'input' ? feed.get(ref.node) : ids.has(ref.node) ? { node: ids.get(ref.node)!, pin: ref.pin } : undefined const added: Wire[] = [] for (const w of child.wires) { if (!ids.has(w.to.node)) continue const from = resolve(w.from) if (!from) continue const wire: Wire = { id: uid('w'), from, to: { node: ids.get(w.to.node)!, pin: w.to.pin } } if (ids.has(w.from.node) && w.pts) wire.pts = w.pts.map(([x, y]) => [x + ox, y + oy]) if (w.color) wire.color = w.color added.push(wire) } for (const w of def.wires) { if (w.from.node !== chip.id) continue const inside = child.wires.find(x => x.to.node === w.from.pin) const from = inside && resolve(inside.from) if (from) added.push({ id: uid('w'), from, to: w.to }) } def.nodes = def.nodes.filter(n => n !== chip) def.wires = [...def.wires.filter(w => w.from.node !== chip.id && w.to.node !== chip.id), ...added] return { ok: true, nodes: [...ids.values()] } } /** Points one placed component at its own copy of the definition, so edits to it don't change the others. */ export function makeUnique(project: Project, def: ComponentDef, nodeId: string): ComponentDef | undefined { const node = def.nodes.find(n => n.id === nodeId) if (!node?.chip) return undefined const copy = duplicateComponent(project, node.chip) if (copy) node.chip = copy.id return copy }