A finer component boxes, a regrouped parts list with keyboard search, a real green for wires and cables

- Box designer: drag pins up or down to open gaps between groups; size (+/−) and turn (R) lamps, displays, screens and drawings; pixels belong to named screens, each placed on its own; displays of the components inside can be shown on the box (off unless ticked); a list of everything the box can show, each optional; the box grows to hold what it shows
- Lamps and displays deep inside placed components light up on the box
- Parts list: one search box for parts and components (letters in order match too), recently placed parts first, grouped Logic / Inputs / Outputs / Wiring / Notes, then components by group; groups fold away
- Keys: / searches the parts list (Enter starts placing), Shift+A or Ctrl+K adds a part at the mouse
- Wires and cables get a green; the default swatch shows grey, as the default really is

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-22 06:48:42 +02:00
parent 09f945d2c5
commit 794acad140
20 changed files with 1221 additions and 249 deletions

View File

@ -450,6 +450,80 @@ kbd {
width: 100%;
}
.search.part-search {
margin: 10px 10px 4px;
}
.search.part-search:focus-within {
border-color: var(--accent);
}
.search kbd {
padding: 0 5px;
border: 1px solid var(--border);
border-radius: 4px;
color: var(--muted);
font-family: var(--font-mono);
font-size: 10px;
}
/* Parts list groups: a heading that folds the group away. */
.group-head {
display: flex;
align-items: center;
gap: 5px;
width: 100%;
padding: 12px 10px 5px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-align: left;
text-transform: uppercase;
}
.group-head:hover {
color: var(--text);
}
.group-count {
margin-left: auto;
font-family: var(--font-mono);
font-size: 10px;
font-weight: 500;
letter-spacing: 0;
}
.group-tag {
color: var(--muted);
font-size: 11px;
}
.recent-parts {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 0 10px;
}
.recent-chip {
display: inline-flex;
max-width: 100%;
align-items: center;
gap: 5px;
padding: 3px 8px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel-2);
color: var(--text);
font-size: 12px;
cursor: grab;
}
.recent-chip:hover {
border-color: var(--accent);
}
.intro {
padding: 12px;
font-size: 13px;
@ -739,6 +813,7 @@ kbd {
.wire.c-red { --w-on: #ff5c5c; --w-off: #6b3337; }
.wire.c-orange { --w-on: #ff9f43; --w-off: #6b4a2b; }
.wire.c-yellow { --w-on: #ffd93d; --w-off: #625a2e; }
.wire.c-green { --w-on: #3ddc84; --w-off: #2a5a3f; }
.wire.c-blue { --w-on: #4dabff; --w-off: #2b4a6b; }
.wire.c-purple { --w-on: #b388ff; --w-off: #463768; }
.wire.c-pink { --w-on: #ff7ac6; --w-off: #673657; }
@ -851,6 +926,7 @@ kbd {
.harness.c-red { --w-on: #ff5c5c; --w-off: #6b3337; }
.harness.c-orange { --w-on: #ff9f43; --w-off: #6b4a2b; }
.harness.c-yellow { --w-on: #ffd93d; --w-off: #625a2e; }
.harness.c-green { --w-on: #3ddc84; --w-off: #2a5a3f; }
.harness.c-blue { --w-on: #4dabff; --w-off: #2b4a6b; }
.harness.c-purple { --w-on: #b388ff; --w-off: #463768; }
.harness.c-pink { --w-on: #ff7ac6; --w-off: #673657; }
@ -1717,13 +1793,15 @@ kbd {
outline: 1px solid var(--border);
}
/* The default colour: grey like an unlit wire or a cable's sleeve, struck through. */
.swatch.none {
background: var(--on);
background: linear-gradient(135deg, transparent 45%, #8592a3 45% 55%, transparent 55%), #3b4554;
}
.swatch.c-red { --w-on: #ff5c5c; }
.swatch.c-orange { --w-on: #ff9f43; }
.swatch.c-yellow { --w-on: #ffd93d; }
.swatch.c-green { --w-on: #3ddc84; }
.swatch.c-blue { --w-on: #4dabff; }
.swatch.c-purple { --w-on: #b388ff; }
.swatch.c-pink { --w-on: #ff7ac6; }
@ -2643,6 +2721,7 @@ kbd {
.lane.c-red { --w-on: #ff5c5c; --w-off: #6b3337; }
.lane.c-orange { --w-on: #ff9f43; --w-off: #6b4a2b; }
.lane.c-yellow { --w-on: #ffd93d; --w-off: #625a2e; }
.lane.c-green { --w-on: #3ddc84; --w-off: #2a5a3f; }
.lane.c-blue { --w-on: #4dabff; --w-off: #2b4a6b; }
.lane.c-purple { --w-on: #b388ff; --w-off: #463768; }
.lane.c-pink { --w-on: #ff7ac6; --w-off: #673657; }
@ -3077,7 +3156,65 @@ kbd {
/* ── Face designer ──────────────────────────────────────────────── */
.modal.face-modal {
width: min(760px, 100%);
width: min(900px, 100%);
}
.face-body {
display: flex;
gap: 12px;
align-items: flex-start;
}
.face-side {
flex: 1 1 200px;
min-width: 0;
max-height: 440px;
overflow-y: auto;
}
.face-side h3 {
margin: 0 0 6px;
}
.face-side h3 + * {
margin-bottom: 4px;
}
.face-side .hint {
margin: 0 0 6px;
}
.face-list {
display: grid;
gap: 1px;
margin-bottom: 12px;
}
.face-list li {
padding: 2px 4px;
border-radius: 5px;
font-size: 12px;
}
.face-list li.sel {
background: rgb(76 194 255 / 0.12);
}
.face-list .check {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.face-thing.face-pinbox {
stroke: transparent;
cursor: ns-resize;
}
.face-thing.face-pinbox:hover,
.face-thing.face-pinbox.sel {
stroke: rgb(76 194 255 / 0.7);
}
.face-tools {
@ -3223,3 +3360,20 @@ kbd {
border-color: var(--accent);
color: var(--accent);
}
/* ── Quick add (Shift+A, Ctrl+K) ────────────────────────────────── */
.quick-add {
position: fixed;
z-index: 60;
width: 300px;
padding-bottom: 6px;
border: 1px solid #2d3745;
border-radius: 10px;
background: rgb(22 28 36 / 0.97);
box-shadow: 0 12px 32px rgb(0 0 0 / 0.45);
animation: ctx-in 90ms ease-out;
}
.quick-add .item {
cursor: pointer;
}

View File

@ -69,6 +69,10 @@ function rename() {
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 sameScreen = computed(() => {
const set = new Set(nodes.value.map(n => n.screen ?? ''))
return set.size === 1 ? [...set][0] : ''
})
const color = computed(() => {
const set = new Set(nodes.value.map(n => n.color ?? ''))
return set.size === 1 ? [...set][0] : null
@ -239,6 +243,15 @@ function pack() {
</div>
</div>
<label v-if="only('pixel')" class="field" title="Pixels with the same screen name make one screen on the component's box">
<span>Screen on the box, for all</span>
<input
:value="sameScreen"
placeholder="Main screen"
@change="ed.setScreen(ids, ($event.target as HTMLInputElement).value)"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
</label>
<div v-if="colorable" class="field">
<span>Colour</span>
<div class="swatches">

View File

@ -604,6 +604,7 @@ function onWireDown(e: PointerEvent, el: Element, w: Pt) {
}
function onPointerMove(e: PointerEvent) {
lastClient = { x: e.clientX, y: e.clientY }
const w = toWorld(e)
cursor.value = w
altDown.value = e.altKey
@ -925,6 +926,17 @@ function onKey(e: KeyboardEvent) {
e.preventDefault()
return openMenuForSelection()
}
// Finding parts from the keyboard: / searches the parts list, Shift+A or Ctrl+K adds one at the mouse.
if (e.key === '/' && !mod) {
e.preventDefault()
ed.toggleSidebar('left', true)
ed.partSearch.value++
return
}
if ((e.shiftKey && key === 'a' && !mod) || (mod && key === 'k')) {
e.preventDefault()
return openQuickAdd()
}
// Keys bound to switches, buttons and panel rows win over the shortcuts below.
if (!mod && !e.altKey && e.key.length === 1) {
const bound = def.value.nodes.filter(n => n.key === key && (n.kind === 'input' || n.kind === 'button'))
@ -1188,6 +1200,27 @@ watch(
},
)
// ── Quick add ───────────────────────────────────────────────────────
/** The quick-add box: where it opened on screen and on the canvas. */
const quick = ref<{ x: number; y: number; at: Pt } | null>(null)
let lastClient = { x: 0, y: 0 }
function openQuickAdd() {
const r = root.value!.getBoundingClientRect()
const inside = lastClient.x >= r.left && lastClient.x <= r.right && lastClient.y >= r.top && lastClient.y <= r.bottom
const x = inside ? lastClient.x : r.left + r.width / 2
const y = inside ? lastClient.y : r.top + r.height / 3
quick.value = { x, y, at: toWorld({ clientX: x, clientY: y }) }
}
function onQuickPick(p: { kind: CircuitNode['kind']; chip?: string }) {
const q = quick.value
quick.value = null
if (!q) return
const { node, links } = landing(p, q.at, false)
ed.addNode(p, node.x, node.y, links)
}
// ── Context menu ────────────────────────────────────────────────────
const menu = ref<{ x: number; y: number; entries: MenuEntry[]; keyboard?: boolean } | null>(null)
const { build } = useMenu()
@ -1500,6 +1533,7 @@ defineExpose({ fit, zoomAt })
<rect v-if="boxRect" v-bind="boxRect" />
</g>
</svg>
<EditorQuickAdd v-if="quick" :x="quick.x" :y="quick.y" @pick="onQuickPick" @close="quick = null" />
<EditorContextMenu v-if="menu" :x="menu.x" :y="menu.y" :entries="menu.entries" :keyboard="menu.keyboard" @close="menu = null" />
<div v-if="!def.nodes.length" class="empty-hint">

View File

@ -1,8 +1,9 @@
<script setup lang="ts">
// Drawing a component's box by hand: drag its lamps, displays, screen and
// name where they belong, draw lines, boxes, circles and text on it, size
// it. Everything shows live on the box, and on every copy placed.
import { GRID as G } from '~/lib/logic/geometry'
// Drawing a component's box by hand: place, size and turn its lamps,
// displays, screens and name; show displays of the components inside it;
// space its pins apart; draw lines, boxes, circles and text. Everything
// shows live on the box, and on every copy placed.
import { faceCandidates, faceTransform, GRID as G, shapeTransform, type FaceItem } from '~/lib/logic/geometry'
import { uid } from '~/lib/logic/ops'
import { FACE_INKS, type CircuitNode, type FaceDesign, type FaceInk, type FaceShape } from '~/lib/logic/types'
@ -14,7 +15,7 @@ const body = computed(() => shape.value.body)
type Tool = 'move' | 'line' | 'rect' | 'ellipse' | 'text'
const TOOLS: { id: Tool; icon: string; title: string }[] = [
{ id: 'move', icon: 'lucide:mouse-pointer-2', title: 'Move and resize' },
{ id: 'move', icon: 'lucide:mouse-pointer-2', title: 'Move, size and turn' },
{ id: 'line', icon: 'lucide:minus', title: 'Line' },
{ id: 'rect', icon: 'lucide:square', title: 'Box' },
{ id: 'ellipse', icon: 'lucide:circle', title: 'Circle' },
@ -24,12 +25,12 @@ const INK_HEX: Record<FaceInk, string> = { muted: '#6b778a', text: '#dbe2ea', re
const tool = ref<Tool>('move')
const ink = ref<FaceInk>('muted')
const fill = ref(false)
/** What is selected: a drawing's id, a lamp or display node id, 'screen' or 'name'. */
/** What is selected: a drawing's id, a box item's key, 'name', or 'pin:<key>'. */
const sel = ref<string | null>(null)
const VIEW_W = 700
const VIEW_H = 420
const PAD = 30
const VIEW_W = 620
const VIEW_H = 440
const PAD = 34
const k = computed(() => Math.min(3, (VIEW_W - 2 * PAD) / (Math.max(body.value.w, 4) * G), (VIEW_H - 2 * PAD) / (Math.max(body.value.h, 3) * G)))
const svg = ref<SVGSVGElement>()
@ -39,7 +40,7 @@ function design(): FaceDesign {
if (!d.design) {
const s = shape.value
const place: Record<string, { x: number; y: number }> = {}
for (const it of s.face ?? []) place[it.kind === 'screen' ? 'screen' : it.id] = { x: it.x, y: it.y - s.body.y }
for (const it of s.face ?? []) place[it.key] = { x: it.x, y: it.y - s.body.y }
d.design = { w: s.body.w, h: s.body.h, place, shapes: [] }
}
d.design.place ??= {}
@ -56,39 +57,42 @@ function at(e: PointerEvent) {
}
const nameText = computed(() => def.value?.name ?? '')
const top = computed(() => body.value.y)
/** Everything that can be grabbed on the box, in grid units from its top left corner. */
const things = computed(() => {
const top = body.value.y
const out: { id: string; label: string; x: number; y: number; w: number; h: number }[] = []
for (const it of shape.value.face ?? []) {
out.push({ id: it.kind === 'screen' ? 'screen' : it.id, label: it.label || it.kind, x: it.x, y: it.y - top, w: it.w, h: it.h })
}
if (shape.value.nameAt !== null) {
const c = shape.value.nameAt ?? { x: body.value.w / 2, y: shape.value.nameY ?? 0 }
const w = nameText.value.length * 0.5 + 0.6
out.push({ id: 'name', label: 'name', x: c.x - w / 2, y: c.y - top - 0.55, w, h: 1.1 })
}
return out
/** The box's items as placed, plus the name, to grab. */
const items = computed(() => shape.value.face ?? [])
const nameBox = computed(() => {
if (shape.value.nameAt === null) return null
const c = shape.value.nameAt ?? { x: body.value.w / 2, y: shape.value.nameY ?? 0 }
const w = nameText.value.length * 0.5 + 0.6
return { x: c.x - w / 2, y: c.y - 0.55, w, h: 1.1 }
})
/** Pins on both edges, to drag up and down. */
const pins = computed(() => [
...shape.value.inputs.filter(p => !p.bus).map(p => ({ ...p, side: 'in' as const })),
...shape.value.outputs.filter(p => !p.bus).map(p => ({ ...p, side: 'out' as const })),
])
const shapes = computed(() => def.value?.design?.shapes ?? [])
const selShape = computed(() => shapes.value.find(s => s.id === sel.value))
const selThing = computed(() => things.value.find(t => t.id === sel.value))
const selItem = computed(() => items.value.find(it => it.key === sel.value))
/** Things left off the box, to put back. */
const hidden = computed(() => {
/** Everything the box can show, with whether it does. */
const candidates = computed(() => {
const d = def.value
return (d?.design?.hide ?? []).map(id => ({
id,
label: id === 'name' ? 'Name' : id === 'screen' ? 'Screen' : d?.nodes.find(n => n.id === id)?.label?.trim() || (d?.nodes.find(n => n.id === id)?.kind ?? id),
}))
if (!d) return []
const hide = new Set(d.design?.hide ?? [])
const show = new Set(d.design?.show ?? [])
return faceCandidates(d, ed.getDef.value).map(c => ({ ...c, shown: c.nested ? show.has(c.key) && !hide.has(c.key) : !hide.has(c.key) }))
})
const nameShown = computed(() => !(def.value?.design?.hide ?? []).includes('name'))
type Drag =
| { type: 'create'; id: string }
| { type: 'move'; id: string; start: { x: number; y: number }; orig: { x: number; y: number } }
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
| { type: 'pin'; key: string; side: 'in' | 'out'; start: number; rows: { key: string; dy: number; set: boolean }[]; index: number }
const drag = ref<Drag | null>(null)
function onDown(e: PointerEvent) {
@ -120,14 +124,22 @@ function onDown(e: PointerEvent) {
return
}
sel.value = id
if (id.startsWith('pin:')) {
const key = id.slice(4)
const pin = pins.value.find(x => x.key === key)!
const side = pins.value.filter(x => x.side === pin.side)
const pinAt = def.value.design?.pinAt ?? {}
drag.value = { type: 'pin', key, side: pin.side, start: p.y, rows: side.map(x => ({ key: x.key, dy: x.dy, set: pinAt[x.key] !== undefined })), index: side.findIndex(x => x.key === key) }
return
}
const handle = el!.getAttribute('data-handle') as 'a' | 'b' | null
const sh = shapes.value.find(s => s.id === id)
if (handle && sh) {
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
return
}
const t = things.value.find(x => x.id === id)
const orig = sh ? { x: sh.x, y: sh.y } : t ? { x: t.x, y: t.y } : null
const it = items.value.find(x => x.key === id)
const orig = sh ? { x: sh.x, y: sh.y } : it ? { x: it.x, y: it.y - top.value } : id === 'name' && nameBox.value ? { x: nameBox.value.x, y: nameBox.value.y - top.value } : null
if (orig) drag.value = { type: 'move', id, start: p, orig }
}
@ -147,6 +159,17 @@ function onMove(e: PointerEvent) {
}
return
}
if (d.type === 'pin') {
// Dragging a pin moves it and the pins below it on that edge: a gap opens above it.
const prev = d.index > 0 ? d.rows[d.index - 1]!.dy : -1
const delta = Math.max(Math.round(p.y - d.start), prev + 1 - d.rows[d.index]!.dy)
const pinAt = (design().pinAt ??= {})
d.rows.forEach((r, i) => {
if (i === d.index) pinAt[r.key] = Math.max(0, r.dy + delta)
else if (i > d.index && r.set) pinAt[r.key] = Math.max(0, r.dy + delta)
})
return
}
if (d.type === 'move') {
const x = snap(d.orig.x + p.x - d.start.x)
const y = snap(d.orig.y + p.y - d.start.y)
@ -198,17 +221,64 @@ function remove() {
ed.commit(false)
}
function hide(id: string) {
/** Shows or leaves off a thing: own items are shown unless left off, displays of parts inside only when shown. */
function setShown(key: string, nested: boolean, on: boolean) {
const d = design()
d.hide = [...new Set([...(d.hide ?? []), id])]
sel.value = null
const hide = new Set(d.hide ?? [])
const show = new Set(d.show ?? [])
if (on) hide.delete(key)
else hide.add(key)
if (nested) {
if (on) show.add(key)
else show.delete(key)
}
d.hide = [...hide]
d.show = [...show]
if (!d.hide.length) delete d.hide
if (!d.show.length) delete d.show
if (!on && sel.value === key) sel.value = null
ed.commit(false)
}
function show(id: string) {
/** Grows or shrinks the selected item (steps of a quarter), or the size of a text. */
function grow(by: number) {
const s = selShape.value
if (s?.kind === 'text') {
s.size = Math.min(4, Math.max(0.5, Math.round(((s.size ?? 1) + by) * 4) / 4))
return ed.commit(false)
}
const key = sel.value
if (!key || !selItem.value) return
const d = design()
d.hide = (d.hide ?? []).filter(x => x !== id)
if (!d.hide.length) delete d.hide
const next = Math.min(4, Math.max(0.25, Math.round(((d.scale?.[key] ?? 1) + by) * 4) / 4))
d.scale ??= {}
if (next === 1) delete d.scale[key]
else d.scale[key] = next
ed.commit(false)
}
/** Turns the selected item or drawing a quarter. */
function turn(by: 90 | -90) {
const s = selShape.value
if (s) {
const r = (((s.rotate ?? 0) + by) % 360 + 360) % 360
if (r) s.rotate = r
else delete s.rotate
return ed.commit(false)
}
const key = sel.value
if (!key || !selItem.value) return
const d = design()
const r = (((d.rotate?.[key] ?? 0) + by) % 360 + 360) % 360
d.rotate ??= {}
if (r) d.rotate[key] = r
else delete d.rotate[key]
ed.commit(false)
}
function resetPins() {
if (!def.value?.design?.pinAt) return
delete def.value.design.pinAt
ed.commit(false)
}
@ -233,7 +303,7 @@ function toggleFill() {
function setSize(axis: 'w' | 'h', e: Event) {
const v = Number((e.target as HTMLInputElement).value)
if (!(v > 0)) return
design()[axis] = Math.min(80, Math.max(2, Math.round(v * 2) / 2))
design()[axis] = Math.min(120, Math.max(2, Math.round(v * 2) / 2))
ed.commit(false)
}
@ -246,12 +316,18 @@ function reset() {
const textInput = ref<HTMLInputElement>()
// Keys while the designer is open: R turns, + and − size, Delete removes a drawing.
onMounted(() => window.addEventListener('keydown', onKey))
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
function onKey(e: KeyboardEvent) {
if ((e.target as HTMLElement).closest('input, textarea, select')) return
if ((e.target as HTMLElement).closest?.('input, textarea, select') || e.ctrlKey || e.metaKey || e.altKey) return
if ((e.key === 'Delete' || e.key === 'Backspace') && selShape.value) {
e.preventDefault()
remove()
}
} else if (e.key === 'r' || e.key === 'R') turn(e.shiftKey ? -90 : 90)
else if (e.key === '+' || e.key === '=') grow(0.25)
else if (e.key === '-') grow(-0.25)
}
function close() {
@ -268,15 +344,25 @@ const grips = computed(() => {
{ h: 'b', x: s.x + s.w, y: s.y + s.h },
]
})
const kindName = (it: FaceItem) => (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
const selLabel = computed(() => {
if (selShape.value) return { line: 'Line', rect: 'Box', ellipse: 'Circle', text: 'Text' }[selShape.value.kind]
if (selItem.value) return `${kindName(selItem.value)}${selItem.value.label ? ` ${selItem.value.label}` : ''}`
if (sel.value === 'name') return 'The name'
if (sel.value?.startsWith('pin:')) return `Pin ${pins.value.find(p => `pin:${p.key}` === sel.value)?.label ?? ''}`
return ''
})
const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:binary', screen: 'lucide:monitor' }
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div v-if="def" class="modal face-modal" role="dialog" aria-labelledby="face-title" tabindex="-1" @keydown="onKey">
<div v-if="def" class="modal face-modal" role="dialog" aria-labelledby="face-title" tabindex="-1">
<div class="flex items-start justify-between gap-4">
<div>
<h2 id="face-title">The box of "{{ def.name }}"</h2>
<p class="hint mt-1">Drag lamps, displays and the name where you want them, draw on it, size it. Every placed copy shows it.</p>
<p class="hint mt-1">Place, size and turn what it shows, drag pins apart, draw on it. Every placed copy shows it.</p>
</div>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
@ -301,98 +387,161 @@ const grips = computed(() => {
<button class="btn-sm" :class="{ on: selShape?.fill ?? fill }" title="Fill boxes and circles lightly" @click="toggleFill">
<Icon name="lucide:paint-bucket" class="size-3.5" /> Fill
</button>
<label class="face-size">W <input type="number" min="2" max="80" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
<label class="face-size">H <input type="number" min="2" max="80" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
<label class="face-size">W <input type="number" min="2" max="120" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
<label class="face-size">H <input type="number" min="2" max="120" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
<button class="btn-sm ml-auto" :disabled="!def.design" title="Back to the automatic layout; drawings are removed" @click="reset">
<Icon name="lucide:rotate-ccw" class="size-3.5" /> Automatic
</button>
</div>
<svg
ref="svg"
class="face-canvas"
:class="{ drawing: tool !== 'move' }"
:width="VIEW_W"
:height="VIEW_H"
@pointerdown="onDown"
@pointermove="onMove"
@pointerup="onUp"
@pointercancel="onUp"
>
<defs>
<pattern id="face-grid" :width="G * k / 2" :height="G * k / 2" patternUnits="userSpaceOnUse" :x="PAD" :y="PAD">
<circle cx="0.6" cy="0.6" r="0.6" fill="#2a3442" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#face-grid)" />
<g :transform="`translate(${PAD} ${PAD - body.y * G * k}) scale(${k})`">
<EditorNodeView :node="preview" :shape="shape" :selected="false" />
<g :transform="`translate(0 ${body.y * G})`">
<div class="face-body">
<svg
ref="svg"
class="face-canvas"
:class="{ drawing: tool !== 'move' }"
:width="VIEW_W"
:height="VIEW_H"
@pointerdown="onDown"
@pointermove="onMove"
@pointerup="onUp"
@pointercancel="onUp"
>
<defs>
<pattern id="face-grid" :width="(G * k) / 2" :height="(G * k) / 2" patternUnits="userSpaceOnUse" :x="PAD" :y="PAD">
<circle cx="0.6" cy="0.6" r="0.6" fill="#2a3442" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#face-grid)" />
<g :transform="`translate(${PAD} ${PAD - body.y * G * k}) scale(${k})`">
<EditorNodeView :node="preview" :shape="shape" :selected="false" />
<!-- Things on the box, grabbed where they are drawn (sized and turned alike) -->
<g v-for="it in items" :key="it.key" :transform="faceTransform(it)">
<rect
:x="it.x * G - 2"
:y="it.y * G - 2"
:width="it.w * G + 4"
:height="it.h * G + 4"
rx="3"
class="face-thing"
:class="{ sel: sel === it.key }"
:data-face="it.key"
/>
</g>
<rect
v-for="t in things"
:key="t.id"
:x="t.x * G - 2"
:y="t.y * G - 2"
:width="t.w * G + 4"
:height="t.h * G + 4"
v-if="nameBox"
:x="nameBox.x * G"
:y="nameBox.y * G"
:width="nameBox.w * G"
:height="nameBox.h * G"
rx="3"
class="face-thing"
:class="{ sel: sel === t.id }"
:data-face="t.id"
:class="{ sel: sel === 'name' }"
data-face="name"
/>
<template v-for="s in shapes" :key="s.id">
<line
v-if="s.kind === 'line'"
:x1="s.x * G"
:y1="s.y * G"
:x2="(s.x + s.w) * G"
:y2="(s.y + s.h) * G"
class="face-hit"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
<rect
v-else
:x="Math.min(s.x, s.x + s.w) * G - 2"
:y="Math.min(s.y, s.y + s.h) * G - 2"
:width="Math.max(Math.abs(s.w) * G, s.kind === 'text' ? (s.text?.length ?? 1) * 6.6 * (s.size ?? 1) : 0) + 4"
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
rx="2"
class="face-thing shape"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
</template>
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
<rect
v-for="p in pins"
:key="`pin-${p.key}`"
:x="(p.dx - (p.side === 'in' ? 0.45 : 1.6)) * G"
:y="(p.dy - 0.42) * G"
:width="2.05 * G"
:height="0.84 * G"
rx="3"
class="face-thing face-pinbox"
:class="{ sel: sel === `pin:${p.key}` }"
:data-face="`pin:${p.key}`"
/>
<g :transform="`translate(0 ${body.y * G})`">
<g v-for="s in shapes" :key="s.id" :transform="shapeTransform(s)">
<line
v-if="s.kind === 'line'"
:x1="s.x * G"
:y1="s.y * G"
:x2="(s.x + s.w) * G"
:y2="(s.y + s.h) * G"
class="face-hit"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
<rect
v-else
:x="Math.min(s.x, s.x + s.w) * G - 2"
:y="Math.min(s.y, s.y + s.h) * G - 2"
:width="Math.max(Math.abs(s.w) * G, s.kind === 'text' ? (s.text?.length ?? 1) * 6.6 * (s.size ?? 1) : 0) + 4"
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
rx="2"
class="face-thing shape"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
</g>
<g v-if="selShape" :transform="shapeTransform(selShape)">
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
</g>
</g>
</g>
</g>
</svg>
</svg>
<aside class="face-side">
<h3>On the box</h3>
<ul class="face-list">
<li>
<label class="check">
<input type="checkbox" :checked="nameShown" @change="setShown('name', false, ($event.target as HTMLInputElement).checked)" />
<Icon name="lucide:type" class="size-3.5" /> Name
</label>
</li>
<li v-for="c in candidates.filter(x => !x.nested)" :key="c.key" :class="{ sel: sel === c.key }">
<label class="check">
<input type="checkbox" :checked="c.shown" @change="setShown(c.key, false, ($event.target as HTMLInputElement).checked)" />
<Icon :name="ICON[c.kind] ?? 'lucide:box'" class="size-3.5" />
<span class="truncate">{{ c.label }}</span>
</label>
</li>
</ul>
<template v-if="candidates.some(x => x.nested)">
<h3>From parts inside</h3>
<ul class="face-list">
<li v-for="c in candidates.filter(x => x.nested)" :key="c.key" :class="{ sel: sel === c.key }">
<label class="check">
<input type="checkbox" :checked="c.shown" @change="setShown(c.key, true, ($event.target as HTMLInputElement).checked)" />
<Icon :name="ICON[c.kind] ?? 'lucide:box'" class="size-3.5" />
<span class="truncate">{{ c.label }}</span>
</label>
</li>
</ul>
</template>
<p v-if="!candidates.length" class="hint">No lamps, displays or pixels inside yet.</p>
<h3>Pins</h3>
<p class="hint">Drag a pin up or down: the pins under it follow, so groups get gaps.</p>
<button class="btn-sm" :disabled="!def.design?.pinAt" @click="resetPins"><Icon name="lucide:rows-3" class="size-3.5" /> Pins evenly again</button>
</aside>
</div>
<div class="face-props">
<template v-if="selShape">
<template v-if="selShape.kind === 'text'">
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
<select :value="selShape.size ?? 1" class="text-input w-28" @change="(selShape.size = Number(($event.target as HTMLSelectElement).value)), ed.commit(false)">
<option :value="0.75">Small</option>
<option :value="1">Normal</option>
<option :value="1.5">Large</option>
<option :value="2">Huge</option>
</select>
<template v-if="sel && selLabel">
<span class="font-semibold">{{ selLabel }}</span>
<template v-if="selShape || selItem">
<div class="flex gap-1" title="Turn (R, Shift+R)">
<button class="icon-btn" @click="turn(-90)"><Icon name="lucide:rotate-ccw" class="size-4" /></button>
<button class="icon-btn" @click="turn(90)"><Icon name="lucide:rotate-cw" class="size-4" /></button>
</div>
<div v-if="selItem || selShape?.kind === 'text'" class="flex items-center gap-1" title="Size (+, −)">
<button class="icon-btn" @click="grow(-0.25)"><Icon name="lucide:minus" class="size-4" /></button>
<span class="tabular-nums text-xs">{{ Math.round(((selShape ? selShape.size : def.design?.scale?.[sel]) ?? 1) * 100) }}%</span>
<button class="icon-btn" @click="grow(0.25)"><Icon name="lucide:plus" class="size-4" /></button>
</div>
</template>
<span v-else class="hint">{{ { line: 'Line', rect: 'Box', ellipse: 'Circle' }[selShape.kind] }}: drag it, or its dots to resize. Shift keeps a new line straight.</span>
<button class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
<template v-if="selShape?.kind === 'text'">
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
</template>
<button v-if="selShape" class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
<button v-else-if="selItem" class="btn-sm ml-auto" @click="setShown(selItem.key, selItem.key.includes('/'), false)">
<Icon name="lucide:eye-off" class="size-3.5" /> Leave off
</button>
<button v-else-if="sel === 'name'" class="btn-sm ml-auto" @click="setShown('name', false, false)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off</button>
</template>
<template v-else-if="selThing">
<span class="hint">{{ selThing.id === 'name' ? 'The name' : selThing.label }}: drag it where it belongs.</span>
<button class="btn-sm ml-auto" @click="hide(selThing.id)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off the box</button>
</template>
<span v-else class="hint">Pick a tool to draw, or drag things on the box. Delete removes a drawing.</span>
</div>
<div v-if="hidden.length" class="face-hidden">
<span class="hint">Left off:</span>
<button v-for="h in hidden" :key="h.id" class="btn-sm" title="Put it back on the box" @click="show(h.id)">
<Icon name="lucide:eye" class="size-3.5" /> {{ h.label }}
</button>
<span v-else class="hint">Pick a tool to draw, or drag things on the box. R turns, + and − size, Delete removes a drawing.</span>
</div>
</div>
</div>

View File

@ -32,6 +32,8 @@ const SHORTCUTS: [string, string][] = [
['Alt + click an input pin', 'Inverts it (a bubble); counted honestly as one NAND'],
['Send signal / Use signal', 'Name a signal (CLK, RESET) once and use it anywhere in the circuit without a wire'],
['Ctrl+F', 'Find a part, signal or component in every circuit, and where a component is used'],
['Shift+A or Ctrl+K', 'Add a part at the mouse: type a few letters, arrows to choose, Enter to place'],
['/', 'Search the parts list; Enter starts placing the one chosen'],
['Ctrl+P', 'Print the circuit as a sheet with a title block, or save it as PDF'],
['Select switches or buttons, Combine', 'One input panel (all rows can become buttons); lamps or output pins combine into an output panel'],
['Select panels, Merge', 'One panel with all their rows; inside a component input panel rows are inputs, output panel rows outputs'],

View File

@ -149,6 +149,9 @@ const widens = computed(() => {
})
const inputs = computed(() => inputCount(n.value, ed.getDef.value))
/** Screen names used by the pixels of this circuit. */
const screenNames = computed(() => [...new Set(ed.def.value.nodes.filter(x => x.kind === 'pixel' && x.screen).map(x => x.screen!))].sort())
/** Groups of pins a new cable can plug onto. */
const cables = computed(() => ed.cableChoices(n.value))
@ -469,6 +472,19 @@ function setRowHz(row: PanelRow, e: Event) {
</label>
</template>
<label v-if="n.kind === 'pixel'" class="field" title="Pixels with the same screen name make one screen on the component's box; without a name, the main screen">
<span>Screen on the box</span>
<input
:value="n.screen ?? ''"
list="screen-names"
placeholder="Main screen"
@change="ed.setScreen([n.id], ($event.target as HTMLInputElement).value)"
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
<datalist id="screen-names">
<option v-for="name in screenNames" :key="name" :value="name" />
</datalist>
</label>
<div v-if="n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel'" class="field">
<span>Colour</span>
<div class="swatches">
@ -538,7 +554,7 @@ function setRowHz(row: PanelRow, e: Event) {
<div v-if="cableBundle" class="field">
<span>Sleeve colour (the wires inside keep theirs)</span>
<div class="swatches">
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default" @click="ed.setCableColor(cableBundle.id, undefined)" />
<button class="swatch none" :class="{ active: !sleeveColor }" title="Default: grey" @click="ed.setCableColor(cableBundle.id, undefined)" />
<button
v-for="c in WIRE_COLORS"
:key="c"

View File

@ -2,7 +2,7 @@
import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { GRID as G, noteLines, noteScale, PANEL_CONTROL_W, type Shape } from '~/lib/logic/geometry'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, shapeTransform, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode } from '~/lib/logic/types'
const props = defineProps<{
@ -154,7 +154,7 @@ const title = computed(() => {
<text v-if="node.label" :x="(b.w * G) / 2" :y="b.y * G - 5" text-anchor="middle" class="instance-label">{{ node.label }}</text>
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body chip" :class="{ missing: !chipDef }" />
<!-- Drawings on a hand-drawn box, under its lamps and displays -->
<template v-for="d in shape.drawing" :key="d.id">
<g v-for="d in shape.drawing" :key="d.id" :transform="shapeTransform(d)">
<line v-if="d.kind === 'line'" :x1="d.x * G" :y1="d.y * G" :x2="(d.x + d.w) * G" :y2="(d.y + d.h) * G" class="face-ink" :class="`ink-${d.ink ?? 'muted'}`" />
<rect
v-else-if="d.kind === 'rect'"
@ -183,7 +183,7 @@ const title = computed(() => {
:class="`ink-${d.ink ?? 'text'}`"
:style="{ fontSize: `${11 * (d.size ?? 1)}px` }"
>{{ d.text }}</text>
</template>
</g>
<text
v-if="shape.nameAt !== null"
:x="(shape.nameAt?.x ?? b.w / 2) * G"
@ -191,7 +191,7 @@ const title = computed(() => {
text-anchor="middle"
class="chip-name"
>{{ chipDef?.name ?? 'Missing' }}</text>
<template v-for="f in shape.face" :key="f.id">
<g v-for="f in shape.face" :key="f.id" :transform="faceTransform(f)">
<template v-if="f.kind === 'screen'">
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />
<rect
@ -215,7 +215,7 @@ const title = computed(() => {
</g>
</template>
<text v-if="f.label" :x="(f.x + f.w / 2) * G" :y="(f.y + f.h - 0.15) * G" text-anchor="middle" class="face-label">{{ f.label }}</text>
</template>
</g>
<text v-for="p in shape.inputs" :key="p.key" :x="5" :y="p.dy * G + 3.5" class="pin-label">{{ p.label }}</text>
<text v-for="p in shape.outputs" :key="p.key" :x="b.w * G - 5" :y="p.dy * G + 3.5" text-anchor="end" class="pin-label">{{ p.label }}</text>
</template>

View File

@ -3,48 +3,69 @@ import { shortCount } from '~/lib/logic/analyze'
import { CHALLENGES } from '~/lib/logic/challenges'
import { campaignProgress, challengeName, challengeOpen, defUsable, isCampaign, KIND_UNLOCK, NEEDS } from '~/lib/logic/progress'
import { weekKey, weeklyId } from '~/lib/logic/puzzles'
import { BASIC_GROUPS } from '~/composables/useParts'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
const ed = useEditor()
const tab = ref<'parts' | 'challenges'>('parts')
const query = ref('')
const BASICS: { kind: NodeKind; name: string; icon: string; key?: string; hint: string }[] = [
{ kind: 'nand', name: 'NAND', icon: 'lucide:square-function', key: 'N', hint: 'The one logic gate. Output is 0 only when both inputs are 1.' },
{ kind: 'input', name: 'Input', icon: 'lucide:toggle-left', key: 'I', hint: 'A switch. Inside a component it becomes an input pin.' },
{ kind: 'output', name: 'Output', icon: 'lucide:log-out', key: 'O', hint: 'Shows a value. Inside a component it becomes an output pin.' },
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.' },
{ kind: 'button', name: 'Push button', icon: 'lucide:circle-dot', key: 'B', hint: '1 while held down.' },
{ kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour. "Attach input panel" on a component or a cable bundle makes one for its free inputs.' },
{ kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of lamps with names. Inside a component its rows are output pins. "Attach output panel" on a component makes one for its outputs; select lamps or output pins to combine them into one.' },
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.' },
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.' },
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.' },
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F.' },
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1. Pixels inside a component show on its box as one screen: build your own LCD.' },
{ kind: 'bundle', name: 'Cable bundle', icon: 'lucide:merge', hint: 'Gathers several wires into one cable. Or select wires and press "Bundle into cable".' },
{ kind: 'split', name: 'Cable split', icon: 'lucide:split', hint: 'Fans a cable out into its wires again.' },
{ kind: 'tag', name: 'Send signal', icon: 'lucide:flag', hint: 'Names the signal wired into it, like CLK or RESET. Every "Use signal" of that name in this circuit carries it, without a wire.' },
{ kind: 'ref', name: 'Use signal', icon: 'lucide:tag', hint: 'The signal of the "Send signal" with the same name, anywhere in this circuit: no long wires for clock, reset or control lines.' },
{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.' },
]
const { componentGroups, search, recentParts } = useParts()
const GROUP_ORDER = ['', 'Puzzles', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Displays', 'Demos']
// ── Search: type to narrow everything down; arrows pick, Enter places ──
const searchInput = ref<HTMLInputElement>()
const hits = computed(() => (query.value.trim() ? search(query.value, 30) : []))
const at = ref(0)
watch(query, () => (at.value = 0))
watch(
() => ed.partSearch.value,
() => {
tab.value = 'parts'
nextTick(() => {
searchInput.value?.focus()
searchInput.value?.select()
})
},
)
const groups = computed(() => {
const q = query.value.trim().toLowerCase()
const map = new Map<string, ComponentDef[]>()
for (const d of ed.project.value.components) {
if (q && !d.name.toLowerCase().includes(q)) continue
const g = d.group?.trim() ?? ''
if (!map.has(g)) map.set(g, [])
map.get(g)!.push(d)
function onSearchKey(e: KeyboardEvent) {
const n = hits.value.length
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
if (n) at.value = (at.value + (e.key === 'ArrowDown' ? 1 : -1) + n) % n
} else if (e.key === 'Enter') {
e.preventDefault()
const h = hits.value[at.value]
if (h) {
pick(h.kind, h.chip)
query.value = ''
searchInput.value?.blur()
}
} else if (e.key === 'Escape') {
query.value = ''
searchInput.value?.blur()
}
const rank = (g: string) => (GROUP_ORDER.includes(g) ? GROUP_ORDER.indexOf(g) : GROUP_ORDER.length)
return [...map.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([name, defs]) => ({ name: name || 'My components', defs }))
})
}
// ── Groups that can be folded away; remembered in this browser ──
const FOLD_KEY = 'logigate:palette-folded'
const folded = ref<Set<string>>(
(() => {
try {
return new Set<string>(JSON.parse(localStorage.getItem(FOLD_KEY) ?? '[]'))
} catch {
return new Set<string>()
}
})(),
)
function fold(name: string) {
const next = new Set(folded.value)
if (!next.delete(name)) next.add(name)
folded.value = next
try {
localStorage.setItem(FOLD_KEY, JSON.stringify([...next]))
} catch {}
}
function pick(kind: NodeKind, chip?: string) {
if (chip && !ed.canPlace(chip)) return
@ -109,66 +130,122 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
</div>
<div v-if="tab === 'parts'" class="scroll">
<h3>Basics</h3>
<ul class="items">
<li v-for="item in BASICS" :key="item.kind">
<button
class="item"
:class="{ active: ed.placing.value?.kind === item.kind && !ed.placing.value?.chip, blocked: !ed.canPlaceKind(item.kind) }"
:title="ed.canPlaceKind(item.kind) ? item.hint : lockedHint(item.kind)"
:draggable="ed.canPlaceKind(item.kind)"
@click="pick(item.kind)"
@dragstart="onDragStart($event, item.kind)"
@dragend="ed.dragPart.value = null"
>
<span v-if="item.kind === 'nand'" class="nand-badge">&amp;</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>
</li>
</ul>
<div class="search">
<div class="search part-search">
<Icon name="lucide:search" class="size-3.5 text-(--muted)" />
<input v-model="query" placeholder="Find component" />
<input ref="searchInput" v-model="query" placeholder="Find a part" @keydown="onSearchKey" />
<kbd v-if="!query" title="Press / on the canvas to search, Shift+A to add at the mouse">/</kbd>
<button v-else class="icon-btn" title="Clear (Esc)" @click="query = ''"><Icon name="lucide:x" class="size-3.5" /></button>
</div>
<template v-for="g in groups" :key="g.name">
<h3>{{ g.name }}</h3>
<ul class="items">
<li v-for="d in g.defs" :key="d.id" class="comp-row">
<!-- Searching: one list of everything that matches -->
<template v-if="query.trim()">
<p v-if="!hits.length" class="hint px-3 pt-3">Nothing called "{{ query.trim() }}" fits here.</p>
<ul class="items mt-2">
<li v-for="(h, i) in hits" :key="h.chip ?? h.kind">
<button
class="item"
:class="{ active: ed.placing.value?.chip === d.id, current: d.id === ed.def.value.id, blocked: !ed.canPlace(d.id) }"
:title="compTitle(d)"
:draggable="ed.canPlace(d.id)"
@click="pick('chip', d.id)"
@dragstart="onDragStart($event, 'chip', d.id)"
:class="{ active: i === at }"
:draggable="true"
@click="pick(h.kind, h.chip)"
@dragstart="onDragStart($event, h.kind, h.chip)"
@dragend="ed.dragPart.value = null"
@pointerenter="at = i"
>
<Icon :name="d.challenge && solved.has(d.challenge) ? 'lucide:badge-check' : 'lucide:box'" class="size-4 shrink-0" :class="d.challenge && solved.has(d.challenge) ? 'text-(--on)' : 'text-(--muted)'" />
<span class="grow truncate">{{ d.name }}</span>
<span v-if="d.id === ed.def.value.id" class="editing">editing</span>
<span v-else-if="ed.transistors(d.id)" class="tcount" :title="`${ed.transistors(d.id).toLocaleString()} transistors`">{{ shortCount(ed.transistors(d.id)) }}T</span>
</button>
<button v-if="d.id !== ed.def.value.id" class="open" title="Open and edit" @click="ed.open(d.id)">
<Icon name="lucide:pencil" class="size-3.5" />
<span v-if="h.kind === 'nand'" class="nand-badge">&amp;</span>
<Icon v-else :name="h.icon" class="size-4 shrink-0 text-(--muted)" />
<span class="grow truncate">{{ h.name }}</span>
<span class="group-tag">{{ h.group }}</span>
</button>
</li>
</ul>
<p class="hint px-3 pt-2">↑ ↓ to choose, Enter to place, Esc to clear.</p>
</template>
<div class="grid gap-2 px-3 pt-2 pb-4">
<button class="btn w-full" @click="ed.createComponent()">
<Icon name="lucide:plus" class="size-4" /> New component
</button>
<button class="btn btn-ghost w-full" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples()">
<Icon name="lucide:library" class="size-4" /> Add example parts
</button>
</div>
<template v-else>
<template v-if="recentParts.length">
<h3>Recent</h3>
<div class="recent-parts">
<button
v-for="r in recentParts"
:key="r.chip ?? r.kind"
class="recent-chip"
:title="`Place ${r.name}`"
draggable="true"
@click="pick(r.kind, r.chip)"
@dragstart="onDragStart($event, r.kind, r.chip)"
@dragend="ed.dragPart.value = null"
>
<Icon :name="r.icon" class="size-3.5 shrink-0" />
<span class="truncate">{{ r.name }}</span>
</button>
</div>
</template>
<template v-for="g in BASIC_GROUPS" :key="g.name">
<button class="group-head" @click="fold(g.name)">
<Icon :name="folded.has(g.name) ? 'lucide:chevron-right' : 'lucide:chevron-down'" class="size-3.5" />
<span>{{ g.name }}</span>
</button>
<ul v-if="!folded.has(g.name)" class="items">
<li v-for="item in g.parts" :key="item.kind">
<button
class="item"
:class="{ active: ed.placing.value?.kind === item.kind && !ed.placing.value?.chip, blocked: !ed.canPlaceKind(item.kind) }"
:title="ed.canPlaceKind(item.kind) ? item.hint : lockedHint(item.kind)"
:draggable="ed.canPlaceKind(item.kind)"
@click="pick(item.kind)"
@dragstart="onDragStart($event, item.kind)"
@dragend="ed.dragPart.value = null"
>
<span v-if="item.kind === 'nand'" class="nand-badge">&amp;</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>
</li>
</ul>
</template>
<template v-for="g in componentGroups" :key="g.name">
<button class="group-head" @click="fold(`c:${g.name}`)">
<Icon :name="folded.has(`c:${g.name}`) ? 'lucide:chevron-right' : 'lucide:chevron-down'" class="size-3.5" />
<span>{{ g.name }}</span>
<span class="group-count">{{ g.defs.length }}</span>
</button>
<ul v-if="!folded.has(`c:${g.name}`)" class="items">
<li v-for="d in g.defs" :key="d.id" class="comp-row">
<button
class="item"
:class="{ active: ed.placing.value?.chip === d.id, current: d.id === ed.def.value.id, blocked: !ed.canPlace(d.id) }"
:title="compTitle(d)"
:draggable="ed.canPlace(d.id)"
@click="pick('chip', d.id)"
@dragstart="onDragStart($event, 'chip', d.id)"
@dragend="ed.dragPart.value = null"
>
<Icon :name="d.challenge && solved.has(d.challenge) ? 'lucide:badge-check' : 'lucide:box'" class="size-4 shrink-0" :class="d.challenge && solved.has(d.challenge) ? 'text-(--on)' : 'text-(--muted)'" />
<span class="grow truncate">{{ d.name }}</span>
<span v-if="d.id === ed.def.value.id" class="editing">editing</span>
<span v-else-if="ed.transistors(d.id)" class="tcount" :title="`${ed.transistors(d.id).toLocaleString()} transistors`">{{ shortCount(ed.transistors(d.id)) }}T</span>
</button>
<button v-if="d.id !== ed.def.value.id" class="open" title="Open and edit" @click="ed.open(d.id)">
<Icon name="lucide:pencil" class="size-3.5" />
</button>
</li>
</ul>
</template>
<div class="grid gap-2 px-3 pt-3 pb-4">
<button class="btn w-full" @click="ed.createComponent()">
<Icon name="lucide:plus" class="size-4" /> New component
</button>
<button class="btn btn-ghost w-full" title="NOT, AND, … up to a 4-bit counter, all built from NAND" @click="ed.loadExamples()">
<Icon name="lucide:library" class="size-4" /> Add example parts
</button>
</div>
</template>
</div>
<div v-else class="scroll">

View File

@ -0,0 +1,67 @@
<script setup lang="ts">
// Adding a part from the keyboard (Shift+A or Ctrl+K): a search box at the
// mouse; type a few letters, arrows to choose, Enter puts it right there.
import type { NodeKind } from '~/lib/logic/types'
const props = defineProps<{ x: number; y: number }>()
const emit = defineEmits<{ pick: [p: { kind: NodeKind; chip?: string }]; close: [] }>()
const { search } = useParts()
const query = ref('')
const at = ref(0)
const input = ref<HTMLInputElement>()
const el = ref<HTMLElement>()
const hits = computed(() => search(query.value, 10))
watch(query, () => (at.value = 0))
const pos = ref({ left: props.x, top: props.y })
onMounted(() => {
input.value?.focus()
const r = el.value!.getBoundingClientRect()
pos.value = { left: Math.max(8, Math.min(props.x, window.innerWidth - r.width - 8)), top: Math.max(8, Math.min(props.y, window.innerHeight - 380)) }
window.addEventListener('pointerdown', outside, true)
})
onBeforeUnmount(() => window.removeEventListener('pointerdown', outside, true))
function outside(e: Event) {
if (!el.value?.contains(e.target as Node)) emit('close')
}
function onKey(e: KeyboardEvent) {
e.stopPropagation()
const n = hits.value.length
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
if (n) at.value = (at.value + (e.key === 'ArrowDown' ? 1 : -1) + n) % n
} else if (e.key === 'Enter') {
e.preventDefault()
const h = hits.value[at.value]
if (h) emit('pick', { kind: h.kind, chip: h.chip })
} else if (e.key === 'Escape') {
e.preventDefault()
emit('close')
}
}
</script>
<template>
<Teleport to="body">
<div ref="el" class="quick-add" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @keydown="onKey">
<div class="search part-search">
<Icon name="lucide:plus" class="size-3.5 text-(--muted)" />
<input ref="input" v-model="query" placeholder="Add a part here…" />
</div>
<ul class="items">
<li v-for="(h, i) in hits" :key="h.chip ?? h.kind">
<button class="item" :class="{ active: i === at }" @pointerenter="at = i" @click="emit('pick', { kind: h.kind, chip: h.chip })">
<span v-if="h.kind === 'nand'" class="nand-badge">&amp;</span>
<Icon v-else :name="h.icon" class="size-4 shrink-0 text-(--muted)" />
<span class="grow truncate">{{ h.name }}</span>
<span class="group-tag">{{ h.group }}</span>
</button>
</li>
</ul>
<p v-if="!hits.length" class="hint px-3 pb-2">Nothing called "{{ query.trim() }}" fits here.</p>
</div>
</Teleport>
</template>

View File

@ -20,7 +20,7 @@ const isCable = computed(() => wires.value.length === 1 && cable.value?.id === w
<div class="field">
<span>{{ isCable ? 'Sleeve colour' : 'Colour' }}</span>
<div class="swatches">
<button class="swatch none" :class="{ active: wireColor === '' }" title="Default" @click="ed.setWireColor(undefined)" />
<button class="swatch none" :class="{ active: wireColor === '' }" title="Default: grey, green while on" @click="ed.setWireColor(undefined)" />
<button
v-for="c in WIRE_COLORS"
:key="c"

View File

@ -16,6 +16,7 @@ import {
type PinGroup,
} from '~/lib/logic/cables'
import { fitLinks, fitSpots } from '~/lib/logic/fit'
import { rememberPart } from '~/lib/recent'
import { checkCircuit } from '~/lib/logic/check'
import { loadSoundSettings, saveSoundSettings, sfx, type Sound, type SoundSettings } from '~/lib/audio'
import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUnlocked, NEEDS, unlockedBy } from '~/lib/logic/progress'
@ -438,6 +439,9 @@ function create() {
}
// ── Editing ───────────────────────────────────────────────────────
/** Asks the parts list to focus its search box ("/" on the canvas). */
const partSearch = ref(0)
/** A part being dragged in from the parts list, so the canvas can show where it would connect. */
const dragPart = ref<Placing | null>(null)
@ -459,6 +463,7 @@ function create() {
if (p.kind === 'panel' || p.kind === 'outpanel') node.rows = newPanelRows()
if (p.kind === 'bundle' || p.kind === 'split') node.bits = 4
def.value.nodes.push(node)
rememberPart(p.kind, p.chip)
const swap = (r: PinRef) => (r.node === 'ghost' ? { node: node.id, pin: r.pin } : r)
const made = links.filter(l => addWire(swap(l.from), swap(l.to))).length
selection.value = [node.id]
@ -784,6 +789,17 @@ function create() {
notify(`${res.panel.kind === 'outpanel' ? 'Output' : 'Input'} panel with ${res.panel.rows?.length ?? 0} rows`)
}
/** Puts pixels on a named screen of the component's box ('' for the main screen). */
function setScreen(ids: string[], name: string) {
const v = name.trim()
for (const n of nodesById(ids)) {
if (n.kind !== 'pixel') continue
if (v) n.screen = v
else delete n.screen
}
commit(false)
}
/** Every row of an input panel the same kind: all switches, all buttons or all clocks. */
function setRowsType(panel: CircuitNode, type: PanelControl) {
for (const r of panel.rows ?? []) {
@ -2004,6 +2020,7 @@ function create() {
mergeSelectedPanels,
combineSelected,
setRowsType,
setScreen,
setRowType,
addRow,
dropRow,
@ -2029,6 +2046,7 @@ function create() {
setPitch,
addCablePanel,
dragPart,
partSearch,
cableChoices,
cableOut,
cableIn,

View File

@ -49,7 +49,9 @@ export interface CanvasOps {
}
const LAMP_HEX: Record<string, string> = { yellow: '#ffd34d', red: '#ff5c5c', green: '#3ddc84', blue: '#4dabff', white: '#f4f6fa' }
const WIRE_HEX: Record<string, string> = { red: '#ff5c5c', orange: '#ff9f43', yellow: '#ffd93d', blue: '#4dabff', purple: '#b388ff', pink: '#ff7ac6' }
const WIRE_HEX: Record<string, string> = { red: '#ff5c5c', orange: '#ff9f43', yellow: '#ffd93d', green: '#3ddc84', blue: '#4dabff', purple: '#b388ff', pink: '#ff7ac6' }
/** The default wire colour: grey, like an unlit wire or a cable's sleeve. */
const DEFAULT_WIRE = 'linear-gradient(135deg, transparent 45%, #8592a3 45% 55%, transparent 55%), #3b4554'
const ARRANGE: { how: Arrange; label: string; icon: string }[] = [
{ how: 'left', label: 'Line up on the left', icon: 'lucide:align-start-vertical' },
@ -287,7 +289,7 @@ export function useMenu() {
{
label: 'Sleeve colour',
swatches: [undefined, ...WIRE_COLORS].map(c => ({
color: c ? WIRE_HEX[c]! : '#3ddc84',
color: c ? WIRE_HEX[c]! : DEFAULT_WIRE,
title: c ?? 'Default',
active: sleeve === c,
run: () => ed.setCableColor(bundle.id, c),
@ -404,7 +406,7 @@ export function useMenu() {
out.push({
label: cable ? 'Sleeve colour' : 'Colour',
swatches: [undefined, ...WIRE_COLORS].map(c => ({
color: c ? WIRE_HEX[c]! : '#3ddc84',
color: c ? WIRE_HEX[c]! : DEFAULT_WIRE,
title: c ?? 'Default',
active: colors.size === 1 && colors.has(c),
run: () => ed.setWireColor(c),

141
app/composables/useParts.ts Normal file
View File

@ -0,0 +1,141 @@
// Everything that can be placed, grouped for the parts list and searchable
// by keyboard (the list's search box, and the quick-add box at the mouse):
// the built-in parts by what they are for, then the components by group.
import { defUsable } from '~/lib/logic/progress'
import { matchScore } from '~/lib/match'
import { recentParts } from '~/lib/recent'
import type { ComponentDef, NodeKind } from '~/lib/logic/types'
export interface BasicPart {
kind: NodeKind
name: string
icon: string
/** Key that places it straight away. */
key?: string
hint: string
/** Other words people search for it by. */
aka?: string
}
export const BASIC_GROUPS: { name: string; parts: BasicPart[] }[] = [
{
name: 'Logic',
parts: [{ kind: 'nand', name: 'NAND', icon: 'lucide:square-function', key: 'N', hint: 'The one logic gate. Output is 0 only when both inputs are 1.', aka: 'gate' }],
},
{
name: 'Inputs',
parts: [
{ kind: 'input', name: 'Input switch', icon: 'lucide:toggle-left', key: 'I', hint: 'A switch. Inside a component it becomes an input pin.', aka: 'pin in toggle' },
{ kind: 'button', name: 'Push button', icon: 'lucide:circle-dot', key: 'B', hint: '1 while held down.', aka: 'momentary' },
{ kind: 'clock', name: 'Clock', icon: 'lucide:audio-waveform', key: 'C', hint: 'Square wave. Speed and pause are in the top bar.', aka: 'oscillator tick' },
{ kind: 'panel', name: 'Input panel', icon: 'lucide:sliders-vertical', key: 'P', hint: 'A column of switches, buttons and clocks, each with its own name, key and colour.', aka: 'switches buttons' },
{ kind: 'high', name: 'Constant 1', icon: 'lucide:plus', hint: 'Always 1, like the supply rail.', aka: 'vcc high one supply' },
{ kind: 'low', name: 'Ground (0)', icon: 'lucide:arrow-down-to-line', hint: 'Always 0.', aka: 'gnd low zero' },
],
},
{
name: 'Outputs',
parts: [
{ kind: 'output', name: 'Output pin', icon: 'lucide:log-out', key: 'O', hint: 'Shows a value. Inside a component it becomes an output pin.', aka: 'pin out' },
{ kind: 'lamp', name: 'Lamp', icon: 'lucide:lightbulb', key: 'L', hint: 'Lights up at 1.', aka: 'led light' },
{ kind: 'outpanel', name: 'Output panel', icon: 'lucide:list-checks', hint: 'A column of named lamps. Inside a component its rows are output pins.', aka: 'lamps leds' },
{ kind: 'hex', name: 'Hex display', icon: 'lucide:binary', key: 'H', hint: 'Shows 4 bits as 0–F, and passes them on.', aka: 'seven segment 7seg digit' },
{ kind: 'pixel', name: 'Pixel', icon: 'lucide:square', key: 'X', hint: 'One square of a screen, lit at 1. Pixels inside a component show on its box as screens.', aka: 'screen lcd' },
],
},
{
name: 'Wiring',
parts: [
{ kind: 'bundle', name: 'Cable bundle', icon: 'lucide:merge', hint: 'Gathers several wires into one cable.', aka: 'bus' },
{ kind: 'split', name: 'Cable split', icon: 'lucide:split', hint: 'Fans a cable out into its wires again.', aka: 'bus' },
{ kind: 'tag', name: 'Send signal', icon: 'lucide:flag', hint: 'Names the signal wired into it, like CLK or RESET.', aka: 'label net tag' },
{ kind: 'ref', name: 'Use signal', icon: 'lucide:tag', hint: 'The signal of the "Send signal" with the same name, anywhere in this circuit.', aka: 'label net reference' },
],
},
{
name: 'Notes',
parts: [{ kind: 'note', name: 'Note', icon: 'lucide:sticky-note', key: 'T', hint: 'Text label for your drawing.', aka: 'text comment' }],
},
]
export const BASIC_PARTS = BASIC_GROUPS.flatMap(g => g.parts)
/** Library groups in this order; your own components come first. */
export const GROUP_ORDER = ['', 'Puzzles', 'Gates', 'Routing', 'Arithmetic', 'Memory', 'Displays', 'Demos']
export interface PartHit {
kind: NodeKind
chip?: string
name: string
icon: string
/** Where it lives in the list. */
group: string
key?: string
score: number
}
export function useParts() {
const ed = useEditor()
const recent = recentParts
/** Components grouped like the list shows them. */
const componentGroups = computed(() => {
const map = new Map<string, ComponentDef[]>()
for (const d of ed.project.value.components) {
const g = d.group?.trim() ?? ''
if (!map.has(g)) map.set(g, [])
map.get(g)!.push(d)
}
const rank = (g: string) => (GROUP_ORDER.includes(g) ? GROUP_ORDER.indexOf(g) : GROUP_ORDER.length)
return [...map.entries()]
.sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))
.map(([name, defs]) => ({ name: name || 'My components', defs }))
})
const placeable = (d: ComponentDef) => d.id !== ed.def.value.id && ed.canPlace(d.id) && defUsable(ed.project.value, d)
/** Everything that matches, best first: built-in parts and components that can go in the open circuit. */
function search(query: string, limit = 12): PartHit[] {
const q = query.trim().toLowerCase()
const hits: PartHit[] = []
for (const g of BASIC_GROUPS) {
for (const p of g.parts) {
if (!ed.canPlaceKind(p.kind)) continue
const score = Math.max(matchScore(p.name, q), matchScore(p.aka ?? '', q) * 0.8, p.key && q === p.key.toLowerCase() ? 90 : 0)
if (score) hits.push({ kind: p.kind, name: p.name, icon: p.icon, group: g.name, key: p.key, score: score + 1 })
}
}
for (const g of componentGroups.value) {
for (const d of g.defs) {
if (!placeable(d)) continue
const score = matchScore(d.name, q)
if (score) hits.push({ kind: 'chip', chip: d.id, name: d.name, icon: 'lucide:box', group: g.name, score })
}
}
if (!q) {
// Nothing typed yet: what was used lately, then the basics.
const order = new Map(recent.value.map((k, i) => [k, i]))
const at = (h: PartHit) => order.get(h.chip ? `chip:${h.chip}` : h.kind) ?? Infinity
return hits.sort((a, b) => at(a) - at(b)).slice(0, limit)
}
return hits.sort((a, b) => b.score - a.score || a.name.length - b.name.length).slice(0, limit)
}
/** The recently placed parts that still exist and can be placed here. */
const recentList = computed(() =>
recent.value
.map(k => {
if (!k.startsWith('chip:')) {
const p = BASIC_PARTS.find(b => b.kind === k)
return p && ed.canPlaceKind(p.kind) ? { kind: p.kind, name: p.name, icon: p.icon } : null
}
const d = ed.getDef.value(k.slice(5))
return d && placeable(d) ? { kind: 'chip' as NodeKind, chip: d.id, name: d.name, icon: 'lucide:box' } : null
})
.filter((x): x is { kind: NodeKind; chip?: string; name: string; icon: string } => !!x)
.slice(0, 6),
)
return { componentGroups, search, recentParts: recentList }
}

View File

@ -288,7 +288,8 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
}
if (stack.length === 1) {
// Lamps, displays and pixels inside placed components, at every depth: a box may show those of parts inside it.
if (stack.length >= 1) {
for (const n of def.nodes) {
if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') for (const k of inputKeys(n)) rawFace.set(`${path}${n.id}:${k}`, pinIn(n, k))
}

View File

@ -39,8 +39,15 @@ export interface ScreenPixel {
}
export interface FaceItem {
/** Node id inside the component; for a screen, the first pixel's. */
/** Node id inside the component; for a screen, the first pixel's; a path (chip/…/node) for a display inside. */
id: string
/** What a design calls it: the node id, 'screen' or 'screen:<name>', or '<chip node id>/<its key>'. */
key: string
/** Size and turn from a hand-drawn box. */
scale?: number
rotate?: number
/** A display of a component inside: that component's name. */
from?: string
kind: 'lamp' | 'hex' | 'screen'
/** Screen only: its pixels and the size of one, in grid units. */
pixels?: ScreenPixel[]
@ -112,8 +119,32 @@ export function chipPins(def: ComponentDef): ChipPins {
export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h: number } {
const empty = { items: [], w: 0, h: 0 }
if (def.face === false) return empty
const nodes = def.nodes.filter(n => n.kind === 'lamp' || n.kind === 'hex').sort((a, b) => a.y - b.y || a.x - b.x)
const rows: CircuitNode[][] = []
return autoFace(def, ownFaceItems(def))
}
/** The lamps, displays and screens of a component itself, before they are laid out. */
function ownFaceItems(def: ComponentDef): FaceItem[] {
const items: FaceItem[] = []
for (const n of def.nodes) {
if (n.kind !== 'lamp' && n.kind !== 'hex') continue
const label = n.label?.trim() ?? ''
const w = Math.max(n.kind === 'hex' ? 1.6 : 1.4, label.length * FACE_CHAR + 0.4)
const h = (n.kind === 'hex' ? 2.2 : 1.2) + (label ? 0.7 : 0)
items.push({ id: n.id, key: n.id, kind: n.kind, label, color: n.color, x: n.x, y: n.y, w, h })
}
return [...items, ...screenLayouts(def)]
}
/**
* Lays the items out the way they sit inside: lamps and displays at about
* the same height share a row, screens go below.
*/
function autoFace(def: ComponentDef, all: FaceItem[]): { items: FaceItem[]; w: number; h: number } {
const empty = { items: [], w: 0, h: 0 }
void def
// The x and y of an item here are where its node sits inside, used for ordering.
const nodes = all.filter(it => it.kind !== 'screen').sort((a, b) => a.y - b.y || a.x - b.x)
const rows: FaceItem[][] = []
for (const n of nodes) {
const row = rows[rows.length - 1]
if (row && Math.abs(n.y - row[0]!.y) <= 1) row.push(n)
@ -127,18 +158,14 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h
let x = 0
let h = 0
for (const n of row) {
const label = n.label?.trim() ?? ''
const iw = Math.max(n.kind === 'hex' ? 1.6 : 1.4, label.length * FACE_CHAR + 0.4)
const ih = (n.kind === 'hex' ? 2.2 : 1.2) + (label ? 0.7 : 0)
items.push({ id: n.id, kind: n.kind as 'lamp' | 'hex', label, color: n.color, x, y, w: iw, h: ih })
x += iw + 0.3
h = Math.max(h, ih)
items.push({ ...n, x, y })
x += n.w + 0.3
h = Math.max(h, n.h)
}
w = Math.max(w, x - 0.3)
y += h + 0.3
}
const screen = screenLayout(def)
if (screen) {
for (const screen of all.filter(it => it.kind === 'screen')) {
w = Math.max(w, screen.w)
items.push({ ...screen, x: (w - screen.w) / 2, y })
y += screen.h + 0.3
@ -147,14 +174,97 @@ export function faceLayout(def: ComponentDef): { items: FaceItem[]; w: number; h
return { items, w, h: y - 0.3 }
}
/**
* What a component shows on its box, for a component placed inside another
* one to offer: the items its own design shows (or all, laid out
* automatically), including displays of components inside it it shows.
*/
function shownItems(def: ComponentDef, get: DefLookup, depth: number): FaceItem[] {
if (def.face === false || depth > 4) return []
const d = def.design
const hide = new Set(d?.hide ?? [])
const own = ownFaceItems(def).filter(it => !hide.has(it.key))
if (!d?.show?.length) return own
const show = new Set(d.show)
return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key))]
}
/**
* Everything a component's box can show, for the box designer: its own
* lamps, displays and screens (shown unless left off), and the displays of
* components inside it (left off unless shown).
*/
export function faceCandidates(def: ComponentDef, get: DefLookup): { key: string; label: string; kind: FaceItem['kind']; nested: boolean }[] {
if (def.face === false) return []
const own = ownFaceItems(def).map(it => ({ key: it.key, label: it.label || (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp'), kind: it.kind, nested: false }))
const nested = nestedItems(def, get).map(it => ({ key: it.key, label: [it.from, it.label].filter(Boolean).join(' ') || it.kind, kind: it.kind, nested: true }))
return [...own, ...nested]
}
/** A box item's size and turn, as an SVG transform: grown from its top left corner, turned around its middle. */
export function faceTransform(f: FaceItem): string | undefined {
if (!f.scale && !f.rotate) return undefined
const k = f.scale ?? 1
const x = f.x * GRID
const y = f.y * GRID
const cx = x + (f.w * k * GRID) / 2
const cy = y + (f.h * k * GRID) / 2
return `${f.rotate ? `rotate(${f.rotate} ${cx} ${cy}) ` : ''}translate(${x} ${y}) scale(${k}) translate(${-x} ${-y})`
}
/** A drawing on a box turned around its middle, as an SVG transform. */
export function shapeTransform(d: FaceShape): string | undefined {
if (!d.rotate) return undefined
const w = d.kind === 'text' ? (d.text?.length ?? 1) * 0.42 * (d.size ?? 1) : d.w
const h = d.kind === 'text' ? (d.size ?? 1) : d.h
return `rotate(${d.rotate} ${(d.x + w / 2) * GRID} ${(d.y + h / 2) * GRID})`
}
/** Displays of the components inside one: each keyed by its chip node and its own key there. */
export function nestedItems(def: ComponentDef, get: DefLookup, depth = 0): FaceItem[] {
const out: FaceItem[] = []
for (const n of def.nodes) {
if (n.kind !== 'chip' || !n.chip || n.chip === def.id) continue
const child = get(n.chip)
if (!child) continue
const name = n.label?.trim() || child.name
for (const it of shownItems(child, get, depth + 1)) {
out.push({
...it,
id: `${n.id}/${it.id}`,
key: `${n.id}/${it.key}`,
// On the box it keeps its own name; the designer lists it with the part's.
from: name,
pixels: it.pixels?.map(p => ({ ...p, id: `${n.id}/${p.id}` })),
})
}
}
return out
}
/**
* Pixels inside a component, drawn as one screen without gaps: every
* distinct column and row they sit on becomes a column and row of the
* screen, so they can be spaced out inside for wiring.
*/
export function screenLayout(def: ComponentDef): FaceItem | null {
const pixels = def.nodes.filter(n => n.kind === 'pixel')
if (!pixels.length) return null
return screenLayouts(def)[0] ?? null
}
/** Pixels make one screen per screen name (those without a name the main screen, listed first). */
export function screenLayouts(def: ComponentDef): FaceItem[] {
const groups = new Map<string, CircuitNode[]>()
for (const n of def.nodes) {
if (n.kind !== 'pixel') continue
const g = n.screen?.trim() ?? ''
groups.set(g, [...(groups.get(g) ?? []), n])
}
return [...groups.entries()]
.sort(([a], [b]) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)))
.map(([name, pixels]) => screenOf(pixels, name))
}
function screenOf(pixels: CircuitNode[], name: string): FaceItem {
const xs = [...new Set(pixels.map(n => n.x))].sort((a, b) => a - b)
const ys = [...new Set(pixels.map(n => n.y))].sort((a, b) => a - b)
const col = new Map(xs.map((x, i) => [x, i]))
@ -163,10 +273,11 @@ export function screenLayout(def: ComponentDef): FaceItem | null {
const px = size <= 8 ? 1 : size <= 32 ? 0.5 : 0.25
return {
id: pixels[0]!.id,
key: name ? `screen:${name}` : 'screen',
kind: 'screen',
label: '',
x: 0,
y: 0,
label: name,
x: Math.min(...pixels.map(n => n.x)),
y: Math.min(...pixels.map(n => n.y)),
w: xs.length * px,
h: ys.length * px,
px,
@ -205,25 +316,68 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
* need), everything placed where it was put, the rest where it would go
* anyway, and its drawings.
*/
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup): Shape {
const auto = boxShape(def.name, pins, face)
const d = def.design!
const top = auto.body.y
const pinH = Math.max(pins.inputs.length, pins.outputs.length, 1)
const w = Math.max(2, d.w)
const h = Math.max(pinH === 1 ? 2 : pinH, d.h)
const hide = new Set(d.hide ?? [])
const place = d.place ?? {}
// Pins on their edges: where they were put, the others one row under the pin above.
const placePins = <P extends PinInfo>(list: P[]) => {
let prev = -Infinity
return list.map(p => {
const want = d.pinAt?.[p.key]
const dy = Math.max(want ?? (prev === -Infinity ? p.dy : prev + 1), prev + 1, 0)
prev = dy
return { ...p, dy }
})
}
const inputs = placePins(auto.inputs)
const lowest = Math.max(0, ...inputs.map(p => p.dy), ...auto.outputs.map(p => d.pinAt?.[p.key] ?? p.dy))
const w = Math.max(2, d.w)
const outputs = placePins(auto.outputs).map(p => ({ ...p, dx: w }))
const bottom = Math.max(...inputs.map(p => p.dy), ...outputs.map(p => p.dy), lowest)
const h = Math.max(d.h, bottom - top + 0.5, 2)
// Own items where auto layout put them unless placed; displays of parts inside only when shown.
const show = new Set(d.show ?? [])
const nested = nestedItems(def, get).filter(it => show.has(it.key))
let below = (auto.face ?? []).reduce((m, it) => Math.max(m, it.y + it.h), auto.body.y + auto.body.h - 0.6) + 0.3
const items = [
...(auto.face ?? []),
...nested.map(it => {
const at = { ...it, x: 0.6, y: below }
below += it.h + 0.3
return at
}),
]
const shown = items
.filter(it => !hide.has(it.key))
.map(it => {
const at = place[it.key]
const scale = d.scale?.[it.key]
const rotate = d.rotate?.[it.key]
return { ...it, ...(at ? { x: at.x, y: top + at.y } : {}), ...(scale ? { scale } : {}), ...(rotate ? { rotate } : {}) }
})
// The box is never smaller than what it shows (sized and turned as shown).
let right = w
let floor = top + h
for (const it of shown) {
const k = it.scale ?? 1
const turned = it.rotate === 90 || it.rotate === 270
const iw = (turned ? it.h : it.w) * k
const ih = (turned ? it.w : it.h) * k
const cx = it.x + (it.w * k) / 2
const cy = it.y + (it.h * k) / 2
right = Math.max(right, cx + iw / 2 + 0.3)
floor = Math.max(floor, cy + ih / 2 + 0.3)
}
const bw = Math.ceil(right * 2) / 2
return {
...auto,
body: { x: 0, y: top, w, h },
outputs: auto.outputs.map(p => ({ ...p, dx: w })),
face: (auto.face ?? [])
.filter(it => !hide.has(it.kind === 'screen' ? 'screen' : it.id))
.map(it => {
const at = place[it.kind === 'screen' ? 'screen' : it.id]
return at ? { ...it, x: at.x, y: top + at.y } : it
}),
inputs,
outputs: bw === w ? outputs : outputs.map(p => ({ ...p, dx: bw })),
body: { x: 0, y: top, w: bw, h: Math.ceil((floor - top) * 2) / 2 },
face: shown,
nameAt: hide.has('name') ? null : place.name ? { x: place.name.x, y: top + place.name.y } : undefined,
drawing: (d.shapes ?? []).map(sh => ({ ...sh, y: top + sh.y })),
}
@ -434,7 +588,7 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
if (!def) return MISSING_SHAPE
const pins = chipPins(def)
const face = faceLayout(def)
if (def.design) return designedShape(def, pins, face)
if (def.design) return designedShape(def, pins, face, getDef)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}

View File

@ -40,6 +40,7 @@ function cleanNode(n: CircuitNode) {
if (n[k] !== undefined && !(Array.isArray(n[k]) && n[k]!.every(v => typeof v === 'string'))) delete n[k]
}
if (n.inner !== undefined && n.inner !== true) delete n.inner
if (n.screen !== undefined && typeof n.screen !== 'string') delete n.screen
}
const MAX_ROWS = 256
@ -69,7 +70,17 @@ function cleanDesign(d: ComponentDef) {
if (!f.place || typeof f.place !== 'object' || Array.isArray(f.place)) delete f.place
else for (const [k, v] of Object.entries(f.place)) if (!v || !num(v.x, -200, 400) || !num(v.y, -200, 400)) delete f.place[k]
}
if (f.hide !== undefined && !(Array.isArray(f.hide) && f.hide.every(v => typeof v === 'string'))) delete f.hide
for (const k of ['hide', 'show'] as const) if (f[k] !== undefined && !(Array.isArray(f[k]) && f[k]!.every(v => typeof v === 'string'))) delete f[k]
// Sizes, turns and pin rows: numbers in range only.
const nums = (rec: Record<string, number> | undefined, ok: (v: number) => boolean) => {
if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return undefined
for (const [k, v] of Object.entries(rec)) if (!(typeof v === 'number' && ok(v))) delete rec[k]
return rec
}
if (f.scale !== undefined) f.scale = nums(f.scale, v => v >= 0.25 && v <= 4)
if (f.rotate !== undefined) f.rotate = nums(f.rotate, v => [0, 90, 180, 270].includes(v))
if (f.pinAt !== undefined) f.pinAt = nums(f.pinAt, v => Number.isInteger(v) && v >= 0 && v <= 1000)
for (const k of ['scale', 'rotate', 'pinAt'] as const) if (f[k] === undefined) delete f[k]
if (f.shapes !== undefined) {
f.shapes = Array.isArray(f.shapes)
? f.shapes
@ -87,6 +98,7 @@ function cleanDesign(d: ComponentDef) {
if (sh.text !== undefined && typeof sh.text !== 'string') delete sh.text
if (sh.size !== undefined && !num(sh.size, 0.25, 4)) delete sh.size
if (sh.fill !== undefined && sh.fill !== true) delete sh.fill
if (sh.rotate !== undefined && ![0, 90, 180, 270].includes(sh.rotate)) delete sh.rotate
}
}
}

View File

@ -66,6 +66,8 @@ export interface CircuitNode {
invert?: string[]
/** Panel whose rows stay inside a component instead of becoming its pins (an input panel's switches stay as set). */
inner?: boolean
/** Pixel: the screen it belongs to on the component's box; pixels without one make the main screen. */
screen?: string
}
export const PANEL_CONTROLS = ['switch', 'button', 'clock'] as const
@ -113,7 +115,7 @@ export interface Wire {
color?: WireColor
}
export const WIRE_COLORS = ['red', 'orange', 'yellow', 'blue', 'purple', 'pink'] as const
export const WIRE_COLORS = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'pink'] as const
export type WireColor = (typeof WIRE_COLORS)[number]
export interface ComponentDef {
@ -147,10 +149,22 @@ export type FaceInk = (typeof FACE_INKS)[number]
export interface FaceDesign {
w: number
h: number
/** Top left corner of lamps and displays (by node id), the pixel screen ('screen') and the name ('name'). */
/**
* Top left corner of things on the box, by key: a lamp or display (its
* node id), a pixel screen ('screen', or 'screen:<name>'), the name
* ('name'), or a display of a component inside ('<chip node id>/<its key>').
*/
place?: Record<string, { x: number; y: number }>
/** Left off the box: lamp and display node ids, 'screen', 'name'. */
/** Left off the box (keys as in place). */
hide?: string[]
/** Displays of components inside, shown on this box (they are left off unless listed). */
show?: string[]
/** Size of a thing on the box, 1 as it comes. */
scale?: Record<string, number>
/** Turn of a thing on the box in degrees: 0, 90, 180 or 270. */
rotate?: Record<string, number>
/** Row of a pin on its edge (by pin key); pins without one follow the pin above. */
pinAt?: Record<string, number>
shapes?: FaceShape[]
}
@ -168,6 +182,8 @@ export interface FaceShape {
fill?: boolean
/** Text size: 1 is normal. */
size?: number
/** Turn in degrees around its middle. */
rotate?: number
}
export interface Settings {

17
app/lib/match.ts Normal file
View File

@ -0,0 +1,17 @@
// How well a name matches what was typed, for finding parts by keyboard.
/**
* The whole name, its start, a word start, anywhere in it, or its letters
* in order (adr4 finds Adder 4); 0 for no match. Empty input matches all.
*/
export function matchScore(text: string, q: string): number {
const t = text.toLowerCase()
if (!q) return 1
if (t === q) return 100
if (t.startsWith(q)) return 80
if (t.split(/[\s\-_/()]+/).some(w => w.startsWith(q))) return 60
if (t.includes(q)) return 40
let i = 0
for (const c of t) if (c === q[i]) i++
return i === q.length ? 15 : 0
}

26
app/lib/recent.ts Normal file
View File

@ -0,0 +1,26 @@
// Parts placed lately, newest first ("nand", "chip:<id>"), kept in this
// browser: the parts list and the quick-add box offer them first.
import { ref } from 'vue'
import type { NodeKind } from './logic/types'
const KEY = 'logigate:recent-parts'
function load(): string[] {
try {
const v = JSON.parse(localStorage.getItem(KEY) ?? '[]')
return Array.isArray(v) ? v.filter(x => typeof x === 'string').slice(0, 8) : []
} catch {
return []
}
}
export const recentParts = ref<string[]>(typeof localStorage === 'undefined' ? [] : load())
export function rememberPart(kind: NodeKind, chip?: string) {
const key = chip ? `chip:${chip}` : kind
recentParts.value = [key, ...recentParts.value.filter(k => k !== key)].slice(0, 8)
try {
localStorage.setItem(KEY, JSON.stringify(recentParts.value))
} catch {}
}

View File

@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { shapeOf } from '../app/lib/logic/geometry'
import { faceCandidates, screenLayouts, shapeOf } from '../app/lib/logic/geometry'
import { matchScore } from '../app/lib/match'
import { createProject, lookup } from '../app/lib/logic/ops'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
@ -86,3 +87,75 @@ describe('a box drawn by hand', () => {
expect(toProject(JSON.parse(JSON.stringify(p))).components.find(d => d.id === 'inner')!.design).toBeUndefined()
})
})
describe('the box, finer', () => {
it('pixels make one screen per screen name', () => {
const def: ComponentDef = {
id: 'd',
name: 'D',
symbol: 'box',
nodes: [
{ id: 'p1', kind: 'pixel', x: 0, y: 0 },
{ id: 'p2', kind: 'pixel', x: 1, y: 0 },
{ id: 'q1', kind: 'pixel', x: 0, y: 5, screen: 'Status' },
],
wires: [],
}
expect(screenLayouts(def).map(s => [s.key, s.pixels!.length])).toEqual([
['screen', 2],
['screen:Status', 1],
])
})
it('shows displays of components inside when asked, with their values, and spaces pins', () => {
const { p, inner } = shown()
const outer: ComponentDef = {
id: 'outer',
name: 'Outer',
symbol: 'box',
nodes: [
{ id: 'x', kind: 'input', x: 0, y: 0, label: 'X' },
{ id: 'y', kind: 'input', x: 0, y: 1, label: 'Y' },
{ id: 'u', kind: 'chip', chip: 'inner', x: 5, y: 0 },
],
wires: [{ id: 'w', from: { node: 'x', pin: 'q' }, to: { node: 'u', pin: 'a' } }],
}
const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 's', kind: 'input', x: -4, y: 0 },
{ id: 'o', kind: 'chip', chip: 'outer', x: 0, y: 0 },
],
wires: [{ id: 'v', from: { node: 's', pin: 'q' }, to: { node: 'o', pin: 'x' } }],
}
p.components.push(outer, root)
const get = lookup(p)
const cands = faceCandidates(outer, get)
expect(cands.filter(c => c.nested).map(c => c.key)).toEqual(['u/l', 'u/h'])
const chip = { id: 'o', kind: 'chip' as const, chip: 'outer', x: 0, y: 0 }
expect(shapeOf(chip, get).face ?? []).toEqual([])
outer.design = { w: 8, h: 6, show: ['u/l'], scale: { 'u/l': 2 }, rotate: { 'u/l': 90 }, pinAt: { y: 3 } }
const s = shapeOf(chip, get)
expect(s.face).toEqual([expect.objectContaining({ id: 'u/l', key: 'u/l', scale: 2, rotate: 90 })])
// Y was put three rows down, under X: a gap.
expect(s.inputs.map(i => i.dy)).toEqual([0, 3])
// The lamp deep inside lights on the outer box when its signal is on.
const sim = new Simulator(compile(get, 'root'))
sim.setSource('s', true)
sim.run()
expect(sim.face('o', 'u/l', 'a')).toBe(1)
void inner
})
})
describe('finding parts', () => {
it('matches names by start, word, inside, and letters in order', () => {
expect(matchScore('Adder 4', 'adder 4')).toBeGreaterThan(matchScore('Adder 4', 'add'))
expect(matchScore('Adder 4', 'add')).toBeGreaterThan(matchScore('Full Adder', 'add'))
expect(matchScore('Full Adder', 'add')).toBeGreaterThan(matchScore('Ladder', 'add'))
expect(matchScore('Adder 4', 'adr4')).toBeGreaterThan(0)
expect(matchScore('Lamp', 'xyz')).toBe(0)
})
})