Merge branch 'feat/library'
# Conflicts: # README.md # app/composables/useEditor.ts # app/lib/logic/project.ts
This commit is contained in:
commit
bacc6af17e
|
|
@ -12,6 +12,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
||||||
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
|
- Gates with more inputs: a placed AND, OR, XOR, NAND or NOR (built in, from the examples, or your own) has an "Inputs" setting from 2 to 16. The wide version is a component built as a balanced tree of the two-input gate (NAND and NOR as the plain gate plus a final inverted one), made once per gate and width in "Wide gates" and reused; transistors count honestly and changes to the two-input gate carry through. Which gates qualify is read off their truth table ([app/lib/logic/wide.ts](app/lib/logic/wide.ts)).
|
||||||
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
|
- Campaign (Projects → New campaign): you start with NAND, inputs, outputs, lamps and notes, and no examples. Each challenge opens once the ones it builds on are solved (NOT → AND, OR, SR Latch → …), and your own solution becomes a part you can place. Other basic parts unlock on the way: constants with NOT, the input panel with AND, hex display and pixel with the decoder, cables with Adder 2, the button with the SR latch, the clock with the D latch. Rules in [app/lib/logic/progress.ts](app/lib/logic/progress.ts). Sandbox projects keep everything open.
|
||||||
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
|
- Puzzles: "Publish as puzzle" (This circuit) turns a circuit into a link `/puzzle/<id>`. Only its behaviour is published, as a truth table, or for circuits with memory as a run of input changes from power-on; the circuit stays private. Whoever opens the link gets the puzzle in their project, sees the target and the author's transistor count, and after a pass their solution goes to the server, which re-runs the checks and counts the transistors itself (with a fixed work budget) and keeps each player's best. The board shows everyone's transistor counts and your place. The puzzle of the week is generated from the ISO week, the same for everyone: three or four inputs, one or two outputs, each depending on every input. Players are anonymous ids per browser.
|
||||||
|
- Library: everyone's published components in one public list (bottom bar → Components → Library, Space, or the main menu), searchable by name, description and author, each with its transistors, pins and what it uses. "Publish to the library…" in the menu on a circuit's name sends it with every component it uses and their connector types, under your leaderboard name; the server checks it like any project and counts transistors and pins itself. Publishing the same component again from the same browser and project makes the next version of the same entry; only that browser has the entry's edit key, so only it can update or remove it. "Add" brings an entry into the open project and starts placing it: what the project has in exactly that form already is used as it is, the rest comes with new ids (a name that is taken gets a number) and connector types join one with the same lines. The This panel says where a component came from and offers a newer version, which replaces it in place; what came along with the old version goes once nothing else uses it. Another entry's component is never reused, so updating one entry leaves the others as they were. Challenges and puzzles, and components with a solution anywhere inside, are never published. A campaign takes nothing from the library: it is built from your own work. Logic in [app/lib/logic/library.ts](app/lib/logic/library.ts).
|
||||||
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
|
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
|
||||||
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
|
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
|
||||||
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
|
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
|
||||||
|
|
@ -55,6 +56,7 @@ All in [app/lib/logic/](app/lib/logic/), plain TypeScript with no Vue dependency
|
||||||
- `examples.ts` builds the example library with a small builder; `ops.ts` holds project edits (package selection, copy/paste, prune dangling wires, recursion check).
|
- `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, and the tidy layout), and after a move keeps the hand-placed bends that still leave a clear way (`settleCorners`).
|
- `routing.ts` lays out all wires of a circuit (free lanes, detours, separation, crossings, and the tidy layout), and after a move keeps the hand-placed bends that still leave a clear way (`settleCorners`).
|
||||||
- `move.ts` moves parts for a drag and the arrow keys, always from where they started, with their wires.
|
- `move.ts` moves parts for a drag and the arrow keys, always from where they started, with their wires.
|
||||||
|
- `library.ts` gathers a component with everything it uses for the public library, checks what comes from outside and adds entries to a project (shared with the server, [server/api/library/](server/api/library/)).
|
||||||
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
|
- `progress.ts` holds the campaign rules; `puzzles.ts` makes, checks and scores puzzles and generates the weekly one (shared with the server, [server/api/puzzles/](server/api/puzzles/), storage in `data/puzzles`).
|
||||||
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
|
- `cables.ts` bundles wires into cables (ends where you click, or next to sources and targets), takes them apart again, and lays out the ribbon lines (`offsetPath`, `ribbon`).
|
||||||
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
- `panels.ts` docks input panels to components and keeps them in step; `labels.ts` does series names and names taken from pins.
|
||||||
|
|
@ -66,6 +68,10 @@ 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.
|
[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.
|
||||||
|
|
||||||
|
## Library
|
||||||
|
|
||||||
|
[server/api/library/](server/api/library/): `POST /api/library` publishes `{ player, root, components, connectors }` and returns `{ id, key, version }`; `PUT /api/library/:id` with header `x-edit-key` publishes the next version; `DELETE /api/library/:id` with the key takes it out. `GET /api/library?q=` lists every entry, newest first, narrowed to those with every word in name, description, group or author; `GET /api/library/:id` returns one with its components (`?meta`: without). Each entry is one JSON file in `data/library/entries/`, plus `data/library/index` for the list (both in the daily backup). Only a SHA-256 of the key is stored; authors show by their leaderboard name, never by their player id. Challenge and library marks are dropped from what comes in, and the list keeps only short texts, pin counts and the first 16 pin names a side, so it stays small. Limits: 1 MB per entry, 30 publishes per IP per 10 minutes, 20,000 entries.
|
||||||
|
|
||||||
## Accounts
|
## 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: `data/users`, `data/sessions`, `data/accounts/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<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 plus 500 KB for what its circuits hold, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
|
[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: `data/users`, `data/sessions`, `data/accounts/<uid>/` with an index (revision per project, deletions for a year), one file per project, and savegames in `h/<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 plus 500 KB for what its circuits hold, login 20 tries per 10 minutes per IP, 10 new accounts per hour per IP.
|
||||||
|
|
|
||||||
|
|
@ -3362,6 +3362,114 @@ kbd {
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Library: components everyone published ─────────────────────── */
|
||||||
|
.modal.library-modal {
|
||||||
|
width: min(720px, 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.library-modal .search.part-search {
|
||||||
|
margin: 12px 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-entry {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 56px minmax(0, 1fr) auto;
|
||||||
|
gap: 12px;
|
||||||
|
align-items: start;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--panel-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-thumb {
|
||||||
|
width: 56px;
|
||||||
|
height: 56px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-thumb rect {
|
||||||
|
fill: var(--chip);
|
||||||
|
stroke: var(--chip-stroke);
|
||||||
|
stroke-width: 0.12;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-thumb line {
|
||||||
|
stroke: var(--chip-stroke);
|
||||||
|
stroke-width: 0.12;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
min-width: 0;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-by,
|
||||||
|
.lib-stats {
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-desc {
|
||||||
|
display: -webkit-box;
|
||||||
|
margin-top: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.45;
|
||||||
|
color: #c3ccd6;
|
||||||
|
-webkit-line-clamp: 2;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-stats {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 4px 12px;
|
||||||
|
margin-top: 6px;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 560px) {
|
||||||
|
.lib-entry {
|
||||||
|
grid-template-columns: 40px minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-thumb {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.lib-actions {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
flex-direction: row;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A component from the library, in the This panel. */
|
||||||
|
.lib-origin {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
margin: -6px 0 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Face designer ──────────────────────────────────────────────── */
|
/* ── Face designer ──────────────────────────────────────────────── */
|
||||||
.modal.face-modal {
|
.modal.face-modal {
|
||||||
width: min(900px, 100%);
|
width: min(900px, 100%);
|
||||||
|
|
|
||||||
|
|
@ -81,5 +81,7 @@ watch(
|
||||||
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
|
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
|
||||||
<EditorSearchDialog v-if="ed.dialog.value === 'search'" />
|
<EditorSearchDialog v-if="ed.dialog.value === 'search'" />
|
||||||
<EditorFaceDialog v-if="ed.dialog.value === 'face'" />
|
<EditorFaceDialog v-if="ed.dialog.value === 'face'" />
|
||||||
|
<EditorLibraryDialog v-if="ed.dialog.value === 'library'" />
|
||||||
|
<EditorLibraryPublishDialog v-if="ed.dialog.value === 'library-publish'" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
|
||||||
|
|
@ -320,6 +320,7 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))
|
||||||
<div class="flex gap-1">
|
<div class="flex gap-1">
|
||||||
<button class="flyout-new grow" @click="ed.createComponent(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New component</button>
|
<button class="flyout-new grow" @click="ed.createComponent(), (open = null)"><Icon name="lucide:plus" class="size-4" /> New component</button>
|
||||||
<button class="flyout-new" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(), (open = null)"><Icon name="lucide:book-open" class="size-4" /> Examples</button>
|
<button class="flyout-new" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples(), (open = null)"><Icon name="lucide:book-open" class="size-4" /> Examples</button>
|
||||||
|
<button class="flyout-new" title="Components everyone published: find one and add it here" @click="(ed.dialog.value = 'library'), (open = null)"><Icon name="lucide:library-big" class="size-4" /> Library</button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,13 @@
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// "This": what the circuit you are in is. Its name and health on top, four
|
// "This": what the circuit you are in is. Its name, where it came from (the
|
||||||
// numbers (the transistors open their breakdown), its truth table and how it
|
// library, with a newer version to get) and health on top, four numbers
|
||||||
|
// (the transistors open their breakdown), its truth table and how it
|
||||||
// looks as a part. Things to do with it are in the menu on its name in the
|
// looks as a part. Things to do with it are in the menu on its name in the
|
||||||
// top bar; unused components are with the components in the parts bar.
|
// top bar; unused components are with the components in the parts bar.
|
||||||
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
|
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
|
||||||
import { transistorBreakdown } from '~/lib/logic/bulk'
|
import { transistorBreakdown } from '~/lib/logic/bulk'
|
||||||
import { chipPins } from '~/lib/logic/geometry'
|
import { chipPins } from '~/lib/logic/geometry'
|
||||||
|
import { importProblem } from '~/lib/logic/library'
|
||||||
import { usages } from '~/lib/logic/ops'
|
import { usages } from '~/lib/logic/ops'
|
||||||
import type { SymbolKind } from '~/lib/logic/types'
|
import type { SymbolKind } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
|
@ -42,6 +44,27 @@ const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.
|
||||||
const total = computed(() => ed.transistors(def.value.id))
|
const total = computed(() => ed.transistors(def.value.id))
|
||||||
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
|
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
|
||||||
|
|
||||||
|
// ── From the library ────────────────────────────────────────────────
|
||||||
|
/** Where it came from, when it is in the library. */
|
||||||
|
const origin = computed(() => {
|
||||||
|
const f = def.value.from
|
||||||
|
if (ed.ownEntry(def.value)) return f ? `In the library as version ${f.version}, published from here` : 'In the library, published from here'
|
||||||
|
if (!f) return ''
|
||||||
|
return f.inside ? `Came along with a component from the library by ${f.author || 'Anonymous'}` : `From the library by ${f.author || 'Anonymous'}, version ${f.version}`
|
||||||
|
})
|
||||||
|
/** A newer version of it in the library, to update to (not in a campaign, which takes nothing from the library). */
|
||||||
|
const newer = ref<number | null>(null)
|
||||||
|
watch(
|
||||||
|
() => [def.value.id, def.value.from] as const,
|
||||||
|
async ([id, f]) => {
|
||||||
|
newer.value = null
|
||||||
|
if (!f || f.inside || ed.ownEntry(def.value) || importProblem(ed.project.value)) return
|
||||||
|
const v = await ed.libraryVersion(f.id)
|
||||||
|
if (def.value.id === id && v !== null && v > f.version) newer.value = v
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
)
|
||||||
|
|
||||||
function toggleFace(e: Event) {
|
function toggleFace(e: Event) {
|
||||||
def.value.face = (e.target as HTMLInputElement).checked
|
def.value.face = (e.target as HTMLInputElement).checked
|
||||||
ed.commit(false)
|
ed.commit(false)
|
||||||
|
|
@ -78,6 +101,13 @@ const showCost = ref(false)
|
||||||
</template>
|
</template>
|
||||||
<template v-else>{{ def.id === ed.mainId.value ? 'The main circuit' : 'Not used in another circuit' }}</template>
|
<template v-else>{{ def.id === ed.mainId.value ? 'The main circuit' : 'Not used in another circuit' }}</template>
|
||||||
</p>
|
</p>
|
||||||
|
<p v-if="origin" class="lib-origin">
|
||||||
|
<Icon name="lucide:library-big" class="size-3.5 shrink-0" />
|
||||||
|
<span class="grow">{{ origin }}</span>
|
||||||
|
<button v-if="newer" class="btn-sm" title="Replace it here with the newer version, wherever it is used (Ctrl+Z goes back)" @click="ed.updateFromLibrary(def.id)">
|
||||||
|
Get version {{ newer }}
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
|
||||||
<div class="health" :class="worst">
|
<div class="health" :class="worst">
|
||||||
<Icon :name="worst === 'ok' ? 'lucide:circle-check' : LEVEL_ICON[worst]" class="size-4 shrink-0" />
|
<Icon :name="worst === 'ok' ? 'lucide:circle-check' : LEVEL_ICON[worst]" class="size-4 shrink-0" />
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ const SHORTCUTS: [string, string][] = [
|
||||||
['Main (top bar)', 'Back to the main circuit; the names after it lead back to each component you entered'],
|
['Main (top bar)', 'Back to the main circuit; the names after it lead back to each component you entered'],
|
||||||
['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'],
|
['Power off and on (circuit name in the top bar, or Space)', 'Latches, flip-flops and memory keep their bits when you go into a component and back, and in the saved project; this starts the circuit again from all zeros'],
|
||||||
['[', 'Hide or show the panel on the left (This and Pins)'],
|
['[', 'Hide or show the panel on the left (This and Pins)'],
|
||||||
|
['Library (bottom bar: Components, or Space)', 'Components everyone published: search, add one to this project (what it uses comes along; not in a campaign) and place it. Publish your own, or a new version, from the menu on the circuit’s name'],
|
||||||
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
|
['Connectors (bottom bar)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
|
||||||
['Split into lines (right-click a component)', 'A pin per line below a port\'s socket, to wire lines by hand; dropping a wire on the socket does the same. Join lines takes them away'],
|
['Split into lines (right-click a component)', 'A pin per line below a port\'s socket, to wire lines by hand; dropping a wire on the socket does the same. Join lines takes them away'],
|
||||||
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
|
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,170 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
// The public library: components everyone published, newest first. Type to
|
||||||
|
// search names, descriptions and authors. "Add" brings one into the open
|
||||||
|
// project with everything it uses and starts placing it; entries published
|
||||||
|
// from this browser can be taken out again. A campaign can look, not add.
|
||||||
|
import { shortCount } from '~/lib/logic/analyze'
|
||||||
|
import { importProblem, type LibraryMeta } from '~/lib/logic/library'
|
||||||
|
|
||||||
|
const ed = useEditor()
|
||||||
|
const { place } = usePlace()
|
||||||
|
const close = () => (ed.dialog.value = null)
|
||||||
|
|
||||||
|
const query = ref('')
|
||||||
|
const entries = ref<LibraryMeta[] | null>(null)
|
||||||
|
const total = ref(0)
|
||||||
|
const error = ref('')
|
||||||
|
const busy = ref('')
|
||||||
|
const confirmRemove = ref('')
|
||||||
|
const input = ref<HTMLInputElement>()
|
||||||
|
|
||||||
|
// Only the answer to the latest search counts.
|
||||||
|
let asked = 0
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
async function load() {
|
||||||
|
const n = ++asked
|
||||||
|
try {
|
||||||
|
const res = await ed.listLibrary(query.value)
|
||||||
|
if (n !== asked) return
|
||||||
|
entries.value = res.entries
|
||||||
|
total.value = res.total
|
||||||
|
error.value = ''
|
||||||
|
} catch (e) {
|
||||||
|
if (n === asked) error.value = `Could not load the library: ${(e as Error).message}`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
watch(query, () => {
|
||||||
|
clearTimeout(timer)
|
||||||
|
timer = setTimeout(load, 250)
|
||||||
|
})
|
||||||
|
onMounted(() => {
|
||||||
|
void load()
|
||||||
|
input.value?.focus()
|
||||||
|
})
|
||||||
|
onBeforeUnmount(() => clearTimeout(timer))
|
||||||
|
|
||||||
|
const date = (t: number) => new Date(t).toLocaleDateString()
|
||||||
|
|
||||||
|
/** A box with a stub per pin (16 a side at most), inputs left and outputs right. */
|
||||||
|
function thumb(m: LibraryMeta) {
|
||||||
|
const ins = Math.min(m.inputs, 16)
|
||||||
|
const outs = Math.min(m.outputs, 16)
|
||||||
|
const rows = Math.max(1, ins, outs)
|
||||||
|
const at = (n: number) => Array.from({ length: n }, (_, i) => 1 + i + (rows - n) / 2)
|
||||||
|
return { box: `0 0 8 ${rows + 1}`, h: rows, ins: at(ins), outs: at(outs) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pin names for a tooltip, with a mark when there are more than the listing keeps. */
|
||||||
|
const pinList = (names: string[], n: number) => names.join(', ') + (n > names.length ? ', …' : '')
|
||||||
|
|
||||||
|
/** The entries with their pictures, and whether they are yours. */
|
||||||
|
const shown = computed(() => (entries.value ?? []).map(m => ({ m, t: thumb(m), mine: m.id in ed.libKeys.value })))
|
||||||
|
|
||||||
|
/** Why nothing can be added to this project (a campaign); null when it can. */
|
||||||
|
const blocked = computed(() => importProblem(ed.project.value))
|
||||||
|
|
||||||
|
async function add(m: LibraryMeta) {
|
||||||
|
busy.value = m.id
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const root = await ed.addFromLibrary(m.id)
|
||||||
|
close()
|
||||||
|
if (ed.screen.value === 'menu') ed.enterGame()
|
||||||
|
place('chip', root)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message
|
||||||
|
} finally {
|
||||||
|
busy.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove(m: LibraryMeta) {
|
||||||
|
if (confirmRemove.value !== m.id) return (confirmRemove.value = m.id)
|
||||||
|
confirmRemove.value = ''
|
||||||
|
busy.value = m.id
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
await ed.removeFromLibrary(m.id)
|
||||||
|
entries.value = entries.value?.filter(e => e.id !== m.id) ?? null
|
||||||
|
total.value--
|
||||||
|
ed.notify(`"${m.name}" is out of the library. Projects that added it keep their copy.`)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message
|
||||||
|
} finally {
|
||||||
|
busy.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKey(e: KeyboardEvent) {
|
||||||
|
if (e.key !== 'Escape') return
|
||||||
|
e.stopPropagation()
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="modal-backdrop" @click.self="close">
|
||||||
|
<div class="modal library-modal" role="dialog" aria-labelledby="library-title" @keydown="onKey">
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<h2 id="library-title">Library</h2>
|
||||||
|
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||||
|
</div>
|
||||||
|
<p class="hint mt-1">
|
||||||
|
Components everyone published. Add one to "{{ ed.project.value.name }}": it comes with every component it uses, ready to place. To publish your own,
|
||||||
|
open it and use the menu on its name.
|
||||||
|
</p>
|
||||||
|
<div class="search part-search mt-3">
|
||||||
|
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
|
||||||
|
<input ref="input" v-model="query" placeholder="Search by name, description or author…" />
|
||||||
|
</div>
|
||||||
|
<p v-if="blocked" class="hint mt-2">{{ blocked }}.</p>
|
||||||
|
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
|
||||||
|
|
||||||
|
<p v-if="entries === null" class="hint mt-3">{{ error ? '' : 'Loading…' }}</p>
|
||||||
|
<p v-else-if="!entries.length" class="hint mt-3">
|
||||||
|
{{ query.trim() ? `Nothing called "${query.trim()}" yet.` : 'Nothing published yet. Be the first: open a component and publish it from the menu on its name.' }}
|
||||||
|
</p>
|
||||||
|
<ul v-else class="lib-list">
|
||||||
|
<li v-for="{ m, t, mine } in shown" :key="m.id" class="lib-entry">
|
||||||
|
<svg class="lib-thumb" :viewBox="t.box" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
|
||||||
|
<line v-for="(y, i) in t.ins" :key="`i${i}`" x1="0.6" :y1="y" x2="2" :y2="y" />
|
||||||
|
<line v-for="(y, i) in t.outs" :key="`o${i}`" x1="6" :y1="y" x2="7.4" :y2="y" />
|
||||||
|
<rect x="2" y="0.5" width="4" :height="t.h" rx="0.4" />
|
||||||
|
</svg>
|
||||||
|
<div class="lib-main">
|
||||||
|
<div class="lib-title">
|
||||||
|
<span class="truncate">{{ m.name }}</span>
|
||||||
|
<span v-if="mine" class="you-tag">yours</span>
|
||||||
|
</div>
|
||||||
|
<div class="lib-by">by {{ m.author || 'Anonymous' }} · version {{ m.version }} · {{ date(m.updated) }}</div>
|
||||||
|
<p v-if="m.description" class="lib-desc">{{ m.description }}</p>
|
||||||
|
<div class="lib-stats">
|
||||||
|
<span title="Transistors at every depth, 4 per NAND">{{ shortCount(m.transistors) }} transistors</span>
|
||||||
|
<span :title="pinList(m.inNames, m.inputs)">{{ m.inputs }} in</span>
|
||||||
|
<span :title="pinList(m.outNames, m.outputs)">{{ m.outputs }} out</span>
|
||||||
|
<span v-if="m.uses" title="Components it uses; they come along">{{ m.uses }} inside</span>
|
||||||
|
<span v-if="m.connectors">{{ m.connectors }} connector {{ m.connectors === 1 ? 'type' : 'types' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="lib-actions">
|
||||||
|
<button class="btn btn-primary" :disabled="!!busy || !!blocked" :title="blocked ?? 'Add it to this project and place it'" @click="add(m)">
|
||||||
|
<Icon name="lucide:plus" class="size-4" /> {{ busy === m.id ? 'Adding…' : 'Add' }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="mine"
|
||||||
|
class="btn-sm"
|
||||||
|
:class="{ danger: confirmRemove === m.id }"
|
||||||
|
:disabled="!!busy"
|
||||||
|
:title="confirmRemove === m.id ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
|
||||||
|
@click="remove(m)"
|
||||||
|
@pointerleave="confirmRemove === m.id && (confirmRemove = '')"
|
||||||
|
>
|
||||||
|
{{ confirmRemove === m.id ? 'Remove?' : 'Remove' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-if="entries && !query.trim() && total > entries.length" class="hint mt-2">The newest {{ entries.length }} of {{ total }}. Search to find the others.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
@ -0,0 +1,137 @@
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Publishing the open circuit to the library: its name and description as
|
||||||
|
// everyone will see them, your name, and what goes along with it. Published
|
||||||
|
// from this browser before, it goes up as a new version of the same entry.
|
||||||
|
import { shortCount } from '~/lib/logic/analyze'
|
||||||
|
import { chipPins } from '~/lib/logic/geometry'
|
||||||
|
import { LIBRARY_LIMITS, libraryBundle } from '~/lib/logic/library'
|
||||||
|
import type { LibraryOrigin } from '~/lib/logic/types'
|
||||||
|
|
||||||
|
const ed = useEditor()
|
||||||
|
const close = () => (ed.dialog.value = null)
|
||||||
|
|
||||||
|
const def = ed.def
|
||||||
|
/** The entry this is a new version of, when this browser published it before. */
|
||||||
|
const own = ed.ownEntry(def.value)
|
||||||
|
const name = ref(def.value.name)
|
||||||
|
const description = ref(def.value.description ?? '')
|
||||||
|
const author = ref(ed.playerName.value)
|
||||||
|
const busy = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
const done = ref<LibraryOrigin | null>(null)
|
||||||
|
const confirmRemove = ref(false)
|
||||||
|
|
||||||
|
const pins = computed(() => chipPins(def.value))
|
||||||
|
|
||||||
|
/** A list of names, the first few spelled out. */
|
||||||
|
const names = (list: string[]) => (list.length > 6 ? `${list.slice(0, 6).join(', ')} and ${list.length - 6} more` : list.join(', '))
|
||||||
|
|
||||||
|
/** What goes along with it, in words, and whether it all fits. */
|
||||||
|
const along = computed(() => {
|
||||||
|
const b = libraryBundle(ed.project.value, def.value.id)
|
||||||
|
const uses = b.components.filter(d => d.id !== b.root).map(d => d.name)
|
||||||
|
const types = (b.connectors ?? []).map(c => c.name)
|
||||||
|
const parts = [
|
||||||
|
uses.length ? `the ${uses.length === 1 ? 'component' : `${uses.length} components`} it uses (${names(uses)})` : '',
|
||||||
|
types.length ? `${types.length === 1 ? 'the connector type' : 'the connector types'} ${names(types)}` : '',
|
||||||
|
].filter(Boolean)
|
||||||
|
const text = parts.length ? `Goes along: ${parts.join(' and ')}.` : 'It uses no other components.'
|
||||||
|
return { text, tooLarge: JSON.stringify(b).length > LIBRARY_LIMITS.bytes }
|
||||||
|
})
|
||||||
|
const problem = computed(() => ed.libraryProblem.value ?? (along.value.tooLarge ? 'Too large for the library (1 MB at most)' : null))
|
||||||
|
|
||||||
|
async function publish() {
|
||||||
|
busy.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
done.value = await ed.publishToLibrary(name.value, description.value, author.value)
|
||||||
|
ed.play('unlock')
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remove() {
|
||||||
|
if (!confirmRemove.value) return (confirmRemove.value = true)
|
||||||
|
busy.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
await ed.removeFromLibrary(own!)
|
||||||
|
ed.notify(`"${def.value.name}" is out of the library. Projects that added it keep their copy.`)
|
||||||
|
close()
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message
|
||||||
|
} finally {
|
||||||
|
busy.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKey(e: KeyboardEvent) {
|
||||||
|
if (e.key !== 'Escape') return
|
||||||
|
e.stopPropagation()
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="modal-backdrop" @click.self="close">
|
||||||
|
<div class="modal" role="dialog" aria-labelledby="lib-publish-title" @keydown="onKey">
|
||||||
|
<div class="flex items-start justify-between gap-4">
|
||||||
|
<h2 id="lib-publish-title">{{ own ? 'Update in the library' : 'Publish to the library' }}</h2>
|
||||||
|
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="!done">
|
||||||
|
<p class="hint mt-1">
|
||||||
|
<template v-if="own">It goes up as the next version of your entry; projects that added it before are offered the update.</template>
|
||||||
|
<template v-else>Everyone can find it in the library and add it to their projects, together with everything it uses.</template>
|
||||||
|
Only this browser can update or remove it later.
|
||||||
|
</p>
|
||||||
|
<label class="field mt-4">
|
||||||
|
<span>Name</span>
|
||||||
|
<input v-model="name" :maxlength="LIBRARY_LIMITS.name" />
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Description</span>
|
||||||
|
<textarea v-model="description" rows="3" :maxlength="LIBRARY_LIMITS.description" placeholder="What does it do, how do you use it?" />
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Your name, also on the leaderboards</span>
|
||||||
|
<input v-model="author" maxlength="24" placeholder="Anonymous" autocomplete="nickname" />
|
||||||
|
</label>
|
||||||
|
<p class="hint">{{ pins.inputs.length }} in, {{ pins.outputs.length }} out, {{ shortCount(ed.transistors(def.id)) }} transistors. {{ along.text }}</p>
|
||||||
|
<p v-if="problem" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ problem }}</p>
|
||||||
|
<p v-if="error" class="result fail"><Icon name="lucide:circle-x" class="size-4 shrink-0" /> {{ error }}</p>
|
||||||
|
<div class="mt-3 flex flex-wrap items-center gap-2">
|
||||||
|
<button class="btn btn-primary" :disabled="!!problem || busy || !name.trim()" @click="publish">
|
||||||
|
<Icon name="lucide:book-up" class="size-4" /> {{ busy ? 'Publishing…' : own ? 'Publish new version' : 'Publish' }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="own"
|
||||||
|
class="btn-sm ml-auto"
|
||||||
|
:class="{ danger: confirmRemove }"
|
||||||
|
:disabled="busy"
|
||||||
|
:title="confirmRemove ? 'Click again to take it out of the library' : 'Take it out of the library; copies others added stay theirs'"
|
||||||
|
@click="remove"
|
||||||
|
@pointerleave="confirmRemove = false"
|
||||||
|
>
|
||||||
|
{{ confirmRemove ? 'Remove from the library?' : 'Remove from the library' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<p class="result pass">
|
||||||
|
<Icon name="lucide:circle-check" class="size-4 shrink-0" />
|
||||||
|
<span>"{{ def.name }}" is in the library as version {{ done.version }}. Everyone can find it and add it to their projects.</span>
|
||||||
|
</p>
|
||||||
|
<div class="mt-3 flex gap-2">
|
||||||
|
<button class="btn btn-primary" @click="ed.dialog.value = 'library'"><Icon name="lucide:library-big" class="size-4" /> Open the library</button>
|
||||||
|
<button class="btn" @click="close">Done</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
@ -93,6 +93,13 @@ onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
|
||||||
</span>
|
</span>
|
||||||
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
|
<Icon name="lucide:chevron-right" class="chev size-4 shrink-0" />
|
||||||
</button>
|
</button>
|
||||||
|
<button class="title-item" :disabled="!ed.savesReady.value" @click="ed.dialog.value = 'library'">
|
||||||
|
<Icon name="lucide:library-big" class="size-5 shrink-0" />
|
||||||
|
<span class="grow">
|
||||||
|
<span class="label">Library</span>
|
||||||
|
<span class="sub">Components everyone published, to add to your project</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
<button class="title-item" @click="ed.dialog.value = 'settings'">
|
<button class="title-item" @click="ed.dialog.value = 'settings'">
|
||||||
<Icon name="lucide:settings" class="size-5 shrink-0" />
|
<Icon name="lucide:settings" class="size-5 shrink-0" />
|
||||||
<span class="grow"><span class="label">Settings</span></span>
|
<span class="grow"><span class="label">Settings</span></span>
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,23 @@ const ACTIONS: Action[] = [
|
||||||
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
|
{ id: 'tidy', label: 'Tidy this circuit', icon: 'lucide:wand-sparkles', aka: 'wires clean route layout', when: () => ed.def.value.wires.length > 0, run: () => ed.tidyAll() },
|
||||||
{ id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() },
|
{ id: 'tidy-all', label: 'Tidy every circuit', icon: 'lucide:sparkles', aka: 'wires clean route layout all components', run: () => ed.tidyEverything() },
|
||||||
{ id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() },
|
{ id: 'examples', label: 'Add example parts', icon: 'lucide:book-open', aka: 'library not and or adder counter', run: () => ed.loadExamples() },
|
||||||
|
{ id: 'library', label: 'Library: components everyone published', icon: 'lucide:library-big', aka: 'public shared community download import browse', run: () => (ed.dialog.value = 'library') },
|
||||||
|
{
|
||||||
|
id: 'lib-publish',
|
||||||
|
label: 'Publish to the library',
|
||||||
|
icon: 'lucide:book-up',
|
||||||
|
aka: 'share upload public community',
|
||||||
|
when: () => !ed.libraryProblem.value && !ed.ownEntry(ed.def.value),
|
||||||
|
run: () => (ed.dialog.value = 'library-publish'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'lib-update',
|
||||||
|
label: 'Update in the library',
|
||||||
|
icon: 'lucide:book-up',
|
||||||
|
aka: 'publish share upload new version public',
|
||||||
|
when: () => !ed.libraryProblem.value && !!ed.ownEntry(ed.def.value),
|
||||||
|
run: () => (ed.dialog.value = 'library-publish'),
|
||||||
|
},
|
||||||
{ id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() },
|
{ id: 'connector', label: 'New connector type', icon: 'lucide:plug', aka: 'cable hdmi rj45 bus port', when: () => ed.canPlaceKind('portin'), run: () => ed.addConnector() },
|
||||||
{ id: 'power', label: 'Power off and on', icon: 'lucide:power', aka: 'reset state memory bits clear zero restart', when: () => ed.circuitStats.value.sequential, run: () => ed.resetState() },
|
{ id: 'power', label: 'Power off and on', icon: 'lucide:power', aka: 'reset state memory bits clear zero restart', when: () => ed.circuitStats.value.sequential, run: () => ed.resetState() },
|
||||||
{ id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() },
|
{ id: 'undo', label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', when: () => ed.canUndo.value, run: () => ed.undo() },
|
||||||
|
|
|
||||||
|
|
@ -69,6 +69,13 @@ const circuitEntries = computed<MenuEntry[]>(() => {
|
||||||
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: empty, run: () => ed.exportSheet('print') },
|
{ label: 'Print or save as PDF', icon: 'lucide:printer', keys: 'Ctrl+P', disabled: empty, run: () => ed.exportSheet('print') },
|
||||||
{ label: 'Export as SVG', icon: 'lucide:file-image', disabled: empty, run: () => ed.exportSheet('svg') },
|
{ label: 'Export as SVG', icon: 'lucide:file-image', disabled: empty, run: () => ed.exportSheet('svg') },
|
||||||
{ label: 'Publish as a puzzle…', icon: 'lucide:puzzle', disabled: !!ed.task.value || empty, run: () => (ed.dialog.value = 'publish') },
|
{ label: 'Publish as a puzzle…', icon: 'lucide:puzzle', disabled: !!ed.task.value || empty, run: () => (ed.dialog.value = 'publish') },
|
||||||
|
{
|
||||||
|
label: ed.ownEntry(d) ? 'Update in the library…' : 'Publish to the library…',
|
||||||
|
icon: 'lucide:book-up',
|
||||||
|
disabled: !!ed.task.value || empty,
|
||||||
|
note: ed.task.value ? 'challenges stay private' : undefined,
|
||||||
|
run: () => (ed.dialog.value = 'library-publish'),
|
||||||
|
},
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@ import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic
|
||||||
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
|
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
|
||||||
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
|
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
|
||||||
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
|
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
|
||||||
|
import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
|
||||||
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
|
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
|
||||||
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
|
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
|
||||||
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
|
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
|
||||||
|
|
@ -61,6 +62,7 @@ import { packState, stateCarry } from '~/lib/logic/state'
|
||||||
import {
|
import {
|
||||||
cachedAccount,
|
cachedAccount,
|
||||||
currentId,
|
currentId,
|
||||||
|
libraryKeys,
|
||||||
listProjects,
|
listProjects,
|
||||||
loadProject,
|
loadProject,
|
||||||
migrateLegacy,
|
migrateLegacy,
|
||||||
|
|
@ -71,11 +73,12 @@ import {
|
||||||
saveProject,
|
saveProject,
|
||||||
setCachedAccount,
|
setCachedAccount,
|
||||||
setCurrentId,
|
setCurrentId,
|
||||||
|
setLibraryKey,
|
||||||
setPendingDeletes,
|
setPendingDeletes,
|
||||||
type AccountUser,
|
type AccountUser,
|
||||||
type ProjectMeta,
|
type ProjectMeta,
|
||||||
} from '~/lib/logic/storage'
|
} from '~/lib/logic/storage'
|
||||||
import type { CircuitNode, ConnectorType, HeldState, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
|
import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
|
||||||
|
|
||||||
/** A challenge check plus how many transistors the solution uses. */
|
/** A challenge check plus how many transistors the solution uses. */
|
||||||
/** How everyone did on a puzzle, from the server. */
|
/** How everyone did on a puzzle, from the server. */
|
||||||
|
|
@ -169,7 +172,7 @@ function create() {
|
||||||
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
|
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
|
||||||
const labelFocus = ref(0)
|
const labelFocus = ref(0)
|
||||||
const showHelp = ref(false)
|
const showHelp = ref(false)
|
||||||
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
|
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face' | 'library' | 'library-publish'>(null)
|
||||||
/** The component whose box is being drawn in the face designer. */
|
/** The component whose box is being drawn in the face designer. */
|
||||||
const faceFor = ref<string | null>(null)
|
const faceFor = ref<string | null>(null)
|
||||||
function designFace(defId: string) {
|
function designFace(defId: string) {
|
||||||
|
|
@ -1589,6 +1592,114 @@ function create() {
|
||||||
return `${location.origin}/puzzle/${res.id}`
|
return `${location.origin}/puzzle/${res.id}`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Public library ────────────────────────────────────────────────
|
||||||
|
/** Edit keys of the library entries this browser published. */
|
||||||
|
const libKeys = ref(libraryKeys())
|
||||||
|
|
||||||
|
/** The library entry a component is, when this browser published it from here (and so can update or remove it). */
|
||||||
|
function ownEntry(d: ComponentDef | undefined): string | undefined {
|
||||||
|
return d && ownedEntry(libKeys.value, meta.value.id, d.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Why the open circuit can't go to the library; null when it can. */
|
||||||
|
const libraryProblem = computed(() => publishProblem(project.value, def.value.id))
|
||||||
|
|
||||||
|
async function listLibrary(q = ''): Promise<{ entries: LibraryMeta[]; total: number }> {
|
||||||
|
return api('GET', `/api/library?q=${encodeURIComponent(q.trim())}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publishes the open circuit to the library with everything it uses, or a
|
||||||
|
* new version when this browser published it before. The name and
|
||||||
|
* description go to the component too; the author is your leaderboard name.
|
||||||
|
*/
|
||||||
|
async function publishToLibrary(name: string, description: string, author: string): Promise<LibraryOrigin> {
|
||||||
|
const d = def.value
|
||||||
|
const problem = publishProblem(project.value, d.id)
|
||||||
|
if (problem) throw new Error(problem)
|
||||||
|
if (author.trim() !== playerName.value) await setPlayerName(author)
|
||||||
|
const text = description.trim().slice(0, LIBRARY_LIMITS.description)
|
||||||
|
d.name = name.trim().slice(0, LIBRARY_LIMITS.name) || d.name
|
||||||
|
if (text) d.description = text
|
||||||
|
else delete d.description
|
||||||
|
try {
|
||||||
|
const body = { player: playerId(), ...libraryBundle(toRaw(project.value), d.id) }
|
||||||
|
const own = ownEntry(d)
|
||||||
|
let res: { id: string; key?: string; version: number } | undefined
|
||||||
|
if (own) {
|
||||||
|
try {
|
||||||
|
res = await api('PUT', `/api/library/${own}`, body, libKeys.value[own]!.key)
|
||||||
|
} catch (e) {
|
||||||
|
// Gone from the library: it goes in again as a new entry.
|
||||||
|
if ((e as { status?: number }).status !== 404) throw e
|
||||||
|
setLibraryKey(own, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res ??= await api<{ id: string; key: string; version: number }>('POST', '/api/library', body)
|
||||||
|
if (res.key) setLibraryKey(res.id, { key: res.key, project: meta.value.id, def: d.id })
|
||||||
|
libKeys.value = libraryKeys()
|
||||||
|
d.from = { id: res.id, version: res.version, author: playerName.value }
|
||||||
|
return d.from
|
||||||
|
} finally {
|
||||||
|
commit(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Takes an entry this browser published out of the library; components here keep working, just without the mark. */
|
||||||
|
async function removeFromLibrary(id: string) {
|
||||||
|
try {
|
||||||
|
await api('DELETE', `/api/library/${id}`, undefined, libKeys.value[id]?.key)
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as { status?: number }).status !== 404) throw e
|
||||||
|
}
|
||||||
|
setLibraryKey(id, null)
|
||||||
|
libKeys.value = libraryKeys()
|
||||||
|
for (const d of project.value.components) if (d.from?.id === id && !d.from.inside) delete d.from
|
||||||
|
commit(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchEntry(id: string): Promise<{ entry: LibraryMeta; bundle: LibraryBundle }> {
|
||||||
|
const problem = importProblem(project.value)
|
||||||
|
if (problem) throw new Error(problem)
|
||||||
|
const res = await api<{ entry: LibraryMeta; bundle: unknown }>('GET', `/api/library/${encodeURIComponent(id)}`)
|
||||||
|
return { entry: res.entry, bundle: cleanBundle(res.bundle) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const originOf = (entry: LibraryMeta): LibraryOrigin => ({ id: entry.id, version: entry.version, author: entry.author })
|
||||||
|
|
||||||
|
/** Adds a library entry to the open project; returns the id of its component here, ready to place. */
|
||||||
|
async function addFromLibrary(id: string): Promise<string> {
|
||||||
|
const { entry, bundle } = await fetchEntry(id)
|
||||||
|
const res = importBundle(project.value, bundle, originOf(entry))
|
||||||
|
commit()
|
||||||
|
const along = res.added > 1 ? ` and ${res.added - 1} component${res.added === 2 ? '' : 's'} it uses` : ''
|
||||||
|
notify(res.added ? `Added "${entry.name}"${entry.author ? ` by ${entry.author}` : ''}${along}` : `"${entry.name}" is in this project already`)
|
||||||
|
return res.root
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Brings a component from the library to the newest version of its entry, in place: wherever it is used follows. */
|
||||||
|
async function updateFromLibrary(defId: string) {
|
||||||
|
const d = getDef.value(defId)
|
||||||
|
if (!d?.from || d.from.inside) return
|
||||||
|
try {
|
||||||
|
const { entry, bundle } = await fetchEntry(d.from.id)
|
||||||
|
importBundle(project.value, bundle, originOf(entry), d.id)
|
||||||
|
commit()
|
||||||
|
notify(`"${d.name}" is now version ${entry.version} (Ctrl+Z goes back)`)
|
||||||
|
} catch (e) {
|
||||||
|
notify((e as Error).message, 'error')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The newest version of a library entry; null when the library can't be reached or no longer has it. */
|
||||||
|
async function libraryVersion(id: string): Promise<number | null> {
|
||||||
|
try {
|
||||||
|
return (await api<{ entry: LibraryMeta }>('GET', `/api/library/${encodeURIComponent(id)}?meta`)).entry.version
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Several parts at once ─────────────────────────────────────────
|
// ── Several parts at once ─────────────────────────────────────────
|
||||||
const nodesById = (ids: string[]) => {
|
const nodesById = (ids: string[]) => {
|
||||||
const set = new Set(ids)
|
const set = new Set(ids)
|
||||||
|
|
@ -1974,7 +2085,7 @@ function create() {
|
||||||
body: body === undefined ? undefined : JSON.stringify(body),
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
})
|
})
|
||||||
const data = await res.json().catch(() => ({}))
|
const data = await res.json().catch(() => ({}))
|
||||||
if (!res.ok) throw new Error((data as { message?: string }).message || `Server error ${res.status}`)
|
if (!res.ok) throw Object.assign(new Error((data as { message?: string }).message || `Server error ${res.status}`), { status: res.status })
|
||||||
return data as T
|
return data as T
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2545,6 +2656,15 @@ function create() {
|
||||||
beginPuzzle,
|
beginPuzzle,
|
||||||
openPuzzle,
|
openPuzzle,
|
||||||
publishPuzzle,
|
publishPuzzle,
|
||||||
|
ownEntry,
|
||||||
|
libraryProblem,
|
||||||
|
listLibrary,
|
||||||
|
publishToLibrary,
|
||||||
|
removeFromLibrary,
|
||||||
|
addFromLibrary,
|
||||||
|
updateFromLibrary,
|
||||||
|
libraryVersion,
|
||||||
|
libKeys,
|
||||||
isBus,
|
isBus,
|
||||||
pinKind,
|
pinKind,
|
||||||
connectorFor,
|
connectorFor,
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ export function cableKeys(node: CircuitNode): string[] {
|
||||||
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
/** Key of a panel row in the simulator's sources, like a switch's node id. */
|
||||||
export const rowSource = rowPin
|
export const rowSource = rowPin
|
||||||
|
|
||||||
const MAX_DEPTH = 64
|
export const MAX_DEPTH = 64
|
||||||
|
|
||||||
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
|
export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boolean } = {}): Netlist {
|
||||||
const parent: number[] = [LOW, HIGH]
|
const parent: number[] = [LOW, HIGH]
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,372 @@
|
||||||
|
// The public component library: components people published for everyone,
|
||||||
|
// each with every component it uses and the connector types those need.
|
||||||
|
// Publishing sends one component and what it uses (a bundle); adding an
|
||||||
|
// entry to a project brings the bundle in with new ids, and uses what the
|
||||||
|
// project has in exactly that form already. Shared by the browser and the
|
||||||
|
// library server, so it must stay free of browser APIs.
|
||||||
|
|
||||||
|
import { nandCounts, TRANSISTORS_PER_NAND } from './analyze'
|
||||||
|
import { CHALLENGES } from './challenges'
|
||||||
|
import { MAX_DEPTH } from './compile'
|
||||||
|
import { chipPins, type DefLookup } from './geometry'
|
||||||
|
import { containsDef, lookup, uid, uniqueName } from './ops'
|
||||||
|
import { isCampaign, KIND_NAMES } from './progress'
|
||||||
|
import { toProject } from './project'
|
||||||
|
import type { ComponentDef, ConnectorType, LibraryOrigin, Project } from './types'
|
||||||
|
import { NAND_BASE } from './wide'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upper bounds for a published component: the request, its name,
|
||||||
|
* description and group, and the pin names the listing shows (how many per
|
||||||
|
* side, how long each).
|
||||||
|
*/
|
||||||
|
export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400, group: 40, pinNames: 16, pinName: 24 }
|
||||||
|
|
||||||
|
/** What gets published: a component (`root`) and everything it uses, used ones first, with their connector types. */
|
||||||
|
export interface LibraryBundle {
|
||||||
|
root: string
|
||||||
|
components: ComponentDef[]
|
||||||
|
connectors?: ConnectorType[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A library entry as it is listed: what it is, who published it, what it takes. */
|
||||||
|
export interface LibraryMeta {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
description: string
|
||||||
|
group: string
|
||||||
|
/** The publisher's leaderboard name; empty for anonymous. */
|
||||||
|
author: string
|
||||||
|
version: number
|
||||||
|
created: number
|
||||||
|
updated: number
|
||||||
|
/** Transistors at every depth, 4 per NAND. */
|
||||||
|
transistors: number
|
||||||
|
/** Pins on each side. */
|
||||||
|
inputs: number
|
||||||
|
outputs: number
|
||||||
|
/** Names of the first pins on each side, top to bottom, shortened. */
|
||||||
|
inNames: string[]
|
||||||
|
outNames: string[]
|
||||||
|
/** Components it uses, at every depth; they come along. */
|
||||||
|
uses: number
|
||||||
|
/** Connector types that come along. */
|
||||||
|
connectors: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deep copy that also works on Vue reactive proxies (structuredClone does not). */
|
||||||
|
function clone<T>(value: T): T {
|
||||||
|
return JSON.parse(JSON.stringify(value)) as T
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A component and every component it uses, at every depth, each once: the
|
||||||
|
* used ones before the ones that use them, the component itself last. A
|
||||||
|
* component that contains itself is not followed round again.
|
||||||
|
*/
|
||||||
|
export function closure(get: DefLookup, defId: string): ComponentDef[] {
|
||||||
|
const out: ComponentDef[] = []
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const visit = (id: string) => {
|
||||||
|
if (seen.has(id)) return
|
||||||
|
seen.add(id)
|
||||||
|
const def = get(id)
|
||||||
|
if (!def) return
|
||||||
|
for (const n of def.nodes) if (n.kind === 'chip' && n.chip) visit(n.chip)
|
||||||
|
if (def.wide && def.wide.base !== NAND_BASE) visit(def.wide.base)
|
||||||
|
out.push(def)
|
||||||
|
}
|
||||||
|
visit(defId)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Connector types the ports of these components use, in the project's order. */
|
||||||
|
function connectorsUsed(connectors: ConnectorType[] | undefined, defs: ComponentDef[]): ConnectorType[] {
|
||||||
|
const used = new Set(defs.flatMap(d => d.nodes.filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn).map(n => n.conn!)))
|
||||||
|
return (connectors ?? []).filter(c => used.has(c.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why a component can't go to the library, in words; null when it can.
|
||||||
|
* Challenges and puzzles stay private, so nobody gets the answer: neither
|
||||||
|
* a challenge circuit itself nor a solution used anywhere inside it.
|
||||||
|
*/
|
||||||
|
export function publishProblem(project: Project, defId: string): string | null {
|
||||||
|
const get = lookup(project)
|
||||||
|
const def = get(defId)
|
||||||
|
if (!def) return 'Circuit not found'
|
||||||
|
if (def.challenge) return 'Challenges and puzzles stay private, so nobody gets the answer'
|
||||||
|
if (!def.nodes.length) return 'There is nothing in it yet'
|
||||||
|
const solution = closure(get, defId).find(d => d.challenge)
|
||||||
|
if (solution) return `It uses your solution to the ${CHALLENGES.some(c => c.id === solution.challenge) ? 'challenge' : 'puzzle'} "${solution.name}", which stays private`
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why library entries can't be added to a project, in words; null when they
|
||||||
|
* can. A campaign is earned part by part, and a part from the library could
|
||||||
|
* be copied or taken apart into a solution, so a campaign takes none.
|
||||||
|
*/
|
||||||
|
export function importProblem(project: Project): string | null {
|
||||||
|
return isCampaign(project) ? 'A campaign is built from your own work: add library components to another project' : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The library entry a component is when this browser published it, from
|
||||||
|
* this very project and component; its key is in `keys`. The component's
|
||||||
|
* own mark never counts for this, since marks come along in files and links.
|
||||||
|
*/
|
||||||
|
export function ownedEntry(keys: Record<string, { project: string; def: string }>, projectId: string, defId: string): string | undefined {
|
||||||
|
return Object.entries(keys).find(([, k]) => k.project === projectId && k.def === defId)?.[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What publishing a component sends: copies of it and of what it uses,
|
||||||
|
* without challenge or library marks, and their connector types.
|
||||||
|
*/
|
||||||
|
export function libraryBundle(project: Project, defId: string): LibraryBundle {
|
||||||
|
const components = clone(closure(lookup(project), defId))
|
||||||
|
for (const d of components) {
|
||||||
|
delete d.challenge
|
||||||
|
delete d.from
|
||||||
|
}
|
||||||
|
const connectors = clone(connectorsUsed(project.connectors, components))
|
||||||
|
return { root: defId, components, ...(connectors.length ? { connectors } : {}) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parts a published component may have at every depth, so whoever adds it can still run it. */
|
||||||
|
export const MAX_FLAT_PARTS = 10_000_000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the simulator would refuse in a component, or choke on: a component
|
||||||
|
* inside that is missing, one that contains itself, nesting too deep, or
|
||||||
|
* too many parts once every component inside is opened up. Found by looking
|
||||||
|
* at each component once, never by building the whole circuit, so a part
|
||||||
|
* made to be huge costs no more to check than a small one.
|
||||||
|
*/
|
||||||
|
function nestingProblem(get: DefLookup, rootId: string): string | null {
|
||||||
|
const seen = new Map<string, { depth: number; parts: number }>()
|
||||||
|
const busy = new Set<string>()
|
||||||
|
let problem: string | null = null
|
||||||
|
const visit = (def: ComponentDef): { depth: number; parts: number } => {
|
||||||
|
const known = seen.get(def.id)
|
||||||
|
if (known) return known
|
||||||
|
busy.add(def.id)
|
||||||
|
const size = { depth: 1, parts: 0 }
|
||||||
|
for (const n of def.nodes) {
|
||||||
|
const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined
|
||||||
|
if (n.kind !== 'chip') size.parts++
|
||||||
|
else if (!child) problem ??= `Missing component in "${def.name}"`
|
||||||
|
else if (busy.has(child.id)) problem ??= `"${child.name}" contains itself`
|
||||||
|
else {
|
||||||
|
const inner = visit(child)
|
||||||
|
size.depth = Math.max(size.depth, 1 + inner.depth)
|
||||||
|
size.parts += inner.parts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
busy.delete(def.id)
|
||||||
|
seen.set(def.id, size)
|
||||||
|
return size
|
||||||
|
}
|
||||||
|
const size = visit(get(rootId)!)
|
||||||
|
if (size.depth > MAX_DEPTH) problem ??= `Nesting deeper than ${MAX_DEPTH} levels`
|
||||||
|
if (size.parts > MAX_FLAT_PARTS) problem ??= `Too large to run: over ${MAX_FLAT_PARTS.toLocaleString('en')} parts with everything inside opened up`
|
||||||
|
return problem
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every kind of node there is: the built-in parts and components. */
|
||||||
|
const KINDS = new Set<string>([...Object.keys(KIND_NAMES), 'chip'])
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks a bundle from outside with the same checks as any project, plus
|
||||||
|
* the ones a part from a stranger needs: every node and wire well formed,
|
||||||
|
* nothing missing, nothing inside itself, nothing too big to run. Keeps only
|
||||||
|
* the component and what it uses, and drops challenge and library marks:
|
||||||
|
* an entry's components are marked when they are added, never by whoever
|
||||||
|
* published them. Throws with a readable message.
|
||||||
|
*/
|
||||||
|
export function cleanBundle(raw: unknown): LibraryBundle {
|
||||||
|
const b = raw as Partial<LibraryBundle>
|
||||||
|
if (!b || typeof b !== 'object' || typeof b.root !== 'string') throw new Error('Not a component for the library')
|
||||||
|
const p = toProject({ name: 'Library', components: b.components, connectors: b.connectors, openId: b.root })
|
||||||
|
for (const d of p.components) {
|
||||||
|
const broken = () => new Error(`"${d.name}" is broken`)
|
||||||
|
for (const n of d.nodes) {
|
||||||
|
if (!n || typeof n.id !== 'string' || !KINDS.has(n.kind) || !Number.isFinite(n.x) || !Number.isFinite(n.y)) throw broken()
|
||||||
|
if (n.label !== undefined && typeof n.label !== 'string') delete n.label
|
||||||
|
}
|
||||||
|
for (const w of d.wires) {
|
||||||
|
if (!w || typeof w.id !== 'string' || [w.from, w.to].some(r => !r || typeof r.node !== 'string' || typeof r.pin !== 'string')) throw broken()
|
||||||
|
}
|
||||||
|
for (const k of ['description', 'group'] as const) if (d[k] !== undefined && typeof d[k] !== 'string') delete d[k]
|
||||||
|
}
|
||||||
|
const get = lookup(p)
|
||||||
|
const root = get(b.root)
|
||||||
|
if (!root) throw new Error('The component itself is missing')
|
||||||
|
const problem = nestingProblem(get, root.id)
|
||||||
|
if (problem) throw new Error(problem)
|
||||||
|
const components = closure(get, root.id)
|
||||||
|
for (const d of components) {
|
||||||
|
delete d.challenge
|
||||||
|
delete d.from
|
||||||
|
}
|
||||||
|
root.name = root.name.trim().slice(0, LIBRARY_LIMITS.name) || 'Component'
|
||||||
|
if (root.description !== undefined) root.description = root.description.trim().slice(0, LIBRARY_LIMITS.description)
|
||||||
|
if (root.group !== undefined) root.group = root.group.trim().slice(0, LIBRARY_LIMITS.group)
|
||||||
|
const connectors = connectorsUsed(p.connectors, components)
|
||||||
|
return { root: root.id, components, ...(connectors.length ? { connectors } : {}) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the listing says about a cleaned bundle, counted from the circuit
|
||||||
|
* itself so it can be trusted. Small whatever was sent: every entry's
|
||||||
|
* listing is read on each visit to the library.
|
||||||
|
*/
|
||||||
|
export function describeBundle(b: LibraryBundle): Pick<LibraryMeta, 'name' | 'description' | 'group' | 'transistors' | 'inputs' | 'outputs' | 'inNames' | 'outNames' | 'uses' | 'connectors'> {
|
||||||
|
const root = b.components.find(d => d.id === b.root)
|
||||||
|
if (!root) throw new Error('The component itself is missing')
|
||||||
|
const pins = chipPins(root)
|
||||||
|
const names = (list: { label: string }[]) => list.slice(0, LIBRARY_LIMITS.pinNames).map(p => p.label.slice(0, LIBRARY_LIMITS.pinName))
|
||||||
|
return {
|
||||||
|
name: root.name.slice(0, LIBRARY_LIMITS.name),
|
||||||
|
description: (root.description ?? '').slice(0, LIBRARY_LIMITS.description),
|
||||||
|
group: (root.group ?? '').slice(0, LIBRARY_LIMITS.group),
|
||||||
|
transistors: (nandCounts(b.components).get(root.id) ?? 0) * TRANSISTORS_PER_NAND,
|
||||||
|
inputs: pins.inputs.length,
|
||||||
|
outputs: pins.outputs.length,
|
||||||
|
inNames: names(pins.inputs),
|
||||||
|
outNames: names(pins.outputs),
|
||||||
|
uses: b.components.length - 1,
|
||||||
|
connectors: b.connectors?.length ?? 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSON with object keys sorted, so the same data always gives the same text. */
|
||||||
|
function canon(value: unknown): string {
|
||||||
|
return JSON.stringify(value, (_, v) =>
|
||||||
|
v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : v,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a component is, apart from its id, name, texts and marks: the same for two copies of one thing. */
|
||||||
|
const form = (d: ComponentDef) => canon({ symbol: d.symbol, face: d.face, wide: d.wide, design: d.design, nodes: d.nodes, wires: d.wires })
|
||||||
|
|
||||||
|
const sameLines = (a: ConnectorType, b: ConnectorType) => canon(a.lines.map(l => [l.name, !!l.back])) === canon(b.lines.map(l => [l.name, !!l.back]))
|
||||||
|
|
||||||
|
/** Parts of a component that an update replaces; its name and group stay as they are here. */
|
||||||
|
const CONTENT = ['symbol', 'description', 'face', 'wide', 'design', 'nodes', 'wires'] as const
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a library entry to a project. What the project has in exactly this
|
||||||
|
* form already (an earlier import, the examples) is used as it is; the rest
|
||||||
|
* comes in with new ids, and with a number after its name when the name is
|
||||||
|
* taken. A connector type joins the project's type of the same id or name
|
||||||
|
* when their lines match, and comes in as a new type otherwise. The entry's
|
||||||
|
* component is marked with where it came from; the ones it uses are marked
|
||||||
|
* as having come along.
|
||||||
|
*
|
||||||
|
* With `replace` (a component here from the same entry), that component
|
||||||
|
* takes the entry's new version instead, so every place it is used follows.
|
||||||
|
* What came along with the old version and is used nowhere else any more
|
||||||
|
* goes, and the parts that replace it take its names.
|
||||||
|
* Returns the id of the entry's component here and how many were added.
|
||||||
|
*/
|
||||||
|
export function importBundle(project: Project, bundle: LibraryBundle, origin: LibraryOrigin, replace?: string): { root: string; added: number } {
|
||||||
|
const conns = new Map<string, string>()
|
||||||
|
for (const c of bundle.connectors ?? []) {
|
||||||
|
const have = project.connectors ?? []
|
||||||
|
const same = have.find(h => (h.id === c.id || h.name.toLowerCase() === c.name.toLowerCase()) && sameLines(h, c))
|
||||||
|
if (same) {
|
||||||
|
conns.set(c.id, same.id)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const copy = clone(c)
|
||||||
|
if (have.some(h => h.id === copy.id)) copy.id = uid('k')
|
||||||
|
const names = new Set(have.map(h => h.name.toLowerCase()))
|
||||||
|
for (let i = 2; names.has(copy.name.toLowerCase()); i++) copy.name = `${c.name} ${i}`
|
||||||
|
project.connectors = [...have, copy]
|
||||||
|
conns.set(c.id, copy.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Components already here, by form. Not challenge attempts, which are
|
||||||
|
// still being worked on; not another entry's component, which a newer
|
||||||
|
// version of that entry would change under this one; nor anything that
|
||||||
|
// contains the one being replaced, or it would end up inside itself.
|
||||||
|
const forms = new Map<string, string>()
|
||||||
|
for (const d of project.components) {
|
||||||
|
if (d.challenge || (d.from && !d.from.inside && d.from.id !== origin.id) || (replace && containsDef(project, d.id, replace))) continue
|
||||||
|
const k = form(d)
|
||||||
|
if (!forms.has(k)) forms.set(k, d.id)
|
||||||
|
}
|
||||||
|
const target = replace ? project.components.find(d => d.id === replace) : undefined
|
||||||
|
// What came along with the version being replaced.
|
||||||
|
const before = target ? closure(lookup(project), target.id).filter(d => d.from?.inside && d.from.id === origin.id) : []
|
||||||
|
const byId = new Map(bundle.components.map(d => [d.id, d]))
|
||||||
|
const ids = new Map<string, string>()
|
||||||
|
const fresh: { def: ComponentDef; name: string }[] = []
|
||||||
|
let root = ''
|
||||||
|
let added = 0
|
||||||
|
for (const d of closure(id => byId.get(id), bundle.root)) {
|
||||||
|
const copy = clone(d)
|
||||||
|
for (const n of copy.nodes) {
|
||||||
|
if (n.kind === 'chip' && n.chip) n.chip = ids.get(n.chip) ?? n.chip
|
||||||
|
if (n.conn) n.conn = conns.get(n.conn) ?? n.conn
|
||||||
|
}
|
||||||
|
if (copy.wide && copy.wide.base !== NAND_BASE) copy.wide.base = ids.get(copy.wide.base) ?? copy.wide.base
|
||||||
|
delete copy.challenge
|
||||||
|
const isRoot = d.id === bundle.root
|
||||||
|
copy.from = isRoot ? { ...origin } : { ...origin, inside: true }
|
||||||
|
|
||||||
|
if (isRoot && target) {
|
||||||
|
const t = target as unknown as Record<string, unknown>
|
||||||
|
for (const k of CONTENT) {
|
||||||
|
if (copy[k] === undefined) delete t[k]
|
||||||
|
else t[k] = copy[k]
|
||||||
|
}
|
||||||
|
target.from = copy.from
|
||||||
|
delete target.challenge
|
||||||
|
ids.set(d.id, target.id)
|
||||||
|
root = target.id
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const same = forms.get(form(copy))
|
||||||
|
if (same) {
|
||||||
|
ids.set(d.id, same)
|
||||||
|
// The same entry again, unchanged: it now counts as the newer version.
|
||||||
|
const have = project.components.find(x => x.id === same)!
|
||||||
|
if (have.from?.id === copy.from.id && (isRoot ? !have.from.inside : have.from.inside)) have.from = copy.from
|
||||||
|
if (isRoot) root = same
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
copy.id = uid('c')
|
||||||
|
while (project.components.some(x => x.id === copy.id)) copy.id = uid('c')
|
||||||
|
copy.name = uniqueName(project, copy.name)
|
||||||
|
project.components.push(copy)
|
||||||
|
forms.set(form(copy), copy.id)
|
||||||
|
ids.set(d.id, copy.id)
|
||||||
|
fresh.push({ def: copy, name: d.name })
|
||||||
|
added++
|
||||||
|
if (isRoot) root = copy.id
|
||||||
|
}
|
||||||
|
if (target) {
|
||||||
|
dropUnused(project, before)
|
||||||
|
for (const f of fresh) if (f.def.name !== f.name && !project.components.some(x => x.name.toLowerCase() === f.name.toLowerCase())) f.def.name = f.name
|
||||||
|
}
|
||||||
|
return { root, added }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes those of these components that nothing uses (or has open), and then those only they used. */
|
||||||
|
function dropUnused(project: Project, defs: ComponentDef[]) {
|
||||||
|
const left = new Set(defs.map(d => d.id))
|
||||||
|
const used = (id: string) =>
|
||||||
|
id === project.openId || project.components.some(d => d.id !== id && (d.wide?.base === id || d.nodes.some(n => n.kind === 'chip' && n.chip === id)))
|
||||||
|
for (let gone = true; gone; ) {
|
||||||
|
gone = false
|
||||||
|
for (const id of left) {
|
||||||
|
if (used(id)) continue
|
||||||
|
project.components = project.components.filter(d => d.id !== id)
|
||||||
|
left.delete(id)
|
||||||
|
gone = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -160,6 +160,7 @@ export function duplicateComponent(project: Project, id: string): ComponentDef |
|
||||||
if (!src) return undefined
|
if (!src) return undefined
|
||||||
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
|
const copy: ComponentDef = { ...clone(src), id: uid('c'), name: uniqueName(project, `${src.name} copy`) }
|
||||||
delete copy.challenge
|
delete copy.challenge
|
||||||
|
delete copy.from
|
||||||
project.components.push(copy)
|
project.components.push(copy)
|
||||||
return copy
|
return copy
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ import {
|
||||||
type ConnectorType,
|
type ConnectorType,
|
||||||
type FaceDesign,
|
type FaceDesign,
|
||||||
type HeldState,
|
type HeldState,
|
||||||
|
type LibraryOrigin,
|
||||||
type PanelRow,
|
type PanelRow,
|
||||||
type Project,
|
type Project,
|
||||||
type PuzzleSpec,
|
type PuzzleSpec,
|
||||||
|
|
@ -107,6 +108,19 @@ function cleanDesign(d: ComponentDef) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Where a library component came from: an entry id, a version and a name; anything else is dropped. */
|
||||||
|
function cleanOrigin(d: ComponentDef) {
|
||||||
|
const f = d.from as Partial<LibraryOrigin> | undefined
|
||||||
|
if (!f || typeof f.id !== 'string' || !/^[A-Za-z0-9]{6,16}$/.test(f.id) || !Number.isInteger(f.version) || f.version! < 1) {
|
||||||
|
delete d.from
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.from = { id: f.id, version: f.version!, author: typeof f.author === 'string' ? f.author.slice(0, 24) : '', ...(f.inside === true ? { inside: true } : {}) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A wire's corner points: [x, y] pairs of plain numbers, or the wire can't be drawn. */
|
||||||
|
const cornersOk = (pts: unknown) => Array.isArray(pts) && pts.every(p => Array.isArray(p) && p.length === 2 && p.every(v => typeof v === 'number' && Number.isFinite(v)))
|
||||||
|
|
||||||
/** Upper bounds for a project that comes from outside. What its circuits hold has its own room (`state`) on top of `bytes`. */
|
/** Upper bounds for a project that comes from outside. What its circuits hold has its own room (`state`) on top of `bytes`. */
|
||||||
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000, state: 500_000 }
|
export const LIMITS = { bytes: 2_000_000, components: 2_000, nodes: 100_000, state: 500_000 }
|
||||||
|
|
||||||
|
|
@ -126,8 +140,10 @@ export function toProject(data: unknown): Project {
|
||||||
d.symbol ??= 'box'
|
d.symbol ??= 'box'
|
||||||
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
|
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
|
||||||
if (d.design !== undefined) cleanDesign(d)
|
if (d.design !== undefined) cleanDesign(d)
|
||||||
|
if (d.from !== undefined) cleanOrigin(d)
|
||||||
for (const n of d.nodes) cleanNode(n)
|
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
|
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
|
||||||
|
for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts
|
||||||
}
|
}
|
||||||
if (nodes > LIMITS.nodes) throw new Error('Project too large')
|
if (nodes > LIMITS.nodes) throw new Error('Project too large')
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,7 @@ const CURRENT = 'logigate:current'
|
||||||
const LEGACY = 'logigate:project:v1'
|
const LEGACY = 'logigate:project:v1'
|
||||||
const ACCOUNT = 'logigate:account'
|
const ACCOUNT = 'logigate:account'
|
||||||
const PENDING_DELETES = 'logigate:pending-deletes'
|
const PENDING_DELETES = 'logigate:pending-deletes'
|
||||||
|
const LIBRARY_KEYS = 'logigate:library-keys'
|
||||||
const entry = (id: string) => `logigate:p:${id}`
|
const entry = (id: string) => `logigate:p:${id}`
|
||||||
|
|
||||||
function read(key: string): string | null {
|
function read(key: string): string | null {
|
||||||
|
|
@ -157,3 +158,29 @@ export function pendingDeletes(): { owner: string; id: string }[] {
|
||||||
export function setPendingDeletes(list: { owner: string; id: string }[]) {
|
export function setPendingDeletes(list: { owner: string; id: string }[]) {
|
||||||
write(PENDING_DELETES, JSON.stringify(list))
|
write(PENDING_DELETES, JSON.stringify(list))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A library entry published from this browser. */
|
||||||
|
export interface LibraryKey {
|
||||||
|
/** Edit key: updates or removes the entry. */
|
||||||
|
key: string
|
||||||
|
/** The project and component it was published from. */
|
||||||
|
project: string
|
||||||
|
def: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Library entries published from this browser, by entry id. Never part of a project, so whoever gets a copy of it can't change them. */
|
||||||
|
export function libraryKeys(): Record<string, LibraryKey> {
|
||||||
|
try {
|
||||||
|
const keys = JSON.parse(read(LIBRARY_KEYS) ?? '{}')
|
||||||
|
return keys && typeof keys === 'object' && !Array.isArray(keys) ? keys : {}
|
||||||
|
} catch {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setLibraryKey(id: string, own: LibraryKey | null) {
|
||||||
|
const keys = libraryKeys()
|
||||||
|
if (own) keys[id] = own
|
||||||
|
else delete keys[id]
|
||||||
|
write(LIBRARY_KEYS, JSON.stringify(keys))
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -143,6 +143,19 @@ export interface ComponentDef {
|
||||||
wide?: { base: string; n: number }
|
wide?: { base: string; n: number }
|
||||||
/** The component's box drawn by hand; empty: laid out automatically. */
|
/** The component's box drawn by hand; empty: laid out automatically. */
|
||||||
design?: FaceDesign
|
design?: FaceDesign
|
||||||
|
/** Set when the component came from the public library (or was published there from here). */
|
||||||
|
from?: LibraryOrigin
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a component of the public library came from: the entry, its version and who published it. */
|
||||||
|
export interface LibraryOrigin {
|
||||||
|
/** Id of the library entry. */
|
||||||
|
id: string
|
||||||
|
version: number
|
||||||
|
/** The publisher's name at the time; empty for anonymous. */
|
||||||
|
author: string
|
||||||
|
/** Came along inside the entry (a part it uses), rather than being the entry itself. */
|
||||||
|
inside?: true
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
|
export const FACE_INKS = ['muted', 'text', 'red', 'yellow', 'green', 'blue'] as const
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
// Take an entry out of the library. Needs its edit key. Components already
|
||||||
|
// added to projects stay where they are.
|
||||||
|
export default defineEventHandler(async event => {
|
||||||
|
rateLimit(event, 'library', 30, 10 * 60_000)
|
||||||
|
const id = getRouterParam(event, 'id')
|
||||||
|
const key = getHeader(event, 'x-edit-key')
|
||||||
|
await locked('library', async () => {
|
||||||
|
const record = await findEntry(id)
|
||||||
|
if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
|
||||||
|
await libraryStorage().removeItem(entryKey(record.meta.id))
|
||||||
|
await libraryStorage().setItem('index', (await libraryIndex()).filter(m => m.id !== record.meta.id))
|
||||||
|
})
|
||||||
|
return { ok: true }
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
// One library entry with everything it uses, ready to add to a project.
|
||||||
|
// With ?meta only what it is, to look for a newer version.
|
||||||
|
export default defineEventHandler(async event => {
|
||||||
|
const record = await findEntry(getRouterParam(event, 'id'))
|
||||||
|
const entry = publicMeta(record.meta, await playerNames())
|
||||||
|
setHeader(event, 'cache-control', 'no-store')
|
||||||
|
return 'meta' in getQuery(event) ? { entry } : { entry, bundle: record.bundle }
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,19 @@
|
||||||
|
// Publish a new version of a library entry. Needs the edit key from the
|
||||||
|
// first publish; the entry keeps its id and publisher, its version goes up.
|
||||||
|
import { describeBundle } from '../../../app/lib/logic/library'
|
||||||
|
|
||||||
|
export default defineEventHandler(async event => {
|
||||||
|
rateLimit(event, 'library', 30, 10 * 60_000)
|
||||||
|
const id = getRouterParam(event, 'id')
|
||||||
|
const { bundle } = await readLibraryBody(event)
|
||||||
|
const key = getHeader(event, 'x-edit-key')
|
||||||
|
const meta = await locked('library', async () => {
|
||||||
|
const record = await findEntry(id)
|
||||||
|
if (!keyMatches(key, record.keyHash)) throw createError({ statusCode: 403, message: 'This component belongs to someone else' })
|
||||||
|
const meta: LibraryItem = { ...record.meta, ...describeBundle(bundle), version: record.meta.version + 1, updated: Date.now() }
|
||||||
|
await libraryStorage().setItem(entryKey(meta.id), { ...record, meta, bundle })
|
||||||
|
await libraryStorage().setItem('index', (await libraryIndex()).map(m => (m.id === meta.id ? meta : m)))
|
||||||
|
return meta
|
||||||
|
})
|
||||||
|
return { id: meta.id, version: meta.version }
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
// Everybody's published components, newest first. ?q= narrows them to the
|
||||||
|
// ones whose name, description, group or author has every word typed.
|
||||||
|
export default defineEventHandler(async event => {
|
||||||
|
const q = getQuery(event).q
|
||||||
|
const names = await playerNames()
|
||||||
|
const list = (await libraryIndex()).map(m => publicMeta(m, names))
|
||||||
|
setHeader(event, 'cache-control', 'no-store')
|
||||||
|
return { entries: searchLibrary(list, typeof q === 'string' ? q.slice(0, 100) : '').slice(0, 500), total: list.length }
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
// Publish a component to the library, with everything it uses. The server
|
||||||
|
// counts its transistors and pins itself, so the listing can be trusted.
|
||||||
|
// Returns its id and the edit key that updates or removes it later.
|
||||||
|
import { describeBundle } from '../../../app/lib/logic/library'
|
||||||
|
|
||||||
|
export default defineEventHandler(async event => {
|
||||||
|
rateLimit(event, 'library', 30, 10 * 60_000)
|
||||||
|
const { player, bundle } = await readLibraryBody(event)
|
||||||
|
const storage = libraryStorage()
|
||||||
|
const key = newEditKey()
|
||||||
|
const meta = await locked('library', async () => {
|
||||||
|
const index = await libraryIndex()
|
||||||
|
if (index.length >= MAX_ENTRIES) throw createError({ statusCode: 507, message: 'The library is full for now' })
|
||||||
|
let id = newShareId()
|
||||||
|
while (await storage.hasItem(entryKey(id))) id = newShareId()
|
||||||
|
const now = Date.now()
|
||||||
|
const meta: LibraryItem = { id, ...describeBundle(bundle), version: 1, created: now, updated: now, player }
|
||||||
|
await storage.setItem(entryKey(id), { meta, bundle, keyHash: hashKey(key) })
|
||||||
|
await storage.setItem('index', [meta, ...index])
|
||||||
|
return meta
|
||||||
|
})
|
||||||
|
setResponseStatus(event, 201)
|
||||||
|
return { id: meta.id, key, version: meta.version }
|
||||||
|
})
|
||||||
|
|
@ -4,7 +4,7 @@ import { join, resolve } from 'node:path'
|
||||||
export default defineNitroPlugin(() => {
|
export default defineNitroPlugin(() => {
|
||||||
const root = resolve(process.cwd(), 'data')
|
const root = resolve(process.cwd(), 'data')
|
||||||
const storage = useStorage()
|
const storage = useStorage()
|
||||||
for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles']) {
|
for (const name of ['shares', 'users', 'sessions', 'accounts', 'puzzles', 'library']) {
|
||||||
storage.mount(name, safeFsDriver({ base: join(root, name) }))
|
storage.mount(name, safeFsDriver({ base: join(root, name) }))
|
||||||
}
|
}
|
||||||
void removeStaleTemp(root)
|
void removeStaleTemp(root)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
// The public component library, as JSON files under data/library:
|
||||||
|
// entries:<id> holds a published component with everything it uses, index
|
||||||
|
// the list everyone browses. Publishers have no account here, just the
|
||||||
|
// random player id kept in their browser (as on the leaderboards) and an
|
||||||
|
// edit key per entry, which only their browser has; only its hash is stored.
|
||||||
|
|
||||||
|
import type { H3Event } from 'h3'
|
||||||
|
import { cleanBundle, LIBRARY_LIMITS, type LibraryBundle, type LibraryMeta } from '../../app/lib/logic/library'
|
||||||
|
|
||||||
|
/** An entry in the index: its meta with the publisher's player id instead of their name. */
|
||||||
|
export type LibraryItem = Omit<LibraryMeta, 'author'> & { player: string }
|
||||||
|
|
||||||
|
export interface LibraryRecord {
|
||||||
|
meta: LibraryItem
|
||||||
|
bundle: LibraryBundle
|
||||||
|
keyHash: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entries the library holds at most, so the index stays small enough to read on every visit. */
|
||||||
|
export const MAX_ENTRIES = 20_000
|
||||||
|
|
||||||
|
export const libraryStorage = () => useStorage('library')
|
||||||
|
export const entryKey = (id: string) => `entries:${id}`
|
||||||
|
|
||||||
|
export async function libraryIndex(): Promise<LibraryItem[]> {
|
||||||
|
return (await libraryStorage().getItem<LibraryItem[]>('index')) ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An entry as everyone sees it: the author by the name they chose, never their player id. */
|
||||||
|
export function publicMeta(item: LibraryItem, names: Record<string, string>): LibraryMeta {
|
||||||
|
const { player, ...meta } = item
|
||||||
|
return { ...meta, author: names[player] ?? '' }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entries whose name, description, group or author contain every word of the query, newest first. */
|
||||||
|
export function searchLibrary(list: LibraryMeta[], query: string): LibraryMeta[] {
|
||||||
|
const words = query.toLowerCase().split(/\s+/).filter(Boolean)
|
||||||
|
return list
|
||||||
|
.filter(m => {
|
||||||
|
const text = `${m.name} ${m.description} ${m.group} ${m.author}`.toLowerCase()
|
||||||
|
return words.every(w => text.includes(w))
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.updated - a.updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The publisher and their component, checked and cleaned like any project. */
|
||||||
|
export async function readLibraryBody(event: H3Event): Promise<{ player: string; bundle: LibraryBundle }> {
|
||||||
|
const raw = await readRawBody(event, 'utf8')
|
||||||
|
if (!raw) throw createError({ statusCode: 400, message: 'Empty request' })
|
||||||
|
if (raw.length > LIBRARY_LIMITS.bytes) throw createError({ statusCode: 413, message: 'Too large for the library (1 MB at most)' })
|
||||||
|
let body: { player?: unknown }
|
||||||
|
try {
|
||||||
|
body = JSON.parse(raw)
|
||||||
|
} catch {
|
||||||
|
throw createError({ statusCode: 400, message: 'Not valid JSON' })
|
||||||
|
}
|
||||||
|
if (!isPlayer(body.player)) throw createError({ statusCode: 400, message: 'Missing player' })
|
||||||
|
try {
|
||||||
|
return { player: body.player, bundle: cleanBundle(body) }
|
||||||
|
} catch (e) {
|
||||||
|
throw createError({ statusCode: 400, message: (e as Error).message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The entry behind an API id, or a 404. */
|
||||||
|
export async function findEntry(id: string | undefined): Promise<LibraryRecord> {
|
||||||
|
const record = isShareId(id) ? await libraryStorage().getItem<LibraryRecord>(entryKey(id)) : null
|
||||||
|
if (!record) throw createError({ statusCode: 404, message: 'Not in the library (any more)' })
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,95 @@
|
||||||
|
// The library's API handlers, run against stand-ins for Nitro's request
|
||||||
|
// helpers and an in-memory store: publish, update, list, read, remove.
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest'
|
||||||
|
import { libraryBundle } from '../app/lib/logic/library'
|
||||||
|
import { createProject } from '../app/lib/logic/ops'
|
||||||
|
|
||||||
|
interface FakeEvent {
|
||||||
|
body?: string
|
||||||
|
params?: Record<string, string>
|
||||||
|
headers?: Record<string, string>
|
||||||
|
query?: Record<string, string>
|
||||||
|
status?: number
|
||||||
|
}
|
||||||
|
type Handler = (e: FakeEvent) => Promise<Record<string, unknown>>
|
||||||
|
|
||||||
|
const stores = new Map<string, Map<string, unknown>>()
|
||||||
|
const g = globalThis as Record<string, unknown>
|
||||||
|
const handlers: Record<string, Handler> = {}
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
Object.assign(g, {
|
||||||
|
defineEventHandler: (fn: Handler) => fn,
|
||||||
|
createError: ({ statusCode, message }: { statusCode: number; message: string }) => Object.assign(new Error(message), { statusCode }),
|
||||||
|
readRawBody: async (e: FakeEvent) => e.body,
|
||||||
|
readBody: async (e: FakeEvent) => JSON.parse(e.body ?? 'null'),
|
||||||
|
getRouterParam: (e: FakeEvent, k: string) => e.params?.[k],
|
||||||
|
getHeader: (e: FakeEvent, k: string) => e.headers?.[k],
|
||||||
|
getQuery: (e: FakeEvent) => e.query ?? {},
|
||||||
|
getRequestIP: () => '127.0.0.1',
|
||||||
|
setHeader: () => {},
|
||||||
|
setResponseStatus: (e: FakeEvent, s: number) => (e.status = s),
|
||||||
|
useStorage: (name: string) => {
|
||||||
|
if (!stores.has(name)) stores.set(name, new Map())
|
||||||
|
const m = stores.get(name)!
|
||||||
|
return {
|
||||||
|
getItem: async (k: string) => structuredClone(m.get(k) ?? null),
|
||||||
|
setItem: async (k: string, v: unknown) => void m.set(k, structuredClone(v)),
|
||||||
|
hasItem: async (k: string) => m.has(k),
|
||||||
|
removeItem: async (k: string) => void m.delete(k),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
// The server's own helpers, auto-imported there.
|
||||||
|
for (const mod of [await import('../server/utils/shares'), await import('../server/utils/puzzles'), await import('../server/utils/library')]) Object.assign(g, mod)
|
||||||
|
handlers.post = (await import('../server/api/library/index.post')).default as unknown as Handler
|
||||||
|
handlers.list = (await import('../server/api/library/index.get')).default as unknown as Handler
|
||||||
|
handlers.get = (await import('../server/api/library/[id].get')).default as unknown as Handler
|
||||||
|
handlers.put = (await import('../server/api/library/[id].put')).default as unknown as Handler
|
||||||
|
handlers.delete = (await import('../server/api/library/[id].delete')).default as unknown as Handler
|
||||||
|
handlers.name = (await import('../server/api/players/name.post')).default as unknown as Handler
|
||||||
|
})
|
||||||
|
|
||||||
|
const ADA = 'player-ada-000001'
|
||||||
|
const call = (h: string, e: FakeEvent) => handlers[h]!(e)
|
||||||
|
|
||||||
|
describe('library API', () => {
|
||||||
|
it('publishes, lists, updates and removes an entry; only the key holder may change it', async () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
await call('name', { body: JSON.stringify({ player: ADA, name: 'Ada' }) })
|
||||||
|
const made = await call('post', { body: JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') }) })
|
||||||
|
expect(made).toMatchObject({ version: 1 })
|
||||||
|
const id = made.id as string
|
||||||
|
const key = made.key as string
|
||||||
|
|
||||||
|
const list = await call('list', { query: { q: 'adder ada' } })
|
||||||
|
expect(list.total).toBe(1)
|
||||||
|
const [entry] = list.entries as Record<string, unknown>[]
|
||||||
|
// Two half adders (XOR of 4 NANDs, AND of 2) and an OR of 3: 15 NANDs.
|
||||||
|
expect(entry).toMatchObject({ id, name: 'Full Adder', author: 'Ada', transistors: 60, inputs: 3, outputs: 2, inNames: ['A', 'B', 'Cin'], outNames: ['S', 'Cout'], uses: 5, version: 1 })
|
||||||
|
expect(JSON.stringify(list)).not.toContain(ADA)
|
||||||
|
expect((await call('list', { query: { q: 'counter' } })).entries).toEqual([])
|
||||||
|
|
||||||
|
const full = await call('get', { params: { id } })
|
||||||
|
expect((full.bundle as { root: string }).root).toBe('ex-fa')
|
||||||
|
expect(await call('get', { params: { id }, query: { meta: '' } })).not.toHaveProperty('bundle')
|
||||||
|
|
||||||
|
const next = JSON.stringify({ player: ADA, ...libraryBundle(p, 'ex-fa') })
|
||||||
|
await expect(call('put', { params: { id }, headers: { 'x-edit-key': 'wrong' }, body: next })).rejects.toMatchObject({ statusCode: 403 })
|
||||||
|
expect(await call('put', { params: { id }, headers: { 'x-edit-key': key }, body: next })).toEqual({ id, version: 2 })
|
||||||
|
expect(((await call('list', {})).entries as { version: number }[])[0]!.version).toBe(2)
|
||||||
|
|
||||||
|
await expect(call('delete', { params: { id }, headers: { 'x-edit-key': 'wrong' } })).rejects.toMatchObject({ statusCode: 403 })
|
||||||
|
await call('delete', { params: { id }, headers: { 'x-edit-key': key } })
|
||||||
|
expect((await call('list', {})).total).toBe(0)
|
||||||
|
await expect(call('get', { params: { id } })).rejects.toMatchObject({ statusCode: 404 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses requests without a player, broken components and oversized ones', async () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const bundle = libraryBundle(p, 'ex-ha')
|
||||||
|
await expect(call('post', { body: JSON.stringify(bundle) })).rejects.toMatchObject({ statusCode: 400 })
|
||||||
|
await expect(call('post', { body: JSON.stringify({ player: ADA, root: 'ex-ha', components: [] }) })).rejects.toMatchObject({ statusCode: 400 })
|
||||||
|
await expect(call('post', { body: JSON.stringify({ player: ADA, ...bundle, pad: 'x'.repeat(1_000_001) }) })).rejects.toMatchObject({ statusCode: 413 })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,450 @@
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { nandCounts, truthTable } from '../app/lib/logic/analyze'
|
||||||
|
import { cleanBundle, closure, describeBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
|
||||||
|
import { createProject, duplicateComponent, lookup, startChallenge } from '../app/lib/logic/ops'
|
||||||
|
import { parseProject, toProject } from '../app/lib/logic/project'
|
||||||
|
import { libraryKeys, setLibraryKey } from '../app/lib/logic/storage'
|
||||||
|
import { CHALLENGES } from '../app/lib/logic/challenges'
|
||||||
|
import type { ComponentDef, LibraryOrigin, Project, Wire } from '../app/lib/logic/types'
|
||||||
|
import { publicMeta, searchLibrary, type LibraryItem } from '../server/utils/library'
|
||||||
|
|
||||||
|
const w = (id: string, from: [string, string], to: [string, string]): Wire => ({ id, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } })
|
||||||
|
const origin: LibraryOrigin = { id: 'Lib12345', version: 1, author: 'Ada' }
|
||||||
|
|
||||||
|
/** The rows of a component's truth table, as text. */
|
||||||
|
function rows(p: Project, id: string) {
|
||||||
|
const t = truthTable(lookup(p), id)
|
||||||
|
return 'error' in t ? t.error : t.rows.map(r => `${r.ins.join('')}|${r.outs.join('')}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ada's project: the examples, a link of her own and a part that sends two lines over it. */
|
||||||
|
function adasProject(): Project {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
p.connectors = [{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }]
|
||||||
|
const sender: ComponentDef = {
|
||||||
|
id: 'csend',
|
||||||
|
name: 'Sender',
|
||||||
|
symbol: 'box',
|
||||||
|
nodes: [
|
||||||
|
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
|
||||||
|
{ id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
|
||||||
|
{ id: 'x', kind: 'chip', chip: 'ex-xor', x: 6, y: 0 },
|
||||||
|
{ id: 'tx', kind: 'portout', conn: 'k1', x: 20, y: 0 },
|
||||||
|
],
|
||||||
|
wires: [w('w1', ['a', 'q'], ['x', 'a']), w('w2', ['b', 'q'], ['x', 'b']), w('w3', ['x', 'q'], ['tx', 'l0']), w('w4', ['a', 'q'], ['tx', 'l1'])],
|
||||||
|
}
|
||||||
|
p.components.push(sender)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a library entry hands out: the bundle, cleaned as the server does. */
|
||||||
|
const published = (p: Project, id: string) => cleanBundle(JSON.parse(JSON.stringify(libraryBundle(p, id))))
|
||||||
|
|
||||||
|
describe('library: what goes along', () => {
|
||||||
|
it('lists a component after everything it uses, each once, itself last', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const order = closure(lookup(p), 'ex-add4').map(d => d.id)
|
||||||
|
expect(order.at(-1)).toBe('ex-add4')
|
||||||
|
expect(new Set(order).size).toBe(order.length)
|
||||||
|
expect([...order].sort()).toEqual(['ex-add4', 'ex-and', 'ex-fa', 'ex-ha', 'ex-not', 'ex-or', 'ex-xor'])
|
||||||
|
const get = lookup(p)
|
||||||
|
for (const [i, id] of order.entries()) {
|
||||||
|
for (const n of get(id)!.nodes) if (n.kind === 'chip') expect(order.indexOf(n.chip!), `${id} uses ${n.chip}`).toBeLessThan(i)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries the connector types its ports use, without challenge marks', () => {
|
||||||
|
const p = adasProject()
|
||||||
|
p.connectors!.push({ id: 'k2', name: 'Unused', lines: [{ name: 'X' }] })
|
||||||
|
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
|
||||||
|
const b = libraryBundle(p, 'csend')
|
||||||
|
expect(b.root).toBe('csend')
|
||||||
|
expect(b.components.map(d => d.id)).toEqual(['ex-xor', 'csend'])
|
||||||
|
expect(b.connectors?.map(c => c.id)).toEqual(['k1'])
|
||||||
|
expect(b.components.some(d => d.challenge)).toBe(false)
|
||||||
|
// The project itself keeps its marks.
|
||||||
|
expect(p.components.find(d => d.id === 'ex-xor')!.challenge).toBe('xor')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps challenges and puzzle solutions private, at any depth', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
|
||||||
|
expect(publishProblem(p, not.id)).toMatch(/private/)
|
||||||
|
expect(publishProblem(p, 'ex-add4')).toBeNull()
|
||||||
|
// A solution anywhere inside stays private too, a challenge's or a puzzle's.
|
||||||
|
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
|
||||||
|
expect(publishProblem(p, 'ex-add4')).toMatch(/challenge "XOR"/)
|
||||||
|
p.components.find(d => d.id === 'ex-xor')!.challenge = 'pz:abc123'
|
||||||
|
expect(publishProblem(p, 'ex-add4')).toMatch(/puzzle "XOR"/)
|
||||||
|
p.components.push({ id: 'empty', name: 'Empty', symbol: 'box', nodes: [], wires: [] })
|
||||||
|
expect(publishProblem(p, 'empty')).toMatch(/nothing/)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not publish a solved challenge wrapped in a component of its own', () => {
|
||||||
|
const p = createProject({ examples: false, campaign: true })
|
||||||
|
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
|
||||||
|
not.nodes.push({ id: 'g', kind: 'nand', x: 8, y: 0 })
|
||||||
|
p.solved.push('not')
|
||||||
|
p.components.push({ id: 'wrap', name: 'Wrap', symbol: 'box', nodes: [{ id: 'c', kind: 'chip', chip: not.id, x: 0, y: 0 }], wires: [] })
|
||||||
|
expect(publishProblem(p, 'wrap')).toMatch(/challenge "NOT", which stays private/)
|
||||||
|
expect(publishProblem(p, not.id)).toMatch(/private/)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('library: checks on the server', () => {
|
||||||
|
it('keeps only what the component uses and counts it honestly', () => {
|
||||||
|
const p = adasProject()
|
||||||
|
const raw = { ...libraryBundle(p, 'csend'), components: p.components }
|
||||||
|
const b = cleanBundle(JSON.parse(JSON.stringify(raw)))
|
||||||
|
expect(b.components.map(d => d.id)).toEqual(closure(lookup(p), 'csend').map(d => d.id))
|
||||||
|
const meta = describeBundle(b)
|
||||||
|
expect(meta.transistors).toBe(nandCounts(p.components).get('csend')! * 4)
|
||||||
|
expect(meta).toMatchObject({ name: 'Sender', inputs: 2, outputs: 0, inNames: ['A', 'B'], outNames: [], uses: 1, connectors: 1 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the listing small whatever is sent', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-not')))
|
||||||
|
const root = b.components.find((d: ComponentDef) => d.id === 'ex-not')
|
||||||
|
root.group = 'g'.repeat(50_000)
|
||||||
|
root.description = 'd'.repeat(50_000)
|
||||||
|
root.nodes.find((n: { kind: string }) => n.kind === 'input').label = 'x'.repeat(500_000)
|
||||||
|
for (let i = 0; i < 200; i++) root.nodes.push({ id: `o${i}`, kind: 'output', x: 30, y: i, label: 'y'.repeat(1000) })
|
||||||
|
const clean = cleanBundle(b)
|
||||||
|
expect(clean.components.find(d => d.id === 'ex-not')!.group).toHaveLength(LIBRARY_LIMITS.group)
|
||||||
|
const meta = describeBundle(clean)
|
||||||
|
expect(meta).toMatchObject({ inputs: 1, outputs: 201 })
|
||||||
|
expect(meta.outNames).toHaveLength(LIBRARY_LIMITS.pinNames)
|
||||||
|
expect(meta.inNames[0]).toHaveLength(LIBRARY_LIMITS.pinName)
|
||||||
|
expect(JSON.stringify(meta).length).toBeLessThan(2000)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops corner points a wire could not be drawn with', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const b = JSON.parse(JSON.stringify(libraryBundle(p, 'ex-ha')))
|
||||||
|
const ha = b.components.find((d: ComponentDef) => d.id === 'ex-ha')
|
||||||
|
const bent = ha.wires.filter((x: Wire) => x.pts)
|
||||||
|
expect(bent.length).toBeGreaterThan(1)
|
||||||
|
bent[0].pts = [null]
|
||||||
|
bent[1].pts = [[1, 'x']]
|
||||||
|
const clean = cleanBundle(b).components.find(d => d.id === 'ex-ha')!
|
||||||
|
expect(clean.wires.find(x => x.id === bent[0].id)!.pts).toBeUndefined()
|
||||||
|
expect(clean.wires.find(x => x.id === bent[1].id)!.pts).toBeUndefined()
|
||||||
|
// Corners that are fine stay, as in projects loaded from a file or link.
|
||||||
|
expect(clean.wires.filter(x => x.pts)).toHaveLength(bent.length - 2)
|
||||||
|
expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'ex-ha')!.wires).toEqual(p.components.find(d => d.id === 'ex-ha')!.wires)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses missing parts, parts that contain themselves and broken nodes', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const b = libraryBundle(p, 'ex-ha')
|
||||||
|
expect(() => cleanBundle({ ...b, components: b.components.filter(d => d.id !== 'ex-xor') })).toThrow(/Missing component/)
|
||||||
|
const loop = JSON.parse(JSON.stringify(b))
|
||||||
|
loop.components.find((d: ComponentDef) => d.id === 'ex-xor').nodes.push({ id: 'me', kind: 'chip', chip: 'ex-ha', x: 0, y: 9 })
|
||||||
|
expect(() => cleanBundle(loop)).toThrow(/contains itself/)
|
||||||
|
const broken = JSON.parse(JSON.stringify(b))
|
||||||
|
broken.components[0].nodes[0].x = 'left'
|
||||||
|
expect(() => cleanBundle(broken)).toThrow(/broken/)
|
||||||
|
expect(() => cleanBundle({ root: 'nope', components: b.components })).toThrow(/missing/)
|
||||||
|
expect(() => cleanBundle('hello')).toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
/** Components l0 … l<depth>, each holding `n` of the one below; l0 is one NAND. */
|
||||||
|
function tower(depth: number, n: number) {
|
||||||
|
const components: ComponentDef[] = [{ id: 'l0', name: 'L0', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] }]
|
||||||
|
for (let i = 1; i <= depth; i++) {
|
||||||
|
const nodes = Array.from({ length: n }, (_, k) => ({ id: `c${k}`, kind: 'chip' as const, chip: `l${i - 1}`, x: 0, y: 4 * k }))
|
||||||
|
components.push({ id: `l${i}`, name: `L${i}`, symbol: 'box', nodes, wires: [] })
|
||||||
|
}
|
||||||
|
return { root: `l${depth}`, components }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('refuses nesting deeper than the simulator goes, and parts too huge to run, without building them', () => {
|
||||||
|
expect(() => cleanBundle(tower(63, 1))).not.toThrow()
|
||||||
|
expect(() => cleanBundle(tower(64, 1))).toThrow(/Nesting deeper than 64/)
|
||||||
|
// 10^12 NANDs once opened up: refused at once.
|
||||||
|
const t = performance.now()
|
||||||
|
expect(() => cleanBundle(tower(12, 10))).toThrow(/Too large to run/)
|
||||||
|
expect(performance.now() - t).toBeLessThan(1000)
|
||||||
|
expect(describeBundle(cleanBundle(tower(6, 10))).transistors).toBe(4_000_000)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('library: adding an entry to a project', () => {
|
||||||
|
it('brings everything with new ids, wired to each other, computing the same', () => {
|
||||||
|
const ada = adasProject()
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const res = importBundle(bob, published(ada, 'csend'), origin)
|
||||||
|
expect(res.added).toBe(closure(lookup(ada), 'csend').length)
|
||||||
|
const root = bob.components.find(d => d.id === res.root)!
|
||||||
|
expect(root.name).toBe('Sender')
|
||||||
|
expect(root.id).not.toBe('csend')
|
||||||
|
// Every component it uses is here, under its new id.
|
||||||
|
const get = lookup(bob)
|
||||||
|
for (const d of closure(get, root.id)) for (const n of d.nodes) if (n.kind === 'chip') expect(get(n.chip!), n.chip).toBeTruthy()
|
||||||
|
expect(closure(get, root.id)).toHaveLength(res.added)
|
||||||
|
expect(nandCounts(bob.components).get(root.id)).toBe(nandCounts(ada.components).get('csend'))
|
||||||
|
const xor = closure(get, root.id).find(d => d.name === 'XOR')!
|
||||||
|
expect(rows(bob, xor.id)).toEqual(rows(ada, 'ex-xor'))
|
||||||
|
// The connector type came along and the port uses it.
|
||||||
|
expect(bob.connectors).toEqual([{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }])
|
||||||
|
expect(root.nodes.find(n => n.kind === 'portout')!.conn).toBe('k1')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks the entry, and what came along with it', () => {
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-ha'), origin)
|
||||||
|
const added = bob.components.slice(-res.added)
|
||||||
|
expect(added.find(d => d.id === res.root)!.from).toEqual(origin)
|
||||||
|
for (const d of added.filter(d => d.id !== res.root)) expect(d.from).toEqual({ ...origin, inside: true })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('makes a copy of an added component your own, without the mark', () => {
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-xor'), origin)
|
||||||
|
expect(duplicateComponent(bob, res.root)!.from).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks what comes in only by the entry it came with, never by marks the publisher sent', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
ada.components.find(d => d.id === 'ex-xor')!.from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
||||||
|
expect(libraryBundle(ada, 'ex-ha').components.some(d => d.from)).toBe(false)
|
||||||
|
// Eve sends a part claiming to be Cy's entry; the server drops the claim.
|
||||||
|
const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-ha')))
|
||||||
|
forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
||||||
|
const b = cleanBundle(forged)
|
||||||
|
expect(b.components.some(d => d.from)).toBe(false)
|
||||||
|
// And adding never keeps a mark that came with the bundle.
|
||||||
|
forged.components[0].from = { id: 'Xor00001', version: 3, author: 'Cy' }
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
importBundle(bob, forged, origin)
|
||||||
|
for (const d of bob.components.filter(d => d.from)) expect(d.from!.id).toBe(origin.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('uses what is here in the same form, and adds nothing for the same entry twice', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: true })
|
||||||
|
const before = bob.components.length
|
||||||
|
// Bob has the examples: the half adder and all it uses are his already.
|
||||||
|
const first = importBundle(bob, published(ada, 'ex-ha'), origin)
|
||||||
|
expect(first).toEqual({ root: 'ex-ha', added: 0 })
|
||||||
|
expect(bob.components).toHaveLength(before)
|
||||||
|
|
||||||
|
const carl = createProject({ examples: false })
|
||||||
|
const a = importBundle(carl, published(ada, 'ex-fa'), origin)
|
||||||
|
const again = importBundle(carl, published(ada, 'ex-fa'), { ...origin, version: 2 })
|
||||||
|
expect(again).toEqual({ root: a.root, added: 0 })
|
||||||
|
expect(carl.components.find(d => d.id === a.root)!.from).toEqual({ ...origin, version: 2 })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gives a name that is taken by something else a number', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: true })
|
||||||
|
// Bob's NOT differs from Ada's: hers comes in as "NOT 2", with what uses it pointing at hers.
|
||||||
|
ada.components.find(d => d.id === 'ex-not')!.nodes[0]!.x += 1
|
||||||
|
const res = importBundle(bob, published(ada, 'ex-and'), origin)
|
||||||
|
expect(res.added).toBe(2)
|
||||||
|
const and = bob.components.find(d => d.id === res.root)!
|
||||||
|
expect(and.name).toBe('AND 2')
|
||||||
|
const not = bob.components.find(d => d.id === and.nodes.find(n => n.kind === 'chip')!.chip)!
|
||||||
|
expect(not.name).toBe('NOT 2')
|
||||||
|
expect(not.id).not.toBe('ex-not')
|
||||||
|
expect(rows(bob, and.id)).toEqual(rows(ada, 'ex-and'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('joins connector types with the same lines, and keeps different ones apart', () => {
|
||||||
|
const ada = adasProject()
|
||||||
|
const same = createProject({ examples: true })
|
||||||
|
same.connectors = [{ id: 'mine', name: 'link', lines: [{ name: 'D0' }, { name: 'D1' }] }]
|
||||||
|
const a = importBundle(same, published(ada, 'csend'), origin)
|
||||||
|
expect(same.connectors).toHaveLength(1)
|
||||||
|
expect(same.components.find(d => d.id === a.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe('mine')
|
||||||
|
|
||||||
|
const other = createProject({ examples: true })
|
||||||
|
other.connectors = [{ id: 'k1', name: 'Link', lines: [{ name: 'TX' }, { name: 'RX', back: true }] }]
|
||||||
|
const b = importBundle(other, published(ada, 'csend'), origin)
|
||||||
|
expect(other.connectors).toHaveLength(2)
|
||||||
|
const added = other.connectors[1]!
|
||||||
|
expect(added.id).not.toBe('k1')
|
||||||
|
expect(added.name).toBe('Link 2')
|
||||||
|
expect(other.components.find(d => d.id === b.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe(added.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('updates a component in place to a newer version, where it is used too', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const v1 = importBundle(bob, published(ada, 'ex-and'), origin)
|
||||||
|
const main = bob.components.find(d => d.id === 'main')!
|
||||||
|
main.nodes.push({ id: 'u', kind: 'chip', chip: v1.root, x: 10, y: 10 })
|
||||||
|
// Version 2: AND became OR (same pins), now built from Ada's OR.
|
||||||
|
const and = ada.components.find(d => d.id === 'ex-and')!
|
||||||
|
const or = ada.components.find(d => d.id === 'ex-or')!
|
||||||
|
and.nodes = structuredClone(or.nodes)
|
||||||
|
and.wires = structuredClone(or.wires)
|
||||||
|
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, v1.root)
|
||||||
|
expect(v2.root).toBe(v1.root)
|
||||||
|
const updated = bob.components.find(d => d.id === v1.root)!
|
||||||
|
expect(updated.name).toBe('AND')
|
||||||
|
expect(updated.from).toEqual({ ...origin, version: 2 })
|
||||||
|
expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-or'))
|
||||||
|
expect(main.nodes.find(n => n.id === 'u')!.chip).toBe(v1.root)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clears away what came along with the old version, and the new parts take its names', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
|
||||||
|
const oldXor = bob.components.find(d => d.name === 'XOR')!
|
||||||
|
// Version 2: Ada drew her XOR differently.
|
||||||
|
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
||||||
|
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
|
||||||
|
expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
|
||||||
|
expect(bob.components.some(d => d.id === oldXor.id)).toBe(false)
|
||||||
|
expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-ha'))
|
||||||
|
// Updated again: still no "XOR 2".
|
||||||
|
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
||||||
|
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 3 }, v1.root)
|
||||||
|
expect(bob.components.map(d => d.name).sort()).toEqual(['AND', 'Half Adder', 'Main', 'NOT', 'XOR'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps an old part that is used elsewhere', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const v1 = importBundle(bob, published(ada, 'ex-ha'), origin)
|
||||||
|
const oldXor = bob.components.find(d => d.name === 'XOR')!
|
||||||
|
bob.components.find(d => d.id === 'main')!.nodes.push({ id: 'x', kind: 'chip', chip: oldXor.id, x: 20, y: 0 })
|
||||||
|
ada.components.find(d => d.id === 'ex-xor')!.nodes[0]!.y += 1
|
||||||
|
importBundle(bob, published(ada, 'ex-ha'), { ...origin, version: 2 }, v1.root)
|
||||||
|
expect(bob.components.find(d => d.id === oldXor.id)!.name).toBe('XOR')
|
||||||
|
expect(bob.components.some(d => d.name === 'XOR 2')).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('never reuses another entry’s component, so updating one entry leaves the others as they were', () => {
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
// Bob has Ada's XOR entry; Carl's half adder holds an XOR exactly like it.
|
||||||
|
const xor = importBundle(bob, published(ada, 'ex-xor'), origin)
|
||||||
|
const carl = importBundle(bob, published(ada, 'ex-ha'), { id: 'Carl0001', version: 1, author: 'Carl' })
|
||||||
|
const carlsXor = closure(lookup(bob), carl.root).find(d => d.name.startsWith('XOR'))!
|
||||||
|
expect(carlsXor.id).not.toBe(xor.root)
|
||||||
|
expect(carlsXor.from).toEqual({ id: 'Carl0001', version: 1, author: 'Carl', inside: true })
|
||||||
|
// Ada's XOR, version 2, is an OR now: Carl's half adder still adds.
|
||||||
|
const v2 = createProject({ examples: true })
|
||||||
|
const x = v2.components.find(d => d.id === 'ex-xor')!
|
||||||
|
const or = v2.components.find(d => d.id === 'ex-or')!
|
||||||
|
Object.assign(x, { nodes: structuredClone(or.nodes), wires: structuredClone(or.wires) })
|
||||||
|
importBundle(bob, published(v2, 'ex-xor'), { ...origin, version: 2 }, xor.root)
|
||||||
|
expect(rows(bob, xor.root)).toEqual(rows(ada, 'ex-or'))
|
||||||
|
expect(rows(bob, carl.root)).toEqual(rows(ada, 'ex-ha'))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('never reuses the component being updated inside its own new version', () => {
|
||||||
|
const bob = createProject({ examples: false })
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
// The entry was Ada's NOT; its next version is her AND, which uses a NOT exactly like the one Bob has.
|
||||||
|
const res = importBundle(bob, published(ada, 'ex-not'), origin)
|
||||||
|
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, res.root)
|
||||||
|
const get = lookup(bob)
|
||||||
|
expect(closure(get, v2.root).filter(d => d.id === v2.root)).toHaveLength(1)
|
||||||
|
expect(get(v2.root)!.nodes.some(n => n.chip === v2.root)).toBe(false)
|
||||||
|
expect(rows(bob, v2.root)).toEqual(rows(ada, 'ex-and'))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('library: campaign and old projects', () => {
|
||||||
|
it('adds nothing to a campaign, however far it is', () => {
|
||||||
|
const campaign = createProject({ examples: false, campaign: true })
|
||||||
|
expect(importProblem(campaign)).toMatch(/campaign/)
|
||||||
|
campaign.solved.push(...CHALLENGES.map(c => c.id))
|
||||||
|
expect(importProblem(campaign)).toMatch(/campaign/)
|
||||||
|
expect(importProblem(createProject({ examples: true }))).toBeNull()
|
||||||
|
expect(importProblem({ ...createProject({ examples: false }), mode: 'challenges' })).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('loads projects without library marks as before, and drops broken marks', () => {
|
||||||
|
const p = createProject({ examples: true })
|
||||||
|
const plain = toProject(JSON.parse(JSON.stringify(p)))
|
||||||
|
expect(plain.components.some(d => 'from' in d)).toBe(false)
|
||||||
|
expect(plain).toEqual(JSON.parse(JSON.stringify(p)))
|
||||||
|
const marked = JSON.parse(JSON.stringify(p))
|
||||||
|
marked.components[1].from = { id: 'Lib12345', version: 2, author: 'Ada', inside: true, extra: 1 }
|
||||||
|
marked.components[2].from = { id: '../etc', version: 1, author: 'x' }
|
||||||
|
marked.components[3].from = { id: 'Lib12345', version: 0 }
|
||||||
|
const q = parseProject(JSON.stringify(marked))
|
||||||
|
expect(q.components[1]!.from).toEqual({ id: 'Lib12345', version: 2, author: 'Ada', inside: true })
|
||||||
|
expect(q.components[2]!.from).toBeUndefined()
|
||||||
|
expect(q.components[3]!.from).toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('library keys in the browser', () => {
|
||||||
|
it('keeps what was published from here, and reads anything broken as nothing', () => {
|
||||||
|
const map = new Map<string, string>()
|
||||||
|
globalThis.localStorage = { getItem: k => map.get(k) ?? null, setItem: (k, v) => void map.set(k, v), removeItem: k => void map.delete(k) } as Storage
|
||||||
|
expect(libraryKeys()).toEqual({})
|
||||||
|
setLibraryKey('Lib12345', { key: 'secret', project: 'p1', def: 'c1' })
|
||||||
|
setLibraryKey('Lib67890', { key: 'other', project: 'p1', def: 'c2' })
|
||||||
|
setLibraryKey('Lib67890', null)
|
||||||
|
expect(libraryKeys()).toEqual({ Lib12345: { key: 'secret', project: 'p1', def: 'c1' } })
|
||||||
|
map.set('logigate:library-keys', '[1, 2]')
|
||||||
|
expect(libraryKeys()).toEqual({})
|
||||||
|
map.set('logigate:library-keys', 'not json')
|
||||||
|
expect(libraryKeys()).toEqual({})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('owns an entry only where it was published from, whatever a component’s mark says', () => {
|
||||||
|
const keys = { Lib12345: { key: 'secret', project: 'p1', def: 'c1' } }
|
||||||
|
expect(ownedEntry(keys, 'p1', 'c1')).toBe('Lib12345')
|
||||||
|
// The same component in another project, or another component here, is not it.
|
||||||
|
expect(ownedEntry(keys, 'p2', 'c1')).toBeUndefined()
|
||||||
|
expect(ownedEntry(keys, 'p1', 'c2')).toBeUndefined()
|
||||||
|
// A part that came in claiming to be Ada's entry stays someone else's: adding
|
||||||
|
// Eve's entry marks it as Eve's, and only the key record counts anyway.
|
||||||
|
const ada = createProject({ examples: true })
|
||||||
|
const forged = JSON.parse(JSON.stringify(libraryBundle(ada, 'ex-and')))
|
||||||
|
forged.components[0].from = { id: 'Lib12345', version: 1, author: 'Ada' }
|
||||||
|
const p = createProject({ examples: false })
|
||||||
|
const res = importBundle(p, cleanBundle(forged), { id: 'Eve00001', version: 1, author: 'Eve' })
|
||||||
|
for (const d of closure(lookup(p), res.root)) {
|
||||||
|
expect(d.from!.id).toBe('Eve00001')
|
||||||
|
expect(ownedEntry(keys, 'p1', d.id)).toBeUndefined()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('library listing', () => {
|
||||||
|
const item = (id: string, name: string, updated: number, player: string, description = ''): LibraryItem => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
group: '',
|
||||||
|
version: 1,
|
||||||
|
created: 0,
|
||||||
|
updated,
|
||||||
|
transistors: 8,
|
||||||
|
inputs: 1,
|
||||||
|
outputs: 1,
|
||||||
|
inNames: ['A'],
|
||||||
|
outNames: ['Q'],
|
||||||
|
uses: 0,
|
||||||
|
connectors: 0,
|
||||||
|
player,
|
||||||
|
})
|
||||||
|
const names = { 'player-ada-0001': 'Ada' }
|
||||||
|
const list = [item('a1', 'Adder 8', 10, 'player-ada-0001', 'ripple carry'), item('a2', 'ALU', 30, 'player-bob-0002'), item('a3', 'Shifter', 20, 'player-ada-0001')].map(m =>
|
||||||
|
publicMeta(m, names),
|
||||||
|
)
|
||||||
|
|
||||||
|
it('shows authors by their name, never their player id', () => {
|
||||||
|
expect(list[0]!.author).toBe('Ada')
|
||||||
|
expect(list[1]!.author).toBe('')
|
||||||
|
expect(JSON.stringify(list)).not.toContain('player-')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finds every word in name, description or author, newest first', () => {
|
||||||
|
expect(searchLibrary(list, '').map((m: LibraryMeta) => m.id)).toEqual(['a2', 'a3', 'a1'])
|
||||||
|
expect(searchLibrary(list, 'ada').map(m => m.id)).toEqual(['a3', 'a1'])
|
||||||
|
expect(searchLibrary(list, 'Carry ADA').map(m => m.id)).toEqual(['a1'])
|
||||||
|
expect(searchLibrary(list, 'nothing')).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue