A right panel in tabs, Pins list, bulk editing, transistor breakdown, Settings dialog
- Right panel tabs: Selection, Circuit, Pins, Test. Display and sound preferences move to a Settings dialog (gear in the top bar). - Pins tab: every input and output in pin order with live values; rename in place (Enter goes to the next), number a whole side from a pattern, flag duplicate names, centre the canvas on a part. - Several selected parts: narrow by type, swap all, rename all from a pattern, set switches to 0/1 or flip, shared colour/frequency/size, align and spread. - Transistors on every part (NAND 4, switches and lamps 0), NAND 4T in the palette, and a per-part breakdown of the circuit. Test: the count equals 4 x the gates the simulator builds, for every example and wide gate. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
acb9620b2b
commit
74b257ce6e
|
|
@ -11,7 +11,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)).
|
||||
- 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.
|
||||
- Sound (speaker in the top bar; volume and clock ticks under Display): 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.
|
||||
- Cables: a bundle gathers 2 to 32 wires into one thick cable, a split fans it out again in the same order; one bundle can feed several splits. Select some wires and press "Bundle into cable" to have both ends placed for you (the cable takes the wires' colour); "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
|
||||
- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen".
|
||||
|
|
@ -19,12 +19,15 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
|
|||
- Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. On the canvas, a switch, button, clock, lamp or output pin without a name typed by hand shows the name of the component pin it is wired to, dimmed and in italics (or its automatic name, also dimmed); the name follows the wiring as it changes.
|
||||
- Every circuit is a component. Its input and output nodes become its pins, ordered top to bottom. Double-click a component to open it.
|
||||
- Lamps and hex displays inside a component show on its box, with their labels, lit by that instance's state. They are laid out in rows the way they sit inside. A checkbox in the inspector turns this off per component.
|
||||
- The right panel has four tabs. **Selection**: settings of what you clicked (switches to it when you select something on an idle panel). **Circuit**: name, symbol, group, statistics, and where the transistors are (each kind of part with its count; click a line to select those parts). **Pins**: every input and output of the circuit in pin order with its live value; rename in place (Enter goes to the next), "Number all" names a whole side from a pattern (D# → D0, D1, …), duplicate names are flagged, the target icon centres the canvas on a part. **Test**: the challenge or puzzle check and the truth table (opens by itself for a challenge). Display and sound preferences are in Settings (gear in the top bar).
|
||||
- Several selected parts are edited together: chips to narrow the selection by type, swap them all for another part, rename all top to bottom from a pattern, set every switch to 0 or 1 or flip each, one colour, one clock frequency or note size for all, line them up or spread them evenly, plus make component, connect one by one, unlink, duplicate, delete.
|
||||
- Transistors: every part shows its count (4 for a NAND, 0 for switches, lamps and cables, the whole inside for a component; the NAND in the palette shows 4T). The count is 4 per CMOS NAND gate the simulator builds, at every depth; a test checks this against the flattened circuit for every example and every wide gate.
|
||||
- Clicking anything opens its settings on the right. Parts can be swapped in place (wires stay on the pins in the same position): NAND and components with each other, switch/button/clock/constants with each other, output/lamp/display with each other. Clocks have their own frequency or follow the top bar. Switches and buttons can get a keyboard key. Lamps and displays have colours, notes have sizes, components a name on the canvas. Components can be unpacked into their parts or given their own copy of the definition; any part can have all its wires unlinked.
|
||||
- Select parts and press "Make component" to turn them into a new component; wires crossing the selection become pins.
|
||||
- Gate symbols in IEC 60617 (DIN, default) or ANSI. A component with one output can be drawn as a gate symbol.
|
||||
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Display settings on the right with nothing selected). Clicking a junction dot selects its whole signal.
|
||||
- Wires of different signals never share a line: auto-routed wires pick a free column or a detour, and anything still clashing (hand-placed bends) is drawn on its own lane. Crossings are drawn as a bow, triangle, bridge, gap or plain crossing (Settings, the gear in the top bar). Clicking a junction dot selects its whole signal.
|
||||
- Connecting: drag from a pin, or click a pin and then the other one. While a wire is drawn, every pin it can go to is ringed (dashed when it already has a wire, which would be replaced); dropping it on a part uses that part's next free pin. "Connect one by one" (W, or the button with several parts selected; on a component "Wire one by one: Inputs / Outputs") numbers the pins of the selection top to bottom and wires them in turn, one click each; clicking the same component again and again fills its pins in order.
|
||||
- Tidy wiring (Display settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
|
||||
- Tidy wiring (Settings, or "Tidy all wires", which also drops hand-placed bends): every forward wire takes its vertical step in the free gap right in front of the part it feeds. All wires entering parts at the same column are ordered together (each goes where it adds the fewest crossings) and laid out as one compact staircase a grid step apart, slid sideways to where it runs along no other signal; one signal shares one trunk. Only the columns of that gap are looked at, so it stays cheap. On the 4-bit adder without hand routing this cuts crossings from 32 to 18.
|
||||
- Wire editing: drag any segment (a stub keeps the pin end straight), drag corner squares, Alt+drag to pull out a new bend, Ctrl+drag to branch a new wire off a signal, double-click to select the whole signal, Shift+click and box selection for several wires, arrow keys to shift them, six colour tags.
|
||||
- Several projects per browser (Projects dialog: open, rename, duplicate, delete). Export a project file, open a file as a new project, or add the components of a file to the open project.
|
||||
- Accounts: email and password. Signed in, every project in the browser is also kept in the account and synced in both directions (on sign-in, on focus, every minute, and two seconds after a change). If two computers changed the same project, both versions are kept. The untouched starter project of a new browser is not uploaded; signing in there opens your latest project instead.
|
||||
|
|
|
|||
|
|
@ -1700,7 +1700,8 @@ kbd {
|
|||
flex: 0 0 56px;
|
||||
}
|
||||
|
||||
.challenge .score {
|
||||
.challenge .score,
|
||||
.inspector .score {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
|
|
@ -1709,7 +1710,8 @@ kbd {
|
|||
color: var(--muted);
|
||||
}
|
||||
|
||||
.challenge .score strong {
|
||||
.challenge .score strong,
|
||||
.inspector .score strong {
|
||||
color: var(--on);
|
||||
}
|
||||
|
||||
|
|
@ -1801,3 +1803,287 @@ kbd {
|
|||
font-style: italic;
|
||||
opacity: 0.75;
|
||||
}
|
||||
|
||||
/* ── Right panel tabs ───────────────────────────────────────────── */
|
||||
.itabs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
border-bottom: 1px solid var(--border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.itabs button {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 7px 2px 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
|
||||
.itabs button:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.itabs button.active {
|
||||
color: var(--text);
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
|
||||
.itabs button.task:not(.active) {
|
||||
color: var(--lamp);
|
||||
}
|
||||
|
||||
.itabs .badge {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
right: calc(50% - 22px);
|
||||
min-width: 16px;
|
||||
padding: 0 4px;
|
||||
border-radius: 999px;
|
||||
background: rgb(76 194 255 / 0.18);
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 9px;
|
||||
line-height: 14px;
|
||||
}
|
||||
|
||||
.empty-pane {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 6px;
|
||||
padding: 32px 18px !important;
|
||||
text-align: center;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.empty-pane .hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Transistor breakdown ───────────────────────────────────────── */
|
||||
.cost {
|
||||
width: 100%;
|
||||
margin-top: 8px;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.cost td {
|
||||
padding: 4px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.cost tbody tr {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cost tbody tr:hover {
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.cost .num {
|
||||
text-align: right;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cost .strong {
|
||||
color: var(--text);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cost tfoot td {
|
||||
border-bottom: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ── Pins list ──────────────────────────────────────────────────── */
|
||||
.count-pill {
|
||||
margin-left: 4px;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--panel-2);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.io-list {
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.io-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 3px 4px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.io-list li:hover {
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.io-list li.selected {
|
||||
border-color: rgb(76 194 255 / 0.5);
|
||||
background: rgb(76 194 255 / 0.07);
|
||||
}
|
||||
|
||||
.io-value {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 5px;
|
||||
background: var(--panel-2);
|
||||
color: var(--muted);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.io-value.on {
|
||||
background: var(--on-dim);
|
||||
color: var(--on);
|
||||
}
|
||||
|
||||
.io-main {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.io-name {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 3px 6px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
background: transparent;
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.io-name:hover {
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.io-name:focus {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.io-name::placeholder {
|
||||
color: var(--muted);
|
||||
font-weight: 400;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.io-kind {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding-left: 7px;
|
||||
font-size: 10.5px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.io-list li.dup .io-kind {
|
||||
color: var(--lamp);
|
||||
}
|
||||
|
||||
.numbering {
|
||||
margin: 4px 0 12px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
/* ── Bulk editing ───────────────────────────────────────────────── */
|
||||
.type-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.type-chip {
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.type-chip span {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.type-chip:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.arrange {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, 1fr);
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.arrange .icon-btn {
|
||||
width: 100%;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.arrange .icon-btn:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
width: 100%;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 6px 8px;
|
||||
font-size: 13px;
|
||||
color: var(--text);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.text-input:focus {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.tips-box {
|
||||
margin-top: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.tips-box summary {
|
||||
cursor: pointer;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.field small.hint {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.inspector h3 + .score {
|
||||
margin-top: -4px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,5 +46,6 @@ onMounted(() => {
|
|||
<EditorShareDialog v-if="ed.dialog.value === 'share'" />
|
||||
<EditorAccountDialog v-if="ed.dialog.value === 'account'" />
|
||||
<EditorVersionsDialog v-if="ed.dialog.value === 'versions'" />
|
||||
<EditorSettingsDialog v-if="ed.dialog.value === 'settings'" />
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,223 @@
|
|||
<script setup lang="ts">
|
||||
// Settings for several selected parts at once: one change, all of them.
|
||||
import { byPosition, numberedNames, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
|
||||
import { KIND_NAMES } from '~/lib/logic/progress'
|
||||
import { LAMP_COLORS, type LampColor, type NodeKind } from '~/lib/logic/types'
|
||||
|
||||
const ed = useEditor()
|
||||
|
||||
const nodes = computed(() => {
|
||||
const set = new Set(ed.selection.value)
|
||||
return ed.def.value.nodes.filter(n => set.has(n.id))
|
||||
})
|
||||
const ids = computed(() => nodes.value.map(n => n.id))
|
||||
const wires = ed.selectedWires
|
||||
const kinds = computed(() => new Set(nodes.value.map(n => n.kind)))
|
||||
const only = (...ks: NodeKind[]) => nodes.value.length > 0 && [...kinds.value].every(k => ks.includes(k))
|
||||
|
||||
/** The selection by type, biggest group first: click one to keep only those. */
|
||||
const groups = computed(() => {
|
||||
const map = new Map<string, { key: string; name: string; ids: string[] }>()
|
||||
for (const n of nodes.value) {
|
||||
const key = typeKey(n)
|
||||
const name = n.kind === 'chip' ? (n.chip && ed.getDef.value(n.chip)?.name) || 'Missing component' : KIND_NAMES[n.kind] ?? n.kind
|
||||
const g = map.get(key) ?? { key, name, ids: [] }
|
||||
g.ids.push(n.id)
|
||||
map.set(key, g)
|
||||
}
|
||||
return [...map.values()].sort((a, b) => b.ids.length - a.ids.length || a.name.localeCompare(b.name))
|
||||
})
|
||||
|
||||
const transistors = computed(() => nodes.value.reduce((sum, n) => sum + ed.transistorsOfNode(n), 0))
|
||||
|
||||
// ── Change all to ───────────────────────────────────────────────────
|
||||
const family = computed(() => sharedFamily(nodes.value))
|
||||
const currentType = computed(() => (groups.value.length === 1 ? groups.value[0]!.key : ''))
|
||||
const familyKinds = computed<NodeKind[]>(() => (family.value === 'source' ? SOURCE_KINDS : family.value === 'sink' ? SINK_KINDS : []))
|
||||
const swapGroups = computed(() => {
|
||||
const map = new Map<string, { id: string; label: string; ok: boolean }[]>()
|
||||
for (const d of ed.project.value.components) {
|
||||
const p = chipPins(d)
|
||||
const g = d.group?.trim() || 'My components'
|
||||
if (!map.has(g)) map.set(g, [])
|
||||
map.get(g)!.push({ id: d.id, label: `${d.name} (${p.inputs.length} → ${p.outputs.length})`, ok: ed.canPlace(d.id) })
|
||||
}
|
||||
return [...map.entries()]
|
||||
})
|
||||
|
||||
function onSwap(e: Event) {
|
||||
const v = (e.target as HTMLSelectElement).value
|
||||
if (!v || v === currentType.value) return
|
||||
ed.swapMany(ids.value, v.startsWith('chip:') ? { kind: 'chip', chip: v.slice(5) } : { kind: v as NodeKind })
|
||||
}
|
||||
|
||||
// ── Rename all ──────────────────────────────────────────────────────
|
||||
const labelable = computed(() => nodes.value.every(n => !['high', 'low', 'nand', 'bundle', 'split', 'pixel'].includes(n.kind)))
|
||||
const pattern = ref('')
|
||||
const start = ref(0)
|
||||
const ordered = computed(() => [...nodes.value].sort(byPosition))
|
||||
const preview = computed(() => (pattern.value.trim() ? numberedNames(pattern.value, ordered.value.length, start.value) : []))
|
||||
function rename() {
|
||||
ed.renameMany(ids.value, pattern.value, start.value)
|
||||
pattern.value = ''
|
||||
}
|
||||
|
||||
// ── Switches, colours, clocks, notes ────────────────────────────────
|
||||
const switches = computed(() => nodes.value.filter(n => n.kind === 'input'))
|
||||
const switchesOn = computed(() => switches.value.filter(n => n.on).length)
|
||||
const colorable = computed(() => only('lamp', 'hex', 'pixel'))
|
||||
const color = computed(() => {
|
||||
const set = new Set(nodes.value.map(n => n.color ?? ''))
|
||||
return set.size === 1 ? [...set][0] : null
|
||||
})
|
||||
function setColor(c: LampColor | undefined) {
|
||||
ed.patchMany(ids.value, { color: c })
|
||||
}
|
||||
|
||||
const clocks = computed(() => only('clock'))
|
||||
const hzValue = computed(() => {
|
||||
const set = new Set(nodes.value.map(n => n.hz))
|
||||
return set.size === 1 ? [...set][0] : undefined
|
||||
})
|
||||
function setHz(e: Event) {
|
||||
const v = Number((e.target as HTMLInputElement).value)
|
||||
ed.patchMany(ids.value, { hz: v > 0 && v <= 1000 ? v : undefined }, true)
|
||||
}
|
||||
|
||||
const notes = computed(() => only('note'))
|
||||
function setSize(size: 'sm' | 'md' | 'lg') {
|
||||
ed.patchMany(ids.value, { size: size === 'md' ? undefined : size })
|
||||
}
|
||||
|
||||
const ARRANGE: { how: Arrange; icon: string; title: string }[] = [
|
||||
{ how: 'left', icon: 'lucide:align-start-vertical', title: 'Line up on the left' },
|
||||
{ how: 'right', icon: 'lucide:align-end-vertical', title: 'Line up on the right' },
|
||||
{ how: 'top', icon: 'lucide:align-start-horizontal', title: 'Line up at the top' },
|
||||
{ how: 'bottom', icon: 'lucide:align-end-horizontal', title: 'Line up at the bottom' },
|
||||
{ how: 'spread-y', icon: 'lucide:align-vertical-space-around', title: 'Spread evenly top to bottom' },
|
||||
{ how: 'spread-x', icon: 'lucide:align-horizontal-space-around', title: 'Spread evenly left to right' },
|
||||
]
|
||||
|
||||
// ── Make component ──────────────────────────────────────────────────
|
||||
const packName = ref('')
|
||||
function pack() {
|
||||
ed.packageSelected(packName.value || 'Part')
|
||||
packName.value = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3>
|
||||
{{ nodes.length }} part{{ nodes.length === 1 ? '' : 's' }}<template v-if="wires.length">, {{ wires.length }} wire{{ wires.length === 1 ? '' : 's' }}</template> selected
|
||||
</h3>
|
||||
<div v-if="groups.length > 1" class="type-chips">
|
||||
<button v-for="g in groups" :key="g.key" class="type-chip" title="Keep only these selected" @click="ed.selectOnly(g.ids)">
|
||||
{{ g.name }} <span>×{{ g.ids.length }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="score">
|
||||
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||
<span>{{ transistors.toLocaleString() }} transistors in the selection</span>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section v-if="family || labelable || switches.length || colorable || clocks || notes">
|
||||
<h3>Change all</h3>
|
||||
|
||||
<label v-if="family === 'logic'" class="field">
|
||||
<span>Swap all for</span>
|
||||
<select :value="currentType" @change="onSwap">
|
||||
<option v-if="!currentType" value="" disabled>Mixed: pick a part</option>
|
||||
<option value="nand">NAND (2 → 1)</option>
|
||||
<optgroup v-for="[g, defs] in swapGroups" :key="g" :label="g">
|
||||
<option v-for="d in defs" :key="d.id" :value="`chip:${d.id}`" :disabled="!d.ok">{{ d.label }}</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
</label>
|
||||
<label v-else-if="family" class="field">
|
||||
<span>Make them all</span>
|
||||
<select :value="currentType" @change="onSwap">
|
||||
<option v-if="!currentType" value="" disabled>Mixed: pick a type</option>
|
||||
<option v-for="k in familyKinds" :key="k" :value="k">{{ KIND_NAMES[k] }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="family" class="hint -mt-1">Wires stay on the pins in the same position.</p>
|
||||
|
||||
<form v-if="labelable" class="field" @submit.prevent="rename">
|
||||
<span>Rename all, top to bottom</span>
|
||||
<div class="grid grid-cols-[1fr_4.5rem_auto] gap-2">
|
||||
<input v-model="pattern" placeholder="e.g. D# or Reset" title="# becomes a number: D# gives D0, D1, D2" />
|
||||
<input v-model.number="start" type="number" min="0" title="First number" />
|
||||
<button class="btn" type="submit" :disabled="!pattern.trim()">Apply</button>
|
||||
</div>
|
||||
<small v-if="preview.length" class="hint">→ {{ preview.slice(0, 5).join(', ') }}<template v-if="preview.length > 5">, …</template></small>
|
||||
</form>
|
||||
|
||||
<div v-if="switches.length" class="field">
|
||||
<span>Switches: {{ switchesOn }} of {{ switches.length }} on</span>
|
||||
<div class="seg">
|
||||
<button @click="ed.setSwitches(ids, false)">All 0</button>
|
||||
<button @click="ed.setSwitches(ids, true)">All 1</button>
|
||||
<button @click="ed.setSwitches(ids, 'flip')">Flip each</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="colorable" class="field">
|
||||
<span>Colour</span>
|
||||
<div class="swatches">
|
||||
<button class="swatch lamp-swatch default" :class="{ active: color === '' }" title="Default" @click="setColor(undefined)" />
|
||||
<button
|
||||
v-for="c in LAMP_COLORS"
|
||||
:key="c"
|
||||
class="swatch lamp-swatch"
|
||||
:class="[`l-${c}`, { active: color === c }]"
|
||||
:title="c"
|
||||
@click="setColor(c)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label v-if="clocks" class="field">
|
||||
<span>Frequency (Hz), empty follows the top bar</span>
|
||||
<input type="number" min="0.1" max="1000" step="any" :value="hzValue ?? ''" placeholder="top bar" @change="setHz" />
|
||||
</label>
|
||||
|
||||
<div v-if="notes" class="field">
|
||||
<span>Size</span>
|
||||
<div class="seg">
|
||||
<button @click="setSize('sm')">Small</button>
|
||||
<button @click="setSize('md')">Normal</button>
|
||||
<button @click="setSize('lg')">Large</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Arrange</h3>
|
||||
<div class="arrange">
|
||||
<button v-for="a in ARRANGE" :key="a.how" class="icon-btn" :title="a.title" :disabled="nodes.length < 2" @click="ed.arrangeSelected(a.how)">
|
||||
<Icon :name="a.icon" class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h3>Make a component</h3>
|
||||
<p class="hint">Wires that cross the selection border become its pins.</p>
|
||||
<div class="grid grid-cols-[1fr_auto] gap-2">
|
||||
<input v-model="packName" class="text-input" placeholder="e.g. Half Adder" @keydown.enter="pack" />
|
||||
<button class="btn btn-primary" @click="pack"><Icon name="lucide:package" class="size-4" /> Make</button>
|
||||
</div>
|
||||
<button class="btn mt-2 w-full" title="Their pins in order, top to bottom: click where each one goes (W)" @click="ed.startLinking()">
|
||||
<Icon name="lucide:cable" class="size-4" /> Connect one by one
|
||||
</button>
|
||||
<div class="mt-2 grid grid-cols-2 gap-2">
|
||||
<button class="btn" title="Remove every wire attached to the selected parts" @click="ed.unlink(ed.selection.value)"><Icon name="lucide:unlink" class="size-4" /> Unlink all</button>
|
||||
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||
</div>
|
||||
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -167,6 +167,22 @@ watch(
|
|||
},
|
||||
)
|
||||
|
||||
// Centre on a part picked elsewhere (the Pins list), keeping the zoom.
|
||||
watch(
|
||||
() => ed.focusRequest.value,
|
||||
r => {
|
||||
const n = r && nodeMap.value.get(r.id)
|
||||
const s = n && shapes.value.get(n.id)
|
||||
if (!n || !s) return
|
||||
const v = view.value
|
||||
ed.views[def.value.id] = {
|
||||
...v,
|
||||
x: size.w / 2 - (n.x + s.body.x + s.body.w / 2) * G * v.zoom,
|
||||
y: size.h / 2 - (n.y + s.body.y + s.body.h / 2) * G * v.zoom,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
let resize: ResizeObserver | undefined
|
||||
onMounted(() => {
|
||||
resize = new ResizeObserver(([entry]) => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,156 @@
|
|||
<script setup lang="ts">
|
||||
import { TRANSISTORS_PER_NAND } from '~/lib/logic/analyze'
|
||||
import { transistorBreakdown } from '~/lib/logic/bulk'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
import { usages } from '~/lib/logic/ops'
|
||||
import type { SymbolKind } from '~/lib/logic/types'
|
||||
|
||||
const ed = useEditor()
|
||||
const def = ed.def
|
||||
|
||||
const SYMBOLS: { value: SymbolKind; label: string }[] = [
|
||||
{ value: 'box', label: 'Box with name' },
|
||||
{ value: 'and', label: 'AND gate' },
|
||||
{ value: 'or', label: 'OR gate' },
|
||||
{ value: 'xor', label: 'XOR gate' },
|
||||
{ value: 'not', label: 'NOT gate' },
|
||||
{ value: 'buf', label: 'Buffer' },
|
||||
{ value: 'nand', label: 'NAND gate' },
|
||||
{ value: 'nor', label: 'NOR gate' },
|
||||
{ value: 'xnor', label: 'XNOR gate' },
|
||||
]
|
||||
|
||||
const nameInput = ref<HTMLInputElement>()
|
||||
watch(
|
||||
() => ed.labelFocus.value,
|
||||
() =>
|
||||
nextTick(() => {
|
||||
if (ed.selection.value.length) return
|
||||
nameInput.value?.focus()
|
||||
nameInput.value?.select()
|
||||
}),
|
||||
)
|
||||
|
||||
const pins = computed(() => chipPins(def.value))
|
||||
const users = computed(() => usages(ed.project.value, def.value.id))
|
||||
const groupNames = computed(() => [...new Set(ed.project.value.components.map(d => d.group).filter(Boolean))])
|
||||
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
|
||||
const total = computed(() => ed.transistors(def.value.id))
|
||||
const breakdown = computed(() => transistorBreakdown(def.value, ed.nands.value, ed.getDef.value))
|
||||
const showBreakdown = ref(true)
|
||||
|
||||
function toggleFace(e: Event) {
|
||||
def.value.face = (e.target as HTMLInputElement).checked
|
||||
ed.commit(false)
|
||||
}
|
||||
|
||||
const confirmDelete = ref(false)
|
||||
watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3>This circuit</h3>
|
||||
<label class="field">
|
||||
<span>Name</span>
|
||||
<input ref="nameInput" v-model="def.name" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Description</span>
|
||||
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
|
||||
</label>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<label class="field">
|
||||
<span>Drawn as</span>
|
||||
<select v-model="def.symbol" @change="ed.commit(false)">
|
||||
<option v-for="s in SYMBOLS" :key="s.value" :value="s.value">{{ s.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Group</span>
|
||||
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
|
||||
<datalist id="groups">
|
||||
<option v-for="g in groupNames" :key="g" :value="g" />
|
||||
</datalist>
|
||||
</label>
|
||||
</div>
|
||||
<label v-if="hasFace" class="check">
|
||||
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
|
||||
Show its lamps and displays on the component box
|
||||
</label>
|
||||
<dl class="stats">
|
||||
<dt>Pins</dt>
|
||||
<dd>
|
||||
<a href="#" title="List and rename them" @click.prevent="ed.rightTab.value = 'pins'">{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</a>
|
||||
</dd>
|
||||
<dt>NAND gates</dt>
|
||||
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
|
||||
<dt>Transistors</dt>
|
||||
<dd>{{ total.toLocaleString() }}</dd>
|
||||
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
|
||||
</dl>
|
||||
<p v-for="err in ed.errors.value" :key="err" class="result fail">
|
||||
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
|
||||
</p>
|
||||
<p v-if="users.length" class="hint">
|
||||
Used in
|
||||
<template v-for="(u, i) in users" :key="u.id">
|
||||
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
|
||||
</template>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<button class="section-toggle" @click="showBreakdown = !showBreakdown">
|
||||
<Icon :name="showBreakdown ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||
Where the transistors are
|
||||
</button>
|
||||
<template v-if="showBreakdown">
|
||||
<p v-if="!breakdown.length" class="hint mt-2">No gates here yet. Switches, lamps, displays and cables need no transistors.</p>
|
||||
<table v-else class="cost">
|
||||
<tbody>
|
||||
<tr v-for="l in breakdown" :key="l.key" title="Select these parts" @click="ed.selectOnly(l.ids)">
|
||||
<td class="what">{{ l.count }} × {{ l.name }}</td>
|
||||
<td class="num">{{ l.each.toLocaleString() }} each</td>
|
||||
<td class="num strong">{{ l.total.toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td>Total</td>
|
||||
<td class="num">{{ (total / TRANSISTORS_PER_NAND).toLocaleString() }} NAND</td>
|
||||
<td class="num strong">{{ total.toLocaleString() }}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<p class="hint mt-2">
|
||||
Everything here is built from NAND gates, and a CMOS NAND gate has 4 transistors: 2 in parallel to the supply, 2 in series to
|
||||
ground. So the count is 4 per NAND inside, at every depth: a NOT costs 4, an AND 8, a full adder 60. (A NOT made directly in
|
||||
CMOS would need only 2; here it is built from a NAND.)
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="grid gap-2">
|
||||
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
|
||||
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
|
||||
</button>
|
||||
<button
|
||||
v-if="!ed.task.value"
|
||||
class="btn w-full"
|
||||
title="Turn this circuit into a puzzle link: others build the same behaviour, your circuit stays private"
|
||||
@click="ed.dialog.value = 'publish'"
|
||||
>
|
||||
<Icon name="lucide:puzzle" class="size-4" /> Publish as puzzle
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="actions">
|
||||
<button class="btn btn-ghost" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||
<button v-if="!confirmDelete" class="btn btn-ghost" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
<button v-else class="btn btn-danger" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -4,6 +4,8 @@ const ed = useEditor()
|
|||
const SHORTCUTS: [string, string][] = [
|
||||
['Click switch', 'Flip an input between 0 and 1 (give it a keyboard key in its settings)'],
|
||||
['Click anything', 'Its settings appear on the right: swap the part, clock speed, colours, keys, position'],
|
||||
['Select several', 'Change them all at once: swap, rename D0, D1, …, switch all to 0 or 1, line up'],
|
||||
['Pins tab (right)', 'Every input and output in one list: rename them one after another with Enter'],
|
||||
['Drag from a pin', 'Draw a wire to another pin; dropping it on a part uses that part’s next free pin'],
|
||||
['Click a pin, then another', 'The same without holding the mouse button'],
|
||||
['Select parts, then W', 'Connect one by one: click where each of their pins goes, in order (Shift+W: their inputs)'],
|
||||
|
|
|
|||
|
|
@ -1,382 +1,85 @@
|
|||
<script setup lang="ts">
|
||||
import type { ChallengeCheck } from '~/composables/useEditor'
|
||||
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
|
||||
import { cableOf } from '~/lib/logic/cables'
|
||||
import { apiId, isTable } from '~/lib/logic/puzzles'
|
||||
import { chipPins } from '~/lib/logic/geometry'
|
||||
import { usages } from '~/lib/logic/ops'
|
||||
import { WIRE_COLORS, type CrossingStyle, type SymbolKind } from '~/lib/logic/types'
|
||||
// The right panel: tabs for the selection, the circuit, its pins, and testing.
|
||||
import { ioList } from '~/lib/logic/bulk'
|
||||
|
||||
const ed = useEditor()
|
||||
const def = ed.def
|
||||
|
||||
const SYMBOLS: { value: SymbolKind; label: string }[] = [
|
||||
{ value: 'box', label: 'Box with name' },
|
||||
{ value: 'and', label: 'AND gate' },
|
||||
{ value: 'or', label: 'OR gate' },
|
||||
{ value: 'xor', label: 'XOR gate' },
|
||||
{ value: 'not', label: 'NOT gate' },
|
||||
{ value: 'buf', label: 'Buffer' },
|
||||
{ value: 'nand', label: 'NAND gate' },
|
||||
{ value: 'nor', label: 'NOR gate' },
|
||||
{ value: 'xnor', label: 'XNOR gate' },
|
||||
]
|
||||
type Tab = 'selection' | 'circuit' | 'pins' | 'test'
|
||||
|
||||
const single = computed(() =>
|
||||
ed.selection.value.length === 1 && !ed.wireSel.value.length ? def.value.nodes.find(n => n.id === ed.selection.value[0]) : undefined,
|
||||
ed.selection.value.length === 1 && !ed.wireSel.value.length ? ed.def.value.nodes.find(n => n.id === ed.selection.value[0]) : undefined,
|
||||
)
|
||||
const wires = ed.selectedWires
|
||||
const wireColor = computed(() => {
|
||||
const colors = new Set(wires.value.map(w => w.color ?? ''))
|
||||
return colors.size === 1 ? [...colors][0] : null
|
||||
const selected = computed(() => ed.selection.value.length + ed.wireSel.value.length)
|
||||
const pinCount = computed(() => {
|
||||
const io = ioList(ed.def.value)
|
||||
return io.inputs.length + io.outputs.length
|
||||
})
|
||||
const hasTask = computed(() => !!ed.task.value)
|
||||
|
||||
const tabs = computed(() => [
|
||||
{ id: 'selection' as Tab, label: 'Selection', icon: 'lucide:mouse-pointer-2', badge: selected.value || '' },
|
||||
{ id: 'circuit' as Tab, label: 'Circuit', icon: 'lucide:cpu', badge: '' },
|
||||
{ id: 'pins' as Tab, label: 'Pins', icon: 'lucide:list', badge: pinCount.value || '' },
|
||||
{ id: 'test' as Tab, label: 'Test', icon: hasTask.value ? 'lucide:flag' : 'lucide:table', badge: '' },
|
||||
])
|
||||
|
||||
// Selecting something shows its settings, unless you are working in Pins or
|
||||
// Test (where clicking a switch to try the circuit also selects it).
|
||||
let before: Tab = 'circuit'
|
||||
watch(selected, (now, was) => {
|
||||
const tab = ed.rightTab.value
|
||||
if (now && !was && tab === 'circuit') {
|
||||
before = tab
|
||||
ed.rightTab.value = 'selection'
|
||||
} else if (!now && tab === 'selection') ed.rightTab.value = before
|
||||
})
|
||||
const hasFace = computed(() => def.value.nodes.some(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'))
|
||||
const nameInput = ref<HTMLInputElement>()
|
||||
watch(
|
||||
() => ed.labelFocus.value,
|
||||
() =>
|
||||
nextTick(() => {
|
||||
if (single.value) return
|
||||
nameInput.value?.focus()
|
||||
nameInput.value?.select()
|
||||
}),
|
||||
() => {
|
||||
if (selected.value) ed.rightTab.value = 'selection'
|
||||
},
|
||||
)
|
||||
|
||||
const CROSSINGS: { value: CrossingStyle; label: string }[] = [
|
||||
{ value: 'bow', label: 'Bow' },
|
||||
{ value: 'triangle', label: 'Triangle' },
|
||||
{ value: 'bridge', label: 'Bridge' },
|
||||
{ value: 'gap', label: 'Gap' },
|
||||
{ value: 'plain', label: 'Plain' },
|
||||
]
|
||||
const settings = computed(() => ed.project.value.settings)
|
||||
function setCrossing(c: CrossingStyle) {
|
||||
settings.value.crossing = c
|
||||
ed.persist()
|
||||
}
|
||||
|
||||
const pins = computed(() => chipPins(def.value))
|
||||
const users = computed(() => usages(ed.project.value, def.value.id))
|
||||
const groupNames = computed(() => [...new Set(ed.project.value.components.map(d => d.group).filter(Boolean))])
|
||||
// The challenge or puzzle this circuit is for.
|
||||
const challenge = computed(() => {
|
||||
const t = ed.task.value
|
||||
const c = t?.challenge ?? t?.puzzle
|
||||
return t && c ? { id: t.id, name: c.name, goal: c.goal, inputs: c.inputs, outputs: c.outputs, puzzle: t.puzzle } : undefined
|
||||
})
|
||||
const solved = computed(() => !!challenge.value && ed.project.value.solved.includes(challenge.value.id))
|
||||
const board = computed(() => (challenge.value?.puzzle ? ed.boards[challenge.value.id] : undefined))
|
||||
// What the puzzle asks for, as a table to read.
|
||||
const target = computed<TruthTable | null>(() => {
|
||||
const p = challenge.value?.puzzle
|
||||
if (!p) return null
|
||||
return { inputs: p.inputs, outputs: p.outputs, rows: p.steps.map(s => ({ ins: p.inputs.map(l => s.set[l] ?? 0), outs: p.outputs.map(l => s.expect[l] ?? 0), settled: true })) }
|
||||
})
|
||||
// Opening a challenge or puzzle shows what to build.
|
||||
watch(
|
||||
() => challenge.value?.puzzle,
|
||||
p => {
|
||||
if (p && !ed.boards[p.id]) void ed.loadBoard(p)
|
||||
() => ed.def.value.id,
|
||||
() => {
|
||||
if (ed.task.value) ed.rightTab.value = 'test'
|
||||
else if (ed.rightTab.value === 'test') ed.rightTab.value = 'circuit'
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const showTarget = ref(true)
|
||||
const puzzleLink = computed(() => (challenge.value?.puzzle ? `${location.origin}/puzzle/${apiId(challenge.value.puzzle.id)}` : ''))
|
||||
|
||||
const packName = ref('')
|
||||
function pack() {
|
||||
ed.packageSelected(packName.value || 'Part')
|
||||
packName.value = ''
|
||||
}
|
||||
|
||||
const showTable = ref(false)
|
||||
const table = ref<TruthTable | { error: string } | null>(null)
|
||||
function refreshTable() {
|
||||
table.value = showTable.value ? ed.table() : null
|
||||
}
|
||||
watch([showTable, () => ed.sim.value, () => def.value.id], refreshTable)
|
||||
|
||||
const check = ref<ChallengeCheck | null>(null)
|
||||
const bestHere = computed(() => (challenge.value ? ed.project.value.best?.[challenge.value.id] : undefined))
|
||||
const cable = computed(() => (wires.value.length === 1 ? cableOf(def.value, wires.value[0]!) : undefined))
|
||||
watch(() => def.value.id, () => (check.value = null))
|
||||
watch(() => ed.sim.value, () => (check.value = null))
|
||||
function runCheck() {
|
||||
check.value = ed.checkChallenge()
|
||||
}
|
||||
|
||||
function toggleFace(e: Event) {
|
||||
def.value.face = (e.target as HTMLInputElement).checked
|
||||
ed.commit(false)
|
||||
}
|
||||
|
||||
const confirmDelete = ref(false)
|
||||
watch(() => def.value.id, () => (confirmDelete.value = false))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="inspector">
|
||||
<nav class="itabs" role="tablist">
|
||||
<button
|
||||
v-for="t in tabs"
|
||||
:key="t.id"
|
||||
role="tab"
|
||||
:aria-selected="ed.rightTab.value === t.id"
|
||||
:class="{ active: ed.rightTab.value === t.id, task: t.id === 'test' && hasTask }"
|
||||
:title="t.label"
|
||||
@click="ed.rightTab.value = t.id"
|
||||
>
|
||||
<Icon :name="t.icon" class="size-4 shrink-0" />
|
||||
<span class="label">{{ t.label }}</span>
|
||||
<span v-if="t.badge" class="badge">{{ t.badge }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="scroll">
|
||||
<!-- Selection -->
|
||||
<template v-if="ed.rightTab.value === 'selection'">
|
||||
<EditorNodeSettings v-if="single" :key="single.id" :node="single" />
|
||||
|
||||
<section v-else-if="ed.selection.value.length > 1 || (ed.selection.value.length && wires.length)">
|
||||
<h3>
|
||||
{{ ed.selection.value.length }} part{{ ed.selection.value.length === 1 ? '' : 's' }}<template v-if="wires.length">, {{ wires.length }} wire{{ wires.length === 1 ? '' : 's' }}</template> selected
|
||||
</h3>
|
||||
<p class="hint">Turn them into a reusable component. Wires that cross the selection border become its pins.</p>
|
||||
<label class="field">
|
||||
<span>Component name</span>
|
||||
<input v-model="packName" placeholder="e.g. Half Adder" @keydown.enter="pack" />
|
||||
</label>
|
||||
<button class="btn btn-primary w-full" @click="pack"><Icon name="lucide:package" class="size-4" /> Make component</button>
|
||||
<button class="btn mt-2 w-full" title="Their pins in order, top to bottom: click where each one goes (W)" @click="ed.startLinking()">
|
||||
<Icon name="lucide:cable" class="size-4" /> Connect one by one
|
||||
</button>
|
||||
<div class="mt-2 grid grid-cols-2 gap-2">
|
||||
<button class="btn" title="Remove every wire attached to the selected parts" @click="ed.unlink(ed.selection.value)"><Icon name="lucide:unlink" class="size-4" /> Unlink all</button>
|
||||
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||
</div>
|
||||
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
<EditorBulkSettings v-else-if="ed.selection.value.length" />
|
||||
<EditorWireSettings v-else-if="ed.wireSel.value.length" />
|
||||
<section v-else class="empty-pane">
|
||||
<Icon name="lucide:mouse-pointer-click" class="size-6" />
|
||||
<p>Click a part or wire to change it.</p>
|
||||
<p class="hint">Shift + click or drag a box to select several; you can then rename, swap or switch them all at once.</p>
|
||||
</section>
|
||||
|
||||
<section v-else-if="wires.length">
|
||||
<h3>{{ wires.length === 1 ? 'Wire' : `${wires.length} wires` }}</h3>
|
||||
<div class="field">
|
||||
<span>Colour</span>
|
||||
<div class="swatches">
|
||||
<button class="swatch none" :class="{ active: wireColor === '' }" title="Default" @click="ed.setWireColor(undefined)" />
|
||||
<button
|
||||
v-for="c in WIRE_COLORS"
|
||||
:key="c"
|
||||
class="swatch"
|
||||
:class="[`c-${c}`, { active: wireColor === c }]"
|
||||
:title="c"
|
||||
@click="ed.setWireColor(c)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ul class="tips">
|
||||
<li><strong>Drag</strong> a segment to move it, a <strong>corner square</strong> to move a bend.</li>
|
||||
<li><strong>Alt + drag</strong> pulls a new bend out of a segment.</li>
|
||||
<li><strong>Ctrl + drag</strong> starts a new wire from this signal.</li>
|
||||
<li><strong>Double-click</strong> selects the whole signal, <strong>Shift + click</strong> adds wires.</li>
|
||||
<li><strong>Arrow keys</strong> shift the selected wires.</li>
|
||||
</ul>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button v-if="wires.length === 1" class="btn" @click="ed.selectNet(wires[0]!.id)"><Icon name="lucide:git-fork" class="size-4" /> Whole signal</button>
|
||||
<button class="btn" :disabled="!wires.some(w => w.pts)" @click="ed.autoRoute()"><Icon name="lucide:wand-sparkles" class="size-4" /> Auto route</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="wires.length >= 2"
|
||||
class="btn mt-2 w-full"
|
||||
title="Replace these wires with one cable: a bundle after their sources, a split before their targets"
|
||||
@click="ed.bundleSelected()"
|
||||
>
|
||||
<Icon name="lucide:merge" class="size-4" /> Bundle into cable
|
||||
</button>
|
||||
<button v-if="cable" class="btn mt-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cable.id)">
|
||||
<Icon name="lucide:split" class="size-4" /> Remove cable
|
||||
</button>
|
||||
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
</section>
|
||||
|
||||
<!-- Challenge -->
|
||||
<section v-if="challenge" class="challenge" :class="{ solved }">
|
||||
<h3>
|
||||
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
|
||||
{{ challenge.puzzle ? 'Puzzle' : 'Challenge' }}: {{ challenge.name }}
|
||||
</h3>
|
||||
<p>{{ challenge.goal }}</p>
|
||||
<p class="pins">Pins: {{ challenge.inputs.join(', ') }} → {{ challenge.outputs.join(', ') }}</p>
|
||||
<template v-if="target">
|
||||
<button class="section-toggle mt-2" @click="showTarget = !showTarget">
|
||||
<Icon :name="showTarget ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||
{{ isTable(challenge.puzzle!) ? 'Target truth table' : `Target: ${target.rows.length} steps from power-on` }}
|
||||
</button>
|
||||
<div v-if="showTarget" class="target-table">
|
||||
<EditorTruthTable :table="target" />
|
||||
</div>
|
||||
</template>
|
||||
<button class="btn btn-primary w-full" @click="runCheck"><Icon name="lucide:play" class="size-4" /> Check</button>
|
||||
<p v-if="check" class="result" :class="check.pass ? 'pass' : 'fail'">
|
||||
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
|
||||
{{ check.message }}
|
||||
</p>
|
||||
<p class="score">
|
||||
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||
<span>
|
||||
{{ ed.transistors(def.id).toLocaleString() }} transistors now<template v-if="bestHere !== undefined">, best <strong>{{ bestHere.toLocaleString() }}</strong></template>
|
||||
</span>
|
||||
</p>
|
||||
<p v-if="check?.pass && check.record !== undefined" class="result pass">
|
||||
<Icon name="lucide:trophy" class="size-4 shrink-0" /> New record! {{ check.record - check.transistors }} fewer than before ({{ check.record }}).
|
||||
</p>
|
||||
<p v-else-if="check?.pass && check.best === check.transistors" class="hint">Fewer transistors is better: 4 per NAND gate. Can you make it smaller?</p>
|
||||
<div v-if="check?.pass && (check.unlocked?.length || check.nextUp?.length)" class="unlock">
|
||||
<Icon name="lucide:sparkles" class="size-4 shrink-0" />
|
||||
<div>
|
||||
<p v-if="check.unlocked?.length"><strong>Unlocked:</strong> {{ check.unlocked.join(', ') }}</p>
|
||||
<p v-if="check.nextUp?.length"><strong>New challenges:</strong> {{ check.nextUp.join(', ') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="challenge.puzzle">
|
||||
<p v-if="challenge.puzzle.author !== undefined" class="hint mt-2">The author's solution uses {{ challenge.puzzle.author.toLocaleString() }} transistors.</p>
|
||||
<EditorScoreChart v-if="board?.players" :summary="board" :mine="bestHere" />
|
||||
<p v-else class="hint mt-2">No one has solved it yet. Be the first.</p>
|
||||
<button class="btn btn-ghost mt-2 w-full" title="Copy the link to this puzzle" @click="ed.copyText(puzzleLink, 'Puzzle link copied')">
|
||||
<Icon name="lucide:link" class="size-4" /> Copy puzzle link
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<!-- Circuit -->
|
||||
<section>
|
||||
<h3>This circuit</h3>
|
||||
<label class="field">
|
||||
<span>Name</span>
|
||||
<input ref="nameInput" v-model="def.name" @change="ed.commit(false)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Description</span>
|
||||
<textarea v-model="def.description" rows="2" placeholder="What does it do?" @change="ed.commit(false)" />
|
||||
</label>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<label class="field">
|
||||
<span>Drawn as</span>
|
||||
<select v-model="def.symbol" @change="ed.commit(false)">
|
||||
<option v-for="s in SYMBOLS" :key="s.value" :value="s.value">{{ s.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Group</span>
|
||||
<input v-model="def.group" list="groups" placeholder="My components" @change="ed.commit(false)" />
|
||||
<datalist id="groups">
|
||||
<option v-for="g in groupNames" :key="g" :value="g" />
|
||||
</datalist>
|
||||
</label>
|
||||
</div>
|
||||
<label v-if="hasFace" class="check">
|
||||
<input type="checkbox" :checked="def.face !== false" @change="toggleFace" />
|
||||
Show its lamps and displays on the component box
|
||||
</label>
|
||||
<dl class="stats">
|
||||
<dt>Pins</dt>
|
||||
<dd>{{ pins.inputs.length }} in, {{ pins.outputs.length }} out</dd>
|
||||
<dt>NAND gates</dt>
|
||||
<dd>{{ ed.circuitStats.value.nands.toLocaleString() }}</dd>
|
||||
<dt title="CMOS: 4 transistors per NAND gate">Transistors</dt>
|
||||
<dd>{{ ed.transistors(def.id).toLocaleString() }}</dd>
|
||||
<dt>{{ ed.circuitStats.value.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||
<dd>{{ ed.circuitStats.value.sequential ? 'yes (feedback loops)' : `${ed.circuitStats.value.delay} gates` }}</dd>
|
||||
</dl>
|
||||
<p v-for="err in ed.errors.value" :key="err" class="result fail">
|
||||
<Icon name="lucide:triangle-alert" class="size-4 shrink-0" /> {{ err }}
|
||||
</p>
|
||||
<button
|
||||
v-if="!challenge"
|
||||
class="btn mt-1 mb-2 w-full"
|
||||
title="Turn this circuit into a puzzle link: others build the same behaviour, your circuit stays private"
|
||||
@click="ed.dialog.value = 'publish'"
|
||||
>
|
||||
<Icon name="lucide:puzzle" class="size-4" /> Publish as puzzle
|
||||
</button>
|
||||
<p v-if="users.length" class="hint">
|
||||
Used in
|
||||
<template v-for="(u, i) in users" :key="u.id">
|
||||
<a href="#" @click.prevent="ed.open(u.id)">{{ u.name }}</a><template v-if="i < users.length - 1">, </template>
|
||||
</template>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section v-if="!single && !wires.length && !ed.selection.value.length">
|
||||
<h3>Display</h3>
|
||||
<div class="field">
|
||||
<span>Gate symbols</span>
|
||||
<div class="seg">
|
||||
<button :class="{ active: settings.symbols === 'iec' }" @click="settings.symbols = 'iec'; ed.persist()">IEC (DIN)</button>
|
||||
<button :class="{ active: settings.symbols === 'ansi' }" @click="settings.symbols = 'ansi'; ed.persist()">ANSI</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Where unconnected wires cross</span>
|
||||
<div class="crossings">
|
||||
<button
|
||||
v-for="c in CROSSINGS"
|
||||
:key="c.value"
|
||||
class="crossing"
|
||||
:class="{ active: (settings.crossing ?? 'bow') === c.value }"
|
||||
:title="c.label"
|
||||
@click="setCrossing(c.value)"
|
||||
>
|
||||
<EditorCrossingIcon :style="c.value" />
|
||||
<span>{{ c.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="settings.flow" @change="settings.flow = !settings.flow; ed.persist()" />
|
||||
Animate current flow on wires that carry a 1
|
||||
</label>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="!!settings.tidy" @change="ed.setTidy(!settings.tidy)" />
|
||||
Tidy wiring: sorted parallel runs, one trunk per signal, fewer crossings
|
||||
</label>
|
||||
<div class="field mt-3">
|
||||
<span>Sound</span>
|
||||
<div class="flex items-center gap-2">
|
||||
<button class="icon-btn" :title="ed.sound.value.on ? 'Turn sound off' : 'Turn sound on'" @click="ed.setSound({ on: !ed.sound.value.on })">
|
||||
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.05"
|
||||
class="grow"
|
||||
:value="ed.sound.value.volume"
|
||||
:disabled="!ed.sound.value.on"
|
||||
aria-label="Volume"
|
||||
@change="ed.setSound({ volume: Number(($event.target as HTMLInputElement).value) })"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="ed.sound.value.ticks" :disabled="!ed.sound.value.on" @change="ed.setSound({ ticks: !ed.sound.value.ticks })" />
|
||||
Tick on every clock cycle (up to 8 Hz)
|
||||
</label>
|
||||
<button class="btn w-full" title="Remove hand-placed bends in this circuit and lay out every wire tidily (undo brings them back)" @click="ed.tidyAll()">
|
||||
<Icon name="lucide:wand-sparkles" class="size-4" /> Tidy all wires
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="flex items-center gap-1">
|
||||
<button class="section-toggle grow" @click="showTable = !showTable">
|
||||
<Icon :name="showTable ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||
Truth table
|
||||
</button>
|
||||
<template v-if="showTable && table && !('error' in table)">
|
||||
<button class="icon-btn" title="Download as CSV" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-3.5" /></button>
|
||||
<button class="icon-btn" title="Copy as a Markdown table" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
||||
<Icon name="lucide:clipboard-copy" class="size-3.5" />
|
||||
</button>
|
||||
</template>
|
||||
<button class="icon-btn" title="Full screen" @click="ed.dialog.value = 'table'"><Icon name="lucide:maximize-2" class="size-3.5" /></button>
|
||||
</div>
|
||||
<template v-if="showTable && table">
|
||||
<p v-if="'error' in table" class="hint">{{ table.error }}</p>
|
||||
<template v-else>
|
||||
<p v-if="ed.circuitStats.value.sequential" class="hint">This circuit stores state, so the table depends on the order the rows are tried in.</p>
|
||||
<EditorTruthTable :table="table" />
|
||||
</template>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section class="actions">
|
||||
<button class="btn btn-ghost" @click="ed.copyComponent(def.id)"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
|
||||
<button v-if="!confirmDelete" class="btn btn-ghost" @click="confirmDelete = true"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
<button v-else class="btn btn-danger" @click="ed.removeComponent(def.id); confirmDelete = false">Really delete?</button>
|
||||
</section>
|
||||
<EditorCircuitPane v-else-if="ed.rightTab.value === 'circuit'" />
|
||||
<EditorPinsPane v-else-if="ed.rightTab.value === 'pins'" />
|
||||
<EditorTestPane v-else />
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -168,6 +168,14 @@ function setRowHz(row: PanelRow, e: Event) {
|
|||
<template>
|
||||
<section>
|
||||
<h3>{{ title }}</h3>
|
||||
<p class="score" :title="n.kind === 'nand' ? 'CMOS NAND: 2 transistors in parallel to the supply, 2 in series to ground' : ''">
|
||||
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||
<span v-if="n.kind === 'nand'">4 transistors (CMOS: 2 in parallel to the supply, 2 in series to ground)</span>
|
||||
<span v-else-if="n.kind === 'chip'">
|
||||
{{ ed.transistorsOfNode(n).toLocaleString() }} transistors, from {{ (ed.transistorsOfNode(n) / 4).toLocaleString() }} NAND gates inside
|
||||
</span>
|
||||
<span v-else>0 transistors: no logic gate inside</span>
|
||||
</p>
|
||||
|
||||
<label v-if="logic" class="field">
|
||||
<span>Part</span>
|
||||
|
|
@ -319,10 +327,6 @@ function setRowHz(row: PanelRow, e: Event) {
|
|||
<template v-if="n.kind === 'chip' && chipDef">
|
||||
<p v-if="chipDef.description" class="hint">{{ chipDef.description }}</p>
|
||||
<dl v-if="chipStats" class="stats">
|
||||
<dt>NAND gates</dt>
|
||||
<dd>{{ chipStats.nands.toLocaleString() }}</dd>
|
||||
<dt title="CMOS: 4 transistors per NAND gate">Transistors</dt>
|
||||
<dd>{{ ed.transistors(chipDef.id).toLocaleString() }}</dd>
|
||||
<dt>{{ chipStats.sequential ? 'Memory' : 'Delay' }}</dt>
|
||||
<dd>{{ chipStats.sequential ? 'yes (feedback)' : `${chipStats.delay} gates` }}</dd>
|
||||
</dl>
|
||||
|
|
|
|||
|
|
@ -116,6 +116,7 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
|
|||
<span v-if="item.kind === 'nand'" class="nand-badge">&</span>
|
||||
<Icon v-else :name="item.icon" class="size-4 shrink-0 text-(--muted)" />
|
||||
<span class="grow truncate">{{ item.name }}</span>
|
||||
<span v-if="item.kind === 'nand'" class="tcount" title="4 transistors: a CMOS NAND gate">4T</span>
|
||||
<Icon v-if="!ed.canPlaceKind(item.kind)" name="lucide:lock" class="size-3.5 shrink-0 text-(--muted)" />
|
||||
<kbd v-else-if="item.key">{{ item.key }}</kbd>
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,151 @@
|
|||
<script setup lang="ts">
|
||||
// Every input and output of the open circuit in one list, to rename them
|
||||
// quickly: type a name, Enter jumps to the next one.
|
||||
import { duplicateNames, entryLabel, ioList, numberedNames, type IoEntry } from '~/lib/logic/bulk'
|
||||
import { KIND_NAMES } from '~/lib/logic/progress'
|
||||
|
||||
const ed = useEditor()
|
||||
const io = computed(() => ioList(ed.def.value))
|
||||
const groups = computed(() => [
|
||||
{ id: 'in' as const, title: 'Inputs', entries: io.value.inputs, dup: duplicateNames(io.value.inputs) },
|
||||
{ id: 'out' as const, title: 'Outputs', entries: io.value.outputs, dup: duplicateNames(io.value.outputs) },
|
||||
])
|
||||
const selected = computed(() => new Set(ed.selection.value))
|
||||
|
||||
const keyOf = (e: IoEntry) => (e.row ? `${e.node.id}/${e.row.id}` : e.node.id)
|
||||
|
||||
function kindText(e: IoEntry, entries: IoEntry[]): string {
|
||||
if (e.row) return `${e.node.label?.trim() || 'Panel'} · ${e.row.type}`
|
||||
const kind = KIND_NAMES[e.node.kind] ?? e.node.kind
|
||||
if (!e.pin) return kind
|
||||
return `${kind} · pin ${entries.filter(x => x.pin).indexOf(e) + 1}`
|
||||
}
|
||||
|
||||
function placeholder(e: IoEntry, entries: IoEntry[]): string {
|
||||
if (e.row) return e.row.name?.trim() || 'no name'
|
||||
if (e.pin) {
|
||||
const i = entries.filter(x => x.pin).indexOf(e) + 1
|
||||
return e.node.kind === 'input' ? `in${i}` : `out${i}`
|
||||
}
|
||||
return 'no name'
|
||||
}
|
||||
|
||||
/** Live value: 0/1, or the digit a display shows. */
|
||||
function value(e: IoEntry): string {
|
||||
const id = e.node.id
|
||||
if (e.row) return String(ed.val(id, e.row.id))
|
||||
if (e.node.kind === 'hex') return [0, 1, 2, 3].reduce((n, i) => n + (ed.val(id, `b${i}`) << i), 0).toString(16).toUpperCase()
|
||||
return String(ed.val(id, ['output', 'lamp'].includes(e.node.kind) ? 'a' : 'q'))
|
||||
}
|
||||
|
||||
const list = ref<HTMLElement>()
|
||||
function next(e: KeyboardEvent, group: string, i: number) {
|
||||
;(e.target as HTMLInputElement).blur()
|
||||
const el = list.value?.querySelector<HTMLInputElement>(`input[data-group="${group}"][data-i="${i + 1}"]`)
|
||||
el?.focus()
|
||||
el?.select()
|
||||
}
|
||||
|
||||
// Numbering a whole group.
|
||||
const numbering = ref<null | 'in' | 'out'>(null)
|
||||
const pattern = ref('D#')
|
||||
const start = ref(0)
|
||||
const pinsOnly = ref(true)
|
||||
const targets = computed(() => {
|
||||
const g = groups.value.find(x => x.id === numbering.value)
|
||||
return g ? g.entries.filter(e => !pinsOnly.value || e.pin) : []
|
||||
})
|
||||
const preview = computed(() => numberedNames(pattern.value, targets.value.length, start.value))
|
||||
|
||||
function openNumbering(id: 'in' | 'out') {
|
||||
numbering.value = numbering.value === id ? null : id
|
||||
pattern.value = id === 'in' ? 'D#' : 'Q#'
|
||||
pinsOnly.value = groups.value.find(x => x.id === id)!.entries.some(e => e.pin)
|
||||
}
|
||||
|
||||
function applyNumbering() {
|
||||
targets.value.forEach((e, i) => {
|
||||
const name = preview.value[i]!
|
||||
if (e.row) e.row.label = name
|
||||
else {
|
||||
e.node.label = name
|
||||
delete e.node.autoLabel
|
||||
}
|
||||
})
|
||||
ed.commit()
|
||||
numbering.value = null
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="list">
|
||||
<section v-for="g in groups" :key="g.id">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="grow">
|
||||
{{ g.title }} <span class="count-pill">{{ g.entries.length }}</span>
|
||||
</h3>
|
||||
<button v-if="g.entries.length > 1" class="btn-sm" title="Name them all with a numbered pattern" @click="openNumbering(g.id)">
|
||||
<Icon name="lucide:list-ordered" class="size-3.5" /> Number all
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form v-if="numbering === g.id" class="numbering" @submit.prevent="applyNumbering">
|
||||
<div class="grid grid-cols-[1fr_5rem] gap-2">
|
||||
<label class="field mb-0">
|
||||
<span>Pattern (# is the number)</span>
|
||||
<input v-model="pattern" autofocus />
|
||||
</label>
|
||||
<label class="field mb-0">
|
||||
<span>From</span>
|
||||
<input v-model.number="start" type="number" min="0" />
|
||||
</label>
|
||||
</div>
|
||||
<label v-if="g.entries.some(e => !e.pin) && g.entries.some(e => e.pin)" class="check mt-2">
|
||||
<input v-model="pinsOnly" type="checkbox" /> Only the pins (top to bottom)
|
||||
</label>
|
||||
<p class="hint mt-1">{{ preview.slice(0, 6).join(', ') }}<template v-if="preview.length > 6">, …</template></p>
|
||||
<div class="flex gap-2">
|
||||
<button class="btn btn-primary grow" type="submit" :disabled="!targets.length">Rename {{ targets.length }}</button>
|
||||
<button class="btn" type="button" @click="numbering = null">Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<p v-if="!g.entries.length" class="hint">
|
||||
{{ g.id === 'in' ? 'No inputs yet. Place an input switch (I) to give this circuit an input pin.' : 'No outputs yet. Place an output pin (O) or a lamp (L).' }}
|
||||
</p>
|
||||
<ul v-else class="io-list">
|
||||
<li
|
||||
v-for="(e, i) in g.entries"
|
||||
:key="keyOf(e)"
|
||||
:class="{ selected: selected.has(e.node.id), dup: g.dup.has(entryLabel(e).toLowerCase()), pin: e.pin }"
|
||||
>
|
||||
<span class="io-value" :class="{ on: value(e) !== '0' }" :title="`Now ${value(e)}`">{{ value(e) }}</span>
|
||||
<div class="io-main">
|
||||
<input
|
||||
class="io-name"
|
||||
:value="entryLabel(e)"
|
||||
:placeholder="placeholder(e, g.entries)"
|
||||
:data-group="g.id"
|
||||
:data-i="i"
|
||||
spellcheck="false"
|
||||
@focus="ed.selectOnly([e.node.id])"
|
||||
@change="ed.setLabel(e.node, ($event.target as HTMLInputElement).value, e.row)"
|
||||
@keydown.enter.prevent="next($event, g.id, i)"
|
||||
/>
|
||||
<span class="io-kind">
|
||||
<Icon v-if="g.dup.has(entryLabel(e).toLowerCase())" name="lucide:triangle-alert" class="size-3" title="Another one has the same name" />
|
||||
{{ kindText(e, g.entries) }}
|
||||
</span>
|
||||
</div>
|
||||
<button class="icon-btn" title="Show on the canvas" @click="ed.focusNode(e.node.id)"><Icon name="lucide:locate-fixed" class="size-3.5" /></button>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
<section>
|
||||
<p class="hint">
|
||||
Pins are what the circuit shows when you use it as a component, ordered top to bottom. Type a name and press Enter to go to the
|
||||
next one. Clicking a name selects the part; the target icon centres the canvas on it.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
<script setup lang="ts">
|
||||
// Preferences: how circuits look and sound. They belong to the project.
|
||||
import type { CrossingStyle } from '~/lib/logic/types'
|
||||
|
||||
const ed = useEditor()
|
||||
const close = () => (ed.dialog.value = null)
|
||||
const settings = computed(() => ed.project.value.settings)
|
||||
|
||||
const CROSSINGS: { value: CrossingStyle; label: string }[] = [
|
||||
{ value: 'bow', label: 'Bow' },
|
||||
{ value: 'triangle', label: 'Triangle' },
|
||||
{ value: 'bridge', label: 'Bridge' },
|
||||
{ value: 'gap', label: 'Gap' },
|
||||
{ value: 'plain', label: 'Plain' },
|
||||
]
|
||||
|
||||
function set<K extends keyof typeof settings.value>(key: K, value: (typeof settings.value)[K]) {
|
||||
settings.value[key] = value
|
||||
ed.persist()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="modal-backdrop" @click.self="close">
|
||||
<div class="modal" role="dialog" aria-labelledby="settings-title">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<h2 id="settings-title">Settings</h2>
|
||||
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
|
||||
</div>
|
||||
|
||||
<h3>Display</h3>
|
||||
<div class="field">
|
||||
<span>Gate symbols</span>
|
||||
<div class="seg">
|
||||
<button :class="{ active: settings.symbols === 'iec' }" @click="set('symbols', 'iec')">IEC 60617 (DIN)</button>
|
||||
<button :class="{ active: settings.symbols === 'ansi' }" @click="set('symbols', 'ansi')">ANSI (US)</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<span>Where unconnected wires cross</span>
|
||||
<div class="crossings">
|
||||
<button
|
||||
v-for="c in CROSSINGS"
|
||||
:key="c.value"
|
||||
class="crossing"
|
||||
:class="{ active: (settings.crossing ?? 'bow') === c.value }"
|
||||
:title="c.label"
|
||||
@click="set('crossing', c.value)"
|
||||
>
|
||||
<EditorCrossingIcon :style="c.value" />
|
||||
<span>{{ c.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="settings.flow" @change="set('flow', !settings.flow)" />
|
||||
Animate current flow on wires that carry a 1
|
||||
</label>
|
||||
<label class="check">
|
||||
<input type="checkbox" :checked="!!settings.tidy" @change="ed.setTidy(!settings.tidy)" />
|
||||
Tidy wiring: sorted parallel runs, one trunk per signal, fewer crossings
|
||||
</label>
|
||||
|
||||
<h3>Sound</h3>
|
||||
<div class="flex items-center gap-2">
|
||||
<button class="icon-btn" :title="ed.sound.value.on ? 'Turn sound off' : 'Turn sound on'" @click="ed.setSound({ on: !ed.sound.value.on })">
|
||||
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="1"
|
||||
step="0.05"
|
||||
class="grow"
|
||||
:value="ed.sound.value.volume"
|
||||
:disabled="!ed.sound.value.on"
|
||||
aria-label="Volume"
|
||||
@change="ed.setSound({ volume: Number(($event.target as HTMLInputElement).value) })"
|
||||
/>
|
||||
</div>
|
||||
<label class="check mt-2">
|
||||
<input type="checkbox" :checked="ed.sound.value.ticks" :disabled="!ed.sound.value.on" @change="ed.setSound({ ticks: !ed.sound.value.ticks })" />
|
||||
Tick on every clock cycle (up to 8 Hz)
|
||||
</label>
|
||||
|
||||
<button class="btn btn-primary mt-4" @click="close">Done</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
<script setup lang="ts">
|
||||
import type { ChallengeCheck } from '~/composables/useEditor'
|
||||
import { tableMarkdown, type TruthTable } from '~/lib/logic/analyze'
|
||||
import { apiId, isTable } from '~/lib/logic/puzzles'
|
||||
|
||||
const ed = useEditor()
|
||||
const def = ed.def
|
||||
|
||||
// The challenge or puzzle this circuit is for.
|
||||
const challenge = computed(() => {
|
||||
const t = ed.task.value
|
||||
const c = t?.challenge ?? t?.puzzle
|
||||
return t && c ? { id: t.id, name: c.name, goal: c.goal, inputs: c.inputs, outputs: c.outputs, puzzle: t.puzzle } : undefined
|
||||
})
|
||||
const solved = computed(() => !!challenge.value && ed.project.value.solved.includes(challenge.value.id))
|
||||
const board = computed(() => (challenge.value?.puzzle ? ed.boards[challenge.value.id] : undefined))
|
||||
// What the puzzle asks for, as a table to read.
|
||||
const target = computed<TruthTable | null>(() => {
|
||||
const p = challenge.value?.puzzle
|
||||
if (!p) return null
|
||||
return { inputs: p.inputs, outputs: p.outputs, rows: p.steps.map(s => ({ ins: p.inputs.map(l => s.set[l] ?? 0), outs: p.outputs.map(l => s.expect[l] ?? 0), settled: true })) }
|
||||
})
|
||||
watch(
|
||||
() => challenge.value?.puzzle,
|
||||
p => {
|
||||
if (p && !ed.boards[p.id]) void ed.loadBoard(p)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const showTarget = ref(true)
|
||||
const puzzleLink = computed(() => (challenge.value?.puzzle ? `${location.origin}/puzzle/${apiId(challenge.value.puzzle.id)}` : ''))
|
||||
|
||||
const table = ref<TruthTable | { error: string } | null>(null)
|
||||
watch([() => ed.sim.value, () => def.value.id], () => (table.value = ed.table()), { immediate: true })
|
||||
|
||||
const check = ref<ChallengeCheck | null>(null)
|
||||
const bestHere = computed(() => (challenge.value ? ed.project.value.best?.[challenge.value.id] : undefined))
|
||||
watch(() => def.value.id, () => (check.value = null))
|
||||
watch(() => ed.sim.value, () => (check.value = null))
|
||||
function runCheck() {
|
||||
check.value = ed.checkChallenge()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="challenge" class="challenge" :class="{ solved }">
|
||||
<h3>
|
||||
<Icon :name="solved ? 'lucide:badge-check' : 'lucide:flag'" class="size-4" />
|
||||
{{ challenge.puzzle ? 'Puzzle' : 'Challenge' }}: {{ challenge.name }}
|
||||
</h3>
|
||||
<p>{{ challenge.goal }}</p>
|
||||
<p class="pins">Pins: {{ challenge.inputs.join(', ') }} → {{ challenge.outputs.join(', ') }}</p>
|
||||
<template v-if="target">
|
||||
<button class="section-toggle mt-2" @click="showTarget = !showTarget">
|
||||
<Icon :name="showTarget ? 'lucide:chevron-down' : 'lucide:chevron-right'" class="size-4" />
|
||||
{{ isTable(challenge.puzzle!) ? 'Target truth table' : `Target: ${target.rows.length} steps from power-on` }}
|
||||
</button>
|
||||
<div v-if="showTarget" class="target-table">
|
||||
<EditorTruthTable :table="target" />
|
||||
</div>
|
||||
</template>
|
||||
<button class="btn btn-primary w-full" @click="runCheck"><Icon name="lucide:play" class="size-4" /> Check</button>
|
||||
<p v-if="check" class="result" :class="check.pass ? 'pass' : 'fail'">
|
||||
<Icon :name="check.pass ? 'lucide:circle-check' : 'lucide:circle-x'" class="size-4 shrink-0" />
|
||||
{{ check.message }}
|
||||
</p>
|
||||
<p class="score">
|
||||
<Icon name="lucide:cpu" class="size-4 shrink-0" />
|
||||
<span>
|
||||
{{ ed.transistors(def.id).toLocaleString() }} transistors now<template v-if="bestHere !== undefined">, best <strong>{{ bestHere.toLocaleString() }}</strong></template>
|
||||
</span>
|
||||
</p>
|
||||
<p v-if="check?.pass && check.record !== undefined" class="result pass">
|
||||
<Icon name="lucide:trophy" class="size-4 shrink-0" /> New record! {{ check.record - check.transistors }} fewer than before ({{ check.record }}).
|
||||
</p>
|
||||
<p v-else-if="check?.pass && check.best === check.transistors" class="hint">Fewer transistors is better: 4 per NAND gate. Can you make it smaller?</p>
|
||||
<div v-if="check?.pass && (check.unlocked?.length || check.nextUp?.length)" class="unlock">
|
||||
<Icon name="lucide:sparkles" class="size-4 shrink-0" />
|
||||
<div>
|
||||
<p v-if="check.unlocked?.length"><strong>Unlocked:</strong> {{ check.unlocked.join(', ') }}</p>
|
||||
<p v-if="check.nextUp?.length"><strong>New challenges:</strong> {{ check.nextUp.join(', ') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<template v-if="challenge.puzzle">
|
||||
<p v-if="challenge.puzzle.author !== undefined" class="hint mt-2">The author's solution uses {{ challenge.puzzle.author.toLocaleString() }} transistors.</p>
|
||||
<EditorScoreChart v-if="board?.players" :summary="board" :mine="bestHere" />
|
||||
<p v-else class="hint mt-2">No one has solved it yet. Be the first.</p>
|
||||
<button class="btn btn-ghost mt-2 w-full" title="Copy the link to this puzzle" @click="ed.copyText(puzzleLink, 'Puzzle link copied')">
|
||||
<Icon name="lucide:link" class="size-4" /> Copy puzzle link
|
||||
</button>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<div class="flex items-center gap-1">
|
||||
<h3 class="grow">Truth table</h3>
|
||||
<template v-if="table && !('error' in table)">
|
||||
<button class="icon-btn" title="Download as CSV" @click="ed.exportTable(table)"><Icon name="lucide:download" class="size-3.5" /></button>
|
||||
<button class="icon-btn" title="Copy as a Markdown table" @click="ed.copyText(tableMarkdown(table), 'Truth table copied')">
|
||||
<Icon name="lucide:clipboard-copy" class="size-3.5" />
|
||||
</button>
|
||||
</template>
|
||||
<button class="icon-btn" title="Full screen" @click="ed.dialog.value = 'table'"><Icon name="lucide:maximize-2" class="size-3.5" /></button>
|
||||
</div>
|
||||
<template v-if="table">
|
||||
<p v-if="'error' in table" class="hint">{{ table.error }}</p>
|
||||
<template v-else>
|
||||
<p v-if="ed.circuitStats.value.sequential" class="hint">This circuit stores state, so the table depends on the order the rows are tried in.</p>
|
||||
<EditorTruthTable :table="table" />
|
||||
</template>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -84,26 +84,16 @@ const linkIcon = computed(() => {
|
|||
<div class="flex items-center gap-1.5">
|
||||
<button class="tb-btn" title="Undo (Ctrl+Z)" :disabled="!ed.canUndo.value" @click="ed.undo()"><Icon name="lucide:undo-2" class="size-4" /></button>
|
||||
<button class="tb-btn" title="Redo (Ctrl+Shift+Z)" :disabled="!ed.canRedo.value" @click="ed.redo()"><Icon name="lucide:redo-2" class="size-4" /></button>
|
||||
<div class="seg" title="Gate symbols">
|
||||
<button :class="{ active: ed.project.value.settings.symbols === 'iec' }" @click="ed.project.value.settings.symbols = 'iec'; ed.persist()">IEC</button>
|
||||
<button :class="{ active: ed.project.value.settings.symbols === 'ansi' }" @click="ed.project.value.settings.symbols = 'ansi'; ed.persist()">ANSI</button>
|
||||
</div>
|
||||
<button
|
||||
class="tb-btn"
|
||||
:class="{ active: ed.project.value.settings.flow }"
|
||||
title="Animate current flow"
|
||||
@click="ed.project.value.settings.flow = !ed.project.value.settings.flow; ed.persist()"
|
||||
>
|
||||
<Icon name="lucide:zap" class="size-4" />
|
||||
</button>
|
||||
<button
|
||||
class="tb-btn"
|
||||
:class="{ active: ed.sound.value.on }"
|
||||
:title="ed.sound.value.on ? 'Sound on (volume and clock ticks under Display, right)' : 'Sound off'"
|
||||
:title="ed.sound.value.on ? 'Sound on (volume and clock ticks in Settings)' : 'Sound off'"
|
||||
@click="ed.setSound({ on: !ed.sound.value.on })"
|
||||
>
|
||||
<Icon :name="ed.sound.value.on ? 'lucide:volume-2' : 'lucide:volume-x'" class="size-4" />
|
||||
</button>
|
||||
<button class="tb-btn" title="Settings: gate symbols, wire crossings, current flow, tidy wiring, sound" @click="ed.dialog.value = 'settings'">
|
||||
<Icon name="lucide:settings" class="size-4" />
|
||||
</button>
|
||||
<button class="tb-btn share-btn" :class="ed.linkState.value" title="Save online, share a link, export or import a file" @click="ed.dialog.value = 'share'">
|
||||
<Icon :name="linkIcon" class="size-4" />
|
||||
<span class="hidden md:inline">Share</span>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
<script setup lang="ts">
|
||||
import { cableOf } from '~/lib/logic/cables'
|
||||
import { WIRE_COLORS } from '~/lib/logic/types'
|
||||
|
||||
const ed = useEditor()
|
||||
const wires = ed.selectedWires
|
||||
const wireColor = computed(() => {
|
||||
const colors = new Set(wires.value.map(w => w.color ?? ''))
|
||||
return colors.size === 1 ? [...colors][0] : null
|
||||
})
|
||||
const cable = computed(() => (wires.value.length === 1 ? cableOf(ed.def.value, wires.value[0]!) : undefined))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3>{{ wires.length === 1 ? 'Wire' : `${wires.length} wires` }}</h3>
|
||||
<div class="field">
|
||||
<span>Colour</span>
|
||||
<div class="swatches">
|
||||
<button class="swatch none" :class="{ active: wireColor === '' }" title="Default" @click="ed.setWireColor(undefined)" />
|
||||
<button
|
||||
v-for="c in WIRE_COLORS"
|
||||
:key="c"
|
||||
class="swatch"
|
||||
:class="[`c-${c}`, { active: wireColor === c }]"
|
||||
:title="c"
|
||||
@click="ed.setWireColor(c)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button v-if="wires.length === 1" class="btn" @click="ed.selectNet(wires[0]!.id)"><Icon name="lucide:git-fork" class="size-4" /> Whole signal</button>
|
||||
<button class="btn" :disabled="!wires.some(w => w.pts)" @click="ed.autoRoute()"><Icon name="lucide:wand-sparkles" class="size-4" /> Auto route</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="wires.length >= 2"
|
||||
class="btn mt-2 w-full"
|
||||
title="Replace these wires with one cable: a bundle after their sources, a split before their targets"
|
||||
@click="ed.bundleSelected()"
|
||||
>
|
||||
<Icon name="lucide:merge" class="size-4" /> Bundle into cable
|
||||
</button>
|
||||
<button v-if="cable" class="btn mt-2 w-full" title="Take the cable apart again into single wires" @click="ed.removeCable(cable.id)">
|
||||
<Icon name="lucide:split" class="size-4" /> Remove cable
|
||||
</button>
|
||||
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
|
||||
<details class="tips-box">
|
||||
<summary>Editing wires</summary>
|
||||
<ul class="tips">
|
||||
<li><strong>Drag</strong> a segment to move it, a <strong>corner square</strong> to move a bend.</li>
|
||||
<li><strong>Alt + drag</strong> pulls a new bend out of a segment.</li>
|
||||
<li><strong>Ctrl + drag</strong> starts a new wire from this signal.</li>
|
||||
<li><strong>Double-click</strong> selects the whole signal, <strong>Shift + click</strong> adds wires.</li>
|
||||
<li><strong>Arrow keys</strong> shift the selected wires.</li>
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -36,6 +36,7 @@ import {
|
|||
type Clip,
|
||||
type SwapTarget,
|
||||
} from '~/lib/logic/ops'
|
||||
import { arrangeNodes, byPosition, numberedNames, type Arrange } from '~/lib/logic/bulk'
|
||||
import { parseProject, toProject } from '~/lib/logic/project'
|
||||
import { Simulator } from '~/lib/logic/sim'
|
||||
import {
|
||||
|
|
@ -141,7 +142,11 @@ function create() {
|
|||
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
|
||||
const labelFocus = ref(0)
|
||||
const showHelp = ref(false)
|
||||
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish'>(null)
|
||||
const dialog = ref<null | 'projects' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings'>(null)
|
||||
/** Tab shown in the right panel. */
|
||||
const rightTab = ref<'selection' | 'circuit' | 'pins' | 'test'>('circuit')
|
||||
/** Asks the canvas to centre on a part. */
|
||||
const focusRequest = ref<{ id: string; n: number } | null>(null)
|
||||
/** Pins being wired one after another; `at` is the one the next click connects. */
|
||||
const linking = ref<{ queue: LinkEnd[]; at: number } | null>(null)
|
||||
/** Project whose savegames the versions dialog shows. */
|
||||
|
|
@ -877,6 +882,91 @@ function create() {
|
|||
return `${location.origin}/puzzle/${res.id}`
|
||||
}
|
||||
|
||||
// ── Several parts at once ─────────────────────────────────────────
|
||||
const nodesById = (ids: string[]) => {
|
||||
const set = new Set(ids)
|
||||
return def.value.nodes.filter(n => set.has(n.id))
|
||||
}
|
||||
|
||||
/** Swaps every given part for the same new one, keeping wires on matching pins. One undo step. */
|
||||
function swapMany(ids: string[], target: SwapTarget) {
|
||||
let removed = 0
|
||||
for (const n of nodesById(ids)) {
|
||||
if (n.kind === target.kind && n.chip === target.chip) continue
|
||||
removed += swapNode(project.value, def.value, n.id, target)
|
||||
}
|
||||
commit()
|
||||
notify(removed ? `Swapped. ${removed} wire${removed === 1 ? '' : 's'} had no matching pin and were removed.` : `Swapped ${ids.length} parts`)
|
||||
}
|
||||
|
||||
/** Names the parts top to bottom from a pattern (D# → D0, D1, …). An empty pattern clears their names. */
|
||||
function renameMany(ids: string[], pattern: string, start = 0) {
|
||||
const nodes = nodesById(ids).sort(byPosition)
|
||||
const names = numberedNames(pattern, nodes.length, start)
|
||||
nodes.forEach((n, i) => {
|
||||
if (pattern.trim()) n.label = names[i]
|
||||
else delete n.label
|
||||
delete n.autoLabel
|
||||
})
|
||||
commit(false)
|
||||
}
|
||||
|
||||
/** A name typed by hand (Pins list); empty lets connections name the part again. */
|
||||
function setLabel(node: CircuitNode, label: string, row?: PanelRow) {
|
||||
const v = label.trim()
|
||||
if (row) {
|
||||
if (v) row.label = v
|
||||
else delete row.label
|
||||
return commit()
|
||||
}
|
||||
if (v) node.label = v
|
||||
else delete node.label
|
||||
delete node.autoLabel
|
||||
commit(false)
|
||||
}
|
||||
|
||||
/** Sets the switches among the parts to 0 or 1, or flips each. */
|
||||
function setSwitches(ids: string[], to: boolean | 'flip') {
|
||||
for (const n of nodesById(ids)) {
|
||||
if (n.kind !== 'input') continue
|
||||
const on = to === 'flip' ? !n.on : to
|
||||
if (!!n.on === on) continue
|
||||
n.on = on
|
||||
sim.value?.setSource(n.id, on)
|
||||
}
|
||||
play(to === false ? 'off' : 'on')
|
||||
persist()
|
||||
}
|
||||
|
||||
/** The same setting on every part (colour, frequency, note size); undefined removes it. */
|
||||
function patchMany(ids: string[], patch: Pick<CircuitNode, 'color' | 'hz' | 'size'>, structural = false) {
|
||||
for (const n of nodesById(ids)) {
|
||||
for (const [k, v] of Object.entries(patch) as [keyof typeof patch, never][]) {
|
||||
if (v === undefined) delete n[k]
|
||||
else n[k] = v
|
||||
}
|
||||
}
|
||||
commit(structural)
|
||||
}
|
||||
|
||||
function arrangeSelected(how: Arrange) {
|
||||
arrangeNodes(nodesById(selection.value), how)
|
||||
commit(false)
|
||||
}
|
||||
|
||||
/** Narrows the selection to some of its parts. */
|
||||
function selectOnly(ids: string[]) {
|
||||
selection.value = ids
|
||||
wireSel.value = []
|
||||
}
|
||||
|
||||
/** Selects a part and centres the view on it. */
|
||||
function focusNode(id: string) {
|
||||
selection.value = [id]
|
||||
wireSel.value = []
|
||||
focusRequest.value = { id, n: (focusRequest.value?.n ?? 0) + 1 }
|
||||
}
|
||||
|
||||
// ── Transistors ───────────────────────────────────────────────────
|
||||
const nands = computed(() => nandCounts(project.value.components))
|
||||
|
||||
|
|
@ -885,6 +975,12 @@ function create() {
|
|||
return (nands.value.get(defId) ?? 0) * TRANSISTORS_PER_NAND
|
||||
}
|
||||
|
||||
/** Transistors in one placed part: 4 for a NAND, its whole inside for a component, 0 for switches, lamps and cables. */
|
||||
function transistorsOfNode(n: CircuitNode): number {
|
||||
if (n.kind === 'nand') return TRANSISTORS_PER_NAND
|
||||
return n.kind === 'chip' && n.chip ? transistors(n.chip) : 0
|
||||
}
|
||||
|
||||
// ── Cables ────────────────────────────────────────────────────────
|
||||
function bundleSelected() {
|
||||
const res = bundleWires(def.value, wireSel.value, getDef.value)
|
||||
|
|
@ -1521,6 +1617,18 @@ function create() {
|
|||
tidyAll,
|
||||
exportTable,
|
||||
transistors,
|
||||
transistorsOfNode,
|
||||
nands,
|
||||
rightTab,
|
||||
focusRequest,
|
||||
swapMany,
|
||||
renameMany,
|
||||
setLabel,
|
||||
setSwitches,
|
||||
patchMany,
|
||||
arrangeSelected,
|
||||
selectOnly,
|
||||
focusNode,
|
||||
canPlaceKind,
|
||||
setInputs,
|
||||
sound,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,134 @@
|
|||
// Working on many parts at once: grouping a selection, numbered names,
|
||||
// the list of a circuit's inputs and outputs, where its transistors are,
|
||||
// and lining parts up.
|
||||
|
||||
import { TRANSISTORS_PER_NAND } from './analyze'
|
||||
import type { DefLookup } from './geometry'
|
||||
import { SINK_KINDS, SOURCE_KINDS } from './ops'
|
||||
import type { CircuitNode, ComponentDef, PanelRow } from './types'
|
||||
|
||||
/** Top to bottom, then left to right: the order pins and names follow. */
|
||||
export const byPosition = (a: CircuitNode, b: CircuitNode) => a.y - b.y || a.x - b.x
|
||||
|
||||
/**
|
||||
* Names for `count` parts from a pattern. Each run of # becomes a number
|
||||
* counting up from `start`, padded to the run's length (D# → D0, D1;
|
||||
* Q## → Q00, Q01). Without #, several parts get the number appended.
|
||||
*/
|
||||
export function numberedNames(pattern: string, count: number, start = 0): string[] {
|
||||
const p = pattern.trim()
|
||||
return Array.from({ length: count }, (_, i) => {
|
||||
const n = start + i
|
||||
if (p.includes('#')) return p.replace(/#+/g, run => String(n).padStart(run.length, '0'))
|
||||
return count === 1 ? p : `${p}${n}`
|
||||
})
|
||||
}
|
||||
|
||||
/** What sort of part a node is: its kind, or the component it places. */
|
||||
export const typeKey = (n: CircuitNode) => (n.kind === 'chip' ? `chip:${n.chip}` : n.kind)
|
||||
|
||||
export type Family = 'logic' | 'source' | 'sink'
|
||||
|
||||
/** The swap family all nodes share (they can all become the same part), or null. */
|
||||
export function sharedFamily(nodes: CircuitNode[]): Family | null {
|
||||
const fam = (n: CircuitNode): Family | null =>
|
||||
n.kind === 'nand' || n.kind === 'chip' ? 'logic' : SOURCE_KINDS.includes(n.kind) ? 'source' : SINK_KINDS.includes(n.kind) ? 'sink' : null
|
||||
const first = nodes[0] && fam(nodes[0])
|
||||
return first && nodes.every(n => fam(n) === first) ? first : null
|
||||
}
|
||||
|
||||
export interface IoEntry {
|
||||
node: CircuitNode
|
||||
/** For a panel: the row this entry stands for. */
|
||||
row?: PanelRow
|
||||
/** Pins are what the circuit shows when used as a component; the rest stays inside. */
|
||||
pin: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* A circuit's inputs and outputs, for renaming them in one place. Pins come
|
||||
* first, in pin order (top to bottom), then switches, buttons, clocks and
|
||||
* panel rows that stay inside, then lamps and displays.
|
||||
*/
|
||||
export function ioList(def: ComponentDef): { inputs: IoEntry[]; outputs: IoEntry[] } {
|
||||
const of = (kinds: string[]) => def.nodes.filter(n => kinds.includes(n.kind)).sort(byPosition)
|
||||
const inputs: IoEntry[] = [
|
||||
...of(['input']).map(node => ({ node, pin: true })),
|
||||
...of(['button', 'clock']).map(node => ({ node, pin: false })),
|
||||
...of(['panel']).flatMap(node => (node.rows ?? []).map(row => ({ node, row, pin: false }))),
|
||||
]
|
||||
const outputs: IoEntry[] = [...of(['output']).map(node => ({ node, pin: true })), ...of(['lamp', 'hex']).map(node => ({ node, pin: false }))]
|
||||
return { inputs, outputs }
|
||||
}
|
||||
|
||||
export const entryLabel = (e: IoEntry) => (e.row ? (e.row.label ?? '') : (e.node.label ?? '')).trim()
|
||||
|
||||
/** Names that more than one entry uses (pins must be told apart, e.g. for challenges and truth tables). */
|
||||
export function duplicateNames(entries: IoEntry[]): Set<string> {
|
||||
const seen = new Set<string>()
|
||||
const dup = new Set<string>()
|
||||
for (const e of entries) {
|
||||
const l = entryLabel(e).toLowerCase()
|
||||
if (!l) continue
|
||||
if (seen.has(l)) dup.add(l)
|
||||
seen.add(l)
|
||||
}
|
||||
return dup
|
||||
}
|
||||
|
||||
export interface CostLine {
|
||||
key: string
|
||||
name: string
|
||||
count: number
|
||||
/** Transistors in one of them. */
|
||||
each: number
|
||||
total: number
|
||||
ids: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a circuit's transistors are: its own parts grouped by type, most
|
||||
* transistors first. Parts without gates (switches, lamps, cables) are left out.
|
||||
*/
|
||||
export function transistorBreakdown(def: ComponentDef, nandsPerDef: Map<string, number>, get: DefLookup): CostLine[] {
|
||||
const lines = new Map<string, CostLine>()
|
||||
for (const n of def.nodes) {
|
||||
let each = 0
|
||||
let name = ''
|
||||
if (n.kind === 'nand') {
|
||||
each = TRANSISTORS_PER_NAND
|
||||
name = 'NAND'
|
||||
} else if (n.kind === 'chip' && n.chip) {
|
||||
each = (nandsPerDef.get(n.chip) ?? 0) * TRANSISTORS_PER_NAND
|
||||
name = get(n.chip)?.name ?? 'Missing component'
|
||||
}
|
||||
if (!each) continue
|
||||
const key = typeKey(n)
|
||||
const line = lines.get(key) ?? { key, name, count: 0, each, total: 0, ids: [] }
|
||||
line.count++
|
||||
line.total += each
|
||||
line.ids.push(n.id)
|
||||
lines.set(key, line)
|
||||
}
|
||||
return [...lines.values()].sort((a, b) => b.total - a.total || a.name.localeCompare(b.name))
|
||||
}
|
||||
|
||||
export type Arrange = 'left' | 'right' | 'top' | 'bottom' | 'spread-x' | 'spread-y'
|
||||
|
||||
/** Lines parts up on their left/right/top/bottom position, or spreads them evenly between the outermost two. */
|
||||
export function arrangeNodes(nodes: CircuitNode[], how: Arrange): void {
|
||||
if (nodes.length < 2) return
|
||||
const xs = nodes.map(n => n.x)
|
||||
const ys = nodes.map(n => n.y)
|
||||
if (how === 'left') for (const n of nodes) n.x = Math.min(...xs)
|
||||
else if (how === 'right') for (const n of nodes) n.x = Math.max(...xs)
|
||||
else if (how === 'top') for (const n of nodes) n.y = Math.min(...ys)
|
||||
else if (how === 'bottom') for (const n of nodes) n.y = Math.max(...ys)
|
||||
else {
|
||||
const axis = how === 'spread-x' ? 'x' : 'y'
|
||||
const sorted = [...nodes].sort((a, b) => a[axis] - b[axis])
|
||||
const lo = sorted[0]![axis]
|
||||
const step = (sorted[sorted.length - 1]![axis] - lo) / (sorted.length - 1)
|
||||
sorted.forEach((n, i) => (n[axis] = Math.round(lo + i * step)))
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
import { nandCounts, TRANSISTORS_PER_NAND } from '../app/lib/logic/analyze'
|
||||
import { arrangeNodes, duplicateNames, entryLabel, ioList, numberedNames, sharedFamily, transistorBreakdown } from '../app/lib/logic/bulk'
|
||||
import { compile } from '../app/lib/logic/compile'
|
||||
import { createProject, lookup } from '../app/lib/logic/ops'
|
||||
import type { CircuitNode, ComponentDef } from '../app/lib/logic/types'
|
||||
import { NAND_BASE, wideGate } from '../app/lib/logic/wide'
|
||||
|
||||
const node = (id: string, kind: CircuitNode['kind'], x: number, y: number, extra: Partial<CircuitNode> = {}): CircuitNode => ({ id, kind, x, y, ...extra })
|
||||
|
||||
describe('numbered names', () => {
|
||||
it('replaces # runs with a padded counter', () => {
|
||||
expect(numberedNames('D#', 3)).toEqual(['D0', 'D1', 'D2'])
|
||||
expect(numberedNames('Q##', 2, 9)).toEqual(['Q09', 'Q10'])
|
||||
expect(numberedNames('Bit # of #', 2, 1)).toEqual(['Bit 1 of 1', 'Bit 2 of 2'])
|
||||
})
|
||||
|
||||
it('appends the number when there is no #, unless it is a single part', () => {
|
||||
expect(numberedNames('IN', 3, 1)).toEqual(['IN1', 'IN2', 'IN3'])
|
||||
expect(numberedNames('Reset', 1)).toEqual(['Reset'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('the list of inputs and outputs', () => {
|
||||
const def: ComponentDef = {
|
||||
id: 'd',
|
||||
name: 'D',
|
||||
symbol: 'box',
|
||||
nodes: [
|
||||
node('b', 'input', 0, 4, { label: 'B' }),
|
||||
node('a', 'input', 0, 0, { label: 'A' }),
|
||||
node('clk', 'clock', 0, 10),
|
||||
node('p', 'panel', 0, 14, { rows: [{ id: 'r1', type: 'switch', label: 'EN' }, { id: 'r2', type: 'button' }] }),
|
||||
node('l', 'lamp', 10, 4, { label: 'A' }),
|
||||
node('q', 'output', 10, 0, { label: 'Q' }),
|
||||
node('g', 'nand', 5, 0),
|
||||
],
|
||||
wires: [],
|
||||
}
|
||||
|
||||
it('lists pins first in pin order, then the parts that stay inside, with panel rows', () => {
|
||||
const { inputs, outputs } = ioList(def)
|
||||
expect(inputs.map(e => `${e.node.id}${e.row ? `/${e.row.id}` : ''}:${e.pin}`)).toEqual(['a:true', 'b:true', 'clk:false', 'p/r1:false', 'p/r2:false'])
|
||||
expect(outputs.map(e => e.node.id)).toEqual(['q', 'l'])
|
||||
expect(inputs.map(entryLabel)).toEqual(['A', 'B', '', 'EN', ''])
|
||||
})
|
||||
|
||||
it('flags names used twice on the same side only', () => {
|
||||
const { inputs, outputs } = ioList(def)
|
||||
expect([...duplicateNames(inputs)]).toEqual([])
|
||||
expect([...duplicateNames([...inputs, ...outputs])]).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('selections', () => {
|
||||
it('knows when parts can all be swapped to the same thing', () => {
|
||||
expect(sharedFamily([node('1', 'input', 0, 0), node('2', 'clock', 0, 0)])).toBe('source')
|
||||
expect(sharedFamily([node('1', 'nand', 0, 0), node('2', 'chip', 0, 0, { chip: 'x' })])).toBe('logic')
|
||||
expect(sharedFamily([node('1', 'lamp', 0, 0), node('2', 'output', 0, 0)])).toBe('sink')
|
||||
expect(sharedFamily([node('1', 'lamp', 0, 0), node('2', 'input', 0, 0)])).toBeNull()
|
||||
})
|
||||
|
||||
it('lines parts up and spreads them evenly', () => {
|
||||
const ns = [node('1', 'input', 3, 0), node('2', 'input', 1, 7), node('3', 'input', 2, 3)]
|
||||
arrangeNodes(ns, 'left')
|
||||
expect(ns.map(n => n.x)).toEqual([1, 1, 1])
|
||||
arrangeNodes(ns, 'spread-y')
|
||||
expect(ns.map(n => n.y).sort((a, b) => a - b)).toEqual([0, 4, 7])
|
||||
})
|
||||
})
|
||||
|
||||
describe('transistors', () => {
|
||||
const p = createProject({ examples: true })
|
||||
for (const base of [NAND_BASE, 'ex-and', 'ex-or', 'ex-xor', 'ex-nor']) for (const n of [3, 8, 16]) wideGate(p, base, n)
|
||||
const get = lookup(p)
|
||||
const counts = nandCounts(p.components)
|
||||
|
||||
it('count 4 per NAND gate the simulator actually builds, in every component', () => {
|
||||
for (const d of p.components) expect(counts.get(d.id) ?? 0, d.name).toBe(compile(get, d.id).gateOut.length)
|
||||
})
|
||||
|
||||
it('match the textbook NAND builds', () => {
|
||||
const t = (id: string) => (counts.get(id) ?? 0) * TRANSISTORS_PER_NAND
|
||||
expect([t('ex-not'), t('ex-and'), t('ex-or'), t('ex-xor'), t('ex-ha'), t('ex-fa')]).toEqual([4, 8, 12, 16, 24, 60])
|
||||
})
|
||||
|
||||
it('break a circuit down into its parts, adding up to the total', () => {
|
||||
const fa = get('ex-fa')!
|
||||
const lines = transistorBreakdown(fa, counts, get)
|
||||
expect(lines.map(l => [l.name, l.count, l.each, l.total])).toEqual([
|
||||
['Half Adder', 2, 24, 48],
|
||||
['OR', 1, 12, 12],
|
||||
])
|
||||
expect(lines.reduce((s, l) => s + l.total, 0)).toBe((counts.get('ex-fa') ?? 0) * TRANSISTORS_PER_NAND)
|
||||
})
|
||||
})
|
||||
Loading…
Reference in New Issue