logigate/app/components/editor/BulkSettings.vue

312 lines
15 KiB
Vue
Raw Normal View History

<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 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, nearest first: every way to put them on a run of free pins. */
const fitChoices = computed(() => {
const out: { spot: number; start: number; part: string; pins: string; dist: number }[] = []
ed.fits.value.forEach((f, spot) => {
const node = ed.def.value.nodes.find(n => n.id === f.part)
const part = node ? partName(node) : '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]!
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]) })
}
})
return out.sort((a, b) => a.dist - b.dist).slice(0, 8)
})
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="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="fitChoices.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-list">
<button
v-for="c in fitChoices"
:key="`${c.spot}-${c.start}`"
class="btn-sm"
:class="{ active: ed.fitHover.value?.spot === c.spot && ed.fitHover.value?.start === c.start }"
@pointerenter="ed.fitHover.value = { spot: c.spot, start: c.start }"
@pointerleave="ed.fitHover.value = null"
@click="ed.connectFit(c.spot, c.start)"
>
<span class="font-mono">{{ c.pins }}</span> <span class="muted">{{ c.part }}</span>
</button>
</div>
</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>
<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>