A settings for every part, overlap-free wiring with crossing styles, accounts with sync

- Clicking anything opens its settings: swap parts in place (wires stay on
  matching pins), clock frequency per clock, keyboard keys for switches and
  buttons, lamp/display colours, note sizes, component names on the canvas,
  position, unlink all wires, unpack a component, make an independent copy.
- Wires of different signals never share a line: auto routes pick free
  columns or detours, remaining clashes go on separate lanes. Crossings drawn
  as bow, triangle, bridge, gap or plain.
- Accounts (email + scrypt password, httpOnly session) with two-way project
  sync and conflict copies; per-account limits; cross-site writes refused.
- Compatibility suite: a project and both browser-storage layouts from
  release a241adc must load and compute identically.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-20 13:09:37 +02:00
parent a241adc94e
commit 5e17826ba5
43 changed files with 6542 additions and 117 deletions

View File

@ -2,17 +2,20 @@
Logic circuit editor and simulator at <https://logicate.blax.at>, in the spirit of the game "Turing Complete". NAND is the only gate. You draw circuits with it, package them as components, and reuse those in bigger circuits, up to a CPU. Everything runs live while you draw: green wires carry a 1, grey wires a 0.
Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@nuxt/icon`, Inter and JetBrains Mono self-hosted via `@nuxt/fonts`. No tracking. Projects live in the browser's localStorage; the only server part is the share-link API.
Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@nuxt/icon`, Inter and JetBrains Mono self-hosted via `@nuxt/fonts`. No tracking. Projects live in the browser's localStorage, and in the user's account when signed in. The server part is the share-link and account API.
## What it does
- Parts: NAND, input switch, output pin, lamp, push button, clock, constant 1, ground, hex display, note.
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
- Lamps and hex displays inside a component show on its box, with their labels, lit by that instance's state. They are laid out in rows the way they sit inside. A checkbox in the inspector turns this off per component.
- Clicking anything opens its settings on the right. Parts can be swapped in place (wires stay on the pins in the same position): NAND and components with each other, switch/button/clock/constants with each other, output/lamp/display with each other. Clocks have their own frequency or follow the top bar. Switches and buttons can get a keyboard key. Lamps and displays have colours, notes have sizes, components a name on the canvas. Components can be unpacked into their parts or given their own copy of the definition; any part can have all its wires unlinked.
- Select parts and press "Make component" to turn them into a new component; wires crossing the selection become pins.
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Display settings on the right with nothing selected). Clicking a junction dot selects its whole signal.
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
- Several projects per browser (Projects dialog: open, rename, duplicate, delete). Export a project file, open a file as a new project, or add the components of a file to the open project.
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). If two computers changed the same project, both versions are kept. The untouched starter project of a new browser is not uploaded; signing in there opens your latest project instead.
- Share links: `/p/<id>`. The creator's changes save to the link automatically. Anyone else who opens it gets their own copy; their first edit detaches it from the link.
- Truth table, NAND count, gate delay, and loop detection for the open circuit.
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
@ -27,6 +30,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
- Gate outputs are keyed by their path ("chipNode/chipNode/nand"), so latch state survives editing.
- `analyze.ts` builds truth tables, counts NANDs, computes the longest gate path, and runs challenge tests.
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings).
- `wires.ts` edits wire routes (segment and corner drags, splits, branches); `project.ts` validates project data for both the browser and the server; `storage.ts` is the browser's project library.
The editor UI is in [app/components/editor/](app/components/editor/) with state in [app/composables/useEditor.ts](app/composables/useEditor.ts).
@ -35,6 +39,14 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state
[server/api/p/](server/api/p/): `POST /api/p` stores a project and returns `{ id, key }`; `GET /api/p/:id` reads it; `PUT /api/p/:id` with header `x-edit-key` replaces it. Only a SHA-256 of the key is stored. Each link is one JSON file in `data/shares/` (Nitro fs storage). Limits: 2 MB and 100,000 nodes per project, 30 new links and 600 saves per IP per 10 minutes (in memory). The edit key lives only in the creator's browser (project index in localStorage), never in exported files.
## Accounts
[server/api/auth/](server/api/auth/) (register, login, logout, me, password, delete) and [server/api/me/projects/](server/api/me/projects/) (list, get, put, delete). Passwords are hashed with scrypt; the session is a random token in an httpOnly, SameSite=Lax cookie, stored server-side as a SHA-256. API calls that change something are refused when their Origin is another site. Storage (Nitro fs): `data/users`, `data/sessions`, `data/accounts/<uid>/` with an index (revision per project, deletions for a year) and one file per project. Each save sends the revision it started from; a mismatch answers 409 and the browser keeps the other version as a copy. Limits: 1000 projects and 100 MB per account, 2 MB per project, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
## Compatibility
Projects saved by earlier releases must keep working. [tests/compat.test.ts](tests/compat.test.ts) loads a project and both browser-storage layouts written by release a241adc ([tests/fixtures/](tests/fixtures/), never edit them) and checks every component's truth table, NAND count and delay. New fields are optional and have defaults.
## Develop
```bash
@ -47,4 +59,4 @@ pnpm build # .output/
## Deploy
Same pattern as autismus-spektrum. On edgerealm the repo lives in `/mnt/HC_Volume_102040804/srv/logigate`; run `./deploy.sh` there. It pulls, builds in a one-shot container and recreates the `logigate` container. Shared projects live in `data/` next to the repo (mounted into the container), so redeploys keep them; include that folder in backups. Host nginx terminates TLS with the `*.blax.at` wildcard cert and forwards to Traefik, which routes `logicate.blax.at` and `logigate.blax.at` by the labels in [docker-compose.yml](docker-compose.yml).
Same pattern as autismus-spektrum. On edgerealm the repo lives in `/mnt/HC_Volume_102040804/srv/logigate`; run `./deploy.sh` there. It pulls, builds in a one-shot container and recreates the `logigate` container. Share links and accounts live in `data/` next to the repo (mounted into the container), so redeploys keep them; include that folder in backups. Host nginx terminates TLS with the `*.blax.at` wildcard cert and forwards to Traefik, which routes `logicate.blax.at` and `logigate.blax.at` by the labels in [docker-compose.yml](docker-compose.yml).

View File

@ -1370,3 +1370,119 @@ kbd {
.modal.share .result {
align-items: center;
}
/* Lamp and display colours */
.lamp.on.l-red { fill: #ff5c5c; stroke: #ffc2c2; filter: drop-shadow(0 0 6px rgb(255 92 92 / 0.75)); }
.lamp.on.l-green { fill: #3ddc84; stroke: #b5f5d0; filter: drop-shadow(0 0 6px rgb(61 220 132 / 0.75)); }
.lamp.on.l-blue { fill: #4dabff; stroke: #bfe0ff; filter: drop-shadow(0 0 6px rgb(77 171 255 / 0.75)); }
.lamp.on.l-white { fill: #f4f6fa; stroke: #ffffff; filter: drop-shadow(0 0 6px rgb(244 246 250 / 0.7)); }
.l-yellow .seg.on { stroke: #ffd34d; filter: drop-shadow(0 0 3px rgb(255 211 77 / 0.8)); }
.l-green .seg.on { stroke: #3ddc84; filter: drop-shadow(0 0 3px rgb(61 220 132 / 0.8)); }
.l-blue .seg.on { stroke: #4dabff; filter: drop-shadow(0 0 3px rgb(77 171 255 / 0.8)); }
.l-white .seg.on { stroke: #f4f6fa; filter: drop-shadow(0 0 3px rgb(244 246 250 / 0.7)); }
.lamp-swatch.default,
.lamp-swatch.l-yellow { background: #ffd34d; }
.lamp-swatch.default.hex,
.lamp-swatch.l-red { background: #ff5c5c; }
.lamp-swatch.l-green { background: #3ddc84; }
.lamp-swatch.l-blue { background: #4dabff; }
.lamp-swatch.l-white { background: #f4f6fa; }
.instance-label {
fill: var(--accent);
font-family: var(--font-mono);
font-size: 10px;
font-weight: 600;
pointer-events: none;
}
.key-badge {
fill: var(--muted);
font-family: var(--font-mono);
font-size: 8px;
pointer-events: none;
}
.junction {
cursor: pointer;
}
.key-input {
cursor: pointer;
caret-color: transparent;
}
.field.mb-0 {
margin-bottom: 0;
}
.crossings {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 4px;
}
.crossing {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 4px 0 3px;
border: 1px solid var(--border);
border-radius: 6px;
font-size: 10px;
color: var(--muted);
}
.crossing.active {
border-color: var(--accent);
color: var(--accent);
background: rgb(76 194 255 / 0.08);
}
.ci-v,
.ci-h {
fill: none;
stroke-width: 2;
stroke-linejoin: round;
}
.ci-v { stroke: var(--muted); }
.ci-h { stroke: var(--on); }
.account-btn {
position: relative;
}
.avatar {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border-radius: 50%;
background: rgb(76 194 255 / 0.18);
color: var(--accent);
font-size: 11px;
font-weight: 700;
}
.sync-dot {
position: absolute;
right: 5px;
bottom: 5px;
width: 7px;
height: 7px;
border-radius: 50%;
border: 1.5px solid var(--panel);
background: var(--muted);
}
.account-btn.synced .sync-dot { background: var(--on); }
.account-btn.syncing .sync-dot { background: var(--lamp); }
.account-btn.error .sync-dot,
.account-btn.offline .sync-dot { background: var(--danger); }
.modal .hint a {
color: var(--accent);
}

View File

@ -0,0 +1,139 @@
<script setup lang="ts">
const ed = useEditor()
const close = () => (ed.dialog.value = null)
const mode = ref<'signin' | 'create'>('signin')
const email = ref('')
const password = ref('')
const error = ref('')
const busy = ref(false)
const current = ref('')
const next = ref('')
const removeHere = ref(false)
const deletePw = ref('')
const panel = ref<'' | 'password' | 'delete'>('')
const STATE: Record<string, string> = {
syncing: 'Syncing…',
synced: 'All projects are saved in your account',
offline: 'Offline. Changes are kept here and sync when you are back online.',
error: 'Sync failed',
}
async function run(fn: () => Promise<unknown>) {
error.value = ''
busy.value = true
try {
await fn()
return true
} catch (e) {
error.value = (e as Error).message
return false
} finally {
busy.value = false
}
}
async function submit() {
if (await run(() => ed.signIn(email.value, password.value, mode.value === 'create'))) {
password.value = ''
close()
}
}
async function savePassword() {
if (await run(() => ed.changePassword(current.value, next.value))) {
current.value = next.value = ''
panel.value = ''
}
}
async function signOut() {
if (await run(() => ed.signOut(removeHere.value))) close()
}
async function deleteAccount() {
if (await run(() => ed.deleteAccount(deletePw.value))) close()
}
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal account" role="dialog" aria-labelledby="account-title">
<div class="flex items-start justify-between gap-4">
<h2 id="account-title">{{ ed.account.value ? 'Your account' : mode === 'signin' ? 'Sign in' : 'Create an account' }}</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<template v-if="!ed.account.value">
<p class="hint mt-1">
With an account your projects follow you to every computer and browser you sign in on. Projects you already have here are added to it.
</p>
<div class="seg mb-4">
<button :class="{ active: mode === 'signin' }" @click="mode = 'signin'; error = ''">Sign in</button>
<button :class="{ active: mode === 'create' }" @click="mode = 'create'; error = ''">Create account</button>
</div>
<form class="grid gap-1" @submit.prevent="submit">
<label class="field">
<span>Email</span>
<input v-model="email" type="email" autocomplete="email" required />
</label>
<label class="field">
<span>Password{{ mode === 'create' ? ' (at least 8 characters)' : '' }}</span>
<input v-model="password" type="password" :autocomplete="mode === 'create' ? 'new-password' : 'current-password'" required minlength="8" />
</label>
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
<button class="btn btn-primary mt-2" type="submit" :disabled="busy">
<Icon :name="busy ? 'lucide:loader' : mode === 'signin' ? 'lucide:log-in' : 'lucide:user-plus'" class="size-4" :class="{ 'animate-spin': busy }" />
{{ mode === 'signin' ? 'Sign in' : 'Create account' }}
</button>
</form>
<p class="hint mt-4">
Stored on Blax Software's server: your email, your password in scrambled form (scrypt), and your projects. Nothing is shared or used for anything else, and you can delete the account any time.
</p>
</template>
<template v-else>
<p class="mt-2 text-sm">Signed in as <strong>{{ ed.account.value.email }}</strong></p>
<p class="result" :class="ed.cloudState.value === 'error' ? 'fail' : 'pass'">
<Icon
:name="ed.cloudState.value === 'synced' ? 'lucide:cloud-check' : ed.cloudState.value === 'syncing' ? 'lucide:refresh-cw' : 'lucide:cloud-off'"
class="size-4 shrink-0"
:class="{ 'animate-spin': ed.cloudState.value === 'syncing' }"
/>
{{ STATE[ed.cloudState.value] }}<template v-if="ed.cloudState.value === 'error'">: {{ ed.cloudError.value }}</template>
</p>
<div class="mt-3 flex flex-wrap gap-2">
<button class="btn" @click="ed.syncAccount()"><Icon name="lucide:refresh-cw" class="size-4" /> Sync now</button>
<button class="btn" @click="panel = panel === 'password' ? '' : 'password'"><Icon name="lucide:key-round" class="size-4" /> Change password</button>
</div>
<form v-if="panel === 'password'" class="mt-3 grid gap-1" @submit.prevent="savePassword">
<label class="field"><span>Current password</span><input v-model="current" type="password" autocomplete="current-password" required /></label>
<label class="field"><span>New password (at least 8 characters)</span><input v-model="next" type="password" autocomplete="new-password" required minlength="8" /></label>
<button class="btn btn-primary" type="submit" :disabled="busy">Save new password</button>
</form>
<h3>Sign out</h3>
<label class="check">
<input v-model="removeHere" type="checkbox" />
Also remove my projects from this browser (they stay in the account)
</label>
<button class="btn" :disabled="busy" @click="signOut"><Icon name="lucide:log-out" class="size-4" /> Sign out</button>
<h3>Delete account</h3>
<template v-if="panel !== 'delete'">
<button class="btn btn-ghost" @click="panel = 'delete'"><Icon name="lucide:trash-2" class="size-4" /> Delete account…</button>
</template>
<form v-else class="grid gap-1" @submit.prevent="deleteAccount">
<p class="hint">Deletes the account and every project stored in it. The projects in this browser stay here.</p>
<label class="field"><span>Password</span><input v-model="deletePw" type="password" autocomplete="current-password" required /></label>
<button class="btn btn-danger" type="submit" :disabled="busy">Delete account for good</button>
</form>
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
</template>
</div>
</div>
</template>

View File

@ -4,6 +4,7 @@ const ed = useEditor()
onMounted(() => {
const stop = ed.startLoop()
onBeforeUnmount(stop)
void ed.startAccount()
try {
if (!localStorage.getItem('logigate:help-seen')) ed.showHelp.value = true
} catch {}
@ -29,5 +30,6 @@ onMounted(() => {
<EditorHelp v-if="ed.showHelp.value" />
<EditorProjectsDialog v-if="ed.dialog.value === 'projects'" />
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
</div>
</template>

View File

@ -2,6 +2,8 @@
import { GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, Wire } from '~/lib/logic/types'
import { branchCorners, branchTo, moveCorner, moveSegment, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { wirePath } from '~/lib/draw'
const ed = useEditor()
const root = ref<HTMLDivElement>()
@ -18,7 +20,10 @@ const wireSelected = computed(() => new Set(ed.wireSel.value))
// ── Wires ───────────────────────────────────────────────────────────
interface Route {
wire: Wire
/** Whole-grid route, used for dragging, handles and hit areas. */
pts: Pt[]
/** Route as drawn: on its own lane where it would share a line with another signal. */
draw: Pt[]
d: string
src: string
}
@ -26,18 +31,15 @@ interface Route {
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
const routes = computed<Route[]>(() => {
const out: Route[] = []
for (const w of def.value.wires) {
const fn = nodeMap.value.get(w.from.node)
const tn = nodeMap.value.get(w.to.node)
if (!fn || !tn) continue
const a = pinPos(fn, shapes.value.get(fn.id)!, w.from.pin, 'out')
const b = pinPos(tn, shapes.value.get(tn.id)!, w.to.pin, 'in')
if (!a || !b) continue
const pts = routeWire([a.x, a.y], [b.x, b.y], w.pts)
out.push({ wire: w, pts, d: toPath(pts), src: `${w.from.node}:${w.from.pin}` })
const routed = circuitRoutes(def.value, shapes.value)
const hops = new Map<number, Map<number, number[]>>()
for (const c of findCrossings(routed)) {
const segs = hops.get(c.wire) ?? hops.set(c.wire, new Map()).get(c.wire)!
segs.set(c.seg, [...(segs.get(c.seg) ?? []), c.x])
}
return out
const style = ed.project.value.settings.crossing ?? 'bow'
const byId = new Map(def.value.wires.map(w => [w.id, w]))
return routed.map((r, k) => ({ wire: byId.get(r.id)!, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net }))
})
const routeOf = (wire: Wire) => routes.value.find(r => r.wire === wire)
@ -48,8 +50,8 @@ const junctions = computed(() => {
const colors = new Map<string, string>()
for (const r of routes.value) {
const g = groups.get(r.src)
if (g) g.push(r.pts)
else groups.set(r.src, [r.pts])
if (g) g.push(r.draw)
else groups.set(r.src, [r.draw])
if (r.wire.color && !colors.has(r.src)) colors.set(r.src, r.wire.color)
}
const dots: { x: number; y: number; src: string; color: string }[] = []
@ -244,6 +246,15 @@ function onPointerDown(e: PointerEvent) {
return
}
const junctionEl = target.closest('[data-junction]')
if (junctionEl) {
// A junction dot stands for its whole signal.
const src = junctionEl.getAttribute('data-junction')
ed.wireSel.value = def.value.wires.filter(x => `${x.from.node}:${x.from.pin}` === src).map(x => x.id)
ed.selection.value = []
return
}
const wireEl = target.closest('[data-wire]')
if (wireEl) return onWireDown(e, wireEl, w)
@ -480,6 +491,15 @@ function onKey(e: KeyboardEvent) {
}
const mod = e.ctrlKey || e.metaKey
const key = e.key.toLowerCase()
// Keys bound to switches and buttons win over the shortcuts below.
if (!mod && !e.altKey && e.key.length === 1) {
const bound = def.value.nodes.filter(n => n.key === key && (n.kind === 'input' || n.kind === 'button'))
if (bound.length) {
e.preventDefault()
if (!e.repeat) for (const n of bound) n.kind === 'input' ? ed.toggleInput(n) : ed.press(n, true)
return
}
}
if (mod && key === 'z') {
e.preventDefault()
if (e.shiftKey) ed.redo()
@ -519,6 +539,8 @@ function onKey(e: KeyboardEvent) {
function onKeyUp(e: KeyboardEvent) {
if (e.key === ' ') spaceDown.value = false
const key = e.key.toLowerCase()
for (const n of def.value.nodes) if (n.kind === 'button' && n.key === key) ed.press(n, false)
}
// ── Overlays ────────────────────────────────────────────────────────
@ -626,7 +648,7 @@ defineExpose({ fit, zoomAt })
/>
</g>
<g v-for="(j, i) in junctions" :key="`j${i}`" class="wire" :class="[j.color ? `c-${j.color}` : '', { on: srcVal(j.src) === 1 }]">
<circle :cx="j.x * G" :cy="j.y * G" r="3.2" class="junction" />
<circle :cx="j.x * G" :cy="j.y * G" r="3.2" class="junction" :data-junction="j.src" />
</g>
</g>

View File

@ -0,0 +1,14 @@
<script setup lang="ts">
import { wirePath } from '~/lib/draw'
import type { CrossingStyle } from '~/lib/logic/types'
const props = defineProps<{ style: CrossingStyle }>()
const d = computed(() => wirePath([[3, 14], [37, 14]], new Map([[0, [20]]]), props.style, 1))
</script>
<template>
<svg viewBox="0 0 40 24" width="40" height="24" aria-hidden="true">
<path d="M20 3V23" class="ci-v" />
<path :d="d" class="ci-h" />
</svg>
</template>

View File

@ -2,7 +2,8 @@
const ed = useEditor()
const SHORTCUTS: [string, string][] = [
['Click switch', 'Flip an input between 0 and 1'],
['Click switch', 'Flip an input between 0 and 1 (give it a keyboard key in its settings)'],
['Click anything', 'Its settings appear on the right: swap the part, clock speed, colours, keys, position'],
['Drag from a pin', 'Draw a wire to another pin'],
['Drag a wire segment', 'Move that segment; drag a corner square to move a bend'],
['Alt + drag a wire', 'Pull a new bend out of it'],
@ -62,7 +63,7 @@ function close() {
<dd>{{ v }}</dd>
</template>
</dl>
<p class="hint">Your work is saved in this browser. Use Share to get a link or export a file.</p>
<p class="hint">Your work is saved in this browser. Sign in (top right) to have it on every computer; use Share to get a link or export a file.</p>
<button class="btn btn-primary mt-4" @click="close">Start building</button>
</div>
</div>

View File

@ -1,28 +1,13 @@
<script setup lang="ts">
import type { TestResult, TruthTable } from '~/lib/logic/analyze'
import { stats } from '~/lib/logic/analyze'
import { CHALLENGES } from '~/lib/logic/challenges'
import { compile } from '~/lib/logic/compile'
import { chipPins } from '~/lib/logic/geometry'
import { usages } from '~/lib/logic/ops'
import { WIRE_COLORS, type SymbolKind } from '~/lib/logic/types'
import { WIRE_COLORS, type CrossingStyle, type SymbolKind } from '~/lib/logic/types'
const ed = useEditor()
const def = ed.def
const KIND_NAMES: Record<string, string> = {
nand: 'NAND gate',
input: 'Input',
output: 'Output',
lamp: 'Lamp',
button: 'Push button',
clock: 'Clock',
high: 'Constant 1',
low: 'Ground (0)',
hex: 'Hex display',
note: 'Note',
}
const SYMBOLS: { value: SymbolKind; label: string }[] = [
{ value: 'box', label: 'Box with name' },
{ value: 'and', label: 'AND gate' },
@ -44,22 +29,30 @@ const wireColor = computed(() => {
return colors.size === 1 ? [...colors][0] : null
})
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex'))
const chipDef = computed(() => (single.value?.chip ? ed.getDef.value(single.value.chip) : undefined))
const chipStats = computed(() => (chipDef.value ? stats(compile(ed.getDef.value, chipDef.value.id)) : null))
const hasLabel = computed(() => !!single.value && ['input', 'output', 'lamp', 'button', 'note', 'hex'].includes(single.value.kind))
const labelInput = ref<HTMLInputElement | HTMLTextAreaElement>()
const nameInput = ref<HTMLInputElement>()
watch(
() => ed.labelFocus.value,
() =>
nextTick(() => {
const el = labelInput.value ?? nameInput.value
el?.focus()
el?.select()
if (single.value) return
nameInput.value?.focus()
nameInput.value?.select()
}),
)
const CROSSINGS: { value: CrossingStyle; label: string }[] = [
{ value: 'bow', label: 'Bow' },
{ value: 'triangle', label: 'Triangle' },
{ value: 'bridge', label: 'Bridge' },
{ value: 'gap', label: 'Gap' },
{ value: 'plain', label: 'Plain' },
]
const settings = computed(() => ed.project.value.settings)
function setCrossing(c: CrossingStyle) {
settings.value.crossing = c
ed.persist()
}
const pins = computed(() => chipPins(def.value))
const users = computed(() => usages(ed.project.value, def.value.id))
const groupNames = computed(() => [...new Set(ed.project.value.components.map(d => d.group).filter(Boolean))])
@ -99,40 +92,7 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<aside class="inspector">
<div class="scroll">
<!-- Selection -->
<section v-if="single">
<h3>{{ single.kind === 'chip' ? chipDef?.name ?? 'Missing component' : KIND_NAMES[single.kind] }}</h3>
<label v-if="hasLabel" class="field">
<span>{{ single.kind === 'note' ? 'Text' : 'Label' }}</span>
<textarea
v-if="single.kind === 'note'"
ref="labelInput"
v-model="single.label"
rows="3"
@change="ed.commit(false)"
/>
<input v-else ref="labelInput" v-model="single.label" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
</label>
<p v-if="single.kind === 'input'" class="hint">
Click the switch on the canvas to flip it. When this circuit is used as a component, this becomes one of its input pins (pins are ordered top to bottom).
</p>
<p v-else-if="single.kind === 'output'" class="hint">
When this circuit is used as a component, this becomes one of its output pins.
</p>
<p v-else-if="single.kind === 'nand'" class="hint">
Output is 0 only when both inputs are 1. Every other part can be built from this one.
</p>
<template v-else-if="single.kind === 'chip' && chipDef">
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
<dl v-if="chipStats" class="stats">
<dt>NAND gates</dt>
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
</dl>
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
</template>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
<EditorNodeSettings v-if="single" :key="single.id" :node="single" />
<section v-else-if="ed.selection.value.length > 1 || (ed.selection.value.length && wires.length)">
<h3>
@ -144,6 +104,10 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<input v-model="packName" placeholder="e.g. Half Adder" @keydown.enter="pack" />
</label>
<button class="btn btn-primary w-full" @click="pack"><Icon name="lucide:package" class="size-4" /> Make component</button>
<div class="mt-2 grid grid-cols-2 gap-2">
<button class="btn" title="Remove every wire attached to the selected parts" @click="ed.unlink(ed.selection.value)"><Icon name="lucide:unlink" class="size-4" /> Unlink all</button>
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
</div>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
@ -241,6 +205,37 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</p>
</section>
<section v-if="!single && !wires.length && !ed.selection.value.length">
<h3>Display</h3>
<div class="field">
<span>Gate symbols</span>
<div class="seg">
<button :class="{ active: settings.symbols === 'iec' }" @click="settings.symbols = 'iec'; ed.persist()">IEC (DIN)</button>
<button :class="{ active: settings.symbols === 'ansi' }" @click="settings.symbols = 'ansi'; ed.persist()">ANSI</button>
</div>
</div>
<div class="field">
<span>Where unconnected wires cross</span>
<div class="crossings">
<button
v-for="c in CROSSINGS"
:key="c.value"
class="crossing"
:class="{ active: (settings.crossing ?? 'bow') === c.value }"
:title="c.label"
@click="setCrossing(c.value)"
>
<EditorCrossingIcon :style="c.value" />
<span>{{ c.label }}</span>
</button>
</div>
</div>
<label class="check">
<input type="checkbox" :checked="settings.flow" @change="settings.flow = !settings.flow; ed.persist()" />
Animate current flow on wires that carry a 1
</label>
</section>
<section>
<button class="section-toggle" @click="showTable = !showTable">
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />

View File

@ -0,0 +1,251 @@
<script setup lang="ts">
import { stats } from '~/lib/logic/analyze'
import { compile } from '~/lib/logic/compile'
import { chipPins } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { LAMP_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
const props = defineProps<{ node: CircuitNode }>()
const ed = useEditor()
const KIND_NAMES: Record<string, string> = {
nand: 'NAND gate',
input: 'Input switch',
output: 'Output pin',
lamp: 'Lamp',
button: 'Push button',
clock: 'Clock',
high: 'Constant 1',
low: 'Ground (0)',
hex: 'Hex display',
note: 'Note',
}
const HINTS: Record<string, string> = {
input: 'Click it on the canvas to flip it. Inside a component it becomes an input pin; pins are ordered top to bottom.',
output: 'Inside a component it becomes an output pin; pins are ordered top to bottom.',
nand: 'Output is 0 only when both inputs are 1. Every other part can be built from this one.',
high: 'Always 1, like the supply rail.',
low: 'Always 0, like ground.',
button: 'Gives 1 while held down with the mouse or its key.',
lamp: 'Lights up at 1. Inside a component it also shows on the component box.',
hex: 'Shows inputs 1, 2, 4, 8 as one hex digit. Inside a component it also shows on the component box.',
}
const n = computed(() => props.node)
const chipDef = computed(() => (n.value.chip ? ed.getDef.value(n.value.chip) : undefined))
const chipStats = computed(() => (chipDef.value ? stats(compile(ed.getDef.value, chipDef.value.id)) : null))
const title = computed(() => (n.value.kind === 'chip' ? chipDef.value?.name ?? 'Missing component' : KIND_NAMES[n.value.kind]))
const logic = computed(() => n.value.kind === 'nand' || n.value.kind === 'chip')
const family = computed<NodeKind[]>(() => (SOURCE_KINDS.includes(n.value.kind) ? SOURCE_KINDS : SINK_KINDS.includes(n.value.kind) ? SINK_KINDS : []))
const currentType = computed(() => (n.value.kind === 'chip' ? `chip:${n.value.chip}` : n.value.kind))
const wired = computed(() => ed.def.value.wires.some(w => w.from.node === n.value.id || w.to.node === n.value.id))
/** Components grouped like the palette, with their pin counts. */
const swapGroups = computed(() => {
const groups = new Map<string, { id: string; label: string; ok: boolean }[]>()
for (const d of ed.project.value.components) {
const p = chipPins(d)
const g = d.group?.trim() || 'My components'
if (!groups.has(g)) groups.set(g, [])
groups.get(g)!.push({ id: d.id, label: `${d.name} (${p.inputs.length} → ${p.outputs.length})`, ok: ed.canPlace(d.id) })
}
return [...groups.entries()]
})
function onSwap(e: Event) {
const v = (e.target as HTMLSelectElement).value
if (v === currentType.value) return
if (v.startsWith('chip:')) ed.swap(n.value.id, { kind: 'chip', chip: v.slice(5) })
else ed.swap(n.value.id, { kind: v as NodeKind })
}
const labelInput = ref<HTMLInputElement | HTMLTextAreaElement>()
watch(
() => ed.labelFocus.value,
() =>
nextTick(() => {
labelInput.value?.focus()
labelInput.value?.select()
}),
)
const hasLabel = computed(() => n.value.kind !== 'high' && n.value.kind !== 'low' && n.value.kind !== 'nand')
function setHz(e: Event) {
const v = Number((e.target as HTMLInputElement).value)
if (v > 0 && v <= 1000) n.value.hz = v
else delete n.value.hz
ed.commit()
}
function followTopBar(e: Event) {
if ((e.target as HTMLInputElement).checked) delete n.value.hz
else n.value.hz = ed.hz.value > 0 ? ed.hz.value : 2
ed.commit()
}
function setKey(e: KeyboardEvent) {
if (e.key === 'Tab') return
e.preventDefault()
if (e.key === 'Backspace' || e.key === 'Delete' || e.key === 'Escape') delete n.value.key
else if (e.key.length === 1 && e.key !== ' ') n.value.key = e.key.toLowerCase()
else return
ed.commit(false)
;(e.target as HTMLInputElement).blur()
}
function setColor(c: (typeof LAMP_COLORS)[number] | undefined) {
if (c) n.value.color = c
else delete n.value.color
ed.commit(false)
}
function setPos(axis: 'x' | 'y', e: Event) {
const v = Math.round(Number((e.target as HTMLInputElement).value))
if (Number.isFinite(v)) {
n.value[axis] = v
ed.commit(false)
}
}
function setSize(size: 'sm' | 'md' | 'lg') {
if (size === 'md') delete n.value.size
else n.value.size = size
ed.commit(false)
}
function setOn(on: boolean) {
if (!!n.value.on !== on) ed.toggleInput(n.value)
}
</script>
<template>
<section>
<h3>{{ title }}</h3>
<label v-if="logic" class="field">
<span>Part</span>
<select :value="currentType" @change="onSwap">
<option value="nand">NAND (2 → 1)</option>
<optgroup v-for="[g, defs] in swapGroups" :key="g" :label="g">
<option v-for="d in defs" :key="d.id" :value="`chip:${d.id}`" :disabled="!d.ok">{{ d.label }}</option>
</optgroup>
</select>
</label>
<label v-else-if="family.length" class="field">
<span>Type</span>
<select :value="currentType" @change="onSwap">
<option v-for="k in family" :key="k" :value="k">{{ KIND_NAMES[k] }}</option>
</select>
</label>
<p v-if="logic || family.length" class="hint -mt-1">Swapping keeps the wires on the pins in the same position.</p>
<label v-if="hasLabel" class="field">
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : 'Label' }}</span>
<textarea v-if="n.kind === 'note'" ref="labelInput" v-model="n.label" rows="3" @change="ed.commit(false)" />
<input
v-else
ref="labelInput"
v-model="n.label"
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : ''"
@change="ed.commit(false)"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
</label>
<!-- Kind-specific settings -->
<template v-if="n.kind === 'input'">
<div class="field">
<span>Value</span>
<div class="seg">
<button :class="{ active: !n.on }" @click="setOn(false)">0</button>
<button :class="{ active: n.on }" @click="setOn(true)">1</button>
</div>
</div>
</template>
<label v-if="n.kind === 'input' || n.kind === 'button'" class="field">
<span>Keyboard key</span>
<input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input" @keydown="setKey" />
</label>
<template v-if="n.kind === 'clock'">
<label class="check">
<input type="checkbox" :checked="n.hz === undefined" @change="followTopBar" />
Follow the speed in the top bar
</label>
<label v-if="n.hz !== undefined" class="field">
<span>Frequency (Hz)</span>
<input type="number" min="0.1" max="1000" step="any" :value="n.hz" list="hz-presets" @change="setHz" />
<datalist id="hz-presets">
<option v-for="v in [0.5, 1, 2, 5, 10, 30, 100]" :key="v" :value="v" />
</datalist>
</label>
</template>
<div v-if="n.kind === 'lamp' || n.kind === 'hex'" class="field">
<span>Colour</span>
<div class="swatches">
<button class="swatch lamp-swatch default" :class="{ active: !n.color, hex: n.kind === 'hex' }" title="Default" @click="setColor(undefined)" />
<button
v-for="c in LAMP_COLORS"
:key="c"
class="swatch lamp-swatch"
:class="[`l-${c}`, { active: n.color === c }]"
:title="c"
@click="setColor(c)"
/>
</div>
</div>
<div v-if="n.kind === 'note'" class="field">
<span>Size</span>
<div class="seg">
<button :class="{ active: n.size === 'sm' }" @click="setSize('sm')">Small</button>
<button :class="{ active: !n.size }" @click="setSize('md')">Normal</button>
<button :class="{ active: n.size === 'lg' }" @click="setSize('lg')">Large</button>
</div>
</div>
<p v-if="HINTS[n.kind]" class="hint">{{ HINTS[n.kind] }}</p>
<template v-if="n.kind === 'chip' && chipDef">
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
<dl v-if="chipStats" class="stats">
<dt>NAND gates</dt>
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
</dl>
<div class="grid gap-2">
<button class="btn w-full" @click="ed.open(chipDef.id)"><Icon name="lucide:log-in" class="size-4" /> Open component</button>
<button class="btn w-full" title="Replace it with the parts inside; outside wires join them directly" @click="ed.unpack(n.id)">
<Icon name="lucide:ungroup" class="size-4" /> Unpack into parts
</button>
<button class="btn w-full" title="Give this one its own copy, so changing it leaves the others alone" @click="ed.makeIndependent(n.id)">
<Icon name="lucide:copy-plus" class="size-4" /> Make independent copy
</button>
</div>
</template>
<div class="mt-3 grid grid-cols-2 gap-2">
<label class="field mb-0">
<span>X</span>
<input type="number" step="1" :value="n.x" @change="setPos('x', $event)" />
</label>
<label class="field mb-0">
<span>Y</span>
<input type="number" step="1" :value="n.y" @change="setPos('y', $event)" />
</label>
</div>
<div class="mt-3 grid grid-cols-2 gap-2">
<button class="btn" :disabled="!wired" title="Remove every wire attached to it" @click="ed.unlink([n.id])">
<Icon name="lucide:unlink" class="size-4" /> Unlink all
</button>
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
</div>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
</template>

View File

@ -1,6 +1,6 @@
<script setup lang="ts">
import { gateDrawing, sevenSegment } from '~/lib/draw'
import { GRID as G, noteLines, type Shape } from '~/lib/logic/geometry'
import { GRID as G, noteLines, noteScale, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode } from '~/lib/logic/types'
const props = defineProps<{
@ -51,15 +51,16 @@ const title = computed(() => {
<!-- Component box -->
<template v-else-if="node.kind === 'chip'">
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
<text :x="(b.w * G) / 2" :y="(shape.nameY ?? b.y + b.h / 2) * G + 4" text-anchor="middle" class="chip-name">{{ chipDef?.name ?? 'Missing' }}</text>
<template v-for="f in shape.face" :key="f.id">
<template v-if="f.kind === 'lamp'">
<circle :cx="(f.x + f.w / 2) * G" :cy="(f.y + 0.6) * G" :r="0.42 * G" class="lamp" :class="{ on: fv(f.id, 'a') === 1 }" />
<circle :cx="(f.x + f.w / 2) * G" :cy="(f.y + 0.6) * G" :r="0.42 * G" class="lamp" :class="[f.color ? `l-${f.color}` : '', { on: fv(f.id, 'a') === 1 }]" />
</template>
<template v-else>
<rect :x="(f.x + f.w / 2 - 0.62) * G" :y="f.y * G" :width="1.24 * G" :height="2.2 * G" rx="2" class="display" />
<g :transform="`translate(${(f.x + f.w / 2) * G - 1.75 * G * FACE_SCALE} ${(f.y + 0.16) * G}) scale(${FACE_SCALE})`">
<g :transform="`translate(${(f.x + f.w / 2) * G - 1.75 * G * FACE_SCALE} ${(f.y + 0.16) * G}) scale(${FACE_SCALE})`" :class="f.color ? `l-${f.color}` : ''">
<path v-for="(s, i) in faceHex(f.id)" :key="i" :d="s.d" class="seg" :class="{ on: s.on }" />
</g>
</template>
@ -74,6 +75,7 @@ const title = computed(() => {
<text :x="-6" :y="4" text-anchor="end" class="io-label">{{ node.label }}</text>
<rect x="0" :y="-0.6 * G" :width="2 * G" :height="1.2 * G" :rx="0.6 * G" class="switch" :class="{ on: lit }" />
<circle :cx="lit ? 1.4 * G : 0.6 * G" cy="0" :r="0.42 * G" class="knob" />
<text v-if="node.key" :x="G" :y="1.45 * G" text-anchor="middle" class="key-badge">{{ node.key.toUpperCase() }}</text>
</template>
<!-- Output pin -->
@ -86,7 +88,7 @@ const title = computed(() => {
<!-- Lamp: IEC symbol, circle with a cross -->
<template v-else-if="node.kind === 'lamp'">
<path :d="`M0 0H${0.35 * G}`" class="stub" />
<circle :cx="G" cy="0" :r="0.65 * G" class="lamp" :class="{ on: lit }" />
<circle :cx="G" cy="0" :r="0.65 * G" class="lamp" :class="[node.color ? `l-${node.color}` : '', { on: lit }]" />
<path :d="`M${G - 0.46 * G} ${-0.46 * G}L${G + 0.46 * G} ${0.46 * G}M${G + 0.46 * G} ${-0.46 * G}L${G - 0.46 * G} ${0.46 * G}`" class="lamp-cross" :class="{ on: lit }" />
<text v-if="node.label" :x="2 * G + 4" :y="4" class="io-label">{{ node.label }}</text>
</template>
@ -109,6 +111,7 @@ const title = computed(() => {
<rect x="0" :y="-0.7 * G" :width="2.5 * G" :height="1.4 * G" rx="2" class="body" />
<path :d="`M${0.35 * G} ${0.35 * G}H${0.8 * G}V${-0.35 * G}H${1.3 * G}V${0.35 * G}H${1.8 * G}V${-0.35 * G}H${2.15 * G}`" class="wave" :class="{ on: lit }" />
<path :d="`M${2.5 * G} 0H${3 * G}`" class="stub" />
<text :x="1.25 * G" :y="1.55 * G" text-anchor="middle" class="face-label">{{ node.label || (node.hz ? `${node.hz} Hz` : '') }}</text>
</template>
<!-- Push button -->
@ -117,12 +120,15 @@ const title = computed(() => {
<rect x="0" :y="-0.7 * G" :width="1.6 * G" :height="1.4 * G" rx="3" class="body" />
<circle :cx="0.8 * G" cy="0" :r="0.45 * G" class="button" :class="{ on: lit }" />
<path :d="`M${1.6 * G} 0H${2 * G}`" class="stub" />
<text v-if="node.key" :x="0.8 * G" :y="1.55 * G" text-anchor="middle" class="key-badge">{{ node.key.toUpperCase() }}</text>
</template>
<!-- Hex display -->
<template v-else-if="node.kind === 'hex'">
<rect x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body display" />
<path v-for="(s, i) in segments" :key="i" :d="s.d" class="seg" :class="{ on: s.on }" />
<g :class="node.color ? `l-${node.color}` : ''">
<path v-for="(s, i) in segments" :key="i" :d="s.d" class="seg" :class="{ on: s.on }" />
</g>
<text v-for="p in shape.inputs" :key="p.key" :x="4" :y="p.dy * G + 3" class="pin-label tiny">{{ p.label }}</text>
<text v-if="node.label" :x="(b.w * G) / 2" :y="(b.y + b.h) * G + 12" text-anchor="middle" class="face-label">{{ node.label }}</text>
</template>
@ -130,7 +136,14 @@ const title = computed(() => {
<!-- Note -->
<template v-else-if="node.kind === 'note'">
<rect :x="-4" :y="b.y * G" :width="b.w * G + 8" :height="b.h * G" rx="3" class="note-bg" />
<text v-for="(line, i) in noteLines(node)" :key="i" x="0" :y="i * G + 4" class="note">{{ line }}</text>
<text
v-for="(line, i) in noteLines(node)"
:key="i"
x="0"
:y="i * G * noteScale(node) + 4 * noteScale(node)"
class="note"
:style="{ fontSize: `${12 * noteScale(node)}px` }"
>{{ line }}</text>
</template>
<rect

View File

@ -38,7 +38,11 @@ function onFile(e: Event) {
<h2 id="projects-title">Projects</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<p class="hint mt-1">Saved in this browser as you work. Projects with a link are also saved online.</p>
<p class="hint mt-1">
Saved in this browser as you work.
<template v-if="ed.account.value">Also kept in your account, so they are on every computer you sign in on.</template>
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
</p>
<ul class="project-list">
<li v-for="m in ed.projects.value" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
@ -58,6 +62,11 @@ function onFile(e: Event) {
<span class="meta">
{{ when(m.updated) }}
<template v-if="m.link"> · <Icon name="lucide:link" class="size-3" /> {{ m.link.key ? 'your link' : 'from a link' }}</template>
<template v-if="ed.account.value && m.cloud?.owner === ed.account.value.id">
· <Icon :name="m.dirty ? 'lucide:cloud-upload' : 'lucide:cloud-check'" class="size-3" /> {{ m.dirty ? 'saving to account' : 'in your account' }}
</template>
<template v-else-if="ed.account.value && !m.cloud"> · <Icon name="lucide:cloud-upload" class="size-3" /> uploading</template>
<template v-else-if="!ed.account.value"> · <Icon name="lucide:laptop" class="size-3" /> this browser only</template>
</span>
</button>
<button class="icon-btn" title="Rename" @click="startRename(m.id, m.name)"><Icon name="lucide:pencil" class="size-3.5" /></button>

View File

@ -17,6 +17,7 @@ const backName = computed(() => {
const id = ed.nav.value.at(-1)
return id ? ed.getDef.value(id)?.name : undefined
})
const cloudText = computed(() => ({ off: '', syncing: 'syncing', synced: 'all saved', offline: 'offline', error: 'sync failed' })[ed.cloudState.value])
const linkIcon = computed(() => {
switch (ed.linkState.value) {
case 'saved':
@ -100,6 +101,21 @@ const linkIcon = computed(() => {
<span class="hidden md:inline">Share</span>
</button>
<button class="tb-btn" title="Help (?)" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /></button>
<button
class="tb-btn account-btn"
:class="ed.cloudState.value"
:title="ed.account.value ? `${ed.account.value.email}: ${cloudText}` : 'Sign in to keep your projects on every computer'"
@click="ed.dialog.value = 'account'"
>
<template v-if="ed.account.value">
<span class="avatar">{{ ed.account.value.email[0]!.toUpperCase() }}</span>
<span class="sync-dot" />
</template>
<template v-else>
<Icon name="lucide:user" class="size-4" />
<span class="hidden md:inline">Sign in</span>
</template>
</button>
</div>
</header>
</template>

View File

@ -14,27 +14,37 @@ import {
deleteComponent,
duplicateComponent,
lookup,
makeUnique,
mergeComponents,
newComponent,
packageSelection,
pasteClip,
pruneWires,
startChallenge,
swapNode,
uid,
unlinkWires,
unpackChip,
type Clip,
type SwapTarget,
} from '~/lib/logic/ops'
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, NodeKind, PinRef, Project, WireColor } from '~/lib/logic/types'
@ -69,7 +79,7 @@ function create() {
if (p) return { meta: m, project: p }
}
const project = createProject({ examples: true })
const meta: ProjectMeta = { id: newLocalId(), name: project.name, updated: Date.now() }
const meta: ProjectMeta = { id: newLocalId(), name: project.name, updated: Date.now(), starter: true }
// A first visit through a share link should not leave an unused starter
// project behind; it is saved only once something changes in it.
placeholder = location.pathname.startsWith('/p/')
@ -95,7 +105,7 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
const dialog = ref<null | 'projects' | 'share'>(null)
const dialog = ref<null | 'projects' | 'share' | 'account'>(null)
let noticeTimer: ReturnType<typeof setTimeout> | undefined
function notify(text: string, kind: 'ok' | 'error' = 'ok') {
@ -111,16 +121,20 @@ function create() {
// ── Saving ────────────────────────────────────────────────────────
let saveTimer: ReturnType<typeof setTimeout> | undefined
let changed = false
function persistNow() {
clearTimeout(saveTimer)
saveTimer = undefined
meta.value = { ...meta.value, name: project.value.name, updated: Date.now() }
meta.value = { ...meta.value, name: project.value.name, updated: Date.now(), ...(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()
@ -242,7 +256,7 @@ function create() {
let raf = 0
function startLoop() {
let lastT = performance.now()
let acc = 0
let acc: number[] = []
let unsettled = 0
let lastChanges = -1
const frame = (t: number) => {
@ -251,23 +265,32 @@ function create() {
const s = sim.value
if (s) {
let rises = 0
if (running.value && s.nl.clocks.length) {
if (hz.value > 0) {
acc += dt
const half = 500 / hz.value
for (let n = 0; acc >= half && n < 16; n++) {
acc -= half
s.run(BUDGET)
s.setClock(s.clock ^ 1)
if (s.clock) rises++
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))
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
}
if (acc > half) acc = 0
} else {
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
s.setClock(s.clock ^ 1)
if (s.clock) rises++
for (const i of fastest) if (s.toggleClock(i) && i === counted) rises++
}
}
}
@ -395,6 +418,33 @@ function create() {
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.`)
}
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)
@ -524,6 +574,7 @@ function create() {
const m: ProjectMeta = { id: newLocalId(), name: p.name, updated: Date.now() }
if (link) m.link = link
saveProject(m, p)
scheduleCloud()
return m
}
@ -542,6 +593,11 @@ function create() {
}
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
@ -565,8 +621,9 @@ function create() {
const m = listProjects().find(x => x.id === id)
if (!p || !m) return
p.name = clean
saveProject({ ...m, name: clean }, p)
saveProject({ ...m, name: clean, dirty: true }, p)
projects.value = listProjects()
scheduleCloud()
}
function loadExamples() {
@ -641,8 +698,9 @@ function create() {
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 } }
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()
@ -730,6 +788,238 @@ function create() {
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())
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']
}
/** Keeps the account's version as a separate project, so nothing is lost when two devices changed the same one. */
async function keepRemoteCopy(id: string) {
const res = await authCall<{ project?: Project; status: number }>('GET', `/api/me/projects/${id}`)
if (!res.project) return
const p = toProject(res.project)
p.name = `${p.name} (other device)`
saveProject({ id: newLocalId(), name: p.name, updated: Date.now() }, p)
}
async function upload(m: ProjectMeta, uid: string) {
const p = localProject(m)
if (!p) return
const body = { project: p, baseRev: m.cloud?.owner === uid ? m.cloud.rev : 0, link: m.link }
let res = await authCall<{ meta?: CloudMeta; conflict?: boolean; status: number }>('PUT', `/api/me/projects/${m.id}`, body)
if (res.conflict) {
await keepRemoteCopy(m.id)
res = await authCall('PUT', `/api/me/projects/${m.id}`, { ...body, force: true })
notify(`"${m.name}" was also changed on another device. That version is kept as a copy.`)
}
if (res.meta) updateMeta(m.id, { cloud: { owner: uid, rev: res.meta.rev }, dirty: false })
}
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.')
}
/** 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'
}
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)
}
@ -784,6 +1074,10 @@ function create() {
selectNet,
toggleInput,
press,
swap,
unlink,
unpack,
makeIndependent,
copy,
paste,
duplicate,
@ -811,6 +1105,15 @@ function create() {
pushLink,
openLink,
syncUrl,
account,
cloudState,
cloudError,
syncAccount,
signIn,
signOut,
changePassword,
deleteAccount,
startAccount,
copyText,
shape,
}

View File

@ -1,7 +1,7 @@
// SVG geometry for gate symbols, in pixels relative to the node origin.
import { GRID as G, type Shape } from './logic/geometry'
import type { SymbolKind } from './logic/types'
import { GRID as G, type Pt, type Shape } from './logic/geometry'
import type { CrossingStyle, SymbolKind } from './logic/types'
const NEGATED = new Set<SymbolKind>(['nand', 'nor', 'xnor', 'not'])
@ -101,3 +101,39 @@ export function sevenSegment(value: number) {
const bits = SEGMENTS[value & 15]!
return segs.map((s, i) => ({ d: `M${s[0]} ${s[1]}L${s[2]} ${s[3]}`, on: (bits >> i) & 1 }))
}
const HOP = 5
/**
* SVG path for a wire (points in grid units), with a hop drawn on its
* horizontal segments wherever another signal crosses (`hops`: segment
* index to crossing x positions). `scale` is pixels per grid unit.
*/
export function wirePath(pts: Pt[], hops: Map<number, number[]> | undefined, style: CrossingStyle, scale = G): string {
const r = HOP
let d = `M${pts[0]![0] * scale} ${pts[0]![1] * scale}`
for (let i = 0; i < pts.length - 1; i++) {
const [ax, ay] = pts[i]!
const [bx, by] = pts[i + 1]!
const xs = hops?.get(i)
if (xs && style !== 'plain' && ay === by) {
const dir = Math.sign(bx - ax)
const y = ay * scale
let prev = ax * scale
for (const hx of xs.map(x => x * scale).sort((p, q) => dir * (p - q))) {
// Skip hops too close to a corner or to the previous hop.
if (Math.abs(hx - prev) < r + 1 || Math.abs(bx * scale - hx) < r + 1) continue
const s = hx - dir * r
const e = hx + dir * r
d += `L${s} ${y}`
if (style === 'bow') d += `A${r} ${r} 0 0 ${dir > 0 ? 1 : 0} ${e} ${y}`
else if (style === 'triangle') d += `L${hx} ${y - r * 1.3}L${e} ${y}`
else if (style === 'bridge') d += `L${s} ${y - r}L${e} ${y - r}L${e} ${y}`
else d += `M${e} ${y}`
prev = e
}
}
d += `L${bx * scale} ${by * scale}`
}
return d
}

View File

@ -27,6 +27,10 @@ export interface Netlist {
/** User-driven sources in the root circuit (switches, buttons): nodeId → net. */
sources: Map<string, number>
clocks: Int32Array
/** Frequency per clock in Hz; 0 follows the speed in the top bar. */
clockHz: Float64Array
/** Stable identity per clock ("chipNode/…/clockNode"), to keep its level across recompiles. */
clockKeys: string[]
errors: string[]
}
@ -90,7 +94,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
const gB: number[] = []
const gOut: number[] = []
const gateKeys: string[] = []
const clocks: number[] = []
const clocks: { net: number; hz: number; key: string }[] = []
const sources = new Map<string, number>()
const rawPinNet = new Map<string, number>()
const rawTrace = opts.trace ? new Map<string, number>() : undefined
@ -157,7 +161,7 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
union(q, LOW)
break
case 'clock':
clocks.push(q)
clocks.push({ net: q, hz: n.hz ?? 0, key: path + n.id })
break
case 'output':
result.set(n.id, inNet(n.id, 'a'))
@ -231,7 +235,11 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
const tracePinNet = rawTrace ? mapNets(rawTrace) : undefined
const facePinNet = mapNets(rawFace)
const srcs = mapNets(sources)
const clockNets = Int32Array.from(new Set(clocks.map(canon)))
const seenClock = new Set<number>()
const clockList = clocks
.map(c => ({ ...c, net: canon(c.net) }))
.filter(c => !seenClock.has(c.net) && seenClock.add(c.net))
const clockNets = Int32Array.from(clockList.map(c => c.net))
// Fanout in CSR form.
const fanStart = new Int32Array(netCount + 1)
@ -260,6 +268,8 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
facePinNet,
sources: srcs,
clocks: clockNets,
clockHz: Float64Array.from(clockList.map(c => c.hz)),
clockKeys: clockList.map(c => c.key),
errors: [...new Set(errors)],
}
}

View File

@ -1,7 +1,7 @@
// Node shapes and pin positions, all in grid units relative to the node's
// (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, SymbolKind } from './types'
import type { CircuitNode, ComponentDef, LampColor, SymbolKind } from './types'
export const GRID = 16
@ -29,6 +29,7 @@ export interface FaceItem {
id: string
kind: 'lamp' | 'hex'
label: string
color?: LampColor
/** Top-left corner and size in grid units, relative to the chip node. */
x: number
y: number
@ -84,7 +85,7 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h
const label = n.label?.trim() ?? ''
const iw = Math.max(n.kind === 'hex' ? 1.6 : 1.4, label.length * FACE_CHAR + 0.4)
const ih = (n.kind === 'hex' ? 2.2 : 1.2) + (label ? 0.7 : 0)
items.push({ id: n.id, kind: n.kind as 'lamp' | 'hex', label, x, y, w: iw, h: ih })
items.push({ id: n.id, kind: n.kind as 'lamp' | 'hex', label, color: n.color, x, y, w: iw, h: ih })
x += iw + 0.3
h = Math.max(h, ih)
}
@ -177,6 +178,10 @@ export function noteLines(node: CircuitNode): string[] {
return (node.label || 'Note').split('\n')
}
export function noteScale(node: CircuitNode): number {
return node.size === 'sm' ? 0.8 : node.size === 'lg' ? 1.5 : 1
}
export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
switch (node.kind) {
case 'nand':
@ -195,8 +200,9 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
return HEX_SHAPE
case 'note': {
const lines = noteLines(node)
const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR + 1))
return { body: { x: 0, y: -0.75, w, h: lines.length + 0.5 }, inputs: [], outputs: [] }
const k = noteScale(node)
const w = Math.max(2, Math.ceil(Math.max(...lines.map(l => l.length)) * NAME_CHAR * k + 1))
return { body: { x: 0, y: -0.75 * k, w, h: (lines.length + 0.5) * k }, inputs: [], outputs: [] }
}
case 'chip': {
const def = node.chip ? getDef(node.chip) : undefined

View File

@ -5,7 +5,7 @@ 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'
import type { CircuitNode, ComponentDef, NodeKind, Project, Wire } from './types'
export function uid(prefix = ''): string {
return prefix + Math.random().toString(36).slice(2, 10)
@ -318,3 +318,125 @@ export function packageSelection(
}
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<string>): 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<string, string>()
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<string, Wire['from']>()
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
}

View File

@ -1,7 +1,15 @@
// Reading project data from files, links and storage. Shared by the browser
// and the share-link server, so it must stay free of browser APIs.
import { WIRE_COLORS, type Project } from './types'
import { CROSSING_STYLES, LAMP_COLORS, WIRE_COLORS, type CircuitNode, type Project } from './types'
/** Drops optional node settings that are out of range, so a hand-edited file can't break the editor. */
function cleanNode(n: CircuitNode) {
if (n.hz !== undefined && !(typeof n.hz === 'number' && n.hz > 0 && n.hz <= 1000)) delete n.hz
if (n.color !== undefined && !LAMP_COLORS.includes(n.color)) delete n.color
if (n.key !== undefined && !(typeof n.key === 'string' && n.key.length === 1)) delete n.key
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
}
/** Upper bounds for a project that comes from outside. */
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000 }
@ -20,6 +28,7 @@ export function toProject(data: unknown): Project {
}
nodes += d.nodes.length
d.symbol ??= 'box'
for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
}
if (nodes > LIMITS.nodes) throw new Error('Project too large')
@ -28,7 +37,11 @@ export function toProject(data: unknown): Project {
name: typeof p.name === 'string' && p.name.trim() ? p.name.trim().slice(0, 80) : 'Untitled',
components: p.components,
openId: p.components.some(d => d.id === p.openId) ? p.openId! : p.components[0]!.id,
settings: { symbols: p.settings?.symbols === 'ansi' ? 'ansi' : 'iec', flow: p.settings?.flow ?? true },
settings: {
symbols: p.settings?.symbols === 'ansi' ? 'ansi' : 'iec',
flow: p.settings?.flow ?? true,
...(p.settings?.crossing && CROSSING_STYLES.includes(p.settings.crossing) ? { crossing: p.settings.crossing } : {}),
},
solved: Array.isArray(p.solved) ? p.solved.filter(s => typeof s === 'string') : [],
}
}

384
app/lib/logic/routing.ts Normal file
View File

@ -0,0 +1,384 @@
// Routes all wires of a circuit so that wires of different signals never
// run on top of each other.
//
// 1. Wires with hand-placed corners keep them. Every other wire uses its
// usual route if that is free; otherwise the cheapest free alternative:
// another column for the vertical step, or a detour around parts.
// 2. Anything still sharing a line with another signal is drawn on its own
// parallel lane, a quarter grid step apart.
// 3. Crossings between different signals are listed, so the view can draw
// hops (bow, triangle, bridge, gap) at those points.
import { pinPos, routeWire, simplify, type Pt, type Shape } from './geometry'
import type { ComponentDef } from './types'
export interface RouteInput {
id: string
/** Wires with the same net (source pin) may share lines. */
net: string
a: Pt
b: Pt
pts?: Pt[]
}
export interface Box {
x: number
y: number
w: number
h: number
}
export interface Routed {
id: string
net: string
/** Whole-grid route: what dragging and corner handles work on. */
grid: Pt[]
/** Route as drawn, moved onto separate lanes where needed. */
draw: Pt[]
}
export interface Crossing {
/** Index of the routed wire that hops (the horizontal one). */
wire: number
/** Segment of `draw` the hop sits on. */
seg: number
x: number
}
const LANE = 0.25
const EPS = 1e-6
interface Seg {
lo: number
hi: number
net: string
}
/** Lines already taken, by row (horizontal) and column (vertical). */
class Occupancy {
rows = new Map<number, Seg[]>()
cols = new Map<number, Seg[]>()
add(route: Pt[], net: string) {
for (let i = 0; i < route.length - 1; i++) {
const [ax, ay] = route[i]!
const [bx, by] = route[i + 1]!
if (ay === by && ax !== bx) push(this.rows, ay, { lo: Math.min(ax, bx), hi: Math.max(ax, bx), net })
else if (ax === bx && ay !== by) push(this.cols, ax, { lo: Math.min(ay, by), hi: Math.max(ay, by), net })
}
}
/** Length that a segment shares with lines of other nets. */
overlap(a: Pt, b: Pt, net: string): number {
const horizontal = a[1] === b[1]
const list = horizontal ? this.rows.get(a[1]) : this.cols.get(a[0])
if (!list) return 0
const lo = horizontal ? Math.min(a[0], b[0]) : Math.min(a[1], b[1])
const hi = horizontal ? Math.max(a[0], b[0]) : Math.max(a[1], b[1])
let total = 0
for (const s of list) {
if (s.net === net) continue
const o = Math.min(hi, s.hi) - Math.max(lo, s.lo)
// Touching end to end counts too: it would read as one wire.
if (o > 0) total += o
else if (o === 0) total += 0.5
}
return total
}
}
function push<T>(map: Map<number, T[]>, key: number, value: T) {
const list = map.get(key)
if (list) list.push(value)
else map.set(key, [value])
}
/** Node bodies bucketed by area, so a segment only checks the parts near it. */
class BodyIndex {
private cells = new Map<number, Box[]>()
private stamp = new Map<Box, number>()
private query = 0
private static SIZE = 4
private static key = (cx: number, cy: number) => (cx + 50_000) * 100_000 + cy + 50_000
constructor(boxes: Box[]) {
const S = BodyIndex.SIZE
for (const box of boxes) {
for (let cx = Math.floor(box.x / S); cx <= Math.floor((box.x + box.w) / S); cx++) {
for (let cy = Math.floor(box.y / S); cy <= Math.floor((box.y + box.h) / S); cy++) push(this.cells, BodyIndex.key(cx, cy), box)
}
}
}
/** Bodies whose inside (minus a small margin) the segment passes through. */
hits(a: Pt, b: Pt): number {
const S = BodyIndex.SIZE
const q = ++this.query
let n = 0
const lx = Math.min(a[0], b[0])
const hx = Math.max(a[0], b[0])
const ly = Math.min(a[1], b[1])
const hy = Math.max(a[1], b[1])
for (let cx = Math.floor(lx / S); cx <= Math.floor(hx / S); cx++) {
for (let cy = Math.floor(ly / S); cy <= Math.floor(hy / S); cy++) {
for (const box of this.cells.get(BodyIndex.key(cx, cy)) ?? []) {
if (this.stamp.get(box) === q) continue
this.stamp.set(box, q)
const x0 = box.x + 0.2
const x1 = box.x + box.w - 0.2
const y0 = box.y + 0.2
const y1 = box.y + box.h - 0.2
const hit = ly === hy ? ly > y0 && ly < y1 && hx > x0 && lx < x1 : lx > x0 && lx < x1 && hy > y0 && ly < y1
if (hit) n++
}
}
}
return n
}
}
const pinKey = (x: number, y: number) => (x + 50_000) * 100_000 + y + 50_000
/** Cost of a route; stops counting once it is above `limit`. */
function cost(route: Pt[], net: string, occ: Occupancy, bodies: BodyIndex, pins: Set<number>, limit = Infinity): { penalty: number; total: number } {
let penalty = 0
let length = route.length * 0.5
const first = route[0]!
const last = route[route.length - 1]!
for (let i = 0; i < route.length - 1; i++) {
const a = route[i]!
const b = route[i + 1]!
length += Math.abs(b[0] - a[0]) + Math.abs(b[1] - a[1])
penalty += occ.overlap(a, b, net) * 1000 + bodies.hits(a, b) * 60
// Running over someone else's pin looks like a connection.
if (pins.size) {
if (a[1] === b[1]) {
for (let x = Math.min(a[0], b[0]); x <= Math.max(a[0], b[0]); x++) {
if ((x === first[0] && a[1] === first[1]) || (x === last[0] && a[1] === last[1])) continue
if (pins.has(pinKey(x, a[1]))) penalty += 300
}
} else {
for (let y = Math.min(a[1], b[1]); y <= Math.max(a[1], b[1]); y++) {
if ((y === first[1] && a[0] === first[0]) || (y === last[1] && a[0] === last[0])) continue
if (pins.has(pinKey(a[0], y))) penalty += 300
}
}
}
if (penalty + length > limit) return { penalty, total: Infinity }
}
return { penalty, total: penalty + length }
}
/** Alternative routes for a wire whose usual route collides with something. */
function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
const [x1, y1] = a
const [x2, y2] = b
const mid = Math.round((x1 + x2) / 2)
if (x2 >= x1 + 2) {
// Another column for the vertical step.
for (let d = 1; d <= x2 - x1; d++) {
for (const m of [mid + d, mid - d]) if (m > x1 && m < x2) yield [a, [m, y1], [m, y2], b]
}
// Detours: step to a free row and back.
for (let dy = 1; dy <= 6; dy++) {
for (const yd of [Math.min(y1, y2) - dy, Math.max(y1, y2) + dy]) {
for (const m1 of [x1 + 1, x1 + 2]) {
for (const m2 of [x2 - 1, x2 - 2]) {
if (m2 > m1) yield [a, [m1, y1], [m1, yd], [m2, yd], [m2, y2], b]
}
}
}
}
return
}
// Backward wires (feedback): out to the right, around, back in from the left.
const rows = new Set<number>()
for (let d = 0; d <= 6; d++) rows.add(Math.round((y1 + y2) / 2) + d).add(Math.round((y1 + y2) / 2) - d)
for (let d = 2; d <= 7; d++) rows.add(Math.max(y1, y2) + d).add(Math.min(y1, y2) - d)
for (const ym of rows) {
for (const r of [x1 + 1, x1 + 2, x1 + 3]) {
for (const l of [x2 - 1, x2 - 2, x2 - 3]) yield [a, [r, y1], [r, ym], [l, ym], [l, y2], b]
}
}
}
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] {
const usual = routeWire(input.a, input.b)
const base = cost(usual, input.net, occ, bodies, pins)
if (base.penalty === 0) return usual
let best = usual
let bestCost = base.total
for (const c of candidates(input.a, input.b)) {
const route = simplify(c)
const k = cost(route, input.net, occ, bodies, pins, bestCost)
if (k.total < bestCost) {
best = route
bestCost = k.total
if (k.penalty === 0 && route.length <= 4) break
}
}
return best
}
/** Moves lines of different nets that share a row or column onto separate lanes. */
function separate(routes: Routed[]) {
interface Item {
r: number
i: number
lo: number
hi: number
net: string
}
const rows = new Map<number, Item[]>()
const cols = new Map<number, Item[]>()
routes.forEach((route, r) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay === by && ax !== bx) push(rows, ay, { r, i, lo: Math.min(ax, bx), hi: Math.max(ax, bx), net: route.net })
else if (ax === bx && ay !== by) push(cols, ax, { r, i, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net })
}
})
const shifts = new Map<number, { i: number; axis: 0 | 1; off: number }[]>()
const plan = (lines: Map<number, Item[]>, axis: 0 | 1) => {
for (const items of lines.values()) {
if (new Set(items.map(it => it.net)).size < 2) continue
// Clusters of segments that overlap (or touch) each other.
items.sort((p, q) => p.lo - q.lo)
let cluster: Item[] = []
let reach = -Infinity
const flush = () => {
const nets = [...new Set(cluster.map(it => it.net))]
if (nets.length > 1) {
const lane = new Map(nets.map((n, k) => [n, k === 0 ? 0 : (k % 2 ? 1 : -1) * Math.ceil(k / 2) * LANE]))
for (const it of cluster) {
const off = lane.get(it.net)!
if (off) push(shifts, it.r, { i: it.i, axis, off })
}
}
cluster = []
}
for (const it of items) {
if (it.lo > reach + EPS) flush()
cluster.push(it)
reach = Math.max(reach, it.hi)
}
flush()
}
}
plan(rows, 1)
plan(cols, 0)
for (const [r, list] of shifts) {
const p = routes[r]!.draw
list.sort((x, y) => y.i - x.i)
for (const shift of list) {
const { axis, off } = shift
let i = shift.i
const last = p.length - 1
const toward = (from: Pt, to: Pt): Pt => [from[0] + Math.sign(to[0] - from[0]) * 0.5, from[1] + Math.sign(to[1] - from[1]) * 0.5]
if (i + 1 === last) {
// Keep the last half step on the pin's line: shift a copy of it.
const s = toward(p[last]!, p[i]!)
p.splice(last, 0, [...s] as Pt, [...s] as Pt)
}
if (i === 0) {
const s = toward(p[0]!, p[1]!)
p.splice(1, 0, [...s] as Pt, [...s] as Pt)
i = 2
}
p[i]![axis] += off
p[i + 1]![axis] += off
}
}
}
/** Crossings of horizontal lines over vertical lines of other nets. */
export function findCrossings(routes: Routed[]): Crossing[] {
const verticals: { x: number; lo: number; hi: number; net: string }[] = []
routes.forEach(route => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ax === bx && ay !== by) verticals.push({ x: ax, lo: Math.min(ay, by), hi: Math.max(ay, by), net: route.net })
}
})
verticals.sort((p, q) => p.x - q.x)
const out: Crossing[] = []
routes.forEach((route, w) => {
const p = route.draw
for (let i = 0; i < p.length - 1; i++) {
const [ax, ay] = p[i]!
const [bx, by] = p[i + 1]!
if (ay !== by || ax === bx) continue
const lo = Math.min(ax, bx)
const hi = Math.max(ax, bx)
// First vertical at x > lo.
let k = 0
let top = verticals.length
while (k < top) {
const m = (k + top) >> 1
if (verticals[m]!.x <= lo + EPS) k = m + 1
else top = m
}
for (; k < verticals.length && verticals[k]!.x < hi - EPS; k++) {
const v = verticals[k]!
if (v.net !== route.net && ay > v.lo + EPS && ay < v.hi - EPS) out.push({ wire: w, seg: i, x: v.x })
}
}
})
return out
}
export function routeAll(inputs: RouteInput[], bodies: Box[], pins: Pt[]): Routed[] {
const occ = new Occupancy()
const pinSet = new Set(pins.map(([x, y]) => pinKey(x, y)))
const bodyIndex = new BodyIndex(bodies)
const grid = new Map<string, Pt[]>()
// Hand-routed wires first: they are fixed, the others route around them.
for (const w of inputs) {
if (!w.pts?.length) continue
const r = routeWire(w.a, w.b, w.pts)
grid.set(w.id, r)
occ.add(r, w.net)
}
for (const w of inputs) {
if (w.pts?.length) continue
const r = autoRoute(w, occ, bodyIndex, pinSet)
grid.set(w.id, r)
occ.add(r, w.net)
}
const routes = inputs.map(w => {
const g = grid.get(w.id)!
return { id: w.id, net: w.net, grid: g, draw: g.map(p => [p[0], p[1]] as Pt) }
})
separate(routes)
return routes
}
/** Routes every wire of a circuit, given the shapes of its parts. */
export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>): Routed[] {
const nodes = new Map(def.nodes.map(n => [n.id, n]))
const bodies: Box[] = []
const pins: Pt[] = []
for (const n of def.nodes) {
const s = shapes.get(n.id)
if (!s) continue
if (n.kind !== 'note') bodies.push({ x: n.x + s.body.x, y: n.y + s.body.y, w: s.body.w, h: s.body.h })
for (const p of [...s.inputs, ...s.outputs]) pins.push([n.x + p.dx, n.y + p.dy])
}
const inputs: RouteInput[] = []
for (const w of def.wires) {
const fn = nodes.get(w.from.node)
const tn = nodes.get(w.to.node)
if (!fn || !tn) continue
const a = pinPos(fn, shapes.get(fn.id)!, w.from.pin, 'out')
const b = pinPos(tn, shapes.get(tn.id)!, w.to.pin, 'in')
if (!a || !b) continue
inputs.push({ id: w.id, net: `${w.from.node}:${w.from.pin}`, a: [a.x, a.y], b: [b.x, b.y], pts: w.pts })
}
return routeAll(inputs, bodies, pins)
}

View File

@ -8,7 +8,9 @@ import { HIGH, type Netlist } from './compile'
export interface SimCarry {
gates: Map<string, number>
/** Level of all clocks when they ran in lockstep; per-clock levels win. */
clock: number
clocks?: Map<string, number>
}
export class Simulator {
@ -35,7 +37,7 @@ export class Simulator {
if (v !== undefined) this.values[nl.gateOut[i]!] = v
}
this.clock = carry.clock
for (const c of nl.clocks) this.values[c] = carry.clock
nl.clocks.forEach((c, i) => (this.values[c] = carry.clocks?.get(nl.clockKeys[i]!) ?? carry.clock))
}
for (let i = 0; i < gates; i++) this.push(i)
}
@ -69,11 +71,20 @@ export class Simulator {
if (net !== undefined) this.set(net, on ? 1 : 0)
}
/** Set every clock to the same level. */
setClock(v: number) {
this.clock = v
for (const c of this.nl.clocks) this.set(c, v)
}
/** Flip one clock; returns its new level. */
toggleClock(i: number): number {
const net = this.nl.clocks[i]!
const v = this.values[net]! ^ 1
this.set(net, v)
return v
}
/** Evaluate up to `budget` gates. Returns true once nothing is left to do. */
run(budget = 1_000_000): boolean {
const { gateA, gateB, gateOut, fanStart, fanList } = this.nl
@ -111,6 +122,8 @@ export class Simulator {
const gates = new Map<string, number>()
const { gateKeys, gateOut } = this.nl
for (let i = 0; i < gateKeys.length; i++) gates.set(gateKeys[i]!, this.values[gateOut[i]!]!)
return { gates, clock: this.clock }
const clocks = new Map<string, number>()
this.nl.clocks.forEach((c, i) => clocks.set(this.nl.clockKeys[i]!, this.values[c]!))
return { gates, clock: this.clock, clocks }
}
}

View File

@ -15,11 +15,24 @@ export interface ProjectMeta {
name: string
updated: number
link?: ShareLink
/** Set once the project is stored in an account: whose, and which revision this browser has. */
cloud?: { owner: string; rev: number }
/** Changed here since the last upload to the account. */
dirty?: boolean
/** The example project a new browser starts with, never touched yet. */
starter?: boolean
}
export interface AccountUser {
id: string
email: string
}
const INDEX = 'logigate:projects'
const CURRENT = 'logigate:current'
const LEGACY = 'logigate:project:v1'
const ACCOUNT = 'logigate:account'
const PENDING_DELETES = 'logigate:pending-deletes'
const entry = (id: string) => `logigate:p:${id}`
function read(key: string): string | null {
@ -108,3 +121,35 @@ export function migrateLegacy(): void {
}
} catch {}
}
/** The account this browser was last signed in to, so the UI knows before the server answers. */
export function cachedAccount(): AccountUser | null {
try {
const a = JSON.parse(read(ACCOUNT) ?? 'null') as AccountUser | null
return a && typeof a.id === 'string' ? a : null
} catch {
return null
}
}
export function setCachedAccount(user: AccountUser | null) {
if (user) write(ACCOUNT, JSON.stringify(user))
else
try {
localStorage.removeItem(ACCOUNT)
} catch {}
}
/** Account projects deleted while offline, to delete on the server at the next sync. */
export function pendingDeletes(): { owner: string; id: string }[] {
try {
const list = JSON.parse(read(PENDING_DELETES) ?? '[]')
return Array.isArray(list) ? list : []
} catch {
return []
}
}
export function setPendingDeletes(list: { owner: string; id: string }[]) {
write(PENDING_DELETES, JSON.stringify(list))
}

View File

@ -29,8 +29,20 @@ export interface CircuitNode {
label?: string
/** Switch position for 'input' nodes. */
on?: boolean
/** Clock frequency in Hz. Empty: follows the speed in the top bar. */
hz?: number
/** Colour of a lamp or display. Empty: yellow lamp, red display. */
color?: LampColor
/** Keyboard key that flips a switch or holds a button down. */
key?: string
/** Text size of a note. */
size?: NoteSize
}
export const LAMP_COLORS = ['yellow', 'red', 'green', 'blue', 'white'] as const
export type LampColor = (typeof LAMP_COLORS)[number]
export type NoteSize = 'sm' | 'md' | 'lg'
export interface PinRef {
node: string
pin: string
@ -71,8 +83,13 @@ export interface Settings {
symbols: 'iec' | 'ansi'
/** Animate current flow on wires carrying a 1. */
flow: boolean
/** How a wire is drawn where it crosses another, unconnected one. */
crossing?: CrossingStyle
}
export const CROSSING_STYLES = ['bow', 'triangle', 'bridge', 'gap', 'plain'] as const
export type CrossingStyle = (typeof CROSSING_STYLES)[number]
export interface Project {
version: 1
name: string

View File

@ -28,10 +28,13 @@ export default defineNuxtConfig({
clientBundle: { scan: true },
},
// Share links live as JSON files in data/shares (a volume in production).
// Share links and accounts live as JSON files in data/ (a volume in production).
nitro: {
storage: {
shares: { driver: 'fs', base: './data/shares' },
users: { driver: 'fs', base: './data/users' },
sessions: { driver: 'fs', base: './data/sessions' },
accounts: { driver: 'fs', base: './data/accounts' },
},
},

View File

@ -0,0 +1,15 @@
// Delete the account and every project stored with it.
export default defineEventHandler(async event => {
rateLimit(event, 'login', 20, 10 * 60_000)
const user = await requireUser(event)
const body = await readBody<{ password?: unknown }>(event)
if (typeof body?.password !== 'string' || !(await verifyPassword(body.password, user))) {
throw createError({ statusCode: 403, message: 'The password is not right' })
}
await withLock(user.id, () => deleteAccountData(user.id))
await endAllSessions(user.id)
await users().removeItem(emailKey(user.email))
await users().removeItem(`user:${user.id}`)
deleteCookie(event, SESSION_COOKIE, { path: '/' })
return { ok: true }
})

View File

@ -0,0 +1,10 @@
export default defineEventHandler(async event => {
rateLimit(event, 'login', 20, 10 * 60_000)
const body = await readBody<{ email?: unknown; password?: unknown }>(event)
const user = validEmail(body?.email) && typeof body.password === 'string' ? await findUserByEmail(body.email) : null
if (!user || !(await verifyPassword(body.password as string, user))) {
throw createError({ statusCode: 401, message: 'Wrong email or password' })
}
await startSession(event, user.id)
return { user: publicUser(user) }
})

View File

@ -0,0 +1,4 @@
export default defineEventHandler(async event => {
await endSession(event)
return { ok: true }
})

View File

@ -0,0 +1,5 @@
export default defineEventHandler(async event => {
setHeader(event, 'cache-control', 'no-store')
const user = await currentUser(event)
return { user: user ? publicUser(user) : null }
})

View File

@ -0,0 +1,13 @@
// Change the password. Signs out every other device.
export default defineEventHandler(async event => {
rateLimit(event, 'login', 20, 10 * 60_000)
const user = await requireUser(event)
const body = await readBody<{ current?: unknown; next?: unknown }>(event)
if (typeof body?.current !== 'string' || !(await verifyPassword(body.current, user))) {
throw createError({ statusCode: 403, message: 'The current password is not right' })
}
if (!validPassword(body.next)) throw createError({ statusCode: 400, message: 'The new password needs at least 8 characters' })
await users().setItem(`user:${user.id}`, { ...user, ...(await hashPassword(body.next)) })
await endAllSessions(user.id, event)
return { ok: true }
})

View File

@ -0,0 +1,16 @@
import type { User } from '../../utils/auth'
// Create an account and sign in.
export default defineEventHandler(async event => {
rateLimit(event, 'register', 10, 60 * 60_000)
const body = await readBody<{ email?: unknown; password?: unknown }>(event)
if (!validEmail(body?.email)) throw createError({ statusCode: 400, message: 'Please enter a valid email address' })
if (!validPassword(body?.password)) throw createError({ statusCode: 400, message: 'The password needs at least 8 characters' })
const email = body.email.trim()
if (await findUserByEmail(email)) throw createError({ statusCode: 409, message: 'There is already an account with this email. Sign in instead.' })
const user: User = { id: newUserId(), email, created: Date.now(), ...(await hashPassword(body.password)) }
await users().setItem(`user:${user.id}`, user)
await users().setItem(emailKey(email), { uid: user.id })
await startSession(event, user.id)
setResponseStatus(event, 201)
return { user: publicUser(user) }
})

View File

@ -0,0 +1,15 @@
export default defineEventHandler(async event => {
const user = await requireUser(event)
const id = getRouterParam(event, 'id')
if (!isProjectId(id)) throw createError({ statusCode: 404, message: 'Project not found' })
return withLock(user.id, async () => {
const index = await readIndex(user.id)
index.projects = index.projects.filter(p => p.id !== id)
// Remember the deletion for a year, so other devices drop their copy too.
const yearAgo = Date.now() - 365 * 86_400_000
index.deleted = [{ id, at: Date.now() }, ...index.deleted.filter(d => d.id !== id && d.at > yearAgo)].slice(0, 2000)
await accounts().removeItem(projectKey(user.id, id))
await writeIndex(user.id, index)
return { ok: true }
})
})

View File

@ -0,0 +1,10 @@
export default defineEventHandler(async event => {
const user = await requireUser(event)
const id = getRouterParam(event, 'id')
if (!isProjectId(id)) throw createError({ statusCode: 404, message: 'Project not found' })
const meta = (await readIndex(user.id)).projects.find(p => p.id === id)
const project = meta && (await readProject(user.id, id))
if (!meta || !project) throw createError({ statusCode: 404, message: 'Project not found' })
setHeader(event, 'cache-control', 'no-store')
return { meta, project }
})

View File

@ -0,0 +1,48 @@
import { toProject } from '../../../../app/lib/logic/project'
import type { CloudMeta } from '../../../utils/accounts'
// Save a project to the account. `baseRev` is the revision the device last
// had; if another device saved in between, this answers 409 with the newer
// version's meta, unless `force` is set.
export default defineEventHandler(async event => {
rateLimit(event, 'save', 1200, 10 * 60_000)
const user = await requireUser(event)
const id = getRouterParam(event, 'id')
if (!isProjectId(id)) throw createError({ statusCode: 400, message: 'Bad project id' })
const raw = await readRawBody(event, 'utf8')
if (!raw || raw.length > 2_100_000) throw createError({ statusCode: 413, message: 'Project too large' })
let body: { project?: unknown; baseRev?: unknown; force?: unknown; link?: unknown }
try {
body = JSON.parse(raw)
} catch {
throw createError({ statusCode: 400, message: 'Not valid JSON' })
}
let project
try {
project = toProject(body.project)
} catch (e) {
throw createError({ statusCode: 400, message: (e as Error).message })
}
const link = body.link as CloudMeta['link']
const cleanLink = link && isShareId(link.id) ? { id: link.id, ...(typeof link.key === 'string' ? { key: link.key } : {}) } : undefined
return withLock(user.id, async () => {
const index = await readIndex(user.id)
const existing = index.projects.find(p => p.id === id)
if (existing && existing.rev !== body.baseRev && body.force !== true) {
setResponseStatus(event, 409)
return { conflict: true, meta: existing }
}
if (!existing && index.projects.length >= MAX_PROJECTS) throw createError({ statusCode: 409, message: 'Too many projects in this account' })
const size = JSON.stringify(project).length
const others = index.projects.reduce((n, p) => n + (p.id === id ? 0 : (p.size ?? 0)), 0)
if (others + size > MAX_ACCOUNT_BYTES) throw createError({ statusCode: 413, message: 'Your account is full (100 MB). Delete some projects first.' })
const meta: CloudMeta = { id, name: project.name, updated: Date.now(), rev: (existing?.rev ?? 0) + 1, size }
if (cleanLink) meta.link = cleanLink
else if (existing?.link && body.link === undefined) meta.link = existing.link
await accounts().setItem(projectKey(user.id, id), project)
index.projects = [meta, ...index.projects.filter(p => p.id !== id)]
index.deleted = index.deleted.filter(d => d.id !== id)
await writeIndex(user.id, index)
return { meta }
})
})

View File

@ -0,0 +1,6 @@
// The signed-in user's projects (without contents) and recent deletions.
export default defineEventHandler(async event => {
const user = await requireUser(event)
setHeader(event, 'cache-control', 'no-store')
return readIndex(user.id)
})

View File

@ -0,0 +1,13 @@
// Changes through the API must come from this site's own pages.
export default defineEventHandler(event => {
if (!event.path.startsWith('/api/') || ['GET', 'HEAD', 'OPTIONS'].includes(event.method)) return
const origin = getHeader(event, 'origin')
if (!origin) return
let host = ''
try {
host = new URL(origin).host
} catch {}
if (host !== getRequestHost(event, { xForwardedHost: true })) {
throw createError({ statusCode: 403, message: 'Cross-site request refused' })
}
})

51
server/utils/accounts.ts Normal file
View File

@ -0,0 +1,51 @@
// Projects stored per account, with a revision number per project so two
// devices can't silently overwrite each other's work.
import type { Project } from '../../app/lib/logic/types'
export interface CloudMeta {
id: string
name: string
updated: number
rev: number
/** Stored size in bytes, for the per-account limit. */
size?: number
/** Share link of this project, with its edit key, so every device of the owner can update it. */
link?: { id: string; key?: string }
}
export interface AccountIndex {
projects: CloudMeta[]
/** Projects deleted on one device, so the others remove them too. */
deleted: { id: string; at: number }[]
}
export const MAX_PROJECTS = 1000
/** Total size of all projects of one account. */
export const MAX_ACCOUNT_BYTES = 100_000_000
export const accounts = () => useStorage('accounts')
export const isProjectId = (id: unknown): id is string => typeof id === 'string' && /^[A-Za-z0-9]{4,32}$/.test(id)
export async function readIndex(uid: string): Promise<AccountIndex> {
const index = await accounts().getItem<AccountIndex>(`${uid}:index`)
return { projects: index?.projects ?? [], deleted: index?.deleted ?? [] }
}
export const writeIndex = (uid: string, index: AccountIndex) => accounts().setItem(`${uid}:index`, index)
export const projectKey = (uid: string, id: string) => `${uid}:p:${id}`
export const readProject = (uid: string, id: string) => accounts().getItem<Project>(projectKey(uid, id))
// One change at a time per account, so two quick saves can't both read the
// old index and lose one of the updates.
const locks = new Map<string, Promise<unknown>>()
export function withLock<T>(uid: string, fn: () => Promise<T>): Promise<T> {
const prev = locks.get(uid) ?? Promise.resolve()
const next = prev.catch(() => {}).then(fn)
locks.set(uid, next)
next.finally(() => locks.get(uid) === next && locks.delete(uid)).catch(() => {})
return next
}
export async function deleteAccountData(uid: string) {
for (const key of await accounts().getKeys(`${uid}:`)) await accounts().removeItem(key)
}

109
server/utils/auth.ts Normal file
View File

@ -0,0 +1,109 @@
// Accounts: email + password (scrypt), sessions in an httpOnly cookie.
// Stored as JSON files: data/users, data/sessions, data/accounts.
import { createHash, randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
import type { H3Event } from 'h3'
export interface User {
id: string
email: string
hash: string
salt: string
created: number
}
interface Session {
uid: string
created: number
expires: number
}
export const SESSION_COOKIE = 'lg_session'
const SESSION_DAYS = 180
const sha256 = (s: string) => createHash('sha256').update(s).digest('hex')
export const users = () => useStorage('users')
const sessions = () => useStorage<Session>('sessions')
export const emailKey = (email: string) => `email:${sha256(email.trim().toLowerCase())}`
export const publicUser = (u: User) => ({ id: u.id, email: u.email })
export function validEmail(email: unknown): email is string {
return typeof email === 'string' && email.length <= 200 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())
}
export function validPassword(pw: unknown): pw is string {
return typeof pw === 'string' && pw.length >= 8 && pw.length <= 200
}
function scryptHash(password: string, salt: string): Promise<Buffer> {
return new Promise((resolve, reject) =>
scrypt(password.normalize('NFKC'), salt, 64, { N: 16384, r: 8, p: 1 }, (err, key) => (err ? reject(err) : resolve(key))),
)
}
export async function hashPassword(password: string): Promise<{ hash: string; salt: string }> {
const salt = randomBytes(16).toString('hex')
return { hash: (await scryptHash(password, salt)).toString('hex'), salt }
}
export async function verifyPassword(password: string, user: User): Promise<boolean> {
const a = await scryptHash(password, user.salt)
const b = Buffer.from(user.hash, 'hex')
return a.length === b.length && timingSafeEqual(a, b)
}
export async function findUserByEmail(email: string): Promise<User | null> {
const ref = await users().getItem<{ uid: string }>(emailKey(email))
return ref ? users().getItem<User>(`user:${ref.uid}`) : null
}
export async function startSession(event: H3Event, uid: string) {
const token = randomBytes(32).toString('base64url')
const now = Date.now()
await sessions().setItem(sha256(token), { uid, created: now, expires: now + SESSION_DAYS * 86_400_000 })
setCookie(event, SESSION_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: SESSION_DAYS * 86_400,
})
}
export async function endSession(event: H3Event) {
const token = getCookie(event, SESSION_COOKIE)
if (token) await sessions().removeItem(sha256(token))
deleteCookie(event, SESSION_COOKIE, { path: '/' })
}
/** Ends every session of a user (password change, account deletion). */
export async function endAllSessions(uid: string, keep?: H3Event) {
const keepKey = keep ? sha256(getCookie(keep, SESSION_COOKIE) ?? '') : ''
for (const key of await sessions().getKeys()) {
if (key === keepKey) continue
const s = await sessions().getItem(key)
if (s?.uid === uid) await sessions().removeItem(key)
}
}
export async function currentUser(event: H3Event): Promise<User | null> {
const token = getCookie(event, SESSION_COOKIE)
if (!token) return null
const key = sha256(token)
const s = await sessions().getItem(key)
if (!s) return null
if (s.expires < Date.now()) {
await sessions().removeItem(key)
return null
}
return users().getItem<User>(`user:${s.uid}`)
}
export async function requireUser(event: H3Event): Promise<User> {
const user = await currentUser(event)
if (!user) throw createError({ statusCode: 401, message: 'Please sign in' })
return user
}
export const newUserId = () => randomBytes(9).toString('base64url').replace(/[-_]/g, 'x')

75
tests/compat.test.ts Normal file
View File

@ -0,0 +1,75 @@
// Projects saved by earlier releases must keep loading and computing exactly
// as they did. The fixtures were written by release a241adc; never edit them.
import { readFileSync } from 'node:fs'
import { beforeEach, describe, expect, it } from 'vitest'
import { stats, truthTable } from '../app/lib/logic/analyze'
import { compile } from '../app/lib/logic/compile'
import { lookup } from '../app/lib/logic/ops'
import { parseProject } from '../app/lib/logic/project'
import { currentId, listProjects, loadProject, migrateLegacy } from '../app/lib/logic/storage'
const fixture = readFileSync('tests/fixtures/v1-project.json', 'utf8')
const expected = JSON.parse(readFileSync('tests/fixtures/v1-expected.json', 'utf8')) as Record<string, { stats: unknown; table: unknown }>
const storage = JSON.parse(readFileSync('tests/fixtures/v1-localstorage.json', 'utf8')) as Record<string, Record<string, string>>
function fakeLocalStorage(items: Record<string, string>) {
const map = new Map(Object.entries(items))
globalThis.localStorage = {
getItem: k => map.get(k) ?? null,
setItem: (k, v) => void map.set(k, String(v)),
removeItem: k => void map.delete(k),
clear: () => map.clear(),
key: i => [...map.keys()][i] ?? null,
get length() {
return map.size
},
} as Storage
return map
}
describe('projects from release a241adc', () => {
it('load with every component, wire, colour, corner and setting intact', () => {
const before = JSON.parse(fixture)
const p = parseProject(fixture)
expect(p.name).toBe('Compat fixture')
expect(p.settings.symbols).toBe('ansi')
expect(p.solved).toEqual(['not'])
expect(p.components.map(d => d.id)).toEqual(before.components.map((d: { id: string }) => d.id))
for (const d of before.components) {
const now = p.components.find(c => c.id === d.id)!
expect(now.nodes).toEqual(d.nodes)
expect(now.wires).toEqual(d.wires)
}
})
it('compute the same truth tables, NAND counts and delays', () => {
const p = parseProject(fixture)
const get = lookup(p)
for (const d of p.components) {
const t = truthTable(get, d.id)
expect({ stats: stats(compile(get, d.id)), table: 'error' in t ? t.error : t.rows.map(r => [...r.ins, '|', ...r.outs].join('')) }, d.name).toEqual(expected[d.id])
}
})
})
describe('browser storage from earlier releases', () => {
beforeEach(() => fakeLocalStorage({}))
it('moves the first release’s single project into the library', () => {
const map = fakeLocalStorage(storage.legacy!)
migrateLegacy()
const list = listProjects()
expect(list).toHaveLength(1)
expect(currentId()).toBe(list[0]!.id)
expect(loadProject(list[0]!.id)!.components).toHaveLength(JSON.parse(fixture).components.length)
expect(map.has('logigate:project:v1')).toBe(false)
})
it('reads the current library, including share-link keys', () => {
fakeLocalStorage(storage.library!)
migrateLegacy()
expect(listProjects()).toEqual([{ id: 'loc1', name: 'Compat fixture', updated: 1792235588166, link: { id: 'AbCdEfGh', key: 'secret-key' } }])
expect(currentId()).toBe('loc1')
expect(loadProject('loc1')!.name).toBe('Compat fixture')
})
})

793
tests/fixtures/v1-expected.json vendored Normal file
View File

@ -0,0 +1,793 @@
{
"main": {
"stats": {
"nands": 1,
"sequential": false,
"delay": 1
},
"table": "Add at least one output pin"
},
"ex-not": {
"stats": {
"nands": 1,
"sequential": false,
"delay": 1
},
"table": [
"0|1",
"1|0"
]
},
"ex-and": {
"stats": {
"nands": 2,
"sequential": false,
"delay": 2
},
"table": [
"00|0",
"01|0",
"10|0",
"11|1"
]
},
"ex-or": {
"stats": {
"nands": 3,
"sequential": false,
"delay": 2
},
"table": [
"00|0",
"01|1",
"10|1",
"11|1"
]
},
"ex-nor": {
"stats": {
"nands": 4,
"sequential": false,
"delay": 3
},
"table": [
"00|1",
"01|0",
"10|0",
"11|0"
]
},
"ex-xor": {
"stats": {
"nands": 4,
"sequential": false,
"delay": 3
},
"table": [
"00|0",
"01|1",
"10|1",
"11|0"
]
},
"ex-xnor": {
"stats": {
"nands": 5,
"sequential": false,
"delay": 4
},
"table": [
"00|1",
"01|0",
"10|0",
"11|1"
]
},
"ex-mux": {
"stats": {
"nands": 4,
"sequential": false,
"delay": 3
},
"table": [
"000|0",
"001|0",
"010|0",
"011|1",
"100|1",
"101|0",
"110|1",
"111|1"
]
},
"ex-ha": {
"stats": {
"nands": 6,
"sequential": false,
"delay": 3
},
"table": [
"00|00",
"01|10",
"10|10",
"11|01"
]
},
"ex-fa": {
"stats": {
"nands": 15,
"sequential": false,
"delay": 7
},
"table": [
"000|00",
"001|10",
"010|10",
"011|01",
"100|10",
"101|01",
"110|01",
"111|11"
]
},
"ex-sr": {
"stats": {
"nands": 4,
"sequential": true,
"delay": null
},
"table": [
"00|01",
"01|01",
"10|10",
"11|11"
]
},
"ex-dlatch": {
"stats": {
"nands": 9,
"sequential": true,
"delay": null
},
"table": [
"00|01",
"01|01",
"10|01",
"11|10"
]
},
"ex-dff": {
"stats": {
"nands": 19,
"sequential": true,
"delay": null
},
"table": [
"00|01",
"01|01",
"10|01",
"11|10"
]
},
"ex-reg4": {
"stats": {
"nands": 76,
"sequential": true,
"delay": null
},
"table": [
"00000|0000",
"00001|0000",
"00010|0000",
"00011|0001",
"00100|0001",
"00101|0010",
"00110|0010",
"00111|0011",
"01000|0011",
"01001|0100",
"01010|0100",
"01011|0101",
"01100|0101",
"01101|0110",
"01110|0110",
"01111|0111",
"10000|0111",
"10001|1000",
"10010|1000",
"10011|1001",
"10100|1001",
"10101|1010",
"10110|1010",
"10111|1011",
"11000|1011",
"11001|1100",
"11010|1100",
"11011|1101",
"11100|1101",
"11101|1110",
"11110|1110",
"11111|1111"
]
},
"ex-inc4": {
"stats": {
"nands": 24,
"sequential": false,
"delay": 9
},
"table": [
"0000|10000",
"0001|10010",
"0010|10100",
"0011|10110",
"0100|11000",
"0101|11010",
"0110|11100",
"0111|11110",
"1000|01000",
"1001|01010",
"1010|01100",
"1011|01110",
"1100|00100",
"1101|00110",
"1110|00010",
"1111|00001"
]
},
"ex-add4": {
"stats": {
"nands": 60,
"sequential": false,
"delay": 19
},
"table": [
"000000000|00000",
"000000001|10000",
"000000010|00010",
"000000011|10010",
"000000100|00100",
"000000101|10100",
"000000110|00110",
"000000111|10110",
"000001000|01000",
"000001001|11000",
"000001010|01010",
"000001011|11010",
"000001100|01100",
"000001101|11100",
"000001110|01110",
"000001111|11110",
"000010000|10000",
"000010001|01000",
"000010010|10010",
"000010011|01010",
"000010100|10100",
"000010101|01100",
"000010110|10110",
"000010111|01110",
"000011000|11000",
"000011001|00100",
"000011010|11010",
"000011011|00110",
"000011100|11100",
"000011101|00010",
"000011110|11110",
"000011111|00001",
"000100000|00010",
"000100001|10010",
"000100010|00001",
"000100011|10001",
"000100100|00110",
"000100101|10110",
"000100110|00101",
"000100111|10101",
"000101000|01010",
"000101001|11010",
"000101010|01001",
"000101011|11001",
"000101100|01110",
"000101101|11110",
"000101110|01101",
"000101111|11101",
"000110000|10010",
"000110001|01010",
"000110010|10001",
"000110011|01001",
"000110100|10110",
"000110101|01110",
"000110110|10101",
"000110111|01101",
"000111000|11010",
"000111001|00110",
"000111010|11001",
"000111011|00101",
"000111100|11110",
"000111101|00001",
"000111110|11101",
"000111111|00011",
"001000000|00100",
"001000001|10100",
"001000010|00110",
"001000011|10110",
"001000100|00010",
"001000101|10010",
"001000110|00001",
"001000111|10001",
"001001000|01100",
"001001001|11100",
"001001010|01110",
"001001011|11110",
"001001100|01010",
"001001101|11010",
"001001110|01001",
"001001111|11001",
"001010000|10100",
"001010001|01100",
"001010010|10110",
"001010011|01110",
"001010100|10010",
"001010101|01010",
"001010110|10001",
"001010111|01001",
"001011000|11100",
"001011001|00010",
"001011010|11110",
"001011011|00001",
"001011100|11010",
"001011101|00110",
"001011110|11001",
"001011111|00101",
"001100000|00110",
"001100001|10110",
"001100010|00101",
"001100011|10101",
"001100100|00001",
"001100101|10001",
"001100110|00011",
"001100111|10011",
"001101000|01110",
"001101001|11110",
"001101010|01101",
"001101011|11101",
"001101100|01001",
"001101101|11001",
"001101110|01011",
"001101111|11011",
"001110000|10110",
"001110001|01110",
"001110010|10101",
"001110011|01101",
"001110100|10001",
"001110101|01001",
"001110110|10011",
"001110111|01011",
"001111000|11110",
"001111001|00001",
"001111010|11101",
"001111011|00011",
"001111100|11001",
"001111101|00101",
"001111110|11011",
"001111111|00111",
"010000000|01000",
"010000001|11000",
"010000010|01010",
"010000011|11010",
"010000100|01100",
"010000101|11100",
"010000110|01110",
"010000111|11110",
"010001000|00100",
"010001001|10100",
"010001010|00110",
"010001011|10110",
"010001100|00010",
"010001101|10010",
"010001110|00001",
"010001111|10001",
"010010000|11000",
"010010001|00100",
"010010010|11010",
"010010011|00110",
"010010100|11100",
"010010101|00010",
"010010110|11110",
"010010111|00001",
"010011000|10100",
"010011001|01100",
"010011010|10110",
"010011011|01110",
"010011100|10010",
"010011101|01010",
"010011110|10001",
"010011111|01001",
"010100000|01010",
"010100001|11010",
"010100010|01001",
"010100011|11001",
"010100100|01110",
"010100101|11110",
"010100110|01101",
"010100111|11101",
"010101000|00110",
"010101001|10110",
"010101010|00101",
"010101011|10101",
"010101100|00001",
"010101101|10001",
"010101110|00011",
"010101111|10011",
"010110000|11010",
"010110001|00110",
"010110010|11001",
"010110011|00101",
"010110100|11110",
"010110101|00001",
"010110110|11101",
"010110111|00011",
"010111000|10110",
"010111001|01110",
"010111010|10101",
"010111011|01101",
"010111100|10001",
"010111101|01001",
"010111110|10011",
"010111111|01011",
"011000000|01100",
"011000001|11100",
"011000010|01110",
"011000011|11110",
"011000100|01010",
"011000101|11010",
"011000110|01001",
"011000111|11001",
"011001000|00010",
"011001001|10010",
"011001010|00001",
"011001011|10001",
"011001100|00110",
"011001101|10110",
"011001110|00101",
"011001111|10101",
"011010000|11100",
"011010001|00010",
"011010010|11110",
"011010011|00001",
"011010100|11010",
"011010101|00110",
"011010110|11001",
"011010111|00101",
"011011000|10010",
"011011001|01010",
"011011010|10001",
"011011011|01001",
"011011100|10110",
"011011101|01110",
"011011110|10101",
"011011111|01101",
"011100000|01110",
"011100001|11110",
"011100010|01101",
"011100011|11101",
"011100100|01001",
"011100101|11001",
"011100110|01011",
"011100111|11011",
"011101000|00001",
"011101001|10001",
"011101010|00011",
"011101011|10011",
"011101100|00101",
"011101101|10101",
"011101110|00111",
"011101111|10111",
"011110000|11110",
"011110001|00001",
"011110010|11101",
"011110011|00011",
"011110100|11001",
"011110101|00101",
"011110110|11011",
"011110111|00111",
"011111000|10001",
"011111001|01001",
"011111010|10011",
"011111011|01011",
"011111100|10101",
"011111101|01101",
"011111110|10111",
"011111111|01111",
"100000000|10000",
"100000001|01000",
"100000010|10010",
"100000011|01010",
"100000100|10100",
"100000101|01100",
"100000110|10110",
"100000111|01110",
"100001000|11000",
"100001001|00100",
"100001010|11010",
"100001011|00110",
"100001100|11100",
"100001101|00010",
"100001110|11110",
"100001111|00001",
"100010000|01000",
"100010001|11000",
"100010010|01010",
"100010011|11010",
"100010100|01100",
"100010101|11100",
"100010110|01110",
"100010111|11110",
"100011000|00100",
"100011001|10100",
"100011010|00110",
"100011011|10110",
"100011100|00010",
"100011101|10010",
"100011110|00001",
"100011111|10001",
"100100000|10010",
"100100001|01010",
"100100010|10001",
"100100011|01001",
"100100100|10110",
"100100101|01110",
"100100110|10101",
"100100111|01101",
"100101000|11010",
"100101001|00110",
"100101010|11001",
"100101011|00101",
"100101100|11110",
"100101101|00001",
"100101110|11101",
"100101111|00011",
"100110000|01010",
"100110001|11010",
"100110010|01001",
"100110011|11001",
"100110100|01110",
"100110101|11110",
"100110110|01101",
"100110111|11101",
"100111000|00110",
"100111001|10110",
"100111010|00101",
"100111011|10101",
"100111100|00001",
"100111101|10001",
"100111110|00011",
"100111111|10011",
"101000000|10100",
"101000001|01100",
"101000010|10110",
"101000011|01110",
"101000100|10010",
"101000101|01010",
"101000110|10001",
"101000111|01001",
"101001000|11100",
"101001001|00010",
"101001010|11110",
"101001011|00001",
"101001100|11010",
"101001101|00110",
"101001110|11001",
"101001111|00101",
"101010000|01100",
"101010001|11100",
"101010010|01110",
"101010011|11110",
"101010100|01010",
"101010101|11010",
"101010110|01001",
"101010111|11001",
"101011000|00010",
"101011001|10010",
"101011010|00001",
"101011011|10001",
"101011100|00110",
"101011101|10110",
"101011110|00101",
"101011111|10101",
"101100000|10110",
"101100001|01110",
"101100010|10101",
"101100011|01101",
"101100100|10001",
"101100101|01001",
"101100110|10011",
"101100111|01011",
"101101000|11110",
"101101001|00001",
"101101010|11101",
"101101011|00011",
"101101100|11001",
"101101101|00101",
"101101110|11011",
"101101111|00111",
"101110000|01110",
"101110001|11110",
"101110010|01101",
"101110011|11101",
"101110100|01001",
"101110101|11001",
"101110110|01011",
"101110111|11011",
"101111000|00001",
"101111001|10001",
"101111010|00011",
"101111011|10011",
"101111100|00101",
"101111101|10101",
"101111110|00111",
"101111111|10111",
"110000000|11000",
"110000001|00100",
"110000010|11010",
"110000011|00110",
"110000100|11100",
"110000101|00010",
"110000110|11110",
"110000111|00001",
"110001000|10100",
"110001001|01100",
"110001010|10110",
"110001011|01110",
"110001100|10010",
"110001101|01010",
"110001110|10001",
"110001111|01001",
"110010000|00100",
"110010001|10100",
"110010010|00110",
"110010011|10110",
"110010100|00010",
"110010101|10010",
"110010110|00001",
"110010111|10001",
"110011000|01100",
"110011001|11100",
"110011010|01110",
"110011011|11110",
"110011100|01010",
"110011101|11010",
"110011110|01001",
"110011111|11001",
"110100000|11010",
"110100001|00110",
"110100010|11001",
"110100011|00101",
"110100100|11110",
"110100101|00001",
"110100110|11101",
"110100111|00011",
"110101000|10110",
"110101001|01110",
"110101010|10101",
"110101011|01101",
"110101100|10001",
"110101101|01001",
"110101110|10011",
"110101111|01011",
"110110000|00110",
"110110001|10110",
"110110010|00101",
"110110011|10101",
"110110100|00001",
"110110101|10001",
"110110110|00011",
"110110111|10011",
"110111000|01110",
"110111001|11110",
"110111010|01101",
"110111011|11101",
"110111100|01001",
"110111101|11001",
"110111110|01011",
"110111111|11011",
"111000000|11100",
"111000001|00010",
"111000010|11110",
"111000011|00001",
"111000100|11010",
"111000101|00110",
"111000110|11001",
"111000111|00101",
"111001000|10010",
"111001001|01010",
"111001010|10001",
"111001011|01001",
"111001100|10110",
"111001101|01110",
"111001110|10101",
"111001111|01101",
"111010000|00010",
"111010001|10010",
"111010010|00001",
"111010011|10001",
"111010100|00110",
"111010101|10110",
"111010110|00101",
"111010111|10101",
"111011000|01010",
"111011001|11010",
"111011010|01001",
"111011011|11001",
"111011100|01110",
"111011101|11110",
"111011110|01101",
"111011111|11101",
"111100000|11110",
"111100001|00001",
"111100010|11101",
"111100011|00011",
"111100100|11001",
"111100101|00101",
"111100110|11011",
"111100111|00111",
"111101000|10001",
"111101001|01001",
"111101010|10011",
"111101011|01011",
"111101100|10101",
"111101101|01101",
"111101110|10111",
"111101111|01111",
"111110000|00001",
"111110001|10001",
"111110010|00011",
"111110011|10011",
"111110100|00101",
"111110101|10101",
"111110110|00111",
"111110111|10111",
"111111000|01001",
"111111001|11001",
"111111010|01011",
"111111011|11011",
"111111100|01101",
"111111101|11101",
"111111110|01111",
"111111111|11111"
]
},
"ex-cnt4": {
"stats": {
"nands": 109,
"sequential": true,
"delay": null
},
"table": [
"00|0000",
"01|0000",
"10|0000",
"11|0000"
]
},
"ex-demo-counter": {
"stats": {
"nands": 109,
"sequential": true,
"delay": null
},
"table": "Add at least one output pin"
},
"cnco3azcm": {
"stats": {
"nands": 0,
"sequential": false,
"delay": 0
},
"table": [
"00|0",
"01|0",
"10|0",
"11|0"
]
}
}

10
tests/fixtures/v1-localstorage.json vendored Normal file

File diff suppressed because one or more lines are too long

3424
tests/fixtures/v1-project.json vendored Normal file

File diff suppressed because it is too large Load Diff

140
tests/parts.test.ts Normal file
View File

@ -0,0 +1,140 @@
import { describe, expect, it } from 'vitest'
import { runSteps, truthTable } from '../app/lib/logic/analyze'
import { CHALLENGES, challengeSteps } from '../app/lib/logic/challenges'
import { compile } from '../app/lib/logic/compile'
import { createProject, lookup, makeUnique, swapNode, unlinkWires, unpackChip } from '../app/lib/logic/ops'
import { Simulator } from '../app/lib/logic/sim'
const rows = (p: ReturnType<typeof createProject>, id: string) => {
const t = truthTable(lookup(p), id)
if ('error' in t) throw new Error(t.error)
return t.rows.map(r => [...r.ins, ...r.outs].join(''))
}
describe('swapping a placed part', () => {
it('keeps the wires when a NAND becomes an AND', () => {
const p = createProject({ examples: true })
const xor = p.components.find(d => d.id === 'ex-xor')!
const last = xor.nodes.filter(n => n.kind === 'nand').at(-1)!
const wires = xor.wires.length
expect(swapNode(p, xor, last.id, { kind: 'chip', chip: 'ex-and' })).toBe(0)
expect(xor.wires).toHaveLength(wires)
// The final NAND became an AND, so the output is inverted: XNOR.
const xnor = CHALLENGES.find(c => c.id === 'xnor')!
expect(runSteps(lookup(p), 'ex-xor', challengeSteps(xnor)).pass).toBe(true)
})
it('removes only the wires on pins the new part lacks', () => {
const p = createProject({ examples: true })
const main = p.components.find(d => d.id === 'main')!
const nand = main.nodes.find(n => n.kind === 'nand')!
expect(swapNode(p, main, nand.id, { kind: 'chip', chip: 'ex-not' })).toBe(1)
expect(main.wires).toHaveLength(2)
})
it('turns a switch into a clock and back, keeping its wire', () => {
const p = createProject({ examples: true })
const main = p.components.find(d => d.id === 'main')!
const input = main.nodes.find(n => n.kind === 'input')!
input.on = true
swapNode(p, main, input.id, { kind: 'clock' })
expect(input.kind).toBe('clock')
expect(input.on).toBeUndefined()
expect(main.wires.some(w => w.from.node === input.id)).toBe(true)
})
})
describe('unlinking and unpacking', () => {
it('unlinks every wire of a part', () => {
const p = createProject({ examples: true })
const main = p.components.find(d => d.id === 'main')!
const nand = main.nodes.find(n => n.kind === 'nand')!
expect(unlinkWires(main, new Set([nand.id]))).toBe(3)
expect(main.wires).toHaveLength(0)
})
it('unpacks a component into its parts without changing what the circuit does', () => {
const p = createProject({ examples: true })
const before = rows(p, 'ex-fa')
const fa = p.components.find(d => d.id === 'ex-fa')!
const ha = fa.nodes.find(n => n.chip === 'ex-ha')!
const res = unpackChip(p, 'ex-fa', ha.id)
if (!res.ok) throw new Error(res.error)
expect(fa.nodes.some(n => n.id === ha.id)).toBe(false)
expect(res.nodes.length).toBe(2)
expect(rows(p, 'ex-fa')).toEqual(before)
})
it('unpacks a component whose input runs straight to its output', () => {
const p = createProject({ examples: false })
p.components.push(
{
id: 'wire',
name: 'Wire',
symbol: 'box',
nodes: [
{ id: 'i', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'o', kind: 'output', x: 6, y: 0, label: 'Q' },
],
wires: [{ id: 'w', from: { node: 'i', pin: 'q' }, to: { node: 'o', pin: 'a' } }],
},
{
id: 'top',
name: 'Top',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: 0, y: 0, label: 'S' },
{ id: 'c', kind: 'chip', chip: 'wire', x: 4, y: 0 },
{ id: 'q', kind: 'output', x: 12, y: 0, label: 'Q' },
],
wires: [
{ id: 'w1', from: { node: 's', pin: 'q' }, to: { node: 'c', pin: 'i' } },
{ id: 'w2', from: { node: 'c', pin: 'o' }, to: { node: 'q', pin: 'a' } },
],
},
)
expect(unpackChip(p, 'top', 'c').ok).toBe(true)
const top = p.components.find(d => d.id === 'top')!
expect(top.wires.map(w => `${w.from.node}>${w.to.node}`)).toEqual(['s>q'])
})
it('gives one placed component its own copy of the definition', () => {
const p = createProject({ examples: true })
const fa = p.components.find(d => d.id === 'ex-fa')!
const [first, second] = fa.nodes.filter(n => n.chip === 'ex-ha')
const copy = makeUnique(p, fa, first!.id)!
expect(first!.chip).toBe(copy.id)
expect(second!.chip).toBe('ex-ha')
expect(rows(p, 'ex-fa')).toEqual(rows(createProject({ examples: true }), 'ex-fa'))
})
})
describe('clocks with their own frequency', () => {
it('compiles each clock with its frequency and keeps levels per clock', () => {
const p = createProject({ examples: false })
p.components.push({
id: 'clk',
name: 'Clocks',
symbol: 'box',
nodes: [
{ id: 'c1', kind: 'clock', x: 0, y: 0 },
{ id: 'c2', kind: 'clock', x: 0, y: 4, hz: 10 },
{ id: 'l1', kind: 'lamp', x: 6, y: 0 },
{ id: 'l2', kind: 'lamp', x: 6, y: 4 },
],
wires: [
{ id: 'w1', from: { node: 'c1', pin: 'q' }, to: { node: 'l1', pin: 'a' } },
{ id: 'w2', from: { node: 'c2', pin: 'q' }, to: { node: 'l2', pin: 'a' } },
],
})
const nl = compile(lookup(p), 'clk')
expect([...nl.clockHz]).toEqual([0, 10])
const sim = new Simulator(nl)
sim.toggleClock(1)
sim.run()
expect([sim.pin('l1', 'a'), sim.pin('l2', 'a')]).toEqual([0, 1])
const again = new Simulator(compile(lookup(p), 'clk'), sim.carry())
again.run()
expect([again.pin('l1', 'a'), again.pin('l2', 'a')]).toEqual([0, 1])
})
})

19
tests/perf.test.ts Normal file
View File

@ -0,0 +1,19 @@
import { expect, it } from 'vitest'
import { routeAll, type RouteInput } from '../app/lib/logic/routing'
it('routes 400 crowded wires fast enough to redraw while dragging', () => {
const inputs: RouteInput[] = []
const bodies = []
for (let i = 0; i < 400; i++) {
const col = i % 20
const row = Math.floor(i / 20)
// Sources in a column on the left, targets scattered: many wires want the same columns.
inputs.push({ id: `w${i}`, net: `n${i % 150}`, a: [col * 3, row * 3], b: [col * 3 + 8 + (i % 5), row * 3 + ((i * 7) % 11) - 5] })
if (i % 4 === 0) bodies.push({ x: col * 3 + 4, y: row * 3 - 1, w: 2, h: 2 })
}
const t = performance.now()
routeAll(inputs, bodies, [])
const ms = performance.now() - t
console.log(`routeAll(400 wires): ${ms.toFixed(1)} ms`)
expect(ms).toBeLessThan(250)
})

107
tests/routing.test.ts Normal file
View File

@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest'
import { shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup } from '../app/lib/logic/ops'
import { circuitRoutes, findCrossings, routeAll, type Routed } from '../app/lib/logic/routing'
/** Every pair of segments from different nets that lie on the same line and overlap. */
function overlaps(routes: Routed[]) {
const segs: { net: string; h: boolean; c: number; lo: number; hi: number }[] = []
for (const r of routes) {
for (let i = 0; i < r.draw.length - 1; i++) {
const [ax, ay] = r.draw[i]!
const [bx, by] = r.draw[i + 1]!
if (ax === bx && ay === by) continue
const h = ay === by
segs.push({ net: r.net, h, c: h ? ay : ax, lo: h ? Math.min(ax, bx) : Math.min(ay, by), hi: h ? Math.max(ax, bx) : Math.max(ay, by) })
}
}
const bad: string[] = []
for (let i = 0; i < segs.length; i++) {
for (let j = i + 1; j < segs.length; j++) {
const p = segs[i]!
const q = segs[j]!
if (p.net === q.net || p.h !== q.h || Math.abs(p.c - q.c) > 1e-9) continue
if (Math.min(p.hi, q.hi) - Math.max(p.lo, q.lo) > 1e-9) bad.push(`${p.net} / ${q.net} on ${p.h ? 'row' : 'column'} ${p.c}`)
}
}
return bad
}
const square = (r: Routed) => r.draw.every((p, i) => i === 0 || p[0] === r.draw[i - 1]![0] || p[1] === r.draw[i - 1]![1])
describe('routing', () => {
const p = createProject({ examples: true })
const get = lookup(p)
for (const def of p.components) {
it(`${def.name}: no two signals share a line, every wire stays square and ends on its pins`, () => {
const shapes = new Map(def.nodes.map(n => [n.id, shapeOf(n, get)]))
const routes = circuitRoutes(def, shapes)
expect(routes).toHaveLength(def.wires.length)
expect(overlaps(routes)).toEqual([])
for (const r of routes) {
expect(square(r), r.id).toBe(true)
expect(r.draw[0]).toEqual(r.grid[0])
expect(r.draw.at(-1)).toEqual(r.grid.at(-1))
expect(r.grid.every(([x, y]) => Number.isInteger(x) && Number.isInteger(y))).toBe(true)
}
})
}
it('moves an auto-routed wire off a line another signal already uses', () => {
// Two wires from different sources whose usual vertical step would share column 5.
const routes = routeAll(
[
{ id: 'a', net: 'n1', a: [0, 0], b: [10, 6] },
{ id: 'b', net: 'n2', a: [0, 2], b: [10, 8] },
],
[],
[],
)
expect(overlaps(routes)).toEqual([])
expect(routes[0]!.grid).toEqual([[0, 0], [5, 0], [5, 6], [10, 6]])
expect(routes[1]!.grid[1]![0]).not.toBe(5)
})
it('keeps hand-placed corners and draws a clashing wire on its own lane', () => {
const routes = routeAll(
[
{ id: 'a', net: 'n1', a: [0, 0], b: [10, 0], pts: [[2, 0], [2, 4], [8, 4], [8, 0]] },
{ id: 'b', net: 'n2', a: [0, 4], b: [10, 4], pts: [[1, 4], [9, 4]] },
],
[],
[],
)
expect(routes[0]!.grid).toEqual([[0, 0], [2, 0], [2, 4], [8, 4], [8, 0], [10, 0]])
expect(overlaps(routes)).toEqual([])
expect(routes.every(square)).toBe(true)
})
it('lets wires of the same signal share a line', () => {
const routes = routeAll(
[
{ id: 'a', net: 'n1', a: [0, 0], b: [10, 6] },
{ id: 'b', net: 'n1', a: [0, 0], b: [10, 8] },
],
[],
[],
)
expect(routes[0]!.draw).toEqual(routes[0]!.grid)
expect(routes[1]!.draw).toEqual(routes[1]!.grid)
})
it('finds crossings between different signals only', () => {
const routes = routeAll(
[
{ id: 'h', net: 'n1', a: [0, 3], b: [10, 3] },
{ id: 'v', net: 'n2', a: [5, 0], b: [6, 8], pts: [[5, 0], [5, 8]] },
{ id: 'v2', net: 'n1', a: [0, 3], b: [8, 9], pts: [[7, 3], [7, 9]] },
],
[],
[],
)
const c = findCrossings(routes)
// v2 shares h's line (same signal), so it hops over v as well; nothing hops over its own signal.
expect(c.map(x => [routes[x.wire]!.id, x.x])).toEqual([['h', 5], ['v2', 5]])
})
})