A right-click menu for parts, wires and the canvas, "Wire them all to" as cards, plugged latches in plain greys

- Right click (or the menu key) shows what can be done with what is under the pointer: one part (open, rename, change to, inputs, colour, speed, panels, unpack, plug and unplug, cable colour), several parts (wire them all to with live preview, connect one by one, switches, change all, arrange, keep only, make a component), wires (bundle, colour, whole signal, straighten, remove cable) or empty canvas (paste here, add a part here, select all, fit, tidy, undo); right drag still moves the view
- "Wire them all to": a card per part, each fit a strip of its pins, and which wire goes where for the fit pointed at
- Plugged cable ends no longer look selected: grey connector, steel clips
- Icons named in menus are bundled for the browser too

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-21 12:33:30 +02:00
parent 7ce8ffb9bc
commit f4e2c08658
9 changed files with 1002 additions and 39 deletions

View File

@ -824,19 +824,20 @@ kbd {
.harness.c-purple { --w-on: #b388ff; --w-off: #463768; } .harness.c-purple { --w-on: #b388ff; --w-off: #463768; }
.harness.c-pink { --w-on: #ff7ac6; --w-off: #673657; } .harness.c-pink { --w-on: #ff7ac6; --w-off: #673657; }
/* A plugged cable end: a plain connector in the part's own greys, held by two steel clips. */
.node .body.cable-end.plugged { .node .body.cable-end.plugged {
fill: #253447; fill: #1f2630;
stroke: #6fa3cf; stroke: #5d6878;
} }
.node .latch rect { .node .latch rect {
fill: #6fa3cf; fill: #7a8698;
stroke: #1b2633; stroke: #10151c;
stroke-width: 1; stroke-width: 1;
} }
.node .latch .contact { .node .latch .contact {
stroke: #9fd0f5; stroke: #3a4554;
stroke-width: 2.5; stroke-width: 2.5;
stroke-linecap: round; stroke-linecap: round;
} }
@ -2401,22 +2402,298 @@ kbd {
pointer-events: none; pointer-events: none;
} }
.fit-list { /* "Wire them all to": a card per part, each fit a strip of the pins it takes. */
.fit-cards {
display: grid;
gap: 6px;
}
.fit-card {
padding: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--panel-2);
transition: border-color 120ms;
}
.fit-card.hot {
border-color: rgb(61 220 132 / 0.55);
}
.fit-card-head {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 7px;
color: var(--text);
font-size: 12px;
font-weight: 600;
}
.fit-card-head .fit-icon {
color: var(--muted);
}
.fit-tag {
color: var(--muted);
font-size: 11px;
font-weight: 500;
}
.fit-choices {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 4px; gap: 5px;
} }
.fit-list .btn-sm.active { .fit-choice {
display: inline-flex;
padding: 2px;
border: 1px solid #2f3a48;
border-radius: 6px;
background: #11161d;
gap: 2px;
transition: border-color 100ms, background 100ms;
}
.fit-choice:hover,
.fit-choice.active {
border-color: var(--on); border-color: var(--on);
color: var(--on); background: rgb(61 220 132 / 0.12);
} }
.fit-list .muted { .fit-pill {
min-width: 22px;
padding: 1px 5px;
border-radius: 4px;
background: #1f2732;
color: var(--text);
font-family: var(--font-mono);
font-size: 11px;
line-height: 17px;
text-align: center;
}
.fit-choice:hover .fit-pill,
.fit-choice.active .fit-pill {
background: rgb(61 220 132 / 0.22);
color: #d9ffe9;
}
.fit-map {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(104px, 1fr));
gap: 3px 10px;
margin-top: 8px;
padding: 6px 8px;
border-radius: 6px;
background: var(--bg);
color: var(--muted); color: var(--muted);
font-family: var(--font-mono);
font-size: 11px;
}
.fit-map.live {
color: var(--text);
}
.fit-pair {
display: flex;
align-items: center;
gap: 4px;
min-width: 0;
}
.fit-pair span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.fit-pair .fit-arrow {
flex: 0 0 auto;
color: var(--on);
} }
.box-select.crossing { .box-select.crossing {
fill: rgb(61 220 132 / 0.08); fill: rgb(61 220 132 / 0.08);
stroke: var(--on); stroke: var(--on);
} }
/* ── Context menu ───────────────────────────────────────────────── */
.ctx {
position: fixed;
z-index: 60;
font-size: 13px;
}
.ctx-list {
min-width: 220px;
max-width: 320px;
padding: 5px;
border: 1px solid #2d3745;
border-radius: 10px;
background: rgb(22 28 36 / 0.97);
backdrop-filter: blur(8px);
box-shadow: 0 12px 32px rgb(0 0 0 / 0.45), 0 2px 6px rgb(0 0 0 / 0.3);
animation: ctx-in 90ms ease-out;
}
@keyframes ctx-in {
from { opacity: 0; transform: translateY(-3px) scale(0.98); }
}
.ctx-head {
padding: 5px 9px 4px;
overflow: hidden;
color: var(--muted);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.ctx-sep {
height: 1px;
margin: 4px 6px;
background: var(--border);
}
.ctx-li {
position: relative;
}
.ctx-item {
display: flex;
align-items: center;
gap: 9px;
width: 100%;
min-height: 30px;
padding: 0 9px;
border-radius: 6px;
color: var(--text);
text-align: left;
}
.ctx-item:hover:not(:disabled),
.ctx-item:focus-visible,
.ctx-li.open > .ctx-item {
background: #232c38;
outline: none;
}
.ctx-item:disabled {
color: #566273;
cursor: default;
}
.ctx-item.danger {
color: #ff8787;
}
.ctx-item.danger:hover {
background: rgb(255 107 107 / 0.12);
}
.ctx-icon {
flex: 0 0 16px;
width: 16px;
color: var(--muted);
}
.ctx-icon.checked {
color: var(--on);
}
.ctx-label {
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ctx-note {
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
.ctx-keys {
color: #6b778a;
font-family: var(--font-mono);
font-size: 11px;
white-space: nowrap;
}
.ctx-chevron {
margin-right: -3px;
color: var(--muted);
}
.ctx-sub {
position: absolute;
top: -6px;
left: calc(100% + 2px);
}
.ctx-sub.flip {
right: calc(100% + 2px);
left: auto;
}
.ctx-sub > .ctx-list {
max-height: 60vh;
overflow-y: auto;
}
.ctx-swatches {
display: flex;
align-items: center;
gap: 6px;
min-height: 30px;
padding: 0 9px 0 34px;
color: var(--text);
}
.ctx-dot {
width: 16px;
height: 16px;
border: 2px solid #161c24;
border-radius: 50%;
outline: 1px solid #3a4554;
transition: transform 80ms;
}
.ctx-dot:hover {
transform: scale(1.18);
}
.ctx-dot.active {
outline: 2px solid var(--text);
}
.ctx-input {
display: flex;
align-items: center;
gap: 9px;
padding: 3px 5px 3px 9px;
}
.ctx-input input {
flex: 1;
min-width: 0;
height: 26px;
padding: 0 8px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font-size: 12px;
}
.ctx-input input:focus {
border-color: var(--accent);
outline: none;
}

View File

@ -118,23 +118,55 @@ const others = computed(() => {
const target = ref('') const target = ref('')
const chosen = computed(() => others.value.find(o => o.id === target.value) ?? others.value[0]) const chosen = computed(() => others.value.find(o => o.id === target.value) ?? others.value[0])
const targetId = computed({ get: () => chosen.value?.id ?? '', set: v => (target.value = v) }) const targetId = computed({ get: () => chosen.value?.id ?? '', set: v => (target.value = v) })
/** Where they fit, nearest first: every way to put them on a run of free pins. */ /** Where they fit, one card per part (nearest first), each fit a strip of the pins it takes. */
const fitChoices = computed(() => { const fitCards = computed(() => {
const out: { spot: number; start: number; part: string; pins: string; dist: number }[] = [] const cards = new Map<string, { key: string; name: string; icon: string; side: 'in' | 'out'; dist: number; choices: { spot: number; start: number; pins: string[] }[] }>()
ed.fits.value.forEach((f, spot) => { ed.fits.value.forEach((f, spot) => {
const node = ed.def.value.nodes.find(n => n.id === f.part) const node = ed.def.value.nodes.find(n => n.id === f.part)
const part = node ? partName(node) : 'part' const key = `${f.part}:${f.side}`
const card = cards.get(key) ?? {
key,
name: node ? partName(node) : 'Part',
icon: KIND_ICONS[node?.kind ?? ''] ?? 'lucide:cpu',
side: f.side,
dist: f.dist,
choices: [],
}
const k = f.mine.length const k = f.mine.length
for (let start = 0; start + k <= f.pins.length; start++) { for (let start = 0; start + k <= f.pins.length; start++) {
const a = f.pins[start]! const pins = f.pins.slice(start, start + k).map((p, i) => p.label || String(start + i + 1))
const b = f.pins[start + k - 1]! card.choices.push({ spot, start, pins: pins.length > 5 ? [pins[0]!, '…', pins[pins.length - 1]!] : pins })
const name = (p: typeof a, i: number) => p.label || String(i + 1)
out.push({ spot, start, part, pins: `${name(a, start)}–${name(b, start + k - 1)}`, dist: Math.hypot(a.x - f.from[0], (a.y + b.y) / 2 - f.from[1]) })
} }
card.dist = Math.min(card.dist, f.dist)
cards.set(key, card)
}) })
return out.sort((a, b) => a.dist - b.dist).slice(0, 8) return [...cards.values()].sort((a, b) => a.dist - b.dist)
}) })
const KIND_ICONS: Record<string, string> = {
chip: 'lucide:cpu',
split: 'lucide:split',
bundle: 'lucide:merge',
panel: 'lucide:sliders-vertical',
nand: 'lucide:square-function',
hex: 'lucide:binary',
}
/** Which wire goes where for the fit pointed at (or the nearest one), in signal direction. */
const fitMap = computed(() => {
const h = ed.fitHover.value ?? (fitCards.value[0] ? { spot: fitCards.value[0].choices[0]!.spot, start: fitCards.value[0].choices[0]!.start } : null)
const f = h && ed.fits.value[h.spot]
if (!h || !f) return []
return f.mine.map((m, i) => {
const node = ed.def.value.nodes.find(n => n.id === m.node)
const mine = node?.label?.trim() || (node ? partName(node) : '?')
const theirs = f.pins[h.start + i]?.label || String(h.start + i + 1)
return f.side === 'out' ? { from: theirs, to: mine } : { from: mine, to: theirs }
})
})
const isHot = (spot: number, start: number) => ed.fitHover.value?.spot === spot && ed.fitHover.value?.start === start
function partName(n: { label?: string; chip?: string; kind: NodeKind; autoLabel?: boolean }) { function partName(n: { label?: string; chip?: string; kind: NodeKind; autoLabel?: boolean }) {
return (!n.autoLabel && n.label?.trim()) || (n.chip && ed.getDef.value(n.chip)?.name) || KIND_NAMES[n.kind] || n.kind return (!n.autoLabel && n.label?.trim()) || (n.chip && ed.getDef.value(n.chip)?.name) || KIND_NAMES[n.kind] || n.kind
} }
@ -258,21 +290,38 @@ function pack() {
<section v-if="others.length && chosen"> <section v-if="others.length && chosen">
<h3>Wire them all to</h3> <h3>Wire them all to</h3>
<template v-if="fitChoices.length"> <template v-if="fitCards.length">
<p class="hint">The green boxes on the canvas show where they fit. Point along one to pick the pins, click to wire.</p> <div class="fit-cards">
<div class="fit-list"> <div v-for="(c, ci) in fitCards" :key="c.key" class="fit-card" :class="{ hot: c.choices.some(x => isHot(x.spot, x.start)) }">
<button <div class="fit-card-head">
v-for="c in fitChoices" <Icon :name="c.icon" class="fit-icon size-4 shrink-0" />
:key="`${c.spot}-${c.start}`" <span class="grow truncate">{{ c.name }}</span>
class="btn-sm" <span class="fit-tag">{{ ci === 0 ? 'nearest · ' : '' }}{{ c.side === 'out' ? 'outputs' : 'inputs' }}</span>
:class="{ active: ed.fitHover.value?.spot === c.spot && ed.fitHover.value?.start === c.start }" </div>
@pointerenter="ed.fitHover.value = { spot: c.spot, start: c.start }" <div class="fit-choices">
@pointerleave="ed.fitHover.value = null" <button
@click="ed.connectFit(c.spot, c.start)" v-for="x in c.choices"
> :key="`${x.spot}-${x.start}`"
<span class="font-mono">{{ c.pins }}</span> <span class="muted">{{ c.part }}</span> class="fit-choice"
</button> :class="{ active: isHot(x.spot, x.start) }"
:title="`Wire to ${x.pins.join(' ')}`"
@pointerenter="ed.fitHover.value = { spot: x.spot, start: x.start }"
@pointerleave="ed.fitHover.value = null"
@click="ed.connectFit(x.spot, x.start)"
>
<span v-for="(p, pi) in x.pins" :key="pi" class="fit-pill">{{ p }}</span>
</button>
</div>
</div>
</div> </div>
<div v-if="fitMap.length" class="fit-map" :class="{ live: !!ed.fitHover.value }">
<div v-for="(m, i) in fitMap" :key="i" class="fit-pair">
<span>{{ m.from }}</span>
<Icon name="lucide:arrow-right" class="fit-arrow size-3.5" />
<span>{{ m.to }}</span>
</div>
</div>
<p class="hint mt-2">Point at a choice, or along a green box on the canvas, to see it; click to wire.</p>
</template> </template>
<p v-else-if="canFit(ed.def.value, ed.getDef.value, ids)" class="hint">No part nearby has {{ nodes.length }} free pins in a row for them.</p> <p v-else-if="canFit(ed.def.value, ed.getDef.value, ids)" class="hint">No part nearby has {{ nodes.length }} free pins in a row for them.</p>
<details class="mt-2"> <details class="mt-2">

View File

@ -6,6 +6,7 @@ import { branchCorners, branchTo, moveCorner, moveSegment, routeTouchesBox, segm
import { circuitRoutes, findCrossings } from '~/lib/logic/routing' import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
import { seriesLinks, type Link } from '~/lib/logic/bulk' import { seriesLinks, type Link } from '~/lib/logic/bulk'
import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit' import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { LANE, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { wirePath } from '~/lib/draw' import { wirePath } from '~/lib/draw'
import { pinName } from '~/lib/logic/labels' import { pinName } from '~/lib/logic/labels'
@ -252,7 +253,15 @@ function onDrop(e: DragEvent) {
// ── Pointer interaction ───────────────────────────────────────────── // ── Pointer interaction ─────────────────────────────────────────────
type Drag = type Drag =
| { kind: 'pan'; sx: number; sy: number; vx: number; vy: number } | {
kind: 'pan'
sx: number
sy: number
vx: number
vy: number
/** A right click that doesn't move opens the menu for what is under it. */
menu?: { target: Element; at: Pt }
}
| { | {
kind: 'move' kind: 'move'
start: Pt start: Pt
@ -302,7 +311,8 @@ function onPointerDown(e: PointerEvent) {
const w = toWorld(e) const w = toWorld(e)
const v = view.value const v = view.value
if (e.button === 1 || e.button === 2 || (e.button === 0 && spaceDown.value)) { if (e.button === 1 || e.button === 2 || (e.button === 0 && spaceDown.value)) {
drag.value = { kind: 'pan', sx: e.clientX, sy: e.clientY, vx: v.x, vy: v.y } menu.value = null
drag.value = { kind: 'pan', sx: e.clientX, sy: e.clientY, vx: v.x, vy: v.y, menu: e.button === 2 ? { target: e.target as Element, at: w } : undefined }
root.value!.setPointerCapture(e.pointerId) root.value!.setPointerCapture(e.pointerId)
return return
} }
@ -622,11 +632,14 @@ function targetAt(at: Pt, dir: 'in' | 'out', bus = false): PinRef | null {
return { node: n.id, pin: near.key } return { node: n.id, pin: near.key }
} }
function onPointerUp() { function onPointerUp(e: PointerEvent) {
const d = drag.value const d = drag.value
drag.value = null drag.value = null
if (!d) return if (!d) return
switch (d.kind) { switch (d.kind) {
case 'pan':
if (d.menu && Math.abs(e.clientX - d.sx) + Math.abs(e.clientY - d.sy) < 5) openMenuAt(d.menu.target, d.menu.at, e.clientX, e.clientY)
break
case 'move': case 'move':
if (d.node.kind === 'button') ed.press(d.node, false) if (d.node.kind === 'button') ed.press(d.node, false)
if (d.row && !d.moved) ed.pressRow(d.node, d.row, false) if (d.row && !d.moved) ed.pressRow(d.node, d.row, false)
@ -736,6 +749,10 @@ function onKey(e: KeyboardEvent) {
} }
const mod = e.ctrlKey || e.metaKey const mod = e.ctrlKey || e.metaKey
const key = e.key.toLowerCase() const key = e.key.toLowerCase()
if (e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) {
e.preventDefault()
return openMenuForSelection()
}
// Keys bound to switches, buttons and panel rows win over the shortcuts below. // Keys bound to switches, buttons and panel rows win over the shortcuts below.
if (!mod && !e.altKey && e.key.length === 1) { if (!mod && !e.altKey && e.key.length === 1) {
const bound = def.value.nodes.filter(n => n.key === key && (n.kind === 'input' || n.kind === 'button')) const bound = def.value.nodes.filter(n => n.key === key && (n.kind === 'input' || n.kind === 'button'))
@ -908,6 +925,62 @@ const cableGhost = computed(() => {
return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) } return { nodes: [end('bundle', c.start), end('split', at)], line: toPath(routeWire(c.start, at)) }
}) })
// ── Context menu ────────────────────────────────────────────────────
const menu = ref<{ x: number; y: number; entries: MenuEntry[]; keyboard?: boolean } | null>(null)
const { build } = useMenu()
const canvasOps: CanvasOps = {
fit,
place: (kind, at) => {
const [x, y] = originFor({ kind }, at)
ed.addNode({ kind }, x, y)
},
}
/**
* Right click: on a part or wire it selects that (unless it is in the
* selection already) and shows what can be done with the selection; on
* empty canvas, what can go there.
*/
function openMenuAt(target: Element, at: Pt, x: number, y: number) {
const nodeId = target.closest('[data-node]')?.getAttribute('data-node')
const wireId = target.closest('[data-wire]')?.getAttribute('data-wire')
const junction = target.closest('[data-junction]')?.getAttribute('data-junction')
if (nodeId && nodeMap.value.has(nodeId)) {
if (!selected.value.has(nodeId)) {
ed.selection.value = [nodeId]
ed.wireSel.value = []
}
} else if (wireId) {
if (!wireSelected.value.has(wireId)) {
ed.wireSel.value = [wireId]
ed.selection.value = []
}
} else if (junction) {
ed.wireSel.value = def.value.wires.filter(w => `${w.from.node}:${w.from.pin}` === junction).map(w => w.id)
ed.selection.value = []
}
const onThing = !!(nodeId || wireId || junction)
const entries = build(onThing ? { kind: 'selection' } : { kind: 'canvas', at }, canvasOps)
menu.value = entries.length ? { x: x + 2, y: y + 2, entries } : null
}
/** The menu key (or Shift+F10): the menu for the selection, by its middle. */
function openMenuForSelection() {
const r = root.value!.getBoundingClientRect()
const ids = new Set(ed.selection.value)
const nodes = def.value.nodes.filter(n => ids.has(n.id))
const v = view.value
let at: Pt = [(size.w / 2 - v.x) / (G * v.zoom), (size.h / 2 - v.y) / (G * v.zoom)]
if (nodes.length) {
const b = bounds(nodes)
at = [(b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2]
}
const x = r.left + v.x + at[0] * G * v.zoom
const y = r.top + v.y + at[1] * G * v.zoom
const entries = build(nodes.length || ed.wireSel.value.length ? { kind: 'selection' } : { kind: 'canvas', at }, canvasOps)
menu.value = entries.length ? { x, y, entries, keyboard: true } : null
}
/** Pins a dragged part will connect to when dropped, shown as green rings. */ /** Pins a dragged part will connect to when dropped, shown as green rings. */
const dropRings = computed(() => { const dropRings = computed(() => {
const d = drag.value const d = drag.value
@ -1106,6 +1179,7 @@ defineExpose({ fit, zoomAt })
<rect v-if="boxRect" v-bind="boxRect" /> <rect v-if="boxRect" v-bind="boxRect" />
</g> </g>
</svg> </svg>
<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"> <div v-if="!def.nodes.length" class="empty-hint">
<p class="font-semibold">Empty circuit</p> <p class="font-semibold">Empty circuit</p>

View File

@ -0,0 +1,95 @@
<script setup lang="ts">
// The right-click menu: placed at the pointer, kept on screen, closed by a
// click elsewhere, Escape, scrolling or any choice. Arrow keys walk it.
import type { MenuEntry } from '~/composables/useMenu'
const props = defineProps<{ x: number; y: number; entries: MenuEntry[]; /** Opened from the keyboard: the first entry takes the focus. */ keyboard?: boolean }>()
const emit = defineEmits<{ close: [] }>()
const el = ref<HTMLElement>()
const pos = ref({ left: props.x, top: props.y })
/** Near the right edge, submenus open to the left. */
const flip = ref(false)
function place() {
const r = el.value?.getBoundingClientRect()
if (!r) return
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 - r.height - 8)),
}
flip.value = pos.value.left + r.width * 2 + 16 > window.innerWidth
}
function close() {
emit('close')
}
/** A click or scroll outside closes it; inside, a long submenu may scroll. */
function outside(e: Event) {
if (!el.value?.contains(e.target as Node)) close()
}
function items(list: Element | null | undefined): HTMLButtonElement[] {
return list ? [...list.querySelectorAll<HTMLButtonElement>(':scope > li > .ctx-item:not(:disabled)')] : []
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
return close()
}
const active = document.activeElement as HTMLElement | null
// Keys typed while in the menu stay in it (Enter picks, not the canvas shortcut).
if (active && el.value?.contains(active)) e.stopPropagation()
if (active?.tagName === 'INPUT' && el.value?.contains(active)) return
const list = active?.closest('.ctx-list') ?? el.value?.querySelector('.ctx-list')
const all = items(list)
const at = all.indexOf(active as HTMLButtonElement)
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
const step = e.key === 'ArrowDown' ? 1 : -1
all[(at + step + all.length) % all.length]?.focus()
} else if (e.key === 'ArrowRight' && active?.classList.contains('sub')) {
e.preventDefault()
e.stopPropagation()
active.click()
nextTick(() => items(active.parentElement?.querySelector('.ctx-sub .ctx-list'))[0]?.focus())
} else if (e.key === 'ArrowLeft') {
const owner = list?.closest('.ctx-sub')?.parentElement?.querySelector<HTMLButtonElement>(':scope > .ctx-item')
if (owner) {
e.preventDefault()
e.stopPropagation()
owner.focus()
}
}
}
onMounted(() => {
place()
if (props.keyboard) nextTick(() => items(el.value?.querySelector('.ctx-list'))[0]?.focus({ preventScroll: true }))
window.addEventListener('pointerdown', outside, true)
window.addEventListener('keydown', onKey, true)
window.addEventListener('wheel', outside, { passive: true })
window.addEventListener('resize', close)
window.addEventListener('blur', close)
})
onBeforeUnmount(() => {
window.removeEventListener('pointerdown', outside, true)
window.removeEventListener('keydown', onKey, true)
window.removeEventListener('wheel', outside)
window.removeEventListener('resize', close)
window.removeEventListener('blur', close)
})
</script>
<template>
<Teleport to="body">
<div ref="el" class="ctx" :style="{ left: `${pos.left}px`, top: `${pos.top}px` }" @contextmenu.prevent>
<EditorMenuList :entries="entries" :flip="flip" @done="close" />
</div>
</Teleport>
</template>

View File

@ -18,6 +18,7 @@ const SHORTCUTS: [string, string][] = [
['Double-click a component', 'Open it and see inside'], ['Double-click a component', 'Open it and see inside'],
['Drag on empty space', 'Select parts; across wires (no parts in the box) it selects every wire it crosses'], ['Drag on empty space', 'Select parts; across wires (no parts in the box) it selects every wire it crosses'],
['Drag right to left', 'Select everything the box touches, parts and wires (green box)'], ['Drag right to left', 'Select everything the box touches, parts and wires (green box)'],
['Right click (or the menu key)', 'Everything you can do with what is under the pointer or selected; on empty space: paste, add a part here'],
['Right or middle drag, Space + drag', 'Move the view'], ['Right or middle drag, Space + drag', 'Move the view'],
['Mouse wheel', 'Zoom'], ['Mouse wheel', 'Zoom'],
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'], ['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],

View File

@ -0,0 +1,85 @@
<script setup lang="ts">
// One level of the context menu; entries with children open the next level beside it.
import type { MenuEntry, MenuItem } from '~/composables/useMenu'
defineProps<{ entries: MenuEntry[]; flip?: boolean }>()
const emit = defineEmits<{ done: [] }>()
const open = ref<number | null>(null)
const text = ref('')
let timer: ReturnType<typeof setTimeout> | undefined
function enter(i: number, item: MenuItem) {
clearTimeout(timer)
timer = setTimeout(() => (open.value = item.children ? i : null), 90)
item.hover?.(true)
}
function run(i: number, item: MenuItem) {
if (item.disabled) return
if (item.children) {
open.value = i
return
}
item.hover?.(false)
item.run?.()
emit('done')
}
const isItem = (e: MenuEntry): e is MenuItem => e !== 'sep' && !('head' in e)
/** A submenu that would run off the bottom of the window moves up. */
function keepOnScreen(el: Element | ComponentPublicInstance | null) {
if (!(el instanceof HTMLElement)) return
el.style.top = ''
const over = el.getBoundingClientRect().bottom - (window.innerHeight - 8)
if (over > 0) el.style.top = `${-6 - over}px`
}
</script>
<template>
<ul class="ctx-list" role="menu">
<template v-for="(e, i) in entries" :key="i">
<li v-if="e === 'sep'" class="ctx-sep" role="separator" />
<li v-else-if="!isItem(e)" class="ctx-head">{{ e.head }}</li>
<li v-else class="ctx-li" :class="{ open: open === i }" @pointerenter="enter(i, e)" @pointerleave="e.hover?.(false)">
<div v-if="e.swatches" class="ctx-swatches">
<span class="ctx-label">{{ e.label }}</span>
<button
v-for="s in e.swatches"
:key="s.title"
class="ctx-dot"
:class="{ active: s.active }"
:style="{ background: s.color }"
:title="s.title"
@click="s.run(), emit('done')"
/>
</div>
<form v-else-if="e.input" class="ctx-input" @submit.prevent="e.input.submit(text.trim()), emit('done')">
<Icon v-if="e.icon" :name="e.icon" class="ctx-icon size-4" />
<input v-model="text" :placeholder="e.input.placeholder" :title="`${e.label}: type a name, then Enter`" @keydown.stop />
</form>
<button
v-else
class="ctx-item"
role="menuitem"
:class="{ danger: e.danger, sub: !!e.children }"
:disabled="e.disabled"
:aria-haspopup="e.children ? 'menu' : undefined"
@click="run(i, e)"
>
<Icon v-if="e.checked" name="lucide:check" class="ctx-icon size-4 checked" />
<Icon v-else-if="e.icon" :name="e.icon" class="ctx-icon size-4" />
<span v-else class="ctx-icon" />
<span class="ctx-label">{{ e.label }}</span>
<span v-if="e.note" class="ctx-note">{{ e.note }}</span>
<kbd v-if="e.keys" class="ctx-keys">{{ e.keys }}</kbd>
<Icon v-if="e.children" name="lucide:chevron-right" class="ctx-chevron size-3.5" />
</button>
<div v-if="e.children && open === i" :ref="keepOnScreen" class="ctx-sub" :class="{ flip }">
<EditorMenuList :entries="e.children" :flip="flip" @done="emit('done')" />
</div>
</li>
</template>
</ul>
</template>

View File

@ -776,20 +776,28 @@ function create() {
let clip: Clip | null = null let clip: Clip | null = null
let pasteCount = 0 let pasteCount = 0
/** Something copied, ready to paste. */
const hasClip = ref(false)
function copy() { function copy() {
if (!selection.value.length) return if (!selection.value.length) return
clip = copySelection(def.value, withDocked(selection.value)) clip = copySelection(def.value, withDocked(selection.value))
hasClip.value = true
pasteCount = 0 pasteCount = 0
notify(`Copied ${clip.nodes.length} part${clip.nodes.length === 1 ? '' : 's'}`) notify(`Copied ${clip.nodes.length} part${clip.nodes.length === 1 ? '' : 's'}`)
} }
function paste() { /** Pastes a little below the copy each time, or with its top left corner at `at`. */
function paste(at?: Pt) {
if (!clip) return if (!clip) return
pasteCount++ pasteCount++
const blocked = clip.nodes.filter(n => n.kind === 'chip' && n.chip && !canPlace(n.chip)) const blocked = clip.nodes.filter(n => n.kind === 'chip' && n.chip && !canPlace(n.chip))
const usable: Clip = blocked.length ? { nodes: clip.nodes.filter(n => !blocked.includes(n)), wires: clip.wires } : clip const usable: Clip = blocked.length ? { nodes: clip.nodes.filter(n => !blocked.includes(n)), wires: clip.wires } : clip
if (blocked.length) notify('Skipped parts that would contain this circuit itself', 'error') if (blocked.length) notify('Skipped parts that would contain this circuit itself', 'error')
const ids = pasteClip(def.value, usable, 2 * pasteCount, 2 * pasteCount) const [dx, dy] = at && usable.nodes.length
? [Math.round(at[0]) - Math.min(...usable.nodes.map(n => n.x)), Math.round(at[1]) - Math.min(...usable.nodes.map(n => n.y))]
: [2 * pasteCount, 2 * pasteCount]
const ids = pasteClip(def.value, usable, dx, dy)
const fresh = new Set(ids) const fresh = new Set(ids)
continueSeries(def.value, def.value.nodes.filter(n => fresh.has(n.id))) continueSeries(def.value, def.value.nodes.filter(n => fresh.has(n.id)))
selection.value = ids selection.value = ids
@ -1856,6 +1864,7 @@ function create() {
makeIndependent, makeIndependent,
copy, copy,
paste, paste,
hasClip,
duplicate, duplicate,
selectAll, selectAll,
packageSelected, packageSelected,

372
app/composables/useMenu.ts Normal file
View File

@ -0,0 +1,372 @@
// What the context menu offers for what was right-clicked: one part, several
// parts, wires, or the empty canvas. Every entry runs the same store action
// as the matching button in the side panel.
import { byPosition, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
import { cableOf } from '~/lib/logic/cables'
import { cableBits, chipPins, type Pt } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide'
export interface MenuSwatch {
color: string
title: string
active: boolean
run: () => void
}
export interface MenuItem {
label: string
icon?: string
/** Shortcut shown on the right. */
keys?: string
/** Muted text after the label. */
note?: string
run?: () => void
danger?: boolean
disabled?: boolean
checked?: boolean
children?: MenuItem[]
/** A row of colour dots instead of a line. */
swatches?: MenuSwatch[]
/** A text field; Enter runs it with what was typed. */
input?: { placeholder: string; submit: (text: string) => void }
/** Pointing at it (for fits: shows them on the canvas). */
hover?: (on: boolean) => void
}
/** A heading (no action) or a divider between groups. */
export type MenuEntry = MenuItem | { head: string } | 'sep'
export type MenuTarget = { kind: 'selection' } | { kind: 'canvas'; at: Pt }
export interface CanvasOps {
fit: () => void
place: (kind: NodeKind, at: Pt) => void
}
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 ARRANGE: { how: Arrange; label: string; icon: string }[] = [
{ how: 'left', label: 'Line up on the left', icon: 'lucide:align-start-vertical' },
{ how: 'right', label: 'Line up on the right', icon: 'lucide:align-end-vertical' },
{ how: 'top', label: 'Line up at the top', icon: 'lucide:align-start-horizontal' },
{ how: 'bottom', label: 'Line up at the bottom', icon: 'lucide:align-end-horizontal' },
{ how: 'spread-y', label: 'Spread top to bottom', icon: 'lucide:align-vertical-space-around' },
{ how: 'spread-x', label: 'Spread left to right', icon: 'lucide:align-horizontal-space-around' },
]
const ADD: { kind: NodeKind; label: string; icon: string; keys?: string }[] = [
{ kind: 'nand', label: 'NAND', icon: 'lucide:square-function', keys: 'N' },
{ kind: 'input', label: 'Input', icon: 'lucide:toggle-left', keys: 'I' },
{ kind: 'output', label: 'Output', icon: 'lucide:log-out', keys: 'O' },
{ kind: 'lamp', label: 'Lamp', icon: 'lucide:lightbulb', keys: 'L' },
{ kind: 'button', label: 'Push button', icon: 'lucide:circle-dot', keys: 'B' },
{ kind: 'clock', label: 'Clock', icon: 'lucide:audio-waveform', keys: 'C' },
{ kind: 'panel', label: 'Input panel', icon: 'lucide:sliders-vertical', keys: 'P' },
{ kind: 'hex', label: 'Hex display', icon: 'lucide:binary', keys: 'H' },
{ kind: 'note', label: 'Note', icon: 'lucide:sticky-note', keys: 'T' },
]
const NAMED = ['input', 'output', 'lamp', 'button', 'clock', 'hex', 'note', 'panel', 'chip']
export function useMenu() {
const ed = useEditor()
const nodesOf = (ids: string[]) => {
const set = new Set(ids)
return ed.def.value.nodes.filter(n => set.has(n.id))
}
const partName = (n: CircuitNode) =>
n.kind === 'chip' ? (n.chip && ed.getDef.value(n.chip)?.name) || 'Missing component' : (KIND_NAMES[n.kind] ?? n.kind)
const wired = (ids: string[]) => {
const set = new Set(ids)
return ed.def.value.wires.some(w => set.has(w.from.node) || set.has(w.to.node))
}
function rename(id: string) {
ed.selection.value = [id]
ed.wireSel.value = []
ed.toggleSidebar('right', true)
ed.labelFocus.value++
}
/** Other parts the same pins fit: NAND and components with as many inputs and outputs, or the switch and lamp kinds. */
function swapChoices(nodes: CircuitNode[]): MenuItem[] {
const fam = sharedFamily(nodes)
const current = new Set(nodes.map(typeKey))
const swapTo = (target: { kind: NodeKind; chip?: string }) => () => ed.swapMany(nodes.map(n => n.id), target)
if (fam === 'source' || fam === 'sink') {
return (fam === 'source' ? SOURCE_KINDS : SINK_KINDS).map(k => ({
label: KIND_NAMES[k] ?? k,
checked: current.size === 1 && current.has(k),
run: swapTo({ kind: k }),
}))
}
if (fam !== 'logic') return []
const pins = nodes.map(n => (n.kind === 'nand' ? [2, 1] : n.chip && ed.getDef.value(n.chip) ? [chipPins(ed.getDef.value(n.chip)!).inputs.length, chipPins(ed.getDef.value(n.chip)!).outputs.length] : [0, 0]))
const [ins, outs] = pins[0]!
if (pins.some(p => p[0] !== ins || p[1] !== outs)) return []
const out: MenuItem[] = []
if (ins === 2 && outs === 1) out.push({ label: 'NAND', checked: current.size === 1 && current.has('nand'), run: swapTo({ kind: 'nand' }) })
for (const d of ed.project.value.components) {
if (d.id === ed.def.value.id || !ed.canPlace(d.id)) continue
const p = chipPins(d)
if (p.inputs.length !== ins || p.outputs.length !== outs) continue
out.push({ label: d.name, checked: current.size === 1 && current.has(`chip:${d.id}`), run: swapTo({ kind: 'chip', chip: d.id }) })
}
return out.length > 1 ? out : []
}
function common(ids: string[]): MenuEntry[] {
return [
'sep',
{ label: 'Copy', icon: 'lucide:copy', keys: 'Ctrl+C', run: () => ed.copy() },
{ label: 'Duplicate', icon: 'lucide:copy-plus', keys: 'Ctrl+D', run: () => ed.duplicate() },
{ label: 'Unlink all', icon: 'lucide:unlink', disabled: !wired(ids), run: () => ed.unlink(ids) },
'sep',
{ label: 'Delete', icon: 'lucide:trash-2', keys: 'Del', danger: true, run: () => ed.deleteSelected() },
]
}
function oneNode(n: CircuitNode): MenuEntry[] {
const get = ed.getDef.value
const out: MenuEntry[] = [{ head: n.label?.trim() && !n.autoLabel ? `${partName(n)} · ${n.label.trim()}` : partName(n) }]
if (n.kind === 'chip' && n.chip) out.push({ label: 'Open component', icon: 'lucide:log-in', keys: 'Enter', run: () => ed.open(n.chip!) })
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
const swaps = swapChoices([n])
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps })
const base = baseOf(n, get)
if (base && gateFamily(get, base)) {
const now = inputCount(n, get)
out.push({
label: 'Inputs',
icon: 'lucide:list-plus',
note: String(now),
children: [2, 3, 4, 5, 6, 8].map(k => ({ label: `${k} inputs`, checked: k === now, run: () => ed.setInputs(n, k) })),
})
}
if (n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel') {
out.push({
label: 'Colour',
swatches: [undefined, ...LAMP_COLORS].map(c => ({
color: c ? LAMP_HEX[c]! : n.kind === 'hex' ? LAMP_HEX.red! : LAMP_HEX.yellow!,
title: c ?? 'Default',
active: n.color === c,
run: () => ed.patchMany([n.id], { color: c }),
})),
})
}
if (n.kind === 'clock') {
out.push({
label: 'Speed',
icon: 'lucide:gauge',
note: n.hz ? `${n.hz} Hz` : 'top bar',
children: [
{ label: 'Follow the top bar', checked: n.hz === undefined, run: () => ed.patchMany([n.id], { hz: undefined }, true) },
...[0.5, 1, 2, 5, 10, 30, 100].map(hz => ({ label: `${hz} Hz`, checked: n.hz === hz, run: () => ed.patchMany([n.id], { hz }, true) })),
],
})
}
if (n.kind === 'note') {
out.push({
label: 'Size',
icon: 'lucide:type',
children: [
{ label: 'Small', checked: n.size === 'sm', run: () => ed.patchMany([n.id], { size: 'sm' }) },
{ label: 'Normal', checked: !n.size, run: () => ed.patchMany([n.id], { size: undefined }) },
{ label: 'Large', checked: n.size === 'lg', run: () => ed.patchMany([n.id], { size: 'lg' }) },
],
})
}
if (n.kind === 'chip' && n.chip && get(n.chip)) {
const pins = chipPins(get(n.chip)!)
const docked = ed.def.value.nodes.some(x => x.kind === 'panel' && x.attach === n.id)
out.push('sep')
if (pins.inputs.length && !docked) out.push({ label: 'Attach input panel', icon: 'lucide:sliders-vertical', run: () => ed.addPanel(n.id) })
if (pins.inputs.length) out.push({ label: 'Wire inputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'in') })
if (pins.outputs.length) out.push({ label: 'Wire outputs one by one', icon: 'lucide:cable', run: () => ed.startLinking([n.id], 'out') })
out.push(
{ label: 'Unpack into parts', icon: 'lucide:ungroup', run: () => ed.unpack(n.id) },
{ label: 'Make independent copy', icon: 'lucide:copy-plus', run: () => ed.makeIndependent(n.id) },
)
}
if (n.kind === 'panel') {
out.push('sep')
if (!n.attach) out.push({ label: 'Add row', icon: 'lucide:plus', run: () => ed.addRow(n) })
else out.push({ label: 'Detach from component', icon: 'lucide:link-2-off', run: () => ed.undock(n) })
out.push({ label: 'Wire rows one by one', icon: 'lucide:cable', disabled: !n.rows?.length, run: () => ed.startLinking([n.id]) })
}
if (n.kind === 'bundle' || n.kind === 'split') out.push('sep', ...cableEnd(n))
return [...out, ...common([n.id])]
}
function cableEnd(n: CircuitNode): MenuEntry[] {
const out: MenuEntry[] = []
const feed = n.kind === 'split' ? ed.def.value.wires.find(w => w.to.node === n.id) : undefined
const bundle = n.kind === 'bundle' ? n : feed ? cableOf(ed.def.value, feed) : undefined
if (n.plug) out.push({ label: 'Unplug', icon: 'lucide:unplug', run: () => ed.unplugEnd(n) })
else {
const part = ed.plugTarget(n)
if (part) out.push({ label: `Plug into ${part.label?.trim() && !part.autoLabel ? part.label.trim() : partName(part)}`, icon: 'lucide:plug', run: () => ed.plugEnd(n) })
}
if (n.kind === 'bundle' && !n.plug) {
const fed = new Set(ed.def.value.wires.filter(w => w.to.node === n.id).map(w => w.to.pin))
if (fed.size < cableBits(n)) out.push({ label: 'Attach input panel', icon: 'lucide:sliders-vertical', run: () => ed.addCablePanel(n.id) })
}
if (bundle) {
const sleeve = ed.def.value.wires.find(w => w.from.node === bundle.id)?.color
out.push(
{
label: 'Sleeve colour',
swatches: [undefined, ...WIRE_COLORS].map(c => ({
color: c ? WIRE_HEX[c]! : '#3ddc84',
title: c ?? 'Default',
active: sleeve === c,
run: () => ed.setCableColor(bundle.id, c),
})),
},
{ label: 'Remove cable', icon: 'lucide:split', run: () => ed.removeCable(bundle.id) },
)
}
return out
}
function manyNodes(nodes: CircuitNode[]): MenuEntry[] {
const ids = nodes.map(n => n.id)
const out: MenuEntry[] = [{ head: `${nodes.length} parts` }]
const fits = fitItems()
if (fits.length) out.push({ label: 'Wire them all to', icon: 'lucide:cable', children: fits })
out.push({ label: 'Connect one by one', icon: 'lucide:list-ordered', run: () => ed.startLinking() })
if (nodes.every(n => n.kind === 'input')) {
out.push({
label: 'Switches',
icon: 'lucide:toggle-right',
children: [
{ label: 'All off (0)', run: () => ed.setSwitches(ids, false) },
{ label: 'All on (1)', run: () => ed.setSwitches(ids, true) },
{ label: 'Flip each', run: () => ed.setSwitches(ids, 'flip') },
],
})
}
const swaps = swapChoices(nodes)
if (swaps.length) out.push({ label: 'Change all to', icon: 'lucide:replace', children: swaps })
if (nodes.every(n => n.kind === 'lamp' || n.kind === 'hex' || n.kind === 'pixel')) {
const now = new Set(nodes.map(n => n.color))
out.push({
label: 'Colour',
swatches: [undefined, ...LAMP_COLORS].map(c => ({
color: c ? LAMP_HEX[c]! : LAMP_HEX.yellow!,
title: c ?? 'Default',
active: now.size === 1 && now.has(c),
run: () => ed.patchMany(ids, { color: c }),
})),
})
}
out.push({
label: 'Arrange',
icon: 'lucide:layout-grid',
children: ARRANGE.map(a => ({ label: a.label, icon: a.icon, run: () => ed.arrangeSelected(a.how) })),
})
const types = new Map<string, { name: string; ids: string[] }>()
for (const n of nodes) {
const k = typeKey(n)
const t = types.get(k) ?? { name: partName(n), ids: [] }
t.ids.push(n.id)
types.set(k, t)
}
if (types.size > 1) {
out.push({
label: 'Keep only',
icon: 'lucide:filter',
children: [...types.values()].map(t => ({ label: t.name, note: String(t.ids.length), run: () => ed.selectOnly(t.ids) })),
})
}
out.push({ label: 'Make a component', icon: 'lucide:package', input: { placeholder: 'Make a component…', submit: name => ed.packageSelected(name || 'Part') } })
return [...out, ...common(ids)]
}
/** Every way the selection fits, nearest first; pointing at one shows it on the canvas. */
function fitItems(): MenuItem[] {
const out: (MenuItem & { dist: number })[] = []
ed.fits.value.forEach((f, spot) => {
const part = ed.def.value.nodes.find(n => n.id === f.part)
const k = f.mine.length
for (let start = 0; start + k <= f.pins.length; start++) {
const a = f.pins[start]!
const b = f.pins[start + k - 1]!
out.push({
label: `${a.label || start + 1}–${b.label || start + k}`,
note: part ? (part.label?.trim() && !part.autoLabel ? part.label.trim() : partName(part)) : '',
icon: 'lucide:arrow-right-left',
dist: Math.hypot(a.x - f.from[0], (a.y + b.y) / 2 - f.from[1]),
run: () => ed.connectFit(spot, start),
hover: on => (ed.fitHover.value = on ? { spot, start } : null),
})
}
})
return out.sort((a, b) => a.dist - b.dist).slice(0, 10)
}
function wires(): MenuEntry[] {
const list = ed.selectedWires.value
const kinds = new Map(ed.def.value.nodes.map(n => [n.id, n.kind]))
const cable = list.length === 1 && kinds.get(list[0]!.from.node) === 'bundle' ? list[0] : undefined
const out: MenuEntry[] = [{ head: cable ? 'Cable' : list.length === 1 ? 'Wire' : `${list.length} wires` }]
if (list.length >= 2) {
out.push(
{ label: 'Bundle into cable', icon: 'lucide:merge', keys: 'Ctrl+G', run: () => ed.bundleSelected() },
{ label: 'Place the ends yourself', icon: 'lucide:move', keys: 'Ctrl+Shift+G', run: () => ed.startCable() },
)
}
if (list.length === 1) out.push({ label: 'Select the whole signal', icon: 'lucide:git-branch', keys: 'Double-click', run: () => ed.selectNet(list[0]!.id) })
const colors = new Set(list.map(w => w.color))
out.push({
label: cable ? 'Sleeve colour' : 'Colour',
swatches: [undefined, ...WIRE_COLORS].map(c => ({
color: c ? WIRE_HEX[c]! : '#3ddc84',
title: c ?? 'Default',
active: colors.size === 1 && colors.has(c),
run: () => ed.setWireColor(c),
})),
})
if (list.some(w => w.pts?.length)) out.push({ label: 'Straighten (route automatically)', icon: 'lucide:spline', run: () => ed.autoRoute() })
if (cable) out.push({ label: 'Remove cable', icon: 'lucide:split', run: () => ed.removeCable(cable.from.node) })
out.push('sep', { label: 'Delete', icon: 'lucide:trash-2', keys: 'Del', danger: true, run: () => ed.deleteSelected() })
return out
}
function canvas(at: Pt, ops: CanvasOps): MenuEntry[] {
return [
{ label: 'Paste here', icon: 'lucide:clipboard-paste', keys: 'Ctrl+V', disabled: !ed.hasClip.value, run: () => ed.paste(at) },
{
label: 'Add here',
icon: 'lucide:plus',
children: ADD.filter(a => ed.canPlaceKind(a.kind)).map(a => ({ label: a.label, icon: a.icon, keys: a.keys, run: () => ops.place(a.kind, at) })),
},
'sep',
{ label: 'Select all', icon: 'lucide:box-select', keys: 'Ctrl+A', disabled: !ed.def.value.nodes.length, run: () => ed.selectAll() },
{ label: 'Fit to screen', icon: 'lucide:scan', keys: 'F', run: ops.fit },
{ label: 'Tidy all wires', icon: 'lucide:wand-sparkles', disabled: !ed.def.value.wires.length, run: () => ed.tidyAll() },
'sep',
{ label: 'Undo', icon: 'lucide:undo-2', keys: 'Ctrl+Z', disabled: !ed.canUndo.value, run: () => ed.undo() },
{ label: 'Redo', icon: 'lucide:redo-2', keys: 'Ctrl+Shift+Z', disabled: !ed.canRedo.value, run: () => ed.redo() },
]
}
/** The menu for the current selection, or for a spot on the empty canvas. */
function build(target: MenuTarget, ops: CanvasOps): MenuEntry[] {
if (target.kind === 'canvas') return canvas(target.at, ops)
const nodes = nodesOf(ed.selection.value).sort(byPosition)
if (nodes.length === 1) return oneNode(nodes[0]!)
if (nodes.length > 1) return manyNodes(nodes)
if (ed.wireSel.value.length) return wires()
return []
}
return { build }
}

View File

@ -25,7 +25,8 @@ export default defineNuxtConfig({
icon: { icon: {
serverBundle: { collections: ['lucide'] }, serverBundle: { collections: ['lucide'] },
cssLayer: 'base', cssLayer: 'base',
clientBundle: { scan: true }, // Icons named in menus (app/composables) count too, not only those in templates.
clientBundle: { scan: { globInclude: ['**/*.{vue,ts}'] } },
}, },
// Share links and accounts live as JSON files in data/ (a volume in // Share links and accounts live as JSON files in data/ (a volume in