logigate/app/components/editor/BulkSettings.vue

400 lines
19 KiB
Vue
Raw Permalink 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.

<script setup lang="ts">
// Settings for several selected parts at once: one change, all of them.
import { byPosition, numberedNames, sharedFamily, typeKey, type Arrange } from '~/lib/logic/bulk'
import { canFit } from '~/lib/logic/fit'
import { chipPins } from '~/lib/logic/geometry'
import { pinKeys, SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, type LampColor, type NodeKind } from '~/lib/logic/types'
const ed = useEditor()
const nodes = computed(() => {
const set = new Set(ed.selection.value)
return ed.def.value.nodes.filter(n => set.has(n.id))
})
const ids = computed(() => nodes.value.map(n => n.id))
const wires = ed.selectedWires
const kinds = computed(() => new Set(nodes.value.map(n => n.kind)))
const only = (...ks: NodeKind[]) => nodes.value.length > 0 && [...kinds.value].every(k => ks.includes(k))
/** The selection by type, biggest group first: click one to keep only those. */
const groups = computed(() => {
const map = new Map<string, { key: string; name: string; ids: string[] }>()
for (const n of nodes.value) {
const key = typeKey(n)
const name = n.kind === 'chip' ? (n.chip && ed.getDef.value(n.chip)?.name) || 'Missing component' : KIND_NAMES[n.kind] ?? n.kind
const g = map.get(key) ?? { key, name, ids: [] }
g.ids.push(n.id)
map.set(key, g)
}
return [...map.values()].sort((a, b) => b.ids.length - a.ids.length || a.name.localeCompare(b.name))
})
const transistors = computed(() => nodes.value.reduce((sum, n) => sum + ed.transistorsOfNode(n), 0))
// ── Change all to ───────────────────────────────────────────────────
const family = computed(() => sharedFamily(nodes.value))
const currentType = computed(() => (groups.value.length === 1 ? groups.value[0]!.key : ''))
const familyKinds = computed<NodeKind[]>(() => (family.value === 'source' ? SOURCE_KINDS : family.value === 'sink' ? SINK_KINDS : []))
const swapGroups = computed(() => {
const map = new Map<string, { id: string; label: string; ok: boolean }[]>()
for (const d of ed.project.value.components) {
const p = chipPins(d)
const g = d.group?.trim() || 'My components'
if (!map.has(g)) map.set(g, [])
map.get(g)!.push({ id: d.id, label: `${d.name} (${p.inputs.length} → ${p.outputs.length})`, ok: ed.canPlace(d.id) })
}
return [...map.entries()]
})
function onSwap(e: Event) {
const v = (e.target as HTMLSelectElement).value
if (!v || v === currentType.value) return
ed.swapMany(ids.value, v.startsWith('chip:') ? { kind: 'chip', chip: v.slice(5) } : { kind: v as NodeKind })
}
// ── Rename all ──────────────────────────────────────────────────────
const labelable = computed(() => nodes.value.every(n => !['high', 'low', 'nand', 'bundle', 'split', 'pixel'].includes(n.kind)))
const pattern = ref('')
const start = ref(0)
const ordered = computed(() => [...nodes.value].sort(byPosition))
const preview = computed(() => (pattern.value.trim() ? numberedNames(pattern.value, ordered.value.length, start.value) : []))
function rename() {
ed.renameMany(ids.value, pattern.value, start.value)
pattern.value = ''
}
// ── Switches, colours, clocks, notes ────────────────────────────────
const switches = computed(() => nodes.value.filter(n => n.kind === 'input'))
const switchesOn = computed(() => switches.value.filter(n => n.on).length)
const colorable = computed(() => only('lamp', 'hex', 'pixel'))
const 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
})
function setColor(c: LampColor | undefined) {
ed.patchMany(ids.value, { color: c })
}
const clocks = computed(() => only('clock'))
const hzValue = computed(() => {
const set = new Set(nodes.value.map(n => n.hz))
return set.size === 1 ? [...set][0] : undefined
})
function setHz(e: Event) {
const v = Number((e.target as HTMLInputElement).value)
ed.patchMany(ids.value, { hz: v > 0 && v <= 1000 ? v : undefined }, true)
}
const notes = computed(() => only('note'))
function setSize(size: 'sm' | 'md' | 'lg') {
ed.patchMany(ids.value, { size: size === 'md' ? undefined : size })
}
const ARRANGE: { how: Arrange; icon: string; title: string }[] = [
{ how: 'left', icon: 'lucide:align-start-vertical', title: 'Line up on the left' },
{ how: 'right', icon: 'lucide:align-end-vertical', title: 'Line up on the right' },
{ how: 'top', icon: 'lucide:align-start-horizontal', title: 'Line up at the top' },
{ how: 'bottom', icon: 'lucide:align-end-horizontal', title: 'Line up at the bottom' },
{ how: 'spread-y', icon: 'lucide:align-vertical-space-around', title: 'Spread evenly top to bottom' },
{ how: 'spread-x', icon: 'lucide:align-horizontal-space-around', title: 'Spread evenly left to right' },
]
// ── Wire them all to one part ───────────────────────────────────────
const others = computed(() => {
const sel = new Set(ids.value)
return ed.def.value.nodes
.filter(n => !sel.has(n.id) && n.kind !== 'note')
.map(n => ({ n, pins: pinKeys(n, ed.getDef.value) }))
.filter(o => o.pins.ins.length + o.pins.outs.length > 0)
.sort((a, b) => Number(b.n.kind === 'chip') - Number(a.n.kind === 'chip') || byPosition(a.n, b.n))
.map(o => ({
id: o.n.id,
pins: o.pins,
name: o.n.label?.trim() || (o.n.chip && ed.getDef.value(o.n.chip)?.name) || KIND_NAMES[o.n.kind] || o.n.kind,
}))
})
const target = ref('')
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) })
/** Where they fit, one card per part (nearest first), each fit a strip of the pins it takes. */
const fitCards = computed(() => {
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) => {
const node = ed.def.value.nodes.find(n => n.id === f.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
for (let start = 0; start + k <= f.pins.length; start++) {
const pins = f.pins.slice(start, start + k).map((p, i) => p.label || String(start + i + 1))
card.choices.push({ spot, start, pins: pins.length > 5 ? [pins[0]!, '…', pins[pins.length - 1]!] : pins })
}
card.dist = Math.min(card.dist, f.dist)
cards.set(key, card)
})
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 }) {
return (!n.autoLabel && n.label?.trim()) || (n.chip && ed.getDef.value(n.chip)?.name) || KIND_NAMES[n.kind] || n.kind
}
const mineIn = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).ins.length))
const mineOut = computed(() => nodes.value.some(n => pinKeys(n, ed.getDef.value).outs.length))
// ── Make component ──────────────────────────────────────────────────
const packName = ref('')
function pack() {
ed.packageSelected(packName.value || 'Part')
packName.value = ''
}
</script>
<template>
<section>
<h3>
{{ nodes.length }} part{{ nodes.length === 1 ? '' : 's' }}<template v-if="wires.length">, {{ wires.length }} wire{{ wires.length === 1 ? '' : 's' }}</template> selected
</h3>
<div v-if="groups.length > 1" class="type-chips">
<button v-for="g in groups" :key="g.key" class="type-chip" title="Keep only these selected" @click="ed.selectOnly(g.ids)">
{{ g.name }} <span>×{{ g.ids.length }}</span>
</button>
</div>
<p class="score">
<Icon name="lucide:cpu" class="size-4 shrink-0" />
<span>{{ transistors.toLocaleString() }} transistors in the selection</span>
</p>
</section>
<section v-if="family || labelable || switches.length || colorable || clocks || notes">
<h3>Change all</h3>
<label v-if="family === 'logic'" class="field">
<span>Swap all for</span>
<select :value="currentType" @change="onSwap">
<option v-if="!currentType" value="" disabled>Mixed: pick a part</option>
<option value="nand">NAND (2 → 1)</option>
<optgroup v-for="[g, defs] in swapGroups" :key="g" :label="g">
<option v-for="d in defs" :key="d.id" :value="`chip:${d.id}`" :disabled="!d.ok">{{ d.label }}</option>
</optgroup>
</select>
</label>
<label v-else-if="family" class="field">
<span>Make them all</span>
<select :value="currentType" @change="onSwap">
<option v-if="!currentType" value="" disabled>Mixed: pick a type</option>
<option v-for="k in familyKinds" :key="k" :value="k">{{ KIND_NAMES[k] }}</option>
</select>
</label>
<p v-if="family" class="hint -mt-1">Wires stay on the pins in the same position.</p>
<form v-if="labelable" class="field" @submit.prevent="rename">
<span>Rename all, top to bottom</span>
<div class="grid grid-cols-[1fr_4.5rem_auto] gap-2">
<input v-model="pattern" placeholder="e.g. D# or Reset" title="# becomes a number: D# gives D0, D1, D2" />
<input v-model.number="start" type="number" min="0" title="First number" />
<button class="btn" type="submit" :disabled="!pattern.trim()">Apply</button>
</div>
<small v-if="preview.length" class="hint">→ {{ preview.slice(0, 5).join(', ') }}<template v-if="preview.length > 5">, …</template></small>
</form>
<div v-if="switches.length" class="field">
<span>Switches: {{ switchesOn }} of {{ switches.length }} on</span>
<div class="seg">
<button @click="ed.setSwitches(ids, false)">All 0</button>
<button @click="ed.setSwitches(ids, true)">All 1</button>
<button @click="ed.setSwitches(ids, 'flip')">Flip each</button>
</div>
</div>
<div v-if="only('pixel')" class="field">
<span>Colours, for all</span>
<div class="seg">
<button @click="ed.setRgb(ids, false)">One</button>
<button @click="ed.setRgb(ids, true)">RGB</button>
</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">
<button class="swatch lamp-swatch default" :class="{ active: color === '' }" title="Default" @click="setColor(undefined)" />
<button
v-for="c in LAMP_COLORS"
:key="c"
class="swatch lamp-swatch"
:class="[`l-${c}`, { active: color === c }]"
:title="c"
@click="setColor(c)"
/>
</div>
</div>
<label v-if="clocks" class="field">
<span>Frequency (Hz), empty follows the top bar</span>
<input type="number" min="0.1" max="1000" step="any" :value="hzValue ?? ''" placeholder="top bar" @change="setHz" />
</label>
<div v-if="notes" class="field">
<span>Size</span>
<div class="seg">
<button @click="setSize('sm')">Small</button>
<button @click="setSize('md')">Normal</button>
<button @click="setSize('lg')">Large</button>
</div>
</div>
</section>
<section v-if="wires.length >= 2">
<h3>Cable</h3>
<button class="btn w-full" title="Starts right after the sources, ends right before the targets (Ctrl+G)" @click="ed.bundleSelected(wires.map(w => w.id))">
<Icon name="lucide:merge" class="size-4" /> Bundle the {{ wires.length }} wires into a cable
</button>
<button class="btn btn-ghost mt-1 w-full" title="Click where the cable starts, then where it ends (Ctrl+Shift+G)" @click="ed.startCable(wires.map(w => w.id))">
Place the ends yourself…
</button>
</section>
<section>
<h3>Arrange</h3>
<div class="arrange">
<button v-for="a in ARRANGE" :key="a.how" class="icon-btn" :title="a.title" :disabled="nodes.length < 2" @click="ed.arrangeSelected(a.how)">
<Icon :name="a.icon" class="size-4" />
</button>
</div>
</section>
<section v-if="others.length && chosen">
<h3>Wire them all to</h3>
<template v-if="fitCards.length">
<div class="fit-cards">
<div v-for="(c, ci) in fitCards" :key="c.key" class="fit-card" :class="{ hot: c.choices.some(x => isHot(x.spot, x.start)) }">
<div class="fit-card-head">
<Icon :name="c.icon" class="fit-icon size-4 shrink-0" />
<span class="grow truncate">{{ c.name }}</span>
<span class="fit-tag">{{ ci === 0 ? 'nearest · ' : '' }}{{ c.side === 'out' ? 'outputs' : 'inputs' }}</span>
</div>
<div class="fit-choices">
<button
v-for="x in c.choices"
:key="`${x.spot}-${x.start}`"
class="fit-choice"
: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 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>
<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">
<summary class="hint cursor-pointer">Any part, from its first pin</summary>
<select v-model="targetId" class="text-input mt-2">
<option v-for="o in others" :key="o.id" :value="o.id">{{ o.name }} ({{ o.pins.ins.length }} in, {{ o.pins.outs.length }} out)</option>
</select>
<div class="mt-2 grid gap-2">
<button v-if="mineIn && chosen.pins.outs.length" class="btn w-full" title="Its outputs, in order, into the selected parts, top to bottom" @click="ed.connectSelectionTo(chosen.id, 'in')">
<Icon name="lucide:arrow-right-to-line" class="size-4" /> From {{ chosen.name }}'s outputs
</button>
<button v-if="mineOut && chosen.pins.ins.length" class="btn w-full" title="The selected parts, top to bottom, into its inputs in order" @click="ed.connectSelectionTo(chosen.id, 'out')">
<Icon name="lucide:arrow-left-from-line" class="size-4" /> Into {{ chosen.name }}'s inputs
</button>
</div>
</details>
<p class="hint mt-2">Or drag one wire from a selected part to a pin: the others follow onto the next pins.</p>
</section>
<section v-if="(only('panel') || only('outpanel')) && nodes.length > 1">
<h3>Panels</h3>
<button class="btn w-full" title="One panel with all their rows, top panel first; wires stay on their rows" @click="ed.mergeSelectedPanels()">
<Icon name="lucide:combine" class="size-4" /> Merge into one panel
</button>
</section>
<section v-if="(only('input', 'button', 'clock') || only('output', 'lamp')) && nodes.length > 1">
<h3>Panel</h3>
<button
class="btn w-full"
title="One panel with a row for each, top to bottom: names, settings and wires stay"
@click="ed.combineSelected()"
>
<Icon :name="only('output', 'lamp') ? 'lucide:list-checks' : 'lucide:sliders-vertical'" class="size-4" />
Combine into {{ only('output', 'lamp') ? 'an output' : 'an input' }} panel
</button>
</section>
<section>
<h3>Make a component</h3>
<p class="hint">Wires that cross the selection border become its pins.</p>
<div class="grid grid-cols-[1fr_auto] gap-2">
<input v-model="packName" class="text-input" placeholder="e.g. Half Adder" @keydown.enter="pack" />
<button class="btn btn-primary" @click="pack"><Icon name="lucide:package" class="size-4" /> Make</button>
</div>
<button class="btn mt-2 w-full" title="Their pins in order, top to bottom: click where each one goes (W)" @click="ed.startLinking()">
<Icon name="lucide:cable" class="size-4" /> Connect one by one
</button>
<div class="mt-2 grid grid-cols-2 gap-2">
<button class="btn" title="Remove every wire attached to the selected parts" @click="ed.unlink(ed.selection.value)"><Icon name="lucide:unlink" class="size-4" /> Unlink all</button>
<button class="btn" @click="ed.duplicate()"><Icon name="lucide:copy" class="size-4" /> Duplicate</button>
</div>
<button class="btn btn-ghost mt-2 w-full" @click="ed.deleteSelected()"><Icon name="lucide:trash-2" class="size-4" /> Delete</button>
</section>
</template>