logigate/app/composables/useEditor.ts

2330 lines
82 KiB
TypeScript
Raw Normal View History

// Editor state: the project library, the open project, selection, undo
// history, share links and the running simulation of the open circuit.
// One shared instance for the whole page.
import { nandCounts, runSteps, stats, tableCsv, TRANSISTORS_PER_NAND, truthTable, type Stats, type TestResult, type TruthTable } from '~/lib/logic/analyze'
import {
bundleWires,
cableFromPins,
cableIntoPins,
cablePanel,
dissolveCable,
pinGroups,
pluggedInto,
plugInto,
syncCables,
type PinGroup,
} from '~/lib/logic/cables'
import { fitLinks, fitSpots } from '~/lib/logic/fit'
import { rememberPart } from '~/lib/recent'
import { checkCircuit } from '~/lib/logic/check'
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 { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
import { attachPanel, combineIntoPanel, detachPanel, dockedPanels, mergePanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
import {
addExamples,
containsDef,
copySelection,
createProject,
deleteComponent,
duplicateComponent,
lookup,
makeUnique,
pinKeys,
mergeComponents,
newComponent,
packageSelection,
pasteClip,
pruneWires,
startChallenge,
startPuzzle,
swapNode,
uid,
unlinkWires,
unpackChip,
type Clip,
type SwapTarget,
} from '~/lib/logic/ops'
import { arrangeNodes, byPosition, numberedNames, seriesLinks, type Arrange, type Link } from '~/lib/logic/bulk'
import { parseProject, toProject } from '~/lib/logic/project'
import { Simulator } from '~/lib/logic/sim'
import {
cachedAccount,
currentId,
listProjects,
loadProject,
migrateLegacy,
newLocalId,
pendingDeletes,
removeProject,
saveMeta,
saveProject,
setCachedAccount,
setCurrentId,
setPendingDeletes,
type AccountUser,
type ProjectMeta,
} from '~/lib/logic/storage'
import type { CircuitNode, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
/** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */
export interface PuzzleSummary {
players: number
histogram: { t: number; n: number }[]
you?: { t: number; d: number | null; rank: number }
/** The best ten, named as the players chose (empty: anonymous). */
top?: { name: string; t: number; d: number | null; you?: true }[]
}
export type MenuPage = 'main' | 'load' | 'free' | 'campaign' | 'challenges' | 'leaderboard'
export interface ChallengeCheck extends TestResult {
transistors: number
/** Parts this first solve made usable (campaign). */
unlocked?: string[]
/** Challenges it opened. */
nextUp?: string[]
/** Fewest transistors of any passing solution so far, this one included. */
best?: number
/** Set when this one beat an earlier record: that record. */
record?: number
}
/** One pin waiting to be wired in "connect one by one". */
export interface LinkEnd {
node: string
pin: string
dir: 'in' | 'out'
label: string
}
export interface Placing {
kind: NodeKind
chip?: string
keep?: boolean
}
export interface View {
x: number
y: number
zoom: number
}
export type LinkState = 'none' | 'viewer' | 'dirty' | 'saving' | 'saved' | 'error'
const BUDGET = 300_000
function create() {
// ── Library ───────────────────────────────────────────────────────
migrateLegacy()
const projects = ref<ProjectMeta[]>(listProjects())
function initial(): { meta: ProjectMeta; project: Project } {
const list = listProjects()
const id = currentId()
for (const m of [list.find(m => m.id === id), ...list]) {
if (!m) continue
const p = loadProject(m.id)
if (p) return { meta: m, project: p }
}
const project = createProject({ examples: true })
const meta: ProjectMeta = { id: newLocalId(), name: project.name, updated: Date.now(), starter: true }
// The starter project of a first visit is saved only once something
// changes in it. Signed in on a new device, the account's saves load
// instead, so an untouched starter never becomes a second copy.
placeholder = true
return { meta, project }
}
let placeholder = false
const start = initial()
// The starter project of a first visit is in the list now.
projects.value = listProjects()
const meta = ref<ProjectMeta>(start.meta)
const project = ref<Project>(start.project)
setCurrentId(start.meta.id)
const getDef = computed(() => lookup(project.value))
const def = computed(() => getDef.value(project.value.openId) ?? project.value.components[0]!)
const selection = ref<string[]>([])
const wireSel = ref<string[]>([])
const placing = ref<Placing | null>(null)
const nav = ref<string[]>([])
const views = reactive<Record<string, View>>({})
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
const dialog = ref<null | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
/** The component whose box is being drawn in the face designer. */
const faceFor = ref<string | null>(null)
function designFace(defId: string) {
faceFor.value = defId
dialog.value = 'face'
}
/** Tab shown in the right panel. */
const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit')
/** Which side panels are open; remembered in this browser. */
const sidebars = reactive<{ left: boolean; right: boolean }>({ left: true, right: true })
try {
Object.assign(sidebars, JSON.parse(localStorage.getItem('logigate:sidebars') ?? '{}'))
} catch {}
function toggleSidebar(side: 'left' | 'right', open = !sidebars[side]) {
sidebars[side] = open
try {
localStorage.setItem('logigate:sidebars', JSON.stringify(sidebars))
} catch {}
}
/** Asks the canvas to centre on a part. */
const focusRequest = ref<{ id: string; n: number } | null>(null)
/** Pins being wired one after another; `at` is the one the next click connects. */
const linking = ref<{ queue: LinkEnd[]; at: number } | null>(null)
/** Project whose savegames the versions dialog shows. */
const versionsFor = ref<string | null>(null)
let noticeTimer: ReturnType<typeof setTimeout> | undefined
function notify(text: string, kind: 'ok' | 'error' = 'ok') {
notice.value = { text, kind }
clearTimeout(noticeTimer)
noticeTimer = setTimeout(() => (notice.value = null), 3500)
}
function clearSelection() {
selection.value = []
wireSel.value = []
}
// ── Saving ────────────────────────────────────────────────────────
let saveTimer: ReturnType<typeof setTimeout> | undefined
let changed = false
function persistNow() {
clearTimeout(saveTimer)
saveTimer = undefined
// An untouched starter project is not saved (see initial()).
if (placeholder) return
meta.value = {
...meta.value,
name: project.value.name,
updated: Date.now(),
...(project.value.mode ? { mode: project.value.mode } : {}),
...(changed ? { dirty: true, starter: undefined } : {}),
}
if (!saveProject(toRaw(meta.value), toRaw(project.value))) notify('Browser storage is full. Export your project to keep it.', 'error')
projects.value = listProjects()
if (changed) scheduleCloud()
changed = false
}
function persist() {
placeholder = false
changed = true
clearTimeout(saveTimer)
saveTimer = setTimeout(persistNow, 300)
scheduleSync()
}
// ── History ───────────────────────────────────────────────────────
const snap = () => JSON.stringify({ components: project.value.components, solved: project.value.solved })
let last = snap()
const undoStack: string[] = []
const redoStack: string[] = []
const canUndo = ref(false)
const canRedo = ref(false)
function resetHistory() {
syncCables(project.value)
undoStack.length = 0
redoStack.length = 0
last = snap()
canUndo.value = false
canRedo.value = false
}
/**
* Record a change. Structural changes (parts, wires) rebuild the simulation.
* Cables follow every change: a new name or a moved part shows on them.
*/
function commit(structural = true) {
if (structural) {
syncPanels(project.value)
pruneWires(project.value)
}
syncCables(project.value)
const s = snap()
if (s === last) return
undoStack.push(last)
if (undoStack.length > 200) undoStack.shift()
redoStack.length = 0
last = s
canUndo.value = true
canRedo.value = false
forkIfViewer()
persist()
if (structural) scheduleRebuild()
}
function restore(s: string) {
const data = JSON.parse(s) as Pick<Project, 'components' | 'solved'>
project.value.components = data.components
project.value.solved = data.solved
if (!project.value.components.some(d => d.id === project.value.openId)) project.value.openId = project.value.components[0]!.id
last = s
selection.value = selection.value.filter(id => def.value.nodes.some(n => n.id === id))
wireSel.value = wireSel.value.filter(id => def.value.wires.some(w => w.id === id))
canUndo.value = undoStack.length > 0
canRedo.value = redoStack.length > 0
persist()
scheduleRebuild()
}
function undo() {
const s = undoStack.pop()
if (s === undefined) return
redoStack.push(last)
restore(s)
}
function redo() {
const s = redoStack.pop()
if (s === undefined) return
undoStack.push(last)
restore(s)
}
// ── Simulation ────────────────────────────────────────────────────
const sim = shallowRef<Simulator | null>(null)
let simRoot = ''
const tick = ref(0)
const status = ref<'stable' | 'busy' | 'oscillating'>('stable')
const running = ref(true)
const hz = ref(2)
const cycles = ref(0)
const errors = ref<string[]>([])
const circuitStats = ref<Stats>({ nands: 0, sequential: false, delay: 0 })
const pressed = new Set<string>()
function rebuild() {
const d = def.value
const nl = compile(getDef.value, d.id)
const key = `${meta.value.id}/${d.id}`
const carry = sim.value && simRoot === key ? sim.value.carry() : undefined
const s = new Simulator(nl, carry)
for (const n of d.nodes) {
if (n.kind === 'input') s.setSource(n.id, !!n.on)
else if (n.kind === 'button') s.setSource(n.id, pressed.has(n.id))
else if (n.kind === 'panel') {
for (const r of n.rows ?? []) {
const key = rowSource(n.id, r.id)
if (r.type === 'switch') s.setSource(key, !!r.on)
else if (r.type === 'button') s.setSource(key, pressed.has(key))
}
}
}
s.run(BUDGET)
if (simRoot !== key) cycles.value = 0
sim.value = s
simRoot = key
errors.value = nl.errors
circuitStats.value = stats(nl)
tick.value++
}
let rebuildQueued = false
function scheduleRebuild() {
if (rebuildQueued) return
rebuildQueued = true
queueMicrotask(() => {
rebuildQueued = false
rebuild()
})
}
/** Value at a pin of the open circuit. Reactive through `tick`. */
function val(nodeId: string, pin: string): number {
void tick.value
return sim.value?.pin(nodeId, pin) ?? 0
}
/** Value at a lamp or display inside a chip of the open circuit. */
function faceVal(chipNode: string, inner: string, pin: string): number {
void tick.value
return sim.value?.face(chipNode, inner, pin) ?? 0
}
let raf = 0
function startLoop() {
let lastT = performance.now()
let acc: number[] = []
let unsettled = 0
let lastChanges = -1
const frame = (t: number) => {
const dt = Math.min(100, t - lastT)
lastT = t
const s = sim.value
if (s) {
let rises = 0
let tickHz = 0
const n = s.nl.clocks.length
if (running.value && n) {
if (acc.length !== n) acc = new Array(n).fill(0)
// Ticks count the first clock that follows the top-bar speed (or the first clock).
const counted = Math.max(0, s.nl.clockHz.indexOf(0))
tickHz = s.nl.clockHz[counted] || hz.value
const fastest: number[] = []
for (let i = 0; i < n; i++) {
const f = s.nl.clockHz[i] || hz.value
if (f <= 0) {
fastest.push(i)
continue
}
acc[i]! += dt
const half = 500 / f
for (let k = 0; acc[i]! >= half && k < 16; k++) {
acc[i]! -= half
s.run(BUDGET)
if (s.toggleClock(i) && i === counted) rises++
}
if (acc[i]! > half) acc[i] = 0
}
if (fastest.length) {
const end = performance.now() + 10
while (performance.now() < end) {
if (!s.run(BUDGET)) break
for (const i of fastest) if (s.toggleClock(i) && i === counted) rises++
}
}
}
if (rises) cycles.value += rises
if (rises && sound.value.ticks && tickHz > 0 && tickHz <= 8) play('tick')
const settled = s.run(BUDGET)
unsettled = settled ? 0 : unsettled + 1
status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy'
if (s.changes !== lastChanges) {
lastChanges = s.changes
tick.value++
}
}
raf = requestAnimationFrame(frame)
}
raf = requestAnimationFrame(frame)
return () => cancelAnimationFrame(raf)
}
/** One full clock cycle (rise and fall), each half settled. */
function step() {
const s = sim.value
if (!s) return
s.run(BUDGET)
if (s.clock) {
s.setClock(0)
s.run(BUDGET)
}
s.setClock(1)
s.run(BUDGET)
cycles.value++
s.setClock(0)
s.run(BUDGET)
tick.value++
}
// ── Navigation ────────────────────────────────────────────────────
function open(id: string, push = true) {
if (id === def.value.id || !getDef.value(id)) return
if (push) nav.value.push(def.value.id)
project.value.openId = id
clearSelection()
placing.value = null
linking.value = null
persist()
rebuild()
}
function back() {
const id = nav.value.pop()
if (id) open(id, false)
}
// ── Editing ───────────────────────────────────────────────────────
/** Asks the parts list to focus its search box ("/" on the canvas). */
const partSearch = ref(0)
/** A part being dragged in from the parts list, so the canvas can show where it would connect. */
const dragPart = ref<Placing | null>(null)
/** Places a part; `links` are wires to make at once, with "ghost" standing for the new part. */
function addNode(p: Placing, x: number, y: number, links: Link[] = []): CircuitNode {
const node: CircuitNode = { id: uid('n'), kind: p.kind, x, y }
if (p.chip) node.chip = p.chip
if (p.kind === 'input' || p.kind === 'output') {
node.label = newPinLabel(def.value, p.kind)
node.autoLabel = true
}
if (p.kind === 'note') node.label = 'Note'
if (p.kind === 'tag') {
node.label = uniqueLabel('SIG', usedLabels(def.value, 'signal'))
node.autoLabel = true
}
// A new reference uses the signal sent last.
if (p.kind === 'ref') node.label = def.value.nodes.filter(n => n.kind === 'tag' && n.label?.trim()).at(-1)?.label?.trim() ?? ''
if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
def.value.nodes.push(node)
rememberPart(p.kind, p.chip)
const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r)
const made = links.filter(l => addWire(swap(l.from), swap(l.to))).length
selection.value = [node.id]
wireSel.value = []
commit()
play(made ? 'connect' : 'place')
if (made) notify(`Placed and connected ${made} wire${made === 1 ? '' : 's'}`)
return node
}
function canPlace(chipId: string) {
const d = getDef.value(chipId)
return !containsDef(project.value, chipId, def.value.id) && (!d || defUsable(project.value, d))
}
/** In a campaign, basic parts are earned; elsewhere everything can be placed. */
function canPlaceKind(kind: NodeKind) {
return kindUnlocked(project.value, kind)
}
// ── Sound ─────────────────────────────────────────────────────────
const sound = ref<SoundSettings>(loadSoundSettings())
function play(s: Sound) {
sfx(s, sound.value)
}
function setSound(patch: Partial<SoundSettings>) {
sound.value = { ...sound.value, ...patch }
saveSoundSettings(sound.value)
if (patch.on || patch.volume !== undefined) play('on')
}
/** True when the pin is a cable end (bundle output, split input). */
function isBus(nodeId: string, pin: string, dir: 'in' | 'out'): boolean {
const n = def.value.nodes.find(x => x.id === nodeId)
if (!n) return false
const s = shapeOf(n, getDef.value)
return !!(dir === 'in' ? s.inputs : s.outputs).find(p => p.key === pin)?.bus
}
/** Adds one wire (replacing whatever fed that input) without recording an undo step. False for a cable/wire mismatch. */
function addWire(from: PinRef, to: PinRef, pts?: Pt[]): boolean {
const d = def.value
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) return false
const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin)
d.wires = d.wires.filter(w => w !== old)
const wire: (typeof d.wires)[number] = { id: uid('w'), from, to }
if (pts?.length) wire.pts = pts
const sameNet = d.wires.find(w => w.from.node === from.node && w.from.pin === from.pin && w.color)
if (sameNet?.color) wire.color = sameNet.color
d.wires.push(wire)
// An unnamed switch, lamp or pin takes the name of the component pin it now connects to.
const fn = d.nodes.find(n => n.id === from.node)
const tn = d.nodes.find(n => n.id === to.node)
if (fn && tn) {
adoptName(d, fn, from.pin, tn, to.pin, getDef.value)
adoptName(d, tn, to.pin, fn, from.pin, getDef.value)
}
return true
}
function connect(from: PinRef, to: PinRef, pts?: Pt[]) {
if (!addWire(from, to, pts)) {
play('error')
return notify('A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins', 'error')
}
wireSel.value = []
commit()
play('connect')
}
/**
* Moves a wire's end to another pin: the wire now runs from `from` to
* `to`, keeping its colour. An input that had a wire gets this one instead.
*/
function rewire(wireId: string, from: PinRef, to: PinRef) {
const d = def.value
const old = d.wires.find(w => w.id === wireId)
if (!old) return
if (old.from.node === from.node && old.from.pin === from.pin && old.to.node === to.node && old.to.pin === to.pin) return
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) {
play('error')
return notify('A cable pin only joins another cable pin', 'error')
}
d.wires = d.wires.filter(w => w !== old)
addWire(from, to)
const made = d.wires[d.wires.length - 1]!
if (old.color && !made.color) made.color = old.color
wireSel.value = [made.id]
selection.value = []
commit()
play('connect')
}
/** Several wires as one undo step. */
function connectMany(links: Link[]) {
const made = links.filter(l => addWire(l.from, l.to)).length
if (!made) return
wireSel.value = []
commit()
play('connect')
if (made > 1) notify(`Connected ${made} wires`)
}
/** Asks the canvas for the open circuit as a sheet: printed (or saved as PDF), or as an SVG file. */
const sheetRequest = ref<{ mode: 'print' | 'svg'; n: number } | null>(null)
function exportSheet(mode: 'print' | 'svg') {
sheetRequest.value = { mode, n: (sheetRequest.value?.n ?? 0) + 1 }
}
/** What looks wrong in the open circuit, worst first; a loop that never settles too. */
const issues = computed(() => {
const list = checkCircuit(def.value, getDef.value)
if (status.value === 'oscillating') list.unshift({ level: 'warn', text: 'The circuit keeps changing: a loop that never settles', nodes: [] })
return list
})
/** Shows the parts of a problem: selects them and centres on the first. */
function showIssue(nodes: string[]) {
if (!nodes.length) return
focusNode(nodes[0]!)
selection.value = nodes
}
/** 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
* its inputs (dir 'out'), or its outputs to their inputs (dir 'in').
*/
function connectSelectionTo(targetId: string, dir: 'in' | 'out') {
const target = def.value.nodes.find(n => n.id === targetId)
const first = def.value.nodes.filter(n => selection.value.includes(n.id) && n.id !== targetId).sort(byPosition)[0]
if (!target || !first) return
const mine = dir === 'out' ? pinKeys(first, getDef.value).outs[0] : pinKeys(first, getDef.value).ins[0]
const theirs = dir === 'out' ? pinKeys(target, getDef.value).ins[0] : pinKeys(target, getDef.value).outs[0]
if (!mine || !theirs) return notify('No matching pins to connect', 'error')
connectMany(seriesLinks(def.value, getDef.value, selection.value, { node: first.id, pin: mine, dir }, { node: target.id, pin: theirs }))
}
/** Parts plus the panels docked to them: they move, copy and delete together. */
function withDocked(ids: Iterable<string>): Set<string> {
const set = new Set(ids)
for (const p of dockedPanels(def.value, set)) set.add(p.id)
return set
}
/** What moves along when parts move: docked panels and plugged-in cable ends, and what is plugged into those. */
function withFollowers(ids: Iterable<string>): Set<string> {
const set = new Set(ids)
for (let size = -1; size !== set.size; ) {
size = set.size
for (const p of [...dockedPanels(def.value, set), ...pluggedInto(def.value, set)]) set.add(p.id)
}
return set
}
function deleteSelected() {
const d = def.value
if (!selection.value.length && !wireSel.value.length) return
const ids = withDocked(selection.value)
const wires = new Set(wireSel.value)
d.nodes = d.nodes.filter(n => !ids.has(n.id))
d.wires = d.wires.filter(w => !ids.has(w.from.node) && !ids.has(w.to.node) && !wires.has(w.id))
clearSelection()
commit()
play('delete')
}
const selectedWires = computed(() => {
const ids = new Set(wireSel.value)
return def.value.wires.filter(w => ids.has(w.id))
})
function setWireColor(color: WireColor | undefined) {
for (const w of selectedWires.value) {
if (color) w.color = color
else delete w.color
}
commit(false)
}
function autoRoute() {
for (const w of selectedWires.value) delete w.pts
commit(false)
}
/** Select every wire that carries the same signal (same source pin). */
function selectNet(wireId: string) {
const w = def.value.wires.find(x => x.id === wireId)
if (!w) return
wireSel.value = def.value.wires.filter(x => x.from.node === w.from.node && x.from.pin === w.from.pin).map(x => x.id)
}
function swap(nodeId: string, target: SwapTarget) {
const removed = swapNode(project.value, def.value, nodeId, target)
commit()
if (removed) notify(`Swapped. ${removed} wire${removed === 1 ? '' : 's'} had no matching pin and were removed.`)
}
/** Gives a placed gate `n` inputs, by swapping in its wide version (made on first use). */
function setInputs(node: CircuitNode, n: number) {
const base = baseOf(node, getDef.value)
if (!base) return
if (base !== NAND_BASE && containsDef(project.value, base, def.value.id)) return notify('A component cannot contain itself', 'error')
const target = wideGate(project.value, base, Math.round(n))
if (!target) return notify(`Gates can have 2 to ${MAX_GATE_INPUTS} inputs`, 'error')
if (target.kind === 'chip' && target.chip === node.chip) return
if (target.kind === 'nand' && node.kind === 'nand') return
swap(node.id, target)
}
function unlink(ids: string[]) {
const n = unlinkWires(def.value, new Set(ids))
commit()
notify(n ? `Removed ${n} wire${n === 1 ? '' : 's'}` : 'Nothing was connected')
}
function unpack(nodeId: string) {
const res = unpackChip(project.value, def.value.id, nodeId)
if (!res.ok) return notify(res.error, 'error')
selection.value = res.nodes
wireSel.value = []
commit()
}
function makeIndependent(nodeId: string) {
const copy = makeUnique(project.value, def.value, nodeId)
if (!copy) return
commit()
notify(`This one now uses its own copy, "${copy.name}"`)
}
function toggleInput(node: CircuitNode) {
node.on = !node.on
sim.value?.setSource(node.id, node.on)
play(node.on ? 'on' : 'off')
persist()
}
function press(node: CircuitNode, down: boolean) {
if (down && !pressed.has(node.id)) play('press')
if (down) pressed.add(node.id)
else pressed.delete(node.id)
sim.value?.setSource(node.id, down)
}
/** Click on a panel row: flips a switch row. */
function toggleRow(node: CircuitNode, row: PanelRow) {
if (row.type !== 'switch' || node.kind !== 'panel') return
row.on = !row.on
sim.value?.setSource(rowSource(node.id, row.id), row.on)
play(row.on ? 'on' : 'off')
persist()
}
function pressRow(node: CircuitNode, row: PanelRow, down: boolean) {
if (row.type !== 'button' || node.kind !== 'panel') return
const key = rowSource(node.id, row.id)
if (down && !pressed.has(key)) play('press')
if (down) pressed.add(key)
else pressed.delete(key)
sim.value?.setSource(key, down)
}
// ── Panels ────────────────────────────────────────────────────────
/** Docks a panel to a component: switches for its free inputs (left), or lamps for its outputs (right). */
function addPanel(chipId: string, side: 'in' | 'out' = 'in') {
const panel = attachPanel(project.value, def.value, chipId, side)
if (!panel) return notify(side === 'in' ? 'Every input of this component is already connected' : 'This component has no outputs', 'error')
selection.value = [panel.id]
wireSel.value = []
commit()
const n = panel.rows!.length
notify(side === 'in' ? `Input panel with ${n} switch${n === 1 ? '' : 'es'} attached` : `Output panel with ${n} lamp${n === 1 ? '' : 's'} attached`)
}
/** Pins of the open circuit got new keys: circuits that place it keep their wires on them. */
function followPins(renamed: Map<string, string>) {
if (!renamed.size) return
const id = def.value.id
for (const d of project.value.components) {
const chips = new Set(d.nodes.filter(n => n.kind === 'chip' && n.chip === id).map(n => n.id))
if (!chips.size) continue
for (const w of d.wires) {
const to = chips.has(w.to.node) ? renamed.get(w.to.pin) : undefined
if (to) w.to = { node: w.to.node, pin: to }
const from = chips.has(w.from.node) ? renamed.get(w.from.pin) : undefined
if (from) w.from = { node: w.from.node, pin: from }
}
}
}
/** Joins the selected panels into one; circuits that place this one keep their wires to the rows. */
function mergeSelectedPanels() {
const res = mergePanels(def.value, selection.value)
if (!res) return notify('Select at least two panels of the same kind', 'error')
followPins(res.renamed)
selection.value = [res.panel.id]
wireSel.value = []
commit()
notify(`One panel with ${res.panel.rows?.length ?? 0} rows`)
}
/** The selected switches, buttons and clocks as one input panel, or output pins and lamps as one output panel. */
function combineSelected() {
const res = combineIntoPanel(def.value, selection.value, getDef.value)
if (!res) return notify('Select switches, buttons and clocks, or output pins and lamps (two or more)', 'error')
followPins(res.renamed)
selection.value = [res.panel.id]
wireSel.value = []
commit()
notify(`${res.panel.kind === 'outpanel' ? 'Output' : 'Input'} panel with ${res.panel.rows?.length ?? 0} rows`)
}
// ── Main menu ─────────────────────────────────────────────────────
/** The title menu shows when the app opens at /; links open straight into the editor. */
const screen = ref<'menu' | 'editor'>(location.pathname === '/' ? 'menu' : 'editor')
const menuPage = ref<MenuPage>('main')
/** Tab of the parts panel on the left. */
const paletteTab = ref<'parts' | 'challenges'>('parts')
function enterGame() {
screen.value = 'editor'
menuPage.value = 'main'
}
function showMenu(page: MenuPage = 'main') {
persistNow()
dialog.value = null
paused.value = null
menuPage.value = page
screen.value = 'menu'
}
// ── Pause menu ────────────────────────────────────────────────────
/** The in-game menu over the editor (Esc): its main list, or the saves to load. */
const paused = ref<null | 'main' | 'load'>(null)
function pause(page: 'main' | 'load' = 'main') {
placing.value = null
linking.value = null
paused.value = page
}
/** Saves now: in this browser, and in the account when signed in. */
async function saveNow() {
placeholder = false
changed = true
persistNow()
if (!account.value) return notify('Saved in this browser')
await syncAccount()
notify(cloudState.value === 'synced' ? 'Saved to your account' : 'Saved in this browser; the account will follow when it can be reached', cloudState.value === 'synced' ? 'ok' : 'error')
}
/** A project's mode, from its index entry, or (for projects saved before it was noted there) from the project. */
const modes = new Map<string, Project['mode'] | null>()
function projectMode(m: ProjectMeta): Project['mode'] | undefined {
if (m.mode) return m.mode
if (!modes.has(m.id)) modes.set(m.id, loadProject(m.id)?.mode ?? null)
return modes.get(m.id) ?? undefined
}
/** The newest project of a mode, if any. */
const newestOf = (mode: Project['mode']) => listProjects().filter(m => projectMode(m) === mode).sort((a, b) => b.updated - a.updated)[0]
/** The newest project of a mode, for the menu to show progress (the open one as it is now). */
function projectOf(mode: Project['mode']): Project | null {
const m = newestOf(mode)
if (!m) return null
return m.id === meta.value.id ? project.value : loadProject(m.id)
}
/** Into the campaign: the newest one, or a new one. */
function playCampaign() {
const m = newestOf('campaign')
if (m) switchProject(m.id)
else newProject(false, true)
paletteTab.value = 'challenges'
enterGame()
}
/** Into the challenges project (made on first use: NAND only, every challenge open). */
function intoChallenges() {
const m = newestOf('challenges')
if (m) switchProject(m.id)
else {
persistNow()
const p = createProject({ examples: false, name: 'Challenges' })
p.mode = 'challenges'
activate(addProject(p), p)
}
paletteTab.value = 'challenges'
}
function playChallenge(c: Challenge) {
intoChallenges()
beginChallenge(c)
enterGame()
}
/** The puzzle of the week, in the challenges project. */
function playWeekly() {
intoChallenges()
const spec = project.value.puzzles?.find(p => p.id === weeklyId(weekKey()))
if (spec) beginPuzzle(spec)
else void openPuzzle('weekly')
enterGame()
}
/** Name shown next to your scores on the leaderboards. */
const playerName = ref((() => {
try {
return localStorage.getItem('logigate:player-name') ?? ''
} catch {
return ''
}
})())
async function setPlayerName(name: string) {
const res = await api<{ name: string }>('POST', '/api/players/name', { player: playerId(), name })
playerName.value = res.name
try {
localStorage.setItem('logigate:player-name', res.name)
} catch {}
}
/** A puzzle and its leaderboard from the server ("weekly", "week-2026-43" or a link id). */
async function fetchBoard(id: string): Promise<{ id: string; spec: PuzzleSpec; summary: PuzzleSummary } | null> {
try {
return await api('GET', `/api/puzzles/${encodeURIComponent(id)}?player=${encodeURIComponent(playerId())}`)
} catch {
return null
}
}
/** Puts pixels on a named screen of the component's box ('' for the main screen). */
function setScreen(ids: string[], name: string) {
const v = name.trim()
for (const n of nodesById(ids)) {
if (n.kind !== 'pixel') continue
if (v) n.screen = v
else delete n.screen
}
commit(false)
}
/** Every row of an input panel the same kind: all switches, all buttons or all clocks. */
function setRowsType(panel: CircuitNode, type: PanelControl) {
for (const r of panel.rows ?? []) {
r.type = type
if (type !== 'switch') delete r.on
if (type !== 'clock') delete r.hz
}
commit()
}
function undock(panel: CircuitNode) {
detachPanel(panel)
commit()
}
function setRowType(row: PanelRow, type: PanelControl) {
row.type = type
if (type !== 'switch') delete row.on
if (type !== 'clock') delete row.hz
commit()
}
/** Swaps a row of a free panel with its neighbour; the rows keep their places, so the switches trade them. */
function moveRow(panel: CircuitNode, index: number, by: -1 | 1) {
const rows = panel.rows ?? []
const j = index + by
if (panel.attach || j < 0 || j >= rows.length) return
const at = panelOffsets(rows)
;[rows[index], rows[j]] = [rows[j]!, rows[index]!]
rows.forEach((r, i) => (r.dy = at[i]!))
commit()
}
/** Empty rows above a row of a free panel; the rows below move along. */
function setRowGap(panel: CircuitNode, index: number, gap: number) {
const rows = panel.rows ?? []
if (panel.attach || index < 1 || index >= rows.length) return
const at = panelOffsets(rows)
const shift = at[index - 1]! + 1 + Math.max(0, Math.min(20, Math.round(gap) || 0)) - at[index]!
rows.forEach((r, i) => (r.dy = i < index ? at[i]! : at[i]! + shift))
commit()
}
/** A keyboard key for a panel row (empty to clear it). */
function setRowKey(row: PanelRow, key: string | undefined) {
if (key) row.key = key
else delete row.key
commit(false)
}
function setRowColor(row: PanelRow, color: LampColor | undefined) {
if (color) row.color = color
else delete row.color
commit(false)
}
// ── Cable ends ────────────────────────────────────────────────────
/** The part a cable end's single wires all run to (for a bundle: come from), if just one. */
function plugTarget(end: CircuitNode): CircuitNode | undefined {
const wires = end.kind === 'bundle' ? def.value.wires.filter(w => w.to.node === end.id) : def.value.wires.filter(w => w.from.node === end.id)
const ids = new Set(wires.map(w => (end.kind === 'bundle' ? w.from.node : w.to.node)))
const part = ids.size === 1 ? def.value.nodes.find(n => n.id === [...ids][0]) : undefined
return part && part.kind !== 'bundle' && part.kind !== 'split' ? part : undefined
}
function plugEnd(end: CircuitNode) {
const part = plugTarget(end)
if (!part || !plugInto(def.value, end, part.id, getDef.value)) {
return notify('Its wires must all run to the pins of one part, in the same order as the cable', 'error')
}
commit()
}
/** Pulls a cable end out of its part: it steps two squares away and its wires show again. */
function unplugEnd(end: CircuitNode) {
if (!end.plug) return
delete end.plug
end.x += end.kind === 'bundle' ? 2 : -2
commit()
}
/** Ends dragged away from the part they are plugged into come loose. */
function unplugMoved(ids: Set<string>) {
for (const n of def.value.nodes) if (n.plug && ids.has(n.id) && !ids.has(n.plug)) delete n.plug
}
function setPitch(end: CircuitNode, pitch: number) {
if (end.plug) return
const p = Math.max(1, Math.min(8, Math.round(pitch) || 1))
if (p === 1) delete end.pitch
else end.pitch = p
delete end.offsets
commit()
}
/**
* Pins of a part a new cable can plug onto: groups of its outputs (those
* not already in a plugged cable) and of its free inputs.
*/
function cableChoices(n: CircuitNode): { out: PinGroup[]; in: PinGroup[] } {
const none = { out: [], in: [] }
if (n.kind !== 'chip' && n.kind !== 'panel' && n.kind !== 'hex') return none
const s = shapeOf(n, getDef.value)
const d = def.value
const kinds = new Map(d.nodes.map(x => [x.id, x]))
const cabled = new Set(d.wires.filter(w => w.from.node === n.id && kinds.get(w.to.node)?.plug === n.id).map(w => w.from.pin))
// Inputs already fed by a plugged cable are taken; inputs with a plain wire can take a cable (the wire goes into it).
const fed = new Set(d.wires.filter(w => w.to.node === n.id && kinds.get(w.from.node)?.plug === n.id).map(w => w.to.pin))
const outs = s.outputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
const ins = n.kind === 'panel' ? [] : s.inputs.filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
return { out: pinGroups(outs, k => !cabled.has(k)), in: pinGroups(ins, k => !fed.has(k)) }
}
/**
* A cable from some of a part's outputs. When each of them already has
* one wire, those wires go into the cable (both ends plug in where they
* can); otherwise a new cable starts there with a free end.
*/
function cableOut(nodeId: string, pins: string[]) {
const wires = def.value.wires.filter(w => w.from.node === nodeId && pins.includes(w.from.pin))
const per = new Map<string, number>()
for (const w of wires) per.set(w.from.pin, (per.get(w.from.pin) ?? 0) + 1)
if (wires.length >= 2 && pins.every(p => per.get(p) === 1)) return bundleSelected(wires.map(w => w.id))
const res = cableFromPins(def.value, nodeId, pins, getDef.value)
if (!res.ok) return notify(res.error, 'error')
selection.value = [res.split.id]
wireSel.value = []
commit()
notify(`Cable with ${res.split.bits} wires: drag its free end onto the pins where they go`)
}
/** A cable into some of a part's inputs: their wires go into it when they all have one, else a new cable into the free ones. */
function cableIn(nodeId: string, pins: string[]) {
const wires = def.value.wires.filter(w => w.to.node === nodeId && pins.includes(w.to.pin))
if (wires.length >= 2 && wires.length === pins.length) return bundleSelected(wires.map(w => w.id))
const res = cableIntoPins(def.value, nodeId, pins, getDef.value)
if (!res.ok) return notify(res.error, 'error')
selection.value = [res.bundle.id]
wireSel.value = []
commit()
notify(`Cable with ${res.bundle.bits} wires: drag its free end next to what drives them, or attach an input panel`)
}
function addCablePanel(bundleId: string) {
const panel = cablePanel(def.value, bundleId, getDef.value)
if (!panel) return notify('Every wire of this cable is already driven', 'error')
selection.value = [panel.id]
wireSel.value = []
commit()
notify(`Input panel with ${panel.rows!.length} switches plugged into the cable`)
}
function addRow(panel: CircuitNode) {
panel.rows = [...(panel.rows ?? []), ...newPanelRows(1)]
commit()
}
function dropRow(panel: CircuitNode, rowId: string) {
removeRow(def.value, panel, rowId)
commit()
}
let clip: Clip | null = null
let pasteCount = 0
/** Something copied, ready to paste. */
const hasClip = ref(false)
function copy() {
if (!selection.value.length) return
clip = copySelection(def.value, withDocked(selection.value))
hasClip.value = true
pasteCount = 0
notify(`Copied ${clip.nodes.length} part${clip.nodes.length === 1 ? '' : 's'}`)
}
/** Pastes a little below the copy each time, or with its top left corner at `at`. */
function paste(at?: Pt) {
if (!clip) return
pasteCount++
const blocked = clip.nodes.filter(n => n.kind === 'chip' && n.chip && !canPlace(n.chip))
const usable: Clip = blocked.length ? { nodes: clip.nodes.filter(n => !blocked.includes(n)), wires: clip.wires } : clip
if (blocked.length) notify('Skipped parts that would contain this circuit itself', 'error')
const [dx, dy] = at && usable.nodes.length
? [Math.round(at[0]) - Math.min(...usable.nodes.map(n => n.x)), Math.round(at[1]) - Math.min(...usable.nodes.map(n => n.y))]
: [2 * pasteCount, 2 * pasteCount]
const ids = pasteClip(def.value, usable, dx, dy)
const fresh = new Set(ids)
continueSeries(def.value, def.value.nodes.filter(n => fresh.has(n.id)))
selection.value = ids
wireSel.value = []
commit()
}
function duplicate() {
copy()
paste()
}
// ── Connect one by one ────────────────────────────────────────────
/**
* Pins of the given parts, top to bottom, ready to be wired one after the
* other: their outputs, or their inputs when asked for (or when they have
* no outputs, like lamps).
*/
function linkQueue(ids: string[], want?: 'in' | 'out'): LinkEnd[] {
const nodes = def.value.nodes.filter(n => ids.includes(n.id) && n.kind !== 'note').sort((a, b) => a.y - b.y || a.x - b.x)
const shapes = nodes.map(n => ({ n, s: shapeOf(n, getDef.value) }))
const dir = want ?? (shapes.some(({ s }) => s.outputs.length) ? 'out' : 'in')
const queue: LinkEnd[] = []
for (const { n, s } of shapes) {
for (const p of dir === 'out' ? s.outputs : s.inputs) {
const label = p.label || n.label?.trim() || ''
queue.push({ node: n.id, pin: p.key, dir, label })
}
}
return queue
}
function startLinking(ids = selection.value, want?: 'in' | 'out') {
const queue = linkQueue(ids, want)
if (!queue.length) return notify('Nothing to connect: select parts with pins', 'error')
placing.value = null
linking.value = null
linking.value = { queue, at: 0 }
}
/** Wires the pin whose turn it is to `target`, then moves on to the next one. */
function linkTo(target: PinRef) {
const l = linking.value
const cur = l?.queue[l.at]
if (!l || !cur) return
const here = { node: cur.node, pin: cur.pin }
if (cur.dir === 'out') connect(here, target)
else connect(target, here)
l.at++
if (l.at >= l.queue.length) {
linking.value = null
if (l.queue.length > 1) notify(`Connected ${l.queue.length} pins`)
}
}
function stopLinking() {
linking.value = null
}
// ── Tidy wiring ───────────────────────────────────────────────────
function setTidy(on: boolean) {
if (on) project.value.settings.tidy = true
else delete project.value.settings.tidy
persist()
}
/** Removes all hand-placed bends in the open circuit and lays every wire out tidily. */
function tidyAll() {
const bent = def.value.wires.filter(w => w.pts).length
for (const w of def.value.wires) delete w.pts
project.value.settings.tidy = true
commit(false)
persist()
notify(bent ? `Tidied. ${bent} hand-placed bend${bent === 1 ? ' was' : 's were'} removed (Ctrl+Z brings ${bent === 1 ? 'it' : 'them'} back)` : 'Tidy wiring is on')
}
function selectAll() {
selection.value = def.value.nodes.map(n => n.id)
wireSel.value = def.value.wires.map(w => w.id)
}
function packageSelected(name: string) {
const res = packageSelection(project.value, def.value.id, new Set(selection.value), name)
if (!res.ok) {
notify(res.error, 'error')
return
}
selection.value = [res.chipNode]
wireSel.value = []
commit()
notify(`Created component "${res.def.name}"`)
}
// ── Components ────────────────────────────────────────────────────
function createComponent(name = 'New part') {
const d = newComponent(project.value, name)
commit()
open(d.id)
labelFocus.value++
}
function removeComponent(id: string) {
const err = deleteComponent(project.value, id)
if (err) return notify(err, 'error')
nav.value = nav.value.filter(n => n !== id)
commit()
rebuild()
}
function copyComponent(id: string) {
const d = duplicateComponent(project.value, id)
if (!d) return
commit()
open(d.id)
}
function beginChallenge(c: Challenge) {
const existing = project.value.components.find(d => d.challenge === c.id)
if (existing) return open(existing.id)
if (!challengeOpen(project.value, c.id)) {
play('error')
return notify(`Solve ${(NEEDS[c.id] ?? []).filter(n => !project.value.solved.includes(n)).map(challengeName).join(' and ')} first`, 'error')
}
const d = startChallenge(project.value, c)
commit()
open(d.id)
}
/** The challenge or puzzle the open circuit is for. */
const task = computed(() => {
const id = def.value.challenge
if (!id) return null
const c = CHALLENGES.find(c => c.id === id)
if (c) return { id, challenge: c, puzzle: undefined, steps: challengeSteps(c) }
const p = project.value.puzzles?.find(p => p.id === id)
return p ? { id, challenge: undefined, puzzle: p, steps: p.steps } : null
})
function checkChallenge(): ChallengeCheck | null {
const t = task.value
if (!t) return null
const res = t.puzzle ? scoreSolution(toRaw(project.value.components), def.value.id, toRaw(t.puzzle)) : runSteps(getDef.value, def.value.id, t.steps)
const used = transistors(def.value.id)
const before = project.value.best?.[t.id]
if (!res.pass) {
play('fail')
return { ...res, transistors: used, best: before }
}
let changed = false
const first = !project.value.solved.includes(t.id)
const opened = first && t.challenge ? unlockedBy(project.value, t.id) : { challenges: [], kinds: [] }
if (first) {
project.value.solved.push(t.id)
changed = true
}
const record = before === undefined || used < before
if (record) {
project.value.best = { ...project.value.best, [t.id]: used }
changed = true
}
if (changed) {
commit(false)
persist()
}
const unlocked = isCampaign(project.value) && first && t.challenge ? [def.value.name, ...opened.kinds.map(k => KIND_NAMES[k] ?? k)] : []
const nextUp = opened.challenges.map(challengeName)
play(record && before !== undefined ? 'record' : 'solve')
if (unlocked.length || nextUp.length) play('unlock')
if (t.puzzle) void submitScore(t.puzzle)
return {
...res,
transistors: used,
best: record ? used : before,
record: record && before !== undefined ? before : undefined,
unlocked,
nextUp,
}
}
// ── Puzzles ───────────────────────────────────────────────────────
/** A random id for this browser, so the server can keep one best score per player. */
function playerId(): string {
try {
let id = localStorage.getItem('logigate:player')
if (!id) {
id = uid('p') + uid() + uid()
localStorage.setItem('logigate:player', id)
}
return id
} catch {
return 'anonymous-player'
}
}
/** How everyone did, per puzzle id, as last heard from the server. */
const boards = reactive<Record<string, PuzzleSummary>>({})
async function loadBoard(spec: PuzzleSpec) {
try {
const res = await api<{ summary: PuzzleSummary }>('GET', `/api/puzzles/${apiId(spec.id)}?player=${encodeURIComponent(playerId())}`)
boards[spec.id] = res.summary
} catch {}
}
async function submitScore(spec: PuzzleSpec) {
try {
const res = await api<{ score: { pass: boolean; transistors: number }; summary: PuzzleSummary }>('POST', `/api/puzzles/${apiId(spec.id)}/scores`, {
player: playerId(),
defId: def.value.id,
components: toRaw(project.value.components),
})
boards[spec.id] = res.summary
} catch (e) {
notify(`Your score could not be sent: ${(e as Error).message}`, 'error')
}
}
function beginPuzzle(spec: PuzzleSpec) {
const d = startPuzzle(project.value, spec)
commit()
open(d.id)
void loadBoard(spec)
}
/** Opens a puzzle from the server: a link id, or "weekly". */
async function openPuzzle(id: string) {
try {
const res = await api<{ spec: PuzzleSpec; summary: PuzzleSummary }>('GET', `/api/puzzles/${encodeURIComponent(id)}?player=${encodeURIComponent(playerId())}`)
boards[res.spec.id] = res.summary
beginPuzzle(res.spec)
notify(`Puzzle: ${res.spec.name}`)
} catch (e) {
notify((e as Error).message, 'error')
} finally {
syncUrl()
}
}
/** Publishes the open circuit as a puzzle; returns its link. */
async function publishPuzzle(name: string, goal: string): Promise<string> {
const spec = makePuzzle(toRaw(project.value.components), def.value.id, name, goal)
const res = await api<{ id: string }>('POST', '/api/puzzles', { puzzle: spec })
return `${location.origin}/puzzle/${res.id}`
}
// ── Several parts at once ─────────────────────────────────────────
const nodesById = (ids: string[]) => {
const set = new Set(ids)
return def.value.nodes.filter(n => set.has(n.id))
}
/** Swaps every given part for the same new one, keeping wires on matching pins. One undo step. */
function swapMany(ids: string[], target: SwapTarget) {
let removed = 0
for (const n of nodesById(ids)) {
if (n.kind === target.kind && n.chip === target.chip) continue
removed += swapNode(project.value, def.value, n.id, target)
}
commit()
notify(removed ? `Swapped. ${removed} wire${removed === 1 ? '' : 's'} had no matching pin and were removed.` : `Swapped ${ids.length} parts`)
}
/** Names the parts top to bottom from a pattern (D# → D0, D1, …). An empty pattern clears their names. */
function renameMany(ids: string[], pattern: string, start = 0) {
const nodes = nodesById(ids).sort(byPosition)
const names = numberedNames(pattern, nodes.length, start)
nodes.forEach((n, i) => {
if (pattern.trim()) n.label = names[i]
else delete n.label
delete n.autoLabel
})
// Signal names decide what connects.
commit(nodes.some(n => n.kind === 'tag' || n.kind === 'ref'))
}
/** A name typed by hand (Pins list); empty lets connections name the part again. */
function setLabel(node: CircuitNode, label: string, row?: PanelRow) {
const v = label.trim()
if (row) {
if (v) row.label = v
else delete row.label
return commit()
}
if (v) node.label = v
else delete node.label
delete node.autoLabel
commit(false)
}
/** Sets the switches among the parts to 0 or 1, or flips each. */
function setSwitches(ids: string[], to: boolean | 'flip') {
for (const n of nodesById(ids)) {
if (n.kind !== 'input') continue
const on = to === 'flip' ? !n.on : to
if (!!n.on === on) continue
n.on = on
sim.value?.setSource(n.id, on)
}
play(to === false ? 'off' : 'on')
persist()
}
/** The same setting on every part (colour, frequency, note size); undefined removes it. */
function patchMany(ids: string[], patch: Pick<CircuitNode, 'color' | 'hz' | 'size'>, structural = false) {
for (const n of nodesById(ids)) {
for (const [k, v] of Object.entries(patch) as [keyof typeof patch, never][]) {
if (v === undefined) delete n[k]
else n[k] = v
}
}
commit(structural)
}
function arrangeSelected(how: Arrange) {
arrangeNodes(nodesById(selection.value), how)
commit(false)
}
/** Narrows the selection to some of its parts. */
function selectOnly(ids: string[]) {
selection.value = ids
wireSel.value = []
}
/** A reference to a signal, placed to the right of its tag and selected. */
function useSignal(tag: CircuitNode) {
const name = tag.label?.trim()
if (!name) return notify('Give the signal a name first', 'error')
const b = shapeOf(tag, getDef.value).body
const ref: CircuitNode = { id: uid('n'), kind: 'ref', x: Math.round(tag.x + b.x + b.w + 3), y: tag.y, label: name }
def.value.nodes.push(ref)
selection.value = [ref.id]
wireSel.value = []
commit()
play('place')
}
/** Every tag and reference of a signal. */
function selectSignal(name: string) {
selection.value = def.value.nodes.filter(n => (n.kind === 'tag' || n.kind === 'ref') && n.label?.trim() === name).map(n => n.id)
wireSel.value = []
}
/** Selects a part and centres the view on it. */
function focusNode(id: string) {
selection.value = [id]
wireSel.value = []
focusRequest.value = { id, n: (focusRequest.value?.n ?? 0) + 1 }
}
// ── Transistors ───────────────────────────────────────────────────
const nands = computed(() => nandCounts(project.value.components))
/** Transistors in a component at every depth, 4 per NAND gate. */
function transistors(defId: string): number {
return (nands.value.get(defId) ?? 0) * TRANSISTORS_PER_NAND
}
/** Transistors in one placed part: 4 for a NAND, its whole inside for a component, 0 for switches, lamps and cables. */
function transistorsOfNode(n: CircuitNode): number {
const child = n.kind === 'chip' && n.chip ? getDef.value(n.chip) : undefined
const bubbles = invertedPins(n, child ? chipPins(child) : undefined).length * TRANSISTORS_PER_NAND
if (n.kind === 'nand') return TRANSISTORS_PER_NAND + bubbles
return (n.kind === 'chip' && n.chip ? transistors(n.chip) : 0) + bubbles
}
/** Puts a bubble on an input (it reads the signal inverted, through one NAND), or takes it off. */
function toggleInvert(n: CircuitNode, pin: string) {
if (!INVERTIBLE.has(n.kind)) return
const set = new Set(n.invert ?? [])
if (!set.delete(pin)) set.add(pin)
if (set.size) n.invert = [...set]
else delete n.invert
commit()
}
// ── Cables ────────────────────────────────────────────────────────
/** Bundling with a chosen route: the next click places the start of the cable, the one after its end. */
const cabling = ref<{ wires: string[]; start?: Pt } | null>(null)
function startCable(wires = wireSel.value) {
if (wires.length < 2) return notify('Select at least two wires to bundle (Shift + click or drag a box)', 'error')
placing.value = null
linking.value = null
cabling.value = { wires: [...wires] }
}
function placeCable(at: Pt) {
const c = cabling.value
if (!c) return
if (!c.start) {
c.start = at
return
}
cabling.value = null
bundleSelected(c.wires, { start: c.start, end: at })
}
/** Colour of a cable's sleeve (every cable leaving that bundle); undefined for the default. */
function setCableColor(bundleId: string, color: WireColor | undefined) {
for (const w of def.value.wires) {
if (w.from.node !== bundleId) continue
if (color) w.color = color
else delete w.color
}
commit(false)
}
function bundleSelected(wires = wireSel.value, at?: { start: Pt; end: Pt }) {
const res = bundleWires(def.value, wires, getDef.value, at)
if (!res.ok) return notify(res.error, 'error')
selection.value = [res.bundle.id, res.split.id]
wireSel.value = []
commit()
notify(`${res.bundle.bits} wires bundled into one cable`)
}
function removeCable(bundleId: string) {
const n = dissolveCable(def.value, bundleId)
clearSelection()
commit()
notify(n ? `Cable removed; ${n} wire${n === 1 ? '' : 's'} run on their own again` : 'Cable removed')
}
function setBits(node: CircuitNode, bits: number) {
node.bits = Math.min(MAX_BITS, Math.max(2, Math.round(bits) || 2))
commit()
}
function table(): TruthTable | { error: string } {
return truthTable(getDef.value, def.value.id)
}
// ── Projects ──────────────────────────────────────────────────────
function activate(m: ProjectMeta, p: Project) {
placeholder = false
meta.value = m
project.value = p
setCurrentId(m.id)
resetHistory()
nav.value = []
clearSelection()
placing.value = null
linking.value = null
for (const k of Object.keys(views)) delete views[k]
linkState.value = m.link ? (m.link.key ? 'saved' : 'viewer') : 'none'
projects.value = listProjects()
syncUrl()
rebuild()
}
function switchProject(id: string) {
if (id === meta.value.id) return
persistNow()
const p = loadProject(id)
const m = listProjects().find(x => x.id === id)
if (!p || !m) return notify('Could not open that project', 'error')
activate(m, p)
}
function addProject(p: Project, link?: ProjectMeta['link']): ProjectMeta {
const m: ProjectMeta = { id: newLocalId(), name: p.name, updated: Date.now() }
if (link) m.link = link
saveProject(m, p)
scheduleCloud()
return m
}
function newProject(examples: boolean, campaign = false) {
persistNow()
const p = createProject({ examples, campaign })
activate(addProject(p), p)
if (campaign) notify('Campaign started: you have NAND. Open Challenges on the left and build NOT first.')
}
function duplicateProject(id: string) {
persistNow()
const p = loadProject(id)
if (!p) return
p.name = `${p.name} copy`
activate(addProject(p), p)
}
function deleteProject(id: string) {
const gone = listProjects().find(m => m.id === id)
if (gone?.cloud) {
setPendingDeletes([...pendingDeletes(), { owner: gone.cloud.owner, id }])
scheduleCloud()
}
removeProject(id)
projects.value = listProjects()
if (id !== meta.value.id) return
const next = projects.value[0]
const p = next && loadProject(next.id)
if (next && p) activate(next, p)
else {
const fresh = createProject({ examples: true })
activate(addProject(fresh), fresh)
}
}
function renameProject(id: string, name: string) {
const clean = name.trim().slice(0, 80) || 'Untitled'
if (id === meta.value.id) {
project.value.name = clean
persist()
return
}
const p = loadProject(id)
const m = listProjects().find(x => x.id === id)
if (!p || !m) return
p.name = clean
saveProject({ ...m, name: clean, dirty: true }, p)
projects.value = listProjects()
scheduleCloud()
}
function loadExamples() {
const n = addExamples(project.value)
commit()
notify(n ? `Added ${n} example parts` : 'All examples are already here')
}
function download(name: string, text: string, type = 'application/json') {
const blob = new Blob([text], { type })
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = name
a.click()
URL.revokeObjectURL(a.href)
}
const slug = (name: string, fallback: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || fallback
function exportJson() {
persistNow()
download(`${slug(project.value.name, 'project')}.logigate.json`, JSON.stringify(project.value, null, 1))
}
function exportTable(t: TruthTable) {
download(`${slug(def.value.name, 'circuit')}-truth-table.csv`, tableCsv(t), 'text/csv')
}
/** Opens a project file as a new project in the library. */
async function importAsProject(file: File) {
try {
const p = parseProject(await file.text())
if (p.name === 'Untitled') p.name = file.name.replace(/(\.logigate)?\.json$/i, '')
persistNow()
activate(addProject(p), p)
notify(`Opened ${file.name}`)
} catch (e) {
notify((e as Error).message, 'error')
}
}
/** Adds the components of a project file to the open project. */
async function importComponents(file: File) {
try {
const p = parseProject(await file.text())
const n = mergeComponents(project.value, p.components)
commit()
notify(n ? `Added ${n} component${n === 1 ? '' : 's'} from ${file.name}` : 'Nothing new in that file')
} catch (e) {
notify((e as Error).message, 'error')
}
}
// ── Share links ───────────────────────────────────────────────────
const linkState = ref<LinkState>(meta.value.link ? (meta.value.link.key ? 'saved' : 'viewer') : 'none')
const linkError = ref('')
const linkUrl = computed(() => (meta.value.link ? `${location.origin}/p/${meta.value.link.id}` : ''))
function syncUrl() {
const path = meta.value.link ? `/p/${meta.value.link.id}` : '/'
if (location.pathname !== path) history.replaceState(history.state, '', path)
}
async function api<T>(method: string, url: string, body?: unknown, key?: string): Promise<T> {
const res = await fetch(url, {
method,
headers: { 'content-type': 'application/json', ...(key ? { 'x-edit-key': key } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) throw new Error((data as { message?: string }).message || `Server error ${res.status}`)
return data as T
}
async function createLink() {
persistNow()
linkState.value = 'saving'
try {
const res = await api<{ id: string; key: string }>('POST', '/api/p', { project: toRaw(project.value) })
meta.value = { ...meta.value, link: { id: res.id, key: res.key }, dirty: true }
saveMeta(toRaw(meta.value))
scheduleCloud()
projects.value = listProjects()
linkState.value = 'saved'
syncUrl()
} catch (e) {
linkError.value = (e as Error).message
linkState.value = 'error'
}
}
let syncTimer: ReturnType<typeof setTimeout> | undefined
let syncing = false
async function pushLink() {
const link = meta.value.link
if (!link?.key) return
if (syncing) return scheduleSync()
syncing = true
linkState.value = 'saving'
try {
await api('PUT', `/api/p/${link.id}`, { project: toRaw(project.value) }, link.key)
linkState.value = 'saved'
} catch (e) {
linkError.value = (e as Error).message
linkState.value = 'error'
} finally {
syncing = false
}
}
/** The person who made a link saves to it automatically, a few seconds after each change. */
function scheduleSync() {
if (!meta.value.link?.key) return
linkState.value = 'dirty'
clearTimeout(syncTimer)
syncTimer = setTimeout(pushLink, 2500)
}
/** Editing someone else's shared project turns it into your own copy. */
function forkIfViewer() {
if (!meta.value.link || meta.value.link.key) return
meta.value = { ...meta.value, link: undefined }
saveMeta(toRaw(meta.value))
linkState.value = 'none'
syncUrl()
notify('This is now your own copy. Share it to get your own link.')
}
/** Opens /p/:id: your own linked project, or a fresh copy of someone else's. */
async function openLink(id: string) {
const list = listProjects()
const own = list.find(m => m.link?.id === id && m.link.key)
if (own) {
if (own.id !== meta.value.id) switchProject(own.id)
return
}
try {
const res = await fetch(`/api/p/${encodeURIComponent(id)}`)
if (!res.ok) throw new Error(res.status === 404 ? 'This link does not exist' : 'Could not load the link')
const data = (await res.json()) as { project: unknown }
const p = toProject(data.project)
if (!placeholder) persistNow()
const viewer = list.find(m => m.link?.id === id && !m.link.key)
if (viewer) {
const m = { ...viewer, name: p.name, updated: Date.now() }
saveProject(m, p)
activate(m, p)
} else activate(addProject(p, { id }), p)
notify(`Opened "${p.name}" from a shared link`)
} catch (e) {
notify((e as Error).message, 'error')
if (placeholder) persistNow()
syncUrl()
}
}
async function copyText(text: string, done = 'Link copied') {
try {
await navigator.clipboard.writeText(text)
notify(done)
} catch {
notify('Copy failed: the browser did not allow it', 'error')
}
}
window.addEventListener('beforeunload', () => {
if (saveTimer) persistNow()
})
// ── Account ───────────────────────────────────────────────────────
// Signed in, every project in this browser is also kept in the account and
// other devices get it on their next sync. Each upload names the revision
// it started from; when another device saved in between, both versions are
// kept (the other one as a copy) instead of one silently replacing the other.
const account = ref<AccountUser | null>(cachedAccount())
/** False while a signed-in browser is still loading the account's saves at startup: the menu waits, so nothing is started twice. */
const savesReady = ref(!account.value)
const cloudState = ref<'off' | 'syncing' | 'synced' | 'offline' | 'error'>(account.value ? 'syncing' : 'off')
const cloudError = ref('')
function setAccount(user: AccountUser | null) {
account.value = user
setCachedAccount(user)
cloudState.value = user ? cloudState.value : 'off'
}
async function authCall<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(url, {
method,
headers: { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
})
const data = await res.json().catch(() => ({}))
if (res.status === 401 && url.startsWith('/api/me/')) {
setAccount(null)
notify('You were signed out. Sign in again to keep syncing.', 'error')
}
if (!res.ok && res.status !== 409) throw new Error((data as { message?: string }).message || `Server error ${res.status}`)
return { ...(data as object), status: res.status } as T
}
function localProject(m: ProjectMeta): Project | null {
if (m.id === meta.value.id) {
if (saveTimer) persistNow()
return toRaw(project.value)
}
return loadProject(m.id)
}
function updateMeta(id: string, patch: Partial<ProjectMeta>) {
const m = listProjects().find(x => x.id === id)
if (!m) return
const next = { ...m, ...patch }
if (patch.dirty === false) delete next.dirty
saveMeta(next)
if (id === meta.value.id) meta.value = { ...meta.value, ...patch }
}
interface CloudMeta {
id: string
name: string
updated: number
rev: number
link?: ProjectMeta['link']
}
/** Replaces this browser's copy of a project with the account's current one. */
async function takeRemote(m: ProjectMeta, uid: string, remote: CloudMeta) {
const res = await authCall<{ project?: Project; status: number }>('GET', `/api/me/projects/${m.id}`)
if (!res.project) return
const p = toProject(res.project)
const next: ProjectMeta = { ...m, name: p.name, updated: remote.updated, cloud: { owner: uid, rev: remote.rev } }
delete next.dirty
delete next.snapshot
saveProject(next, p)
if (m.id === meta.value.id) activate(next, p)
}
/**
* One save per project on every device. When another device saved the same
* project in between, the newer save wins everywhere, and the other one is
* kept as a savegame of that project (Load → savegames), never as a copy.
*/
async function upload(m: ProjectMeta, uid: string) {
const p = localProject(m)
if (!p) return
const baseRev = m.cloud?.owner === uid ? m.cloud.rev : 0
const body = { project: p, baseRev, link: m.link, snapshot: m.snapshot === true }
let res = await authCall<{ meta?: CloudMeta; conflict?: boolean; status: number }>('PUT', `/api/me/projects/${m.id}`, body)
if (res.conflict && res.meta) {
if (res.meta.updated > m.updated) {
// The other device's save is newer: this one becomes a savegame.
await authCall('POST', `/api/me/projects/${m.id}/versions`, { project: p, baseRev })
await takeRemote(m, uid, res.meta)
notify(`"${m.name}" was changed later on another device and is loaded now. Your version here is in its savegames.`)
return
}
// This save is newer: it wins, and the server keeps the other one as a savegame.
res = await authCall('PUT', `/api/me/projects/${m.id}`, { ...body, force: true, snapshot: true })
notify(`"${m.name}" was also changed on another device. Yours is newer and saved; the other one is in its savegames.`)
}
if (res.meta) updateMeta(m.id, { cloud: { owner: uid, rev: res.meta.rev }, dirty: false, snapshot: undefined })
}
let syncingAccount = false
let syncAgain = false
/** Brings this browser and the account up to date in both directions. */
async function syncAccount() {
const uid = account.value?.id
if (!uid) return
if (syncingAccount) {
syncAgain = true
return
}
syncingAccount = true
cloudState.value = 'syncing'
try {
if (saveTimer) persistNow()
for (const d of pendingDeletes().filter(d => d.owner === uid)) {
await authCall('DELETE', `/api/me/projects/${d.id}`).catch(() => {})
}
setPendingDeletes(pendingDeletes().filter(d => d.owner !== uid))
const remote = await authCall<{ projects: CloudMeta[]; deleted: { id: string }[]; status: number }>('GET', '/api/me/projects')
if (!account.value) return
// Deleted on another device.
for (const t of remote.deleted) {
const m = listProjects().find(x => x.id === t.id && x.cloud?.owner === uid)
if (m && !m.dirty) {
if (m.id === meta.value.id) {
notify(`"${m.name}" was deleted on another device`)
deleteProject(m.id)
} else removeProject(m.id)
}
}
// New or newer in the account.
for (const r of remote.projects) {
const m = listProjects().find(x => x.id === r.id)
if (m && ((m.cloud && m.cloud.owner !== uid) || m.dirty || (m.cloud?.rev ?? 0) >= r.rev)) continue
const res = await authCall<{ project?: Project; status: number }>('GET', `/api/me/projects/${r.id}`)
if (!res.project) continue
const p = toProject(res.project)
const next: ProjectMeta = { id: r.id, name: p.name, updated: r.updated, cloud: { owner: uid, rev: r.rev } }
const link = r.link ?? m?.link
if (link) next.link = link
saveProject(next, p)
if (r.id === meta.value.id) {
activate(next, p)
notify(`Updated "${p.name}" from another device`)
}
}
// Projects that are new here or changed here (not the untouched starter project).
for (const m of listProjects()) {
if ((m.cloud && m.cloud.owner !== uid) || (m.starter && !m.dirty)) continue
if (!m.cloud || m.dirty) await upload(m, uid)
}
// A new browser: open the account's latest project instead of the untouched starter.
if (meta.value.starter && !meta.value.dirty) {
const latest = listProjects().filter(m => m.cloud?.owner === uid).sort((a, b) => b.updated - a.updated)[0]
const p = latest && loadProject(latest.id)
if (latest && p) {
const starter = meta.value.id
activate(latest, p)
removeProject(starter)
}
}
projects.value = listProjects()
cloudState.value = 'synced'
cloudError.value = ''
} catch (e) {
cloudError.value = (e as Error).message
cloudState.value = navigator.onLine ? 'error' : 'offline'
} finally {
syncingAccount = false
if (syncAgain) {
syncAgain = false
void syncAccount()
}
}
}
let cloudTimer: ReturnType<typeof setTimeout> | undefined
function scheduleCloud() {
if (!account.value) return
clearTimeout(cloudTimer)
cloudTimer = setTimeout(syncAccount, 2000)
}
async function signIn(email: string, password: string, create: boolean) {
const res = await authCall<{ user?: AccountUser; message?: string; status: number }>('POST', create ? '/api/auth/register' : '/api/auth/login', { email, password })
if (!res.user) throw new Error(res.message || 'Could not sign in')
setAccount(res.user)
await syncAccount()
notify(create ? 'Account created. Your projects are now saved in it.' : `Signed in as ${res.user.email}`)
}
async function signOut(removeHere: boolean) {
const uid = account.value?.id
if (uid) await syncAccount()
await authCall('POST', '/api/auth/logout').catch(() => {})
setAccount(null)
if (removeHere && uid) {
for (const m of listProjects()) if (m.cloud?.owner === uid && !m.dirty) removeProject(m.id)
projects.value = listProjects()
if (!projects.value.some(m => m.id === meta.value.id)) deleteProject(meta.value.id)
}
notify('Signed out')
}
async function changePassword(current: string, next: string) {
await authCall('POST', '/api/auth/password', { current, next })
notify('Password changed. Other devices need to sign in again.')
}
async function deleteAccount(password: string) {
const uid = account.value?.id
await authCall('POST', '/api/auth/delete', { password })
setAccount(null)
// The projects stay in this browser, now as local-only projects.
for (const m of listProjects()) {
if (m.cloud?.owner !== uid) continue
const next = { ...m }
delete next.cloud
saveMeta(next)
}
if (meta.value.cloud?.owner === uid) {
const next = { ...meta.value }
delete next.cloud
meta.value = next
}
projects.value = listProjects()
notify('Account deleted. Your projects are still in this browser.')
}
// ── Savegames ─────────────────────────────────────────────────────
interface VersionInfo {
v: number
at: number
rev: number
name: string
size: number
}
async function listVersions(projectId: string): Promise<VersionInfo[]> {
const res = await authCall<{ versions: VersionInfo[]; status: number }>('GET', `/api/me/projects/${projectId}/versions`)
return res.versions ?? []
}
async function fetchVersion(projectId: string, v: number): Promise<Project> {
const res = await authCall<{ version?: { project: unknown }; status: number }>('GET', `/api/me/projects/${projectId}/versions/${v}`)
if (!res.version) throw new Error('Version not found')
return toProject(res.version.project)
}
/**
* Brings back a savegame: as a new project, or in place of the current
* state (which the server keeps as a savegame first, so this can be undone).
*/
async function restoreVersion(projectId: string, v: number, asCopy: boolean) {
if (projectId === meta.value.id && saveTimer) persistNow()
const p = await fetchVersion(projectId, v)
if (asCopy) {
p.name = `${p.name} (${new Date(v).toLocaleDateString()})`
activate(addProject(p), p)
notify(`Opened the saved version as "${p.name}"`)
return
}
const m = listProjects().find(x => x.id === projectId)
if (!m) return
const next: ProjectMeta = { ...m, name: p.name, updated: Date.now(), dirty: true, snapshot: true }
saveProject(next, p)
activate(next, p)
scheduleCloud()
notify('Restored. The state before is kept as a savegame too.')
}
async function listTrash(): Promise<{ id: string; name: string; deleted: number; v: number }[]> {
const res = await authCall<{ projects: { id: string; name: string; deleted: number; v: number }[]; status: number }>('GET', '/api/me/trash')
return res.projects ?? []
}
async function restoreDeleted(item: { id: string; v: number }) {
const p = await fetchVersion(item.id, item.v)
persistNow()
setPendingDeletes(pendingDeletes().filter(d => d.id !== item.id))
const m: ProjectMeta = { id: item.id, name: p.name, updated: Date.now(), dirty: true }
saveProject(m, p)
activate(m, p)
scheduleCloud()
notify(`"${p.name}" is back`)
}
/** Checks the session with the server, then syncs; again on focus and every minute. */
async function startAccount() {
try {
const res = await authCall<{ user: AccountUser | null; status: number }>('GET', '/api/auth/me')
setAccount(res.user)
if (res.user) await syncAccount()
} catch {
if (account.value) cloudState.value = 'offline'
} finally {
savesReady.value = true
}
let lastFocusSync = Date.now()
const onFocus = () => {
if (document.visibilityState === 'visible' && Date.now() - lastFocusSync > 10_000) {
lastFocusSync = Date.now()
void syncAccount()
}
}
document.addEventListener('visibilitychange', onFocus)
window.addEventListener('online', () => void syncAccount())
setInterval(() => document.visibilityState === 'visible' && void syncAccount(), 60_000)
}
function shape(node: CircuitNode) {
return shapeOf(node, getDef.value)
}
rebuild()
return {
project,
meta,
projects,
getDef,
def,
selection,
wireSel,
selectedWires,
clearSelection,
placing,
nav,
views,
notice,
labelFocus,
showHelp,
dialog,
notify,
commit,
persist,
undo,
redo,
canUndo,
canRedo,
sim,
tick,
status,
running,
hz,
cycles,
errors,
circuitStats,
val,
faceVal,
startLoop,
step,
rebuild,
open,
back,
addNode,
canPlace,
connect,
deleteSelected,
setWireColor,
autoRoute,
selectNet,
toggleInput,
press,
toggleRow,
pressRow,
addPanel,
undock,
mergeSelectedPanels,
combineSelected,
setRowsType,
setScreen,
screen,
menuPage,
paletteTab,
enterGame,
showMenu,
projectMode,
projectOf,
playCampaign,
playChallenge,
playWeekly,
playerName,
setPlayerName,
fetchBoard,
setRowType,
addRow,
dropRow,
withDocked,
withFollowers,
issues,
showIssue,
sheetRequest,
exportSheet,
faceFor,
designFace,
fits,
fitHover,
connectFit,
unplugMoved,
moveRow,
setRowGap,
setRowKey,
setRowColor,
plugTarget,
plugEnd,
unplugEnd,
setPitch,
addCablePanel,
dragPart,
partSearch,
cableChoices,
cableOut,
cableIn,
linking,
startLinking,
linkTo,
stopLinking,
setTidy,
tidyAll,
exportTable,
transistors,
transistorsOfNode,
toggleInvert,
nands,
rightTab,
sidebars,
toggleSidebar,
focusRequest,
swapMany,
connectMany,
connectSelectionTo,
rewire,
renameMany,
setLabel,
setSwitches,
patchMany,
arrangeSelected,
selectOnly,
focusNode,
useSignal,
selectSignal,
canPlaceKind,
paused,
pause,
saveNow,
savesReady,
setInputs,
sound,
setSound,
play,
task,
boards,
loadBoard,
beginPuzzle,
openPuzzle,
publishPuzzle,
isBus,
bundleSelected,
cabling,
startCable,
placeCable,
setCableColor,
removeCable,
setBits,
swap,
unlink,
unpack,
makeIndependent,
copy,
paste,
hasClip,
duplicate,
selectAll,
packageSelected,
createComponent,
removeComponent,
copyComponent,
beginChallenge,
checkChallenge,
table,
switchProject,
newProject,
duplicateProject,
deleteProject,
renameProject,
loadExamples,
exportJson,
importAsProject,
importComponents,
linkState,
linkError,
linkUrl,
createLink,
pushLink,
openLink,
syncUrl,
account,
cloudState,
cloudError,
syncAccount,
signIn,
signOut,
changePassword,
deleteAccount,
startAccount,
versionsFor,
listVersions,
restoreVersion,
listTrash,
restoreDeleted,
copyText,
shape,
}
}
let editor: ReturnType<typeof create> | undefined
export function useEditor() {
editor ??= create()
return editor
}