logigate/app/composables/useMenu.ts

373 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 }
}