R saves like a game: one save per project on every device, Load game in the menu, a pause menu, and a lean side panel

- Sync: when two devices changed the same project, the newer save wins
  everywhere and the other becomes a savegame of it (new endpoint to keep
  a savegame without replacing the save), never an "(other device)" copy.
  A first visit keeps its starter unsaved until something changes, and
  the main menu waits for the account's saves before anything starts.
- Main menu: Load game lists every save. In the editor, Esc with nothing
  selected (or the project button) opens a pause menu: Resume, Save,
  Save as copy, Load, Settings, How to play, Main menu. The projects
  dialog is gone.
- Selection tab: name and transistors on top, one icon row (open,
  duplicate, unlink, delete, more = the right-click menu), only the
  settings that matter for the part; pins, component tools, keys, cable
  and panel options fold away and remember it. X/Y fields removed.
  The Circuit tab folds its component settings, transistor breakdown
  and tools the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-22 18:36:17 +02:00
parent 9411527c5d
commit c5b67ee7c1
17 changed files with 824 additions and 377 deletions

View File

@ -32,8 +32,8 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
- Tidy wiring (Settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
- 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.
- Saves are handled like a game: the main menu's "Load game" lists every save (open, rename, copy, delete, savegames, recently deleted, new, open a file), and in the editor Esc (with nothing selected) or the project button opens the pause menu: Resume, Save, Save as copy, Load, Settings, How to play, Main menu. 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). One save per project on every device: if two computers changed the same project, the newer save wins everywhere and the other one is kept as a savegame of that project (never as a second project). A new browser keeps its starter project unsaved until something changes in it, and while signed in the main menu waits for the account's saves before anything can be started, so a second device never makes a twin.
- 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. The table can go full screen, be downloaded as CSV or copied as a Markdown table; the row the switches are set to is highlighted.
- 17 challenges (NOT up to a D flip-flop) checked against a truth table or a step sequence.
@ -69,7 +69,7 @@ The editor UI is in [app/components/editor/](app/components/editor/) with state
No database: everything is JSON files under `data/`, which keeps memory use flat. Three layers protect it:
- **Crash-safe writes** ([server/utils/safe-fs.ts](server/utils/safe-fs.ts), mounted in [server/plugins/storage.ts](server/plugins/storage.ts)). A save writes a temporary file, flushes it to disk, keeps the current intact version as `<file>.bak` and then renames the new file into place. A power cut at any moment leaves the old or the new version; reading falls back to `.bak` when a file is missing or damaged, and leftover temporary files are removed at start.
- **Savegames** ([server/utils/history.ts](server/utils/history.ts)). Before a save replaces an account project, its state is kept as a version (at most one per 15 minutes; always before a restore and on deletion). Kept: the newest 30 plus the last of each day for 90 days. Deleted projects stay restorable for 30 days. In the app: Projects dialog, clock icon (restore, or open as copy), and "Recently deleted".
- **Savegames** ([server/utils/history.ts](server/utils/history.ts)). Before a save replaces an account project, its state is kept as a version (at most one per 15 minutes; always before a restore and on deletion). Kept: the newest 30 plus the last of each day for 90 days. Deleted projects stay restorable for 30 days. In the app: Load game (main or pause menu), clock icon (restore, or open as copy), and "Recently deleted".
- **Daily backup** ([server/utils/backup.ts](server/utils/backup.ts), [server/plugins/backup.ts](server/plugins/backup.ts)). Once a day the production server writes all of `data/` into `backups/logigate-YYYY-MM-DD.ndjson.gz`, leaving out damaged files. Kept: the newest 14 plus the first of each month for a year. `backups/` sits next to `data/` on the same disk, so it protects against damaged files and mistakes, not against losing the disk; copy it elsewhere for that.
Restore a backup on edgerealm (the current `data/` is moved aside first, so this can be undone):

View File

@ -3819,3 +3819,277 @@ table.board {
.menu-board .name-row .field {
margin-bottom: 0;
}
.title-item:disabled {
opacity: 0.45;
cursor: progress;
}
.title-item:disabled:hover {
background: none;
border-color: transparent;
}
.project-list .badge.mode {
color: var(--muted);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0 4px;
}
/* ── Pause menu ─────────────────────────────────────────────────── */
.pause-backdrop {
position: fixed;
inset: 0;
z-index: 65;
display: grid;
place-items: center;
padding: 16px;
background: rgb(5 8 12 / 0.72);
backdrop-filter: blur(3px);
animation: pause-in 0.15s ease-out;
}
.pause {
width: min(360px, 100%);
max-height: calc(100dvh - 32px);
overflow-y: auto;
padding: 22px 20px 18px;
background: rgb(19 24 31 / 0.96);
border: 1px solid var(--border);
border-radius: 14px;
box-shadow: 0 30px 80px rgb(0 0 0 / 0.55);
}
.pause.wide {
width: min(720px, 100%);
}
.pause-kicker {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--muted);
}
.pause h2 {
margin-top: 2px;
font-size: 20px;
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pause-where {
display: flex;
align-items: center;
gap: 6px;
margin-top: 4px;
font-size: 12px;
color: var(--muted);
}
.pause-nav {
display: grid;
gap: 2px;
margin-top: 16px;
}
.pause-item {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
padding: 9px 12px;
border: 1px solid transparent;
border-radius: 8px;
font-size: 15px;
font-weight: 600;
text-align: left;
color: var(--text);
}
.pause-item kbd {
margin-left: auto;
}
.pause-item:hover,
.pause-item:focus-visible {
background: var(--panel-2);
border-color: var(--border);
outline: none;
}
.pause-item:focus-visible {
border-color: var(--accent);
}
.pause-item.primary {
color: var(--on);
}
.pause-item:disabled {
opacity: 0.5;
}
.pause-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
@keyframes pause-in {
from {
opacity: 0;
}
}
/* ── Selection tab: header, compact rows, folds ─────────────────── */
.sel-head {
display: flex;
flex-direction: column;
gap: 8px;
margin: -2px 0 12px;
}
.sel-title {
display: flex;
align-items: baseline;
gap: 8px;
min-width: 0;
}
.inspector .sel-title h3 {
margin: 0;
font-size: 15px;
font-weight: 700;
letter-spacing: 0;
text-transform: none;
color: var(--text);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sel-t {
margin-left: auto;
flex-shrink: 0;
font-family: var(--font-mono);
font-size: 11px;
color: var(--muted);
}
.sel-actions {
display: flex;
gap: 2px;
padding: 3px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--panel-2);
}
.sel-actions .icon-btn {
flex: 1;
width: auto;
}
.sel-actions .icon-btn:disabled {
opacity: 0.35;
}
.icon-btn.danger:hover {
color: var(--danger);
}
.sel-row {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
.sel-row > .field {
margin-bottom: 0;
}
.sel-row .grow {
flex: 1;
min-width: 0;
}
.sel-row .narrow {
flex: 0 0 72px;
}
.field input.auto-name {
color: var(--muted);
font-style: italic;
}
.field-input {
width: 100%;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 6px;
padding: 6px 8px;
font-size: 13px;
color: var(--text);
outline: none;
}
.field-input:focus {
border-color: var(--accent);
}
.fold {
margin: 0 -14px;
border-top: 1px solid var(--border);
}
.fold:last-of-type {
margin-bottom: -14px;
}
.fold-head {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
padding: 9px 14px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted);
text-align: left;
}
.fold-head:hover {
color: var(--text);
background: rgb(255 255 255 / 0.02);
}
.fold-chev {
transition: transform 0.15s;
}
.fold.open .fold-chev {
transform: rotate(90deg);
}
.fold-note {
max-width: 55%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
font-weight: 500;
letter-spacing: 0;
text-transform: none;
}
.fold-body {
padding: 2px 14px 14px;
}

View File

@ -71,7 +71,7 @@ watch(
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
<EditorPublishDialog v-if="ed.dialog.value === 'publish'" />
<EditorHelp v-if="ed.showHelp.value" />
<EditorProjectsDialog v-if="ed.dialog.value === 'projects'" />
<EditorPauseMenu v-if="ed.paused.value && ed.screen.value === 'editor'" />
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
<EditorVersionsDialog v-if="ed.dialog.value === 'versions'" />

View File

@ -912,7 +912,7 @@ function nudge(dx: number, dy: number) {
function onKey(e: KeyboardEvent) {
const el = e.target as HTMLElement
if (el.closest('input, textarea, select, [contenteditable]')) return
if (el.closest?.('input, textarea, select, [contenteditable]')) return
if (ed.dialog.value || ed.showHelp.value) {
if (e.key === 'Escape') {
ed.dialog.value = null
@ -920,6 +920,8 @@ function onKey(e: KeyboardEvent) {
}
return
}
// Paused: the pause menu has the keys.
if (ed.paused.value) return
const mod = e.ctrlKey || e.metaKey
const key = e.key.toLowerCase()
if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
@ -987,6 +989,8 @@ function onKey(e: KeyboardEvent) {
return
}
if (ed.linking.value) return ed.stopLinking()
// Nothing to cancel: Esc pauses, like in a game.
if (!ed.placing.value && !ed.selection.value.length && !ed.wireSel.value.length) return ed.pause()
ed.placing.value = null
ed.clearSelection()
} else if (ARROWS[e.key]) {

View File

@ -38,7 +38,6 @@ const groupNames = computed(() => [...new Set(ed.project.value.components.map(d
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
const total = computed(() => ed.transistors(def.value.id))
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
const showBreakdown = ref(true)
function toggleFace(e: Event) {
def.value.face = (e.target as HTMLInputElement).checked
@ -96,34 +95,10 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</section>
<section>
<h3>This circuit</h3>
<label class="field">
<span>Name</span>
<span>Circuit name</span>
<input ref="nameInput" v-model="def.name" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
</label>
<label class="field">
<span>Description</span>
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
</label>
<div class="grid grid-cols-2 gap-2">
<label class="field">
<span>Drawn as</span>
<select v-model="def.symbol" @change="ed.commit(false)">
<option v-for="s in SYMBOLS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select>
</label>
<label class="field">
<span>Group</span>
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
<datalist id="groups">
<option v-for="g in groupNames" :key="g" :value="g" />
</datalist>
</label>
</div>
<label v-if="hasFace" class="check">
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
Show its lamps and displays on the component box
</label>
<dl class="stats">
<dt>Pins</dt>
<dd>
@ -131,7 +106,7 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</dd>
<dt>NAND gates</dt>
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
<dt>Transistors</dt>
<dt title="CMOS: 4 per NAND gate, at every depth">Transistors</dt>
<dd>{{ total.toLocaleString() }}</dd>
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
@ -145,37 +120,43 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
</template>
</p>
</section>
<section>
<h3>Its box</h3>
<p class="hint">How it looks when placed: {{ def.design ? 'drawn by hand' : 'laid out automatically' }}.</p>
<button class="btn w-full" title="Move lamps, displays and the name, draw lines, boxes and text, size the box" @click="ed.designFace(def.id)">
<EditorFold id="circuit-component" title="As a component" :note="def.group || ''">
<label class="field">
<span>Description</span>
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
</label>
<div class="sel-row">
<label class="field grow">
<span>Drawn as</span>
<select v-model="def.symbol" @change="ed.commit(false)">
<option v-for="s in SYMBOLS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select>
</label>
<label class="field grow">
<span>Group</span>
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
<datalist id="groups">
<option v-for="g in groupNames" :key="g" :value="g" />
</datalist>
</label>
</div>
<label v-if="hasFace" class="check">
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
Show its lamps and displays on the box
</label>
<button class="btn w-full" :title="`How it looks when placed: ${def.design ? 'drawn by hand' : 'laid out automatically'}`" @click="ed.designFace(def.id)">
<Icon name="lucide:pen-tool" class="size-4" /> Design the box
</button>
</section>
</EditorFold>
<section>
<h3>Sheet</h3>
<p class="hint">The circuit as a wiring sheet with a title block: print it, save it as PDF, or keep it as an SVG.</p>
<div class="grid grid-cols-2 gap-2">
<button class="btn" :disabled="!def.nodes.length" title="On white paper (Ctrl+P); choose Save as PDF in the print dialog" @click="ed.exportSheet('print')">
<Icon name="lucide:printer" class="size-4" /> Print / PDF
</button>
<button class="btn" :disabled="!def.nodes.length" title="As on screen, to open in a browser or drawing program" @click="ed.exportSheet('svg')">
<Icon name="lucide:file-image" class="size-4" /> SVG file
</button>
</div>
</section>
<section>
<button class="section-toggle" @click="showBreakdown = !showBreakdown">
<Icon :name="showBreakdown ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
Where the transistors are
</button>
<template v-if="showBreakdown">
<p v-if="!breakdown.length" class="hint mt-2">No gates here yet. Switches, lamps, displays and cables need no transistors.</p>
<table v-else class="cost">
<EditorFold id="circuit-transistors" title="Where the transistors are" :note="total ? total.toLocaleString() : ''">
<p v-if="!breakdown.length" class="hint">No gates here yet. Switches, lamps, displays and cables need no transistors.</p>
<table
v-else
class="cost"
title="Everything is built from NAND gates; a CMOS NAND has 4 transistors (2 in parallel to the supply, 2 in series to ground), so it is 4 per NAND inside, at every depth"
>
<tbody>
<tr v-for="l in breakdown" :key="l.key" title="Select these parts" @click="ed.selectOnly(l.ids)">
<td class="what">{{ l.count }} × {{ l.name }}</td>
@ -191,15 +172,9 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
</tr>
</tfoot>
</table>
<p class="hint mt-2">
Everything here is built from NAND gates, and a CMOS NAND gate has 4 transistors: 2 in parallel to the supply, 2 in series to
ground. So the count is 4 per NAND inside, at every depth: a NOT costs 4, an AND 8, a full adder 60. (A NOT made directly in
CMOS would need only 2; here it is built from a NAND.)
</p>
</template>
</section>
</EditorFold>
<section>
<EditorFold id="circuit-tools" title="Tools">
<div class="grid gap-2">
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
@ -212,12 +187,20 @@ watch(() => def.value.id, () => (confirmDelete.value = false))
>
<Icon name="lucide:puzzle" class="size-4" /> Publish as puzzle
</button>
<div class="sel-row">
<button class="btn grow" :disabled="!def.nodes.length" title="A wiring sheet with a title block on white paper (Ctrl+P); choose Save as PDF in the print dialog" @click="ed.exportSheet('print')">
<Icon name="lucide:printer" class="size-4" /> Print / PDF
</button>
<button class="btn grow" :disabled="!def.nodes.length" title="As on screen, to open in a browser or drawing program" @click="ed.exportSheet('svg')">
<Icon name="lucide:file-image" class="size-4" /> SVG
</button>
</div>
</section>
<section class="actions">
<button class="btn btn-ghost" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
<button v-if="!confirmDelete" class="btn btn-ghost" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
<button v-else class="btn btn-danger" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
<div class="sel-row">
<button class="btn grow" title="A copy of this circuit as a new component" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
<button v-if="!confirmDelete" class="btn grow" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
<button v-else class="btn btn-danger grow" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
</div>
</div>
</EditorFold>
</section>
</template>

View File

@ -0,0 +1,30 @@
<script setup lang="ts">
// A folding group in the side panel. It remembers, per group, whether you
// left it open, so the panel stays as short as you like it.
const props = defineProps<{ title: string; id: string; open?: boolean; /** Short note after the title, like a count. */ note?: string }>()
const KEY = `logigate:fold:${props.id}`
const isOpen = ref(props.open ?? false)
try {
const saved = localStorage.getItem(KEY)
if (saved !== null) isOpen.value = saved === '1'
} catch {}
function toggle() {
isOpen.value = !isOpen.value
try {
localStorage.setItem(KEY, isOpen.value ? '1' : '0')
} catch {}
}
</script>
<template>
<div class="fold" :class="{ open: isOpen }">
<button class="fold-head" :aria-expanded="isOpen" @click="toggle">
<Icon name="lucide:chevron-right" class="fold-chev size-3.5" />
<span class="grow">{{ title }}</span>
<span v-if="note" class="fold-note">{{ note }}</span>
</button>
<div v-if="isOpen" class="fold-body"><slot /></div>
</div>
</template>

View File

@ -2,6 +2,7 @@
const ed = useEditor()
const SHORTCUTS: [string, string][] = [
['Esc (nothing selected)', 'Pause menu: save, save as copy, load, settings, main menu'],
['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'],
['Select several', 'Change them all at once: swap, rename D0, D1, …, switch all to 0 or 1, line up'],

View File

@ -9,13 +9,14 @@ const page = ed.menuPage
const nav = ref<HTMLElement>()
const ITEMS: { page?: MenuPage; label: string; icon: string; sub: string }[] = [
{ page: 'load', label: 'Load game', icon: 'lucide:folder-open', sub: 'Every save: open, rename, copy, savegames' },
{ page: 'free', label: 'Free play', icon: 'lucide:cpu', sub: 'Every part from the start, your own projects' },
{ page: 'campaign', label: 'Campaign', icon: 'lucide:route', sub: 'Start with NAND, earn each part you build' },
{ page: 'challenges', label: 'Challenges', icon: 'lucide:target', sub: 'Single tasks and the puzzle of the week' },
{ page: 'leaderboard', label: 'Leaderboard', icon: 'lucide:trophy', sub: 'Fewest transistors wins' },
]
const TITLES: Record<MenuPage, string> = { main: '', free: 'Free play', campaign: 'Campaign', challenges: 'Challenges', leaderboard: 'Leaderboard' }
const TITLES: Record<MenuPage, string> = { main: '', load: 'Load game', free: 'Free play', campaign: 'Campaign', challenges: 'Challenges', leaderboard: 'Leaderboard' }
function go(p: MenuPage) {
page.value = page.value === p ? 'main' : p
@ -69,14 +70,22 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
<p class="title-tag">From one NAND gate to a computer</p>
<nav ref="nav" class="title-nav" aria-label="Main menu">
<button class="title-item primary" @click="ed.enterGame()">
<button class="title-item primary" :disabled="!ed.savesReady.value" @click="ed.enterGame()">
<Icon name="lucide:play" class="size-5 shrink-0" />
<span class="grow">
<span class="label">Continue</span>
<span class="sub">{{ ed.project.value.name }}</span>
<span class="sub">{{ ed.savesReady.value ? ed.project.value.name : 'Loading your saves…' }}</span>
</span>
</button>
<button v-for="it in ITEMS" :key="it.label" class="title-item" :class="{ active: page === it.page }" @click="go(it.page!)">
<button
v-for="it in ITEMS"
:key="it.label"
class="title-item"
:class="{ active: page === it.page }"
:disabled="!ed.savesReady.value && it.page !== 'leaderboard'"
:title="ed.savesReady.value ? '' : 'Loading your saves from your account…'"
@click="go(it.page!)"
>
<Icon :name="it.icon" class="size-5 shrink-0" />
<span class="grow">
<span class="label">{{ it.label }}</span>
@ -106,7 +115,8 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
<h2>{{ TITLES[page] }}</h2>
</header>
<div class="title-page-body">
<EditorProjectList v-if="page === 'free'" free-only @done="ed.enterGame()" />
<EditorProjectList v-if="page === 'load'" @done="ed.enterGame()" />
<EditorProjectList v-else-if="page === 'free'" free-only @done="ed.enterGame()" />
<EditorMenuCampaign v-else-if="page === 'campaign'" />
<EditorMenuChallenges v-else-if="page === 'challenges'" />
<EditorMenuLeaderboard v-else-if="page === 'leaderboard'" />

View File

@ -1,4 +1,5 @@
<script setup lang="ts">
import type { MenuEntry } from '~/composables/useMenu'
import { stats } from '~/lib/logic/analyze'
import { compile } from '~/lib/logic/compile'
import { cableOf } from '~/lib/logic/cables'
@ -105,14 +106,6 @@ function setColor(c: (typeof LAMP_COLORS)[number] | undefined) {
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
@ -162,6 +155,28 @@ const invertible = computed(() => {
return ed.shape(n.value).inputs.map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
})
const inverted = computed(() => invertible.value.filter(p => p.on).length)
const transistors = computed(() => ed.transistorsOfNode(n.value))
const transistorNote = computed(() =>
n.value.kind === 'nand'
? 'CMOS NAND: 2 transistors in parallel to the supply, 2 in series to ground'
: transistors.value
? `${(transistors.value / 4).toLocaleString()} NAND gates inside, 4 transistors each`
: 'No logic gate inside',
)
// The "more" button opens the same list as a right click on the part.
const menu = useMenu()
const more = ref<{ x: number; y: number; entries: MenuEntry[] } | null>(null)
let closedAt = 0
function openMore(e: MouseEvent) {
// A click on the button while the menu is open closes it (the press already did).
if (performance.now() - closedAt < 300) return
const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
more.value = { x: r.right - 220, y: r.bottom + 4, entries: menu.build({ kind: 'selection' }, { fit: () => {}, place: () => {} }) }
}
/** The bundle of the cable this bundle or split belongs to. */
const cableBundle = computed(() => {
if (n.value.kind === 'bundle') return n.value
@ -243,18 +258,46 @@ function setRowHz(row: PanelRow, e: Event) {
</script>
<template>
<section>
<h3>{{ title }}</h3>
<p class="score" :title="n.kind === 'nand' ? 'CMOS NAND: 2 transistors in parallel to the supply, 2 in series to ground' : ''">
<Icon name="lucide:cpu" class="size-4 shrink-0" />
<span v-if="n.kind === 'nand'">4 transistors (CMOS: 2 in parallel to the supply, 2 in series to ground)</span>
<span v-else-if="n.kind === 'chip'">
{{ ed.transistorsOfNode(n).toLocaleString() }} transistors, from {{ (ed.transistorsOfNode(n) / 4).toLocaleString() }} NAND gates inside
</span>
<span v-else>0 transistors: no logic gate inside</span>
</p>
<section class="sel">
<!-- What it is, and the everyday actions -->
<header class="sel-head">
<div class="sel-title">
<h3 :title="HINTS[n.kind] ?? ''">{{ title }}</h3>
<span class="sel-t" :title="transistorNote">{{ transistors.toLocaleString() }} T</span>
</div>
<div class="sel-actions">
<button v-if="n.kind === 'chip' && chipDef" class="icon-btn" title="Open component (Enter)" @click="ed.open(chipDef.id)">
<Icon name="lucide:log-in" class="size-4" />
</button>
<button class="icon-btn" title="Duplicate (Ctrl+D)" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /></button>
<button class="icon-btn" :disabled="!wired" title="Unlink all its wires" @click="ed.unlink([n.id])"><Icon name="lucide:unlink" class="size-4" /></button>
<button class="icon-btn danger" title="Delete (Del)" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /></button>
<button class="icon-btn" title="Everything else you can do with it (also on right click)" @click="openMore"><Icon name="lucide:ellipsis" class="size-4" /></button>
</div>
</header>
<label v-if="logic" class="field">
<!-- The few settings that matter for this kind of part -->
<label v-if="hasLabel" class="field">
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : n.kind === 'tag' ? 'Signal name' : n.kind === 'ref' ? 'Signal' : 'Name' }}</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"
:class="{ 'auto-name': n.autoLabel }"
:title="n.autoLabel ? 'Named automatically; typing a name keeps it' : ''"
:placeholder="n.kind === 'chip' ? 'e.g. U1, ALU' : n.kind === 'panel' ? 'Shown above the panel' : n.kind === 'tag' || n.kind === 'ref' ? 'e.g. CLK, RESET' : ''"
:list="n.kind === 'ref' ? 'signal-names' : undefined"
@change="onLabel"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
</label>
<datalist id="signal-names">
<option v-for="name in signalNames" :key="name" :value="name" />
</datalist>
<div v-if="logic || family.length || widens" class="sel-row">
<label v-if="logic" class="field grow" title="Swapping keeps the wires on the pins in the same position">
<span>Part</span>
<select :value="currentType" @change="onSwap">
<option value="nand">NAND (2 → 1)</option>
@ -263,60 +306,63 @@ function setRowHz(row: PanelRow, e: Event) {
</optgroup>
</select>
</label>
<label v-else-if="family.length" class="field">
<label v-else-if="family.length" class="field grow" title="Swapping keeps the wires on the pins in the same position">
<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="widens" class="field">
<label v-if="widens" class="field narrow" :title="inputs > 2 ? `Built from ${inputs - 1} two-input gates in a tree, so the transistors count honestly` : 'Up to 16 inputs'">
<span>Inputs</span>
<input
type="number"
min="2"
:max="MAX_GATE_INPUTS"
step="1"
:value="inputs"
@change="ed.setInputs(n, Number(($event.target as HTMLInputElement).value))"
/>
<input type="number" min="2" :max="MAX_GATE_INPUTS" step="1" :value="inputs" @change="ed.setInputs(n, Number(($event.target as HTMLInputElement).value))" />
</label>
<p v-if="widens && inputs > 2" class="hint -mt-1">Built from {{ inputs - 1 }} two-input gates in a tree, so the transistors count honestly.</p>
</div>
<div v-if="invertible.length" class="field">
<span>Inverted inputs (Alt + click a pin)</span>
<div class="invert-pins">
<button
v-for="p in invertible"
:key="p.key"
class="invert-pin"
:class="{ on: p.on }"
:title="p.on ? 'Inverted: one NAND, 4 transistors. Click to take the bubble off.' : 'Invert this input'"
@click="ed.toggleInvert(n, p.key)"
>
<span class="dot" />{{ p.label }}
</button>
<div v-if="n.kind === 'input'" 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>
<label v-if="hasLabel" class="field">
<span>{{ n.kind === 'note' ? 'Text' : n.kind === 'chip' ? 'Name on the canvas' : n.kind === 'tag' ? 'Signal name' : n.kind === 'ref' ? 'Signal' : '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' : n.kind === 'panel' ? 'Shown above the panel' : n.kind === 'tag' || n.kind === 'ref' ? 'e.g. CLK, RESET' : ''"
:list="n.kind === 'ref' ? 'signal-names' : undefined"
@change="onLabel"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
<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>
<p v-if="n.autoLabel && n.label" class="hint -mt-1">Named automatically. Typing a name keeps it.</p>
<datalist id="signal-names">
<option v-for="name in signalNames" :key="name" :value="name" />
<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' || n.kind === 'pixel'" 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>
<!-- Signals -->
<template v-if="n.kind === 'tag'">
@ -324,10 +370,11 @@ function setRowHz(row: PanelRow, e: Event) {
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
<span>{{ senders.length }} "Send signal" parts use this name: they all drive it, like a short.</span>
</p>
<p class="hint">{{ uses.length ? `Used in ${uses.length} place${uses.length === 1 ? '' : 's'}.` : 'Not used anywhere yet.' }}</p>
<div class="mb-2 grid grid-cols-2 gap-2">
<button class="btn" :disabled="!signal" title="A 'Use signal' for it, placed next to it" @click="ed.useSignal(n)"><Icon name="lucide:tag" class="size-4" /> Use it</button>
<button class="btn" :disabled="!uses.length" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
<div class="sel-row">
<button class="btn grow" :disabled="!signal" title="A 'Use signal' for it, placed next to it" @click="ed.useSignal(n)"><Icon name="lucide:tag" class="size-4" /> Use it</button>
<button class="btn grow" :disabled="!uses.length" :title="uses.length ? `Used in ${uses.length} place${uses.length === 1 ? '' : 's'}` : 'Not used anywhere yet'" @click="ed.selectSignal(signal)">
<Icon name="lucide:scan-search" class="size-4" /> {{ uses.length }} uses
</button>
</div>
</template>
<template v-if="n.kind === 'ref'">
@ -335,9 +382,9 @@ function setRowHz(row: PanelRow, e: Event) {
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" />
<span>{{ signal ? `Nothing sends "${signal}" in this circuit, so it reads 0.` : 'Pick the signal it carries.' }}</span>
</p>
<div v-else class="mb-2 grid grid-cols-2 gap-2">
<button class="btn" @click="ed.focusNode(senders[0]!.id)"><Icon name="lucide:locate-fixed" class="size-4" /> Go to source</button>
<button class="btn" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
<div v-else class="sel-row">
<button class="btn grow" @click="ed.focusNode(senders[0]!.id)"><Icon name="lucide:locate-fixed" class="size-4" /> Go to source</button>
<button class="btn grow" @click="ed.selectSignal(signal)"><Icon name="lucide:scan-search" class="size-4" /> Select all</button>
</div>
</template>
@ -417,6 +464,7 @@ function setRowHz(row: PanelRow, e: Event) {
</template>
</div>
</div>
<EditorFold id="panel-options" title="Panel options">
<button class="btn w-full" :disabled="!n.rows?.length" @click="ed.startLinking([n.id], outPanel ? 'in' : 'out')">
<Icon name="lucide:cable" class="size-4" /> Wire rows one by one
</button>
@ -427,116 +475,25 @@ function setRowHz(row: PanelRow, e: Event) {
<input type="checkbox" :checked="!n.inner" @change="setInner(!($event.target as HTMLInputElement).checked)" />
Rows are component {{ outPanel ? 'outputs' : 'inputs' }}
</label>
<p v-if="n.inner" class="hint">{{ outPanel ? 'Kept inside: the lamps only show in here.' : 'Kept inside: in a component the switches stay as set here, buttons read 0.' }}</p>
</EditorFold>
</template>
<div v-if="cables.out.length || cables.in.length" class="field cable-choices">
<span>Plug a cable onto its pins</span>
<div v-if="cables.out.length" class="cable-row">
<span class="hint">From outputs</span>
<button v-for="g in cables.out" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires out of these pins`" @click="ed.cableOut(n.id, g.pins)">{{ g.label }}</button>
</div>
<div v-if="cables.in.length" class="cable-row">
<span class="hint">Into inputs</span>
<button v-for="g in cables.in" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires into these pins`" @click="ed.cableIn(n.id, g.pins)">{{ g.label }}</button>
</div>
</div>
<!-- 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>
<label v-if="n.kind === 'pixel'" class="field" title="Pixels with the same screen name make one screen on the component's box; without a name, the main screen">
<span>Screen on the box</span>
<input
:value="n.screen ?? ''"
list="screen-names"
placeholder="Main screen"
@change="ed.setScreen([n.id], ($event.target as HTMLInputElement).value)"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
<datalist id="screen-names">
<option v-for="name in screenNames" :key="name" :value="name" />
</datalist>
</label>
<div v-if="n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'" 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>
<!-- Cable ends -->
<template v-if="n.kind === 'bundle' || n.kind === 'split'">
<p v-if="n.plug" class="result pass">
<Icon name="lucide:plug-zap" class="size-4 shrink-0" />
<span class="grow">Plugged into {{ partName(n.plug) }}. It moves with it; drag it away to pull it out.</span>
<span class="grow">Plugged into {{ partName(n.plug) }}</span>
<button class="btn-sm" title="Pull it out: it steps aside and its wires show again" @click="ed.unplugEnd(n)">Unplug</button>
</p>
<button
v-else-if="plugPart"
class="btn mb-2 w-full"
:title="`Sit straight on the pins of ${partName(plugPart.id)}, without wires in between`"
@click="ed.plugEnd(n)"
>
<button v-else-if="plugPart" class="btn mb-2 w-full" :title="`Sit straight on the pins of ${partName(plugPart.id)}, without wires in between`" @click="ed.plugEnd(n)">
<Icon name="lucide:plug" class="size-4" /> Plug into {{ partName(plugPart.id) }}
</button>
<button
v-if="n.kind === 'bundle' && undriven && !n.plug"
class="btn mb-2 w-full"
title="A switch for every wire nothing drives yet; the cable plugs into it. Make each row a button or clock, give it a key or colour."
@click="ed.addCablePanel(n.id)"
>
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
</button>
<div class="grid grid-cols-2 gap-2">
<label class="field">
<div class="sel-row">
<label class="field grow">
<span>Wires</span>
<input type="number" min="2" :max="MAX_BITS" step="1" :value="cableBits(n)" @change="ed.setBits(n, Number(($event.target as HTMLInputElement).value))" />
</label>
<label class="field" :title="n.plug ? 'Set by the pins it is plugged into' : 'Rows from one wire to the next, to line up with pins further apart'">
<label class="field grow" :title="n.plug ? 'Set by the pins it is plugged into' : 'Rows from one wire to the next, to line up with pins further apart'">
<span>Spacing</span>
<input
type="number"
@ -550,9 +507,9 @@ function setRowHz(row: PanelRow, e: Event) {
/>
</label>
</div>
<p v-if="n.names?.some(Boolean)" class="hint -mt-1">Wires: {{ n.names.map((x, i) => x || i).join(', ') }}</p>
<EditorFold id="cable-more" title="Cable" :note="n.names?.some(Boolean) ? n.names.map((x, i) => x || i).join(', ') : ''">
<div v-if="cableBundle" class="field">
<span>Sleeve colour (the wires inside keep theirs)</span>
<span>Sleeve colour</span>
<div class="swatches">
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default: grey" @click="ed.setCableColor(cableBundle.id, undefined)" />
<button
@ -565,73 +522,109 @@ function setRowHz(row: PanelRow, e: Event) {
/>
</div>
</div>
<p class="hint">Drag the bundle and the split to decide where the cable starts and ends. Drop an end with its pins on a part's pins to plug it in.</p>
<button v-if="cableBundle" class="btn mb-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cableBundle.id)">
<button
v-if="n.kind === 'bundle' && undriven && !n.plug"
class="btn mb-2 w-full"
title="A switch for every wire nothing drives yet; the cable plugs into it"
@click="ed.addCablePanel(n.id)"
>
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
</button>
<button v-if="cableBundle" class="btn w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cableBundle.id)">
<Icon name="lucide:split" class="size-4" /> Remove cable
</button>
</EditorFold>
</template>
<p v-if="HINTS[n.kind]" class="hint">{{ HINTS[n.kind] }}</p>
<!-- Less used, folded away -->
<EditorFold v-if="n.kind === 'input' || n.kind === 'button'" id="keyboard" title="Keyboard key" :note="n.key?.toUpperCase() ?? ''">
<input :value="n.key ?? ''" readonly placeholder="Click, then press a key" class="key-input field-input" @keydown="setKey" />
</EditorFold>
<template v-if="n.kind === 'chip' && chipDef">
<EditorFold v-if="n.kind === 'pixel'" id="pixel-screen" title="Screen on the box" :note="n.screen ?? ''">
<input
class="field-input"
:value="n.screen ?? ''"
list="screen-names"
placeholder="Main screen"
title="Pixels with the same screen name make one screen on the component's box"
@change="ed.setScreen([n.id], ($event.target as HTMLInputElement).value)"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
<datalist id="screen-names">
<option v-for="name in screenNames" :key="name" :value="name" />
</datalist>
</EditorFold>
<EditorFold v-if="invertible.length || cables.out.length || cables.in.length || chipInputs || chipOutputs" id="pins" title="Pins" :note="inverted ? `${inverted} inverted` : ''">
<div v-if="invertible.length" class="field">
<span>Inverted inputs (Alt + click a pin)</span>
<div class="invert-pins">
<button
v-for="p in invertible"
:key="p.key"
class="invert-pin"
:class="{ on: p.on }"
:title="p.on ? 'Inverted: one NAND, 4 transistors. Click to take the bubble off.' : 'Invert this input'"
@click="ed.toggleInvert(n, p.key)"
>
<span class="dot" />{{ p.label }}
</button>
</div>
</div>
<div v-if="cables.out.length || cables.in.length" class="field cable-choices">
<span>Plug a cable onto its pins</span>
<div v-if="cables.out.length" class="cable-row">
<span class="hint">From outputs</span>
<button v-for="g in cables.out" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires out of these pins`" @click="ed.cableOut(n.id, g.pins)">{{ g.label }}</button>
</div>
<div v-if="cables.in.length" class="cable-row">
<span class="hint">Into inputs</span>
<button v-for="g in cables.in" :key="g.label" class="btn-sm" :title="`A cable with ${g.pins.length} wires into these pins`" @click="ed.cableIn(n.id, g.pins)">{{ g.label }}</button>
</div>
</div>
<div v-if="chipInputs || chipOutputs" class="field mb-0">
<span>Wire one by one</span>
<div class="sel-row">
<button class="btn grow" :disabled="!chipInputs" title="Click the source for each input in turn" @click="ed.startLinking([n.id], 'in')">
<Icon name="lucide:cable" class="size-4" /> Inputs
</button>
<button class="btn grow" :disabled="!chipOutputs" title="Click the target for each output in turn" @click="ed.startLinking([n.id], 'out')">
<Icon name="lucide:cable" class="size-4" /> Outputs
</button>
</div>
</div>
</EditorFold>
<EditorFold v-if="n.kind === 'chip' && chipDef" id="component" title="Component">
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
<dl v-if="chipStats" class="stats">
<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="Move its lamps and displays, draw on it, size it: for every copy" @click="ed.designFace(chipDef.id)">
<Icon name="lucide:pen-tool" class="size-4" /> Design its box
</button>
<button
v-if="chipInputs && !hasPanel"
class="btn w-full"
title="A switch for every free input, docked to the left; each one can become a button or clock"
@click="ed.addPanel(n.id)"
>
<Icon name="lucide:sliders-vertical" class="size-4" /> Attach input panel
<div v-if="(chipInputs && !hasPanel) || (chipOutputs && !hasOutPanel)" class="sel-row">
<button v-if="chipInputs && !hasPanel" class="btn grow" title="A switch for every free input, docked to the left" @click="ed.addPanel(n.id)">
<Icon name="lucide:sliders-vertical" class="size-4" /> Input panel
</button>
<button v-if="chipOutputs && !hasOutPanel" class="btn w-full" title="A lamp for every output, docked to the right" @click="ed.addPanel(n.id, 'out')">
<Icon name="lucide:list-checks" class="size-4" /> Attach output panel
<button v-if="chipOutputs && !hasOutPanel" class="btn grow" title="A lamp for every output, docked to the right" @click="ed.addPanel(n.id, 'out')">
<Icon name="lucide:list-checks" class="size-4" /> Output panel
</button>
<div v-if="chipInputs || chipOutputs" class="field mb-0">
<span>Wire one by one</span>
<div class="grid grid-cols-2 gap-2">
<button class="btn" :disabled="!chipInputs" title="Click the source for each input in turn" @click="ed.startLinking([n.id], 'in')">
<Icon name="lucide:cable" class="size-4" /> Inputs
</div>
<div class="sel-row">
<button class="btn grow" 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
</button>
<button class="btn" :disabled="!chipOutputs" title="Click the target for each output in turn" @click="ed.startLinking([n.id], 'out')">
<Icon name="lucide:cable" class="size-4" /> Outputs
<button class="btn grow" 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" /> Own copy
</button>
</div>
</div>
<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>
</EditorFold>
<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>
<EditorContextMenu v-if="more" :x="more.x" :y="more.y" :entries="more.entries" @close="more = null" />
</section>
</template>

View File

@ -0,0 +1,88 @@
<script setup lang="ts">
// The in-game menu, like pausing a game: resume, save, load, settings, back
// to the title screen. Esc opens it from the editor and closes it again.
const ed = useEditor()
const nav = ref<HTMLElement>()
const saving = ref(false)
const resume = () => (ed.paused.value = null)
async function save() {
saving.value = true
try {
await ed.saveNow()
} finally {
saving.value = false
}
}
function saveCopy() {
ed.duplicateProject(ed.meta.value.id)
resume()
}
const where = computed(() =>
ed.account.value
? ed.cloudState.value === 'synced'
? 'Saved in your account'
: ed.cloudState.value === 'syncing'
? 'Saving to your account…'
: 'Saved in this browser; the account follows when it can be reached'
: 'Saved in this browser as you work',
)
function onKey(e: KeyboardEvent) {
if (ed.dialog.value || ed.showHelp.value) return
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
if (ed.paused.value === 'load') ed.paused.value = 'main'
else resume()
return
}
if ((e.target as HTMLElement).closest('input, textarea, select')) return
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
const list = [...(nav.value?.querySelectorAll<HTMLButtonElement>('button') ?? [])]
const at = list.indexOf(document.activeElement as HTMLButtonElement)
const next = at < 0 ? 0 : (at + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length
list[next]?.focus()
e.preventDefault()
}
onMounted(() => {
window.addEventListener('keydown', onKey, true)
nextTick(() => nav.value?.querySelector('button')?.focus())
})
onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
</script>
<template>
<div class="pause-backdrop" @click.self="resume">
<div class="pause" :class="{ wide: ed.paused.value === 'load' }" role="dialog" aria-label="Paused">
<template v-if="ed.paused.value === 'main'">
<p class="pause-kicker">Paused</p>
<h2>{{ ed.project.value.name }}</h2>
<p class="pause-where">
<Icon :name="ed.account.value ? 'lucide:cloud-check' : 'lucide:laptop'" class="size-3.5" />
{{ where }}
</p>
<nav ref="nav" class="pause-nav">
<button class="pause-item primary" @click="resume"><Icon name="lucide:play" class="size-4" /> Resume <kbd>Esc</kbd></button>
<button class="pause-item" :disabled="saving" @click="save"><Icon name="lucide:save" class="size-4" /> {{ saving ? 'Saving…' : 'Save' }}</button>
<button class="pause-item" title="Keep going in a copy; this one stays as it is" @click="saveCopy"><Icon name="lucide:copy" class="size-4" /> Save as copy</button>
<button class="pause-item" @click="ed.paused.value = 'load'"><Icon name="lucide:folder-open" class="size-4" /> Load</button>
<button class="pause-item" @click="ed.dialog.value = 'settings'"><Icon name="lucide:settings" class="size-4" /> Settings</button>
<button class="pause-item" @click="ed.showHelp.value = true"><Icon name="lucide:circle-help" class="size-4" /> How to play</button>
<button class="pause-item" @click="ed.showMenu()"><Icon name="lucide:house" class="size-4" /> Main menu</button>
</nav>
</template>
<template v-else>
<header class="pause-head">
<button class="tb-btn" title="Back (Esc)" @click="ed.paused.value = 'main'"><Icon name="lucide:arrow-left" class="size-4" /></button>
<h2>Load</h2>
</header>
<EditorProjectList @done="resume" />
</template>
</div>
</div>
</template>

View File

@ -55,7 +55,7 @@ function onFile(e: Event) {
<a v-else href="#" @click.prevent="ed.dialog.value = 'account'">Sign in to have them on every computer.</a>
</p>
<p v-if="!list.length" class="hint mt-3">No projects yet. Start one below.</p>
<p v-if="!list.length" class="hint mt-3">Nothing saved yet. What you build is saved as soon as you change something; or start something new below.</p>
<ul class="project-list">
<li v-for="m in list" :key="m.id" :class="{ current: m.id === ed.meta.value.id }">
<input
@ -70,6 +70,7 @@ function onFile(e: Event) {
<span class="name">
{{ m.name }}
<span v-if="m.id === ed.meta.value.id" class="badge">open</span>
<span v-if="!freeOnly && ed.projectMode(m)" class="badge mode">{{ ed.projectMode(m) === 'campaign' ? 'Campaign' : 'Challenges' }}</span>
</span>
<span class="meta">
{{ when(m.updated) }}

View File

@ -1,16 +0,0 @@
<script setup lang="ts">
const ed = useEditor()
const close = () => (ed.dialog.value = null)
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div class="modal" role="dialog" aria-labelledby="projects-title">
<div class="flex items-start justify-between gap-4">
<h2 id="projects-title">Projects</h2>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<EditorProjectList @done="close" />
</div>
</div>
</template>

View File

@ -63,7 +63,7 @@ function selectAll(e: Event) {
<button class="btn" title="Adds the components from a project file to this project" @click="fileInput?.click()">
<Icon name="lucide:upload" class="size-4" /> Add components from file
</button>
<button class="btn btn-ghost" @click="ed.dialog.value = 'projects'"><Icon name="lucide:folder-open" class="size-4" /> Open file as project</button>
<button class="btn btn-ghost" @click="ed.dialog.value = null; ed.pause('load')"><Icon name="lucide:folder-open" class="size-4" /> Open file as project</button>
<input ref="fileInput" type="file" accept="application/json,.json" class="hidden" @change="onFile" />
</div>
</div>

View File

@ -43,10 +43,9 @@ const linkIcon = computed(() => {
</svg>
<span class="hidden xl:inline">Menu</span>
</button>
<button class="tb-btn project-btn" title="Your projects" @click="ed.dialog.value = 'projects'">
<Icon name="lucide:folder" class="size-4 shrink-0" />
<button class="tb-btn project-btn" title="Menu: save, load, settings (Esc)" @click="ed.pause()">
<Icon name="lucide:menu" class="size-4 shrink-0" />
<span class="truncate">{{ ed.project.value.name }}</span>
<Icon name="lucide:chevron-down" class="size-3.5 shrink-0 text-(--muted)" />
</button>
<span class="text-(--border)">/</span>
<button v-if="backName" class="tb-btn" :title="`Back to ${backName}`" @click="ed.back()">

View File

@ -1,7 +1,7 @@
<script setup lang="ts">
const ed = useEditor()
const close = () => {
ed.dialog.value = 'projects'
ed.dialog.value = null
ed.versionsFor.value = null
}

View File

@ -83,7 +83,7 @@ export interface PuzzleSummary {
top?: { name: string; t: number; d: number | null; you?: true }[]
}
export type MenuPage = 'main' | 'free' | 'campaign' | 'challenges' | 'leaderboard'
export type MenuPage = 'main' | 'load' | 'free' | 'campaign' | 'challenges' | 'leaderboard'
export interface ChallengeCheck extends TestResult {
transistors: number
@ -136,10 +136,10 @@ function create() {
}
const project = createProject({ examples: true })
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/')
if (!placeholder) saveProject(meta, project)
// The starter project of a first visit is saved only once something
// changes in it. Signed in on a new device, the account's saves load
// instead, so an untouched starter never becomes a second copy.
placeholder = true
return { meta, project }
}
@ -163,7 +163,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' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
const dialog = ref<null | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
/** The component whose box is being drawn in the face designer. */
const faceFor = ref<string | null>(null)
function designFace(defId: string) {
@ -208,6 +208,8 @@ function create() {
function persistNow() {
clearTimeout(saveTimer)
saveTimer = undefined
// An untouched starter project is not saved (see initial()).
if (placeholder) return
meta.value = {
...meta.value,
name: project.value.name,
@ -816,10 +818,31 @@ function create() {
function showMenu(page: MenuPage = 'main') {
persistNow()
dialog.value = null
paused.value = null
menuPage.value = page
screen.value = 'menu'
}
// ── Pause menu ────────────────────────────────────────────────────
/** The in-game menu over the editor (Esc): its main list, or the saves to load. */
const paused = ref<null | 'main' | 'load'>(null)
function pause(page: 'main' | 'load' = 'main') {
placing.value = null
linking.value = null
paused.value = page
}
/** Saves now: in this browser, and in the account when signed in. */
async function saveNow() {
placeholder = false
changed = true
persistNow()
if (!account.value) return notify('Saved in this browser')
await syncAccount()
notify(cloudState.value === 'synced' ? 'Saved to your account' : 'Saved in this browser; the account will follow when it can be reached', cloudState.value === 'synced' ? 'ok' : 'error')
}
/** A project's mode, from its index entry, or (for projects saved before it was noted there) from the project. */
const modes = new Map<string, Project['mode'] | null>()
function projectMode(m: ProjectMeta): Project['mode'] | undefined {
@ -1533,6 +1556,7 @@ function create() {
// ── Projects ──────────────────────────────────────────────────────
function activate(m: ProjectMeta, p: Project) {
placeholder = false
meta.value = m
project.value = p
setCurrentId(m.id)
@ -1787,6 +1811,8 @@ function create() {
// it started from; when another device saved in between, both versions are
// kept (the other one as a copy) instead of one silently replacing the other.
const account = ref<AccountUser | null>(cachedAccount())
/** False while a signed-in browser is still loading the account's saves at startup: the menu waits, so nothing is started twice. */
const savesReady = ref(!account.value)
const cloudState = ref<'off' | 'syncing' | 'synced' | 'offline' | 'error'>(account.value ? 'syncing' : 'off')
const cloudError = ref('')
@ -1836,24 +1862,40 @@ function create() {
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}`)
/** Replaces this browser's copy of a project with the account's current one. */
async function takeRemote(m: ProjectMeta, uid: string, remote: CloudMeta) {
const res = await authCall<{ project?: Project; status: number }>('GET', `/api/me/projects/${m.id}`)
if (!res.project) return
const p = toProject(res.project)
p.name = `${p.name} (other device)`
saveProject({ id: newLocalId(), name: p.name, updated: Date.now() }, p)
const next: ProjectMeta = { ...m, name: p.name, updated: remote.updated, cloud: { owner: uid, rev: remote.rev } }
delete next.dirty
delete next.snapshot
saveProject(next, p)
if (m.id === meta.value.id) activate(next, p)
}
/**
* One save per project on every device. When another device saved the same
* project in between, the newer save wins everywhere, and the other one is
* kept as a savegame of that project (Load → savegames), never as a copy.
*/
async function upload(m: ProjectMeta, uid: string) {
const p = localProject(m)
if (!p) return
const body = { project: p, baseRev: m.cloud?.owner === uid ? m.cloud.rev : 0, link: m.link, snapshot: m.snapshot === true }
const baseRev = m.cloud?.owner === uid ? m.cloud.rev : 0
const body = { project: p, baseRev, link: m.link, snapshot: m.snapshot === true }
let res = await authCall<{ meta?: CloudMeta; conflict?: boolean; status: number }>('PUT', `/api/me/projects/${m.id}`, body)
if (res.conflict) {
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.conflict && res.meta) {
if (res.meta.updated > m.updated) {
// The other device's save is newer: this one becomes a savegame.
await authCall('POST', `/api/me/projects/${m.id}/versions`, { project: p, baseRev })
await takeRemote(m, uid, res.meta)
notify(`"${m.name}" was changed later on another device and is loaded now. Your version here is in its savegames.`)
return
}
// This save is newer: it wins, and the server keeps the other one as a savegame.
res = await authCall('PUT', `/api/me/projects/${m.id}`, { ...body, force: true, snapshot: true })
notify(`"${m.name}" was also changed on another device. Yours is newer and saved; the other one is in its savegames.`)
}
if (res.meta) updateMeta(m.id, { cloud: { owner: uid, rev: res.meta.rev }, dirty: false, snapshot: undefined })
}
@ -2058,6 +2100,8 @@ function create() {
if (res.user) await syncAccount()
} catch {
if (account.value) cloudState.value = 'offline'
} finally {
savesReady.value = true
}
let lastFocusSync = Date.now()
const onFocus = () => {
@ -2204,6 +2248,10 @@ function create() {
useSignal,
selectSignal,
canPlaceKind,
paused,
pause,
saveNow,
savesReady,
setInputs,
sound,
setSound,

View File

@ -0,0 +1,32 @@
import { toProject } from '../../../../../app/lib/logic/project'
// Keep a device's own version of a project as a savegame, without making it
// the current one. Used when another device saved something newer: the newer
// save wins, and this one stays restorable from the project's savegames.
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 }
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 })
}
return withLock(user.id, async () => {
const index = await readIndex(user.id)
if (!index.projects.some(p => p.id === id)) throw createError({ statusCode: 404, message: 'Project not found' })
const rev = typeof body.baseRev === 'number' && Number.isInteger(body.baseRev) ? body.baseRev : 0
await keepVersion(user.id, id, { project, rev, at: Date.now(), name: project.name }, true)
setResponseStatus(event, 201)
return { kept: true }
})
})