293 lines
11 KiB
TypeScript
293 lines
11 KiB
TypeScript
// 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, 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<T>(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 }): Project {
|
||
return {
|
||
version: 1,
|
||
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
|
||
}
|
||
|
||
/** 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<string>()
|
||
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<string>()
|
||
const outs = new Set<string>()
|
||
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<string>()
|
||
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<string>): 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<string, string>()
|
||
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<string>,
|
||
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<string, { src: Wire['from']; wires: Wire[]; y: number }>()
|
||
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<string>()
|
||
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 }
|
||
}
|