logigate/app/components/editor/FaceDialog.vue

549 lines
22 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">
// Drawing a component's box by hand: place, size and turn its lamps,
// displays, screens and name; show displays of the components inside it;
// space its pins apart; draw lines, boxes, circles and text. Everything
// shows live on the box, and on every copy placed.
import { faceCandidates, faceTransform, GRID as G, shapeTransform, type FaceItem } from '~/lib/logic/geometry'
import { uid } from '~/lib/logic/ops'
import { FACE_INKS, type CircuitNode, type FaceDesign, type FaceInk, type FaceShape } from '~/lib/logic/types'
const ed = useEditor()
const def = computed(() => (ed.faceFor.value ? ed.getDef.value(ed.faceFor.value) : undefined))
const preview = computed<CircuitNode>(() => ({ id: 'face-preview', kind: 'chip', chip: def.value?.id, x: 0, y: 0 }))
const shape = computed(() => ed.shape(preview.value))
const body = computed(() => shape.value.body)
type Tool = 'move' | 'line' | 'rect' | 'ellipse' | 'text'
const TOOLS: { id: Tool; icon: string; title: string }[] = [
{ id: 'move', icon: 'lucide:mouse-pointer-2', title: 'Move, size and turn' },
{ id: 'line', icon: 'lucide:minus', title: 'Line' },
{ id: 'rect', icon: 'lucide:square', title: 'Box' },
{ id: 'ellipse', icon: 'lucide:circle', title: 'Circle' },
{ id: 'text', icon: 'lucide:type', title: 'Text' },
]
const INK_HEX: Record<FaceInk, string> = { muted: '#6b778a', text: '#dbe2ea', red: '#ff5c5c', yellow: '#ffd34d', green: '#3ddc84', blue: '#4dabff' }
const tool = ref<Tool>('move')
const ink = ref<FaceInk>('muted')
const fill = ref(false)
/** What is selected: a drawing's id, a box item's key, 'name', or 'pin:<key>'. */
const sel = ref<string | null>(null)
const VIEW_W = 620
const VIEW_H = 440
const PAD = 34
const k = computed(() => Math.min(3, (VIEW_W - 2 * PAD) / (Math.max(body.value.w, 4) * G), (VIEW_H - 2 * PAD) / (Math.max(body.value.h, 3) * G)))
const svg = ref<SVGSVGElement>()
/** The design being edited, made from the automatic layout on the first change, so nothing jumps. */
function design(): FaceDesign {
const d = def.value!
if (!d.design) {
const s = shape.value
const place: Record<string, { x: number; y: number }> = {}
for (const it of s.face ?? []) place[it.key] = { x: it.x, y: it.y - s.body.y }
d.design = { w: s.body.w, h: s.body.h, place, shapes: [] }
}
d.design.place ??= {}
d.design.shapes ??= []
return d.design
}
const snap = (v: number) => Math.round(v * 4) / 4
/** Pointer position in grid units from the box's top left corner. */
function at(e: PointerEvent) {
const r = svg.value!.getBoundingClientRect()
return { x: (e.clientX - r.left - PAD) / (G * k.value), y: (e.clientY - r.top - PAD) / (G * k.value) }
}
const nameText = computed(() => def.value?.name ?? '')
const top = computed(() => body.value.y)
/** The box's items as placed, plus the name, to grab. */
const items = computed(() => shape.value.face ?? [])
const nameBox = computed(() => {
if (shape.value.nameAt === null) return null
const c = shape.value.nameAt ?? { x: body.value.w / 2, y: shape.value.nameY ?? 0 }
const w = nameText.value.length * 0.5 + 0.6
return { x: c.x - w / 2, y: c.y - 0.55, w, h: 1.1 }
})
/** Pins on both edges, to drag up and down. */
const pins = computed(() => [
...shape.value.inputs.filter(p => !p.bus).map(p => ({ ...p, side: 'in' as const })),
...shape.value.outputs.filter(p => !p.bus).map(p => ({ ...p, side: 'out' as const })),
])
const shapes = computed(() => def.value?.design?.shapes ?? [])
const selShape = computed(() => shapes.value.find(s => s.id === sel.value))
const selItem = computed(() => items.value.find(it => it.key === sel.value))
/** Everything the box can show, with whether it does. */
const candidates = computed(() => {
const d = def.value
if (!d) return []
const hide = new Set(d.design?.hide ?? [])
const show = new Set(d.design?.show ?? [])
return faceCandidates(d, ed.getDef.value).map(c => ({ ...c, shown: c.nested ? show.has(c.key) && !hide.has(c.key) : !hide.has(c.key) }))
})
const nameShown = computed(() => !(def.value?.design?.hide ?? []).includes('name'))
type Drag =
| { type: 'create'; id: string }
| { type: 'move'; id: string; start: { x: number; y: number }; orig: { x: number; y: number } }
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
| { type: 'pin'; key: string; side: 'in' | 'out'; start: number; rows: { key: string; dy: number; set: boolean }[]; index: number }
const drag = ref<Drag | null>(null)
function onDown(e: PointerEvent) {
if (!def.value || e.button !== 0) return
// No text selection: a later drag over selected text would turn into the browser's drag and drop.
e.preventDefault()
const p = at(e)
svg.value!.setPointerCapture(e.pointerId)
if (tool.value === 'text') {
const s: FaceShape = { id: uid('f'), kind: 'text', x: snap(p.x), y: snap(p.y - 0.5), w: 3, h: 1, text: 'Text', ink: ink.value === 'muted' ? 'text' : ink.value }
design().shapes!.push(s)
sel.value = s.id
tool.value = 'move'
ed.commit(false)
nextTick(() => textInput.value?.select())
return
}
if (tool.value !== 'move') {
const s: FaceShape = { id: uid('f'), kind: tool.value, x: snap(p.x), y: snap(p.y), w: 0, h: 0, ink: ink.value, ...(fill.value && tool.value !== 'line' ? { fill: true } : {}) }
design().shapes!.push(s)
sel.value = s.id
drag.value = { type: 'create', id: s.id }
return
}
const el = (e.target as Element).closest('[data-face]')
const id = el?.getAttribute('data-face')
if (!id) {
sel.value = null
return
}
sel.value = id
if (id.startsWith('pin:')) {
const key = id.slice(4)
const pin = pins.value.find(x => x.key === key)!
const side = pins.value.filter(x => x.side === pin.side)
const pinAt = def.value.design?.pinAt ?? {}
drag.value = { type: 'pin', key, side: pin.side, start: p.y, rows: side.map(x => ({ key: x.key, dy: x.dy, set: pinAt[x.key] !== undefined })), index: side.findIndex(x => x.key === key) }
return
}
const handle = el!.getAttribute('data-handle') as 'a' | 'b' | null
const sh = shapes.value.find(s => s.id === id)
if (handle && sh) {
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
return
}
const it = items.value.find(x => x.key === id)
const orig = sh ? { x: sh.x, y: sh.y } : it ? { x: it.x, y: it.y - top.value } : id === 'name' && nameBox.value ? { x: nameBox.value.x, y: nameBox.value.y - top.value } : null
if (orig) drag.value = { type: 'move', id, start: p, orig }
}
function onMove(e: PointerEvent) {
const d = drag.value
if (!d) return
const p = at(e)
if (d.type === 'create') {
const s = shapes.value.find(x => x.id === d.id)
if (!s) return
s.w = snap(p.x) - s.x
s.h = snap(p.y) - s.y
if (e.shiftKey && s.kind === 'line') {
// Shift: straight across or straight down.
if (Math.abs(s.w) > Math.abs(s.h)) s.h = 0
else s.w = 0
}
return
}
if (d.type === 'pin') {
// Dragging a pin moves it and the pins below it on that edge: a gap opens above it.
const prev = d.index > 0 ? d.rows[d.index - 1]!.dy : -1
const delta = Math.max(Math.round(p.y - d.start), prev + 1 - d.rows[d.index]!.dy)
const pinAt = (design().pinAt ??= {})
d.rows.forEach((r, i) => {
if (i === d.index) pinAt[r.key] = Math.max(0, r.dy + delta)
else if (i > d.index && r.set) pinAt[r.key] = Math.max(0, r.dy + delta)
})
return
}
if (d.type === 'move') {
const x = snap(d.orig.x + p.x - d.start.x)
const y = snap(d.orig.y + p.y - d.start.y)
const s = shapes.value.find(sh => sh.id === d.id)
if (s) {
s.x = x
s.y = y
} else if (d.id === 'name') {
const w = nameText.value.length * 0.5 + 0.6
design().place!.name = { x: x + w / 2, y: y + 0.55 }
} else design().place![d.id] = { x, y }
return
}
const s = shapes.value.find(sh => sh.id === d.id)
if (!s) return
const o = d.orig
if (d.handle === 'b') {
s.w = snap(p.x) - o.x
s.h = snap(p.y) - o.y
} else {
s.x = snap(p.x)
s.y = snap(p.y)
s.w = o.x + o.w - s.x
s.h = o.y + o.h - s.y
}
}
function onUp() {
const d = drag.value
drag.value = null
if (!d) return
if (d.type === 'create') {
const s = shapes.value.find(x => x.id === d.id)
// A click without dragging draws nothing.
if (s && Math.abs(s.w) < 0.25 && Math.abs(s.h) < 0.25) {
design().shapes = shapes.value.filter(x => x !== s)
sel.value = null
return
}
tool.value = 'move'
}
ed.commit(false)
}
function remove() {
if (!selShape.value) return
design().shapes = shapes.value.filter(s => s !== selShape.value)
sel.value = null
ed.commit(false)
}
/** Shows or leaves off a thing: own items are shown unless left off, displays of parts inside only when shown. */
function setShown(key: string, nested: boolean, on: boolean) {
const d = design()
const hide = new Set(d.hide ?? [])
const show = new Set(d.show ?? [])
if (on) hide.delete(key)
else hide.add(key)
if (nested) {
if (on) show.add(key)
else show.delete(key)
}
d.hide = [...hide]
d.show = [...show]
if (!d.hide.length) delete d.hide
if (!d.show.length) delete d.show
if (!on && sel.value === key) sel.value = null
ed.commit(false)
}
/** Grows or shrinks the selected item (steps of a quarter), or the size of a text. */
function grow(by: number) {
const s = selShape.value
if (s?.kind === 'text') {
s.size = Math.min(4, Math.max(0.5, Math.round(((s.size ?? 1) + by) * 4) / 4))
return ed.commit(false)
}
const key = sel.value
if (!key || !selItem.value) return
const d = design()
const next = Math.min(4, Math.max(0.25, Math.round(((d.scale?.[key] ?? 1) + by) * 4) / 4))
d.scale ??= {}
if (next === 1) delete d.scale[key]
else d.scale[key] = next
ed.commit(false)
}
/** Turns the selected item or drawing a quarter. */
function turn(by: 90 | -90) {
const s = selShape.value
if (s) {
const r = (((s.rotate ?? 0) + by) % 360 + 360) % 360
if (r) s.rotate = r
else delete s.rotate
return ed.commit(false)
}
const key = sel.value
if (!key || !selItem.value) return
const d = design()
const r = (((d.rotate?.[key] ?? 0) + by) % 360 + 360) % 360
d.rotate ??= {}
if (r) d.rotate[key] = r
else delete d.rotate[key]
ed.commit(false)
}
function resetPins() {
if (!def.value?.design?.pinAt) return
delete def.value.design.pinAt
ed.commit(false)
}
function setInk(i: FaceInk) {
ink.value = i
if (selShape.value) {
selShape.value.ink = i
ed.commit(false)
}
}
function toggleFill() {
fill.value = !fill.value
const s = selShape.value
if (s && s.kind !== 'line' && s.kind !== 'text') {
if (fill.value) s.fill = true
else delete s.fill
ed.commit(false)
}
}
function setSize(axis: 'w' | 'h', e: Event) {
const v = Number((e.target as HTMLInputElement).value)
if (!(v > 0)) return
design()[axis] = Math.min(120, Math.max(2, Math.round(v * 2) / 2))
ed.commit(false)
}
function reset() {
if (!def.value) return
delete def.value.design
sel.value = null
ed.commit(false)
}
const textInput = ref<HTMLInputElement>()
// Keys while the designer is open: R turns, + and − size, Delete removes a drawing.
onMounted(() => window.addEventListener('keydown', onKey))
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
function onKey(e: KeyboardEvent) {
if ((e.target as HTMLElement).closest?.('input, textarea, select') || e.ctrlKey || e.metaKey || e.altKey) return
if ((e.key === 'Delete' || e.key === 'Backspace') && selShape.value) {
e.preventDefault()
remove()
} else if (e.key === 'r' || e.key === 'R') turn(e.shiftKey ? -90 : 90)
else if (e.key === '+' || e.key === '=') grow(0.25)
else if (e.key === '-') grow(-0.25)
}
function close() {
ed.dialog.value = null
ed.faceFor.value = null
}
/** Ends of a line, or opposite corners of anything else, to drag. */
const grips = computed(() => {
const s = selShape.value
if (!s || s.kind === 'text') return []
return [
{ h: 'a', x: s.x, y: s.y },
{ h: 'b', x: s.x + s.w, y: s.y + s.h },
]
})
const kindName = (it: FaceItem) => (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
const selLabel = computed(() => {
if (selShape.value) return { line: 'Line', rect: 'Box', ellipse: 'Circle', text: 'Text' }[selShape.value.kind]
if (selItem.value) return `${kindName(selItem.value)}${selItem.value.label ? ` ${selItem.value.label}` : ''}`
if (sel.value === 'name') return 'The name'
if (sel.value?.startsWith('pin:')) return `Pin ${pins.value.find(p => `pin:${p.key}` === sel.value)?.label ?? ''}`
return ''
})
const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:binary', screen: 'lucide:monitor' }
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div v-if="def" class="modal face-modal" role="dialog" aria-labelledby="face-title" tabindex="-1">
<div class="flex items-start justify-between gap-4">
<div>
<h2 id="face-title">The box of "{{ def.name }}"</h2>
<p class="hint mt-1">Place, size and turn what it shows, drag pins apart, draw on it. Every placed copy shows it.</p>
</div>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<div class="face-tools">
<div class="seg">
<button v-for="t in TOOLS" :key="t.id" :class="{ active: tool === t.id }" :title="t.title" @click="tool = t.id">
<Icon :name="t.icon" class="size-4" />
</button>
</div>
<div class="face-inks" title="Colour">
<button
v-for="i in FACE_INKS"
:key="i"
class="ctx-dot"
:class="{ active: (selShape?.ink ?? ink) === i }"
:style="{ background: INK_HEX[i] }"
:title="i"
@click="setInk(i)"
/>
</div>
<button class="btn-sm" :class="{ on: selShape?.fill ?? fill }" title="Fill boxes and circles lightly" @click="toggleFill">
<Icon name="lucide:paint-bucket" class="size-3.5" /> Fill
</button>
<label class="face-size">W <input type="number" min="2" max="120" step="0.5" :value="body.w" @change="setSize('w', $event)" /></label>
<label class="face-size">H <input type="number" min="2" max="120" step="0.5" :value="body.h" @change="setSize('h', $event)" /></label>
<button class="btn-sm ml-auto" :disabled="!def.design" title="Back to the automatic layout; drawings are removed" @click="reset">
<Icon name="lucide:rotate-ccw" class="size-3.5" /> Automatic
</button>
</div>
<div class="face-body">
<svg
ref="svg"
class="face-canvas"
:class="{ drawing: tool !== 'move' }"
:width="VIEW_W"
:height="VIEW_H"
@pointerdown="onDown"
@pointermove="onMove"
@pointerup="onUp"
@pointercancel="onUp"
>
<defs>
<pattern id="face-grid" :width="(G * k) / 2" :height="(G * k) / 2" patternUnits="userSpaceOnUse" :x="PAD" :y="PAD">
<circle cx="0.6" cy="0.6" r="0.6" fill="#2a3442" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#face-grid)" />
<g :transform="`translate(${PAD} ${PAD - body.y * G * k}) scale(${k})`">
<EditorNodeView :node="preview" :shape="shape" :selected="false" />
<!-- Things on the box, grabbed where they are drawn (sized and turned alike) -->
<g v-for="it in items" :key="it.key" :transform="faceTransform(it)">
<rect
:x="it.x * G - 2"
:y="it.y * G - 2"
:width="it.w * G + 4"
:height="it.h * G + 4"
rx="3"
class="face-thing"
:class="{ sel: sel === it.key }"
:data-face="it.key"
/>
</g>
<rect
v-if="nameBox"
:x="nameBox.x * G"
:y="nameBox.y * G"
:width="nameBox.w * G"
:height="nameBox.h * G"
rx="3"
class="face-thing"
:class="{ sel: sel === 'name' }"
data-face="name"
/>
<rect
v-for="p in pins"
:key="`pin-${p.key}`"
:x="(p.dx - (p.side === 'in' ? 0.45 : 1.6)) * G"
:y="(p.dy - 0.42) * G"
:width="2.05 * G"
:height="0.84 * G"
rx="3"
class="face-thing face-pinbox"
:class="{ sel: sel === `pin:${p.key}` }"
:data-face="`pin:${p.key}`"
/>
<g :transform="`translate(0 ${body.y * G})`">
<g v-for="s in shapes" :key="s.id" :transform="shapeTransform(s)">
<line
v-if="s.kind === 'line'"
:x1="s.x * G"
:y1="s.y * G"
:x2="(s.x + s.w) * G"
:y2="(s.y + s.h) * G"
class="face-hit"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
<rect
v-else
:x="Math.min(s.x, s.x + s.w) * G - 2"
:y="Math.min(s.y, s.y + s.h) * G - 2"
:width="Math.max(Math.abs(s.w) * G, s.kind === 'text' ? (s.text?.length ?? 1) * 6.6 * (s.size ?? 1) : 0) + 4"
:height="(s.kind === 'text' ? 1 * (s.size ?? 1) : Math.abs(s.h)) * G + 4"
rx="2"
class="face-thing shape"
:class="{ sel: sel === s.id }"
:data-face="s.id"
/>
</g>
<g v-if="selShape" :transform="shapeTransform(selShape)">
<circle v-for="g in grips" :key="g.h" :cx="g.x * G" :cy="g.y * G" r="3.5" class="face-grip" :data-face="sel!" :data-handle="g.h" />
</g>
</g>
</g>
</svg>
<aside class="face-side">
<h3>On the box</h3>
<ul class="face-list">
<li>
<label class="check">
<input type="checkbox" :checked="nameShown" @change="setShown('name', false, ($event.target as HTMLInputElement).checked)" />
<Icon name="lucide:type" class="size-3.5" /> Name
</label>
</li>
<li v-for="c in candidates.filter(x => !x.nested)" :key="c.key" :class="{ sel: sel === c.key }">
<label class="check">
<input type="checkbox" :checked="c.shown" @change="setShown(c.key, false, ($event.target as HTMLInputElement).checked)" />
<Icon :name="ICON[c.kind] ?? 'lucide:box'" class="size-3.5" />
<span class="truncate">{{ c.label }}</span>
</label>
</li>
</ul>
<template v-if="candidates.some(x => x.nested)">
<h3>From parts inside</h3>
<ul class="face-list">
<li v-for="c in candidates.filter(x => x.nested)" :key="c.key" :class="{ sel: sel === c.key }">
<label class="check">
<input type="checkbox" :checked="c.shown" @change="setShown(c.key, true, ($event.target as HTMLInputElement).checked)" />
<Icon :name="ICON[c.kind] ?? 'lucide:box'" class="size-3.5" />
<span class="truncate">{{ c.label }}</span>
</label>
</li>
</ul>
</template>
<p v-if="!candidates.length" class="hint">No lamps, displays or pixels inside yet.</p>
<h3>Pins</h3>
<p class="hint">Drag a pin up or down: the pins under it follow, so groups get gaps.</p>
<button class="btn-sm" :disabled="!def.design?.pinAt" @click="resetPins"><Icon name="lucide:rows-3" class="size-3.5" /> Pins evenly again</button>
</aside>
</div>
<div class="face-props">
<template v-if="sel && selLabel">
<span class="font-semibold">{{ selLabel }}</span>
<template v-if="selShape || selItem">
<div class="flex gap-1" title="Turn (R, Shift+R)">
<button class="icon-btn" @click="turn(-90)"><Icon name="lucide:rotate-ccw" class="size-4" /></button>
<button class="icon-btn" @click="turn(90)"><Icon name="lucide:rotate-cw" class="size-4" /></button>
</div>
<div v-if="selItem || selShape?.kind === 'text'" class="flex items-center gap-1" title="Size (+, −)">
<button class="icon-btn" @click="grow(-0.25)"><Icon name="lucide:minus" class="size-4" /></button>
<span class="tabular-nums text-xs">{{ Math.round(((selShape ? selShape.size : def.design?.scale?.[sel]) ?? 1) * 100) }}%</span>
<button class="icon-btn" @click="grow(0.25)"><Icon name="lucide:plus" class="size-4" /></button>
</div>
</template>
<template v-if="selShape?.kind === 'text'">
<input ref="textInput" v-model="selShape.text" class="text-input" placeholder="Text" @change="ed.commit(false)" />
</template>
<button v-if="selShape" class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
<button v-else-if="selItem" class="btn-sm ml-auto" @click="setShown(selItem.key, selItem.key.includes('/'), false)">
<Icon name="lucide:eye-off" class="size-3.5" /> Leave off
</button>
<button v-else-if="sel === 'name'" class="btn-sm ml-auto" @click="setShown('name', false, false)"><Icon name="lucide:eye-off" class="size-3.5" /> Leave off</button>
</template>
<span v-else class="hint">Pick a tool to draw, or drag things on the box. R turns, + and − size, Delete removes a drawing.</span>
</div>
</div>
</div>
</template>