R box designer: size by the corner, reorder pins, pick and move several, pixels one by one, fitted boxes, displays from inside in free spots

- A picked lamp, display or screen has a size grip on its corner.
- A pin dragged onto or past its neighbour swaps places with it (the
  order is kept in the design; boxes designed before keep theirs).
- Shift + click, or a box around things, picks several: dragged or moved
  with the arrow keys together, drawings among them deleted together.
- A screen can be split into its pixels, each placed on its own (they
  start where they sat, sized and turned as the screen was), or joined.
- New designs fit the box to what is on it (Fit, on and off): it shrinks
  as well as grows. A size typed in turns it off.
- A display of a part inside lands in the first free spot inside the box
  instead of under it, and keeps the size and turn its own box gives it.
- Pointing at a display from a part inside (in the designer and on the
  placed box) says which part it is from.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-27 13:54:30 +01:00
parent 58d5b80322
commit 3563ee9a95
7 changed files with 521 additions and 71 deletions

View File

@ -5673,3 +5673,19 @@ button.tile:hover {
stroke-width: 2;
pointer-events: none;
}
/* Box designer: a box around things to pick them, the size grip, displays from parts inside. */
.face-pickbox {
fill: rgb(76 194 255 / 0.08);
stroke: var(--accent);
stroke-dasharray: 4 3;
pointer-events: none;
}
.face-grip.scale {
cursor: nwse-resize;
}
.face-thing.nested:not(.sel) {
stroke-dasharray: 3 2;
}

View File

@ -1,9 +1,11 @@
<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'
// displays, screens and name; split a screen into pixels to place one by
// one; show displays of the components inside it; space and reorder its
// pins; draw lines, boxes, circles and text. Pick several things (Shift +
// click, or a box around them) to move them together. Everything shows live
// on the box, and on every copy placed.
import { faceCandidates, faceTransform, GRID as G, pixelKey, 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'
@ -25,8 +27,19 @@ const INK_HEX: Record<FaceInk, string> = { muted: '#6b778a', text: '#dbe2ea', re
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>'. */
/** What is selected: a drawing's id, a box item's key, 'name', or 'pin:<key>'; the last one picked. */
const sel = ref<string | null>(null)
/** Everything picked, to move together (Shift + click, or a box around them). */
const group = ref<string[]>([])
const isSel = (id: string) => sel.value === id || group.value.includes(id)
function pick(id: string | null) {
sel.value = id
group.value = id ? [id] : []
}
watch(sel, v => {
if (v && !group.value.includes(v)) group.value = [v]
if (!v) group.value = []
})
const VIEW_W = 620
const VIEW_H = 440
@ -41,7 +54,8 @@ function design(): FaceDesign {
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: [] }
// A new design keeps the box as big as what is on it.
d.design = { w: s.body.w, h: s.body.h, place, shapes: [], fit: true }
}
d.design.place ??= {}
d.design.shapes ??= []
@ -90,8 +104,10 @@ 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: 'move'; start: { x: number; y: number }; origs: Map<string, { x: number; y: number }> }
| { type: 'resize'; id: string; handle: 'a' | 'b'; orig: FaceShape }
| { type: 'scale'; key: string }
| { type: 'box'; start: { x: number; y: number }; cur: { x: number; y: number }; add: boolean }
| { type: 'pin'; key: string; side: 'in' | 'out'; start: number; rows: { key: string; dy: number; set: boolean }[]; index: number }
const drag = ref<Drag | null>(null)
@ -120,10 +136,24 @@ function onDown(e: PointerEvent) {
const el = (e.target as Element).closest('[data-face]')
const id = el?.getAttribute('data-face')
if (!id) {
sel.value = null
// Empty space: a box around things picks them (Shift: adds to what is picked).
if (!e.shiftKey) pick(null)
drag.value = { type: 'box', start: p, cur: p, add: e.shiftKey }
return
}
sel.value = id
if (e.shiftKey && !id.startsWith('pin:')) {
// Shift + click: in or out of what is picked.
group.value = group.value.includes(id) ? group.value.filter(x => x !== id) : [...group.value, id]
sel.value = group.value.at(-1) ?? null
return
}
if (el!.getAttribute('data-handle') === 'scale') {
drag.value = { type: 'scale', key: id }
return
}
const many = group.value.length > 1 && group.value.includes(id)
if (!many) pick(id)
else sel.value = id
if (id.startsWith('pin:')) {
const key = id.slice(4)
const pin = pins.value.find(x => x.key === key)!
@ -138,9 +168,54 @@ function onDown(e: PointerEvent) {
drag.value = { type: 'resize', id, handle, orig: { ...sh } }
return
}
const origs = new Map<string, { x: number; y: number }>()
for (const g of many ? group.value : [id]) {
const o = origOf(g)
if (o) origs.set(g, o)
}
if (origs.size) drag.value = { type: 'move', start: p, origs }
}
/** Where a thing on the box is now, from the box's top left (a drawing's own corner, the name's box). */
function origOf(id: string): { x: number; y: number } | null {
const sh = shapes.value.find(s => s.id === id)
if (sh) return { x: sh.x, y: sh.y }
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 }
if (it) return { x: it.x, y: it.y - top.value }
if (id === 'name' && nameBox.value) return { x: nameBox.value.x, y: nameBox.value.y - top.value }
return null
}
/** Puts a thing on the box with its top left (as origOf gives it) at x, y. */
function putAt(id: string, x: number, y: number) {
const s = shapes.value.find(sh => sh.id === id)
if (s) {
s.x = x
s.y = y
} else if (id === 'name') {
const w = nameText.value.length * 0.5 + 0.6
design().place!.name = { x: x + w / 2, y: y + 0.55 }
} else if (!id.startsWith('pin:')) design().place![id] = { x, y }
}
/** The area a thing covers on the box, from its top left, sized and turned as shown. */
function areaOf(id: string): { x: number; y: number; w: number; h: number } | null {
const sh = shapes.value.find(s => s.id === id)
if (sh) {
const w = sh.kind === 'text' ? (sh.text?.length ?? 1) * 0.42 * (sh.size ?? 1) : Math.abs(sh.w)
const h = sh.kind === 'text' ? (sh.size ?? 1) : Math.abs(sh.h)
return { x: Math.min(sh.x, sh.x + sh.w), y: Math.min(sh.y, sh.y + sh.h), w, h }
}
const it = items.value.find(x => x.key === id)
if (it) {
const k = it.scale ?? 1
const turned = it.rotate === 90 || it.rotate === 270
const w = (turned ? it.h : it.w) * k
const h = (turned ? it.w : it.h) * k
return { x: it.x + (it.w * k) / 2 - w / 2, y: it.y - top.value + (it.h * k) / 2 - h / 2, w, h }
}
if (id === 'name' && nameBox.value) return { ...nameBox.value, y: nameBox.value.y - top.value }
return null
}
function onMove(e: PointerEvent) {
@ -160,10 +235,25 @@ function onMove(e: PointerEvent) {
return
}
if (d.type === 'pin') {
const row = d.rows[d.index]!
const want = Math.max(0, Math.round(row.dy + p.y - d.start))
const next = d.rows[d.index + 1]
const prevRow = d.rows[d.index - 1]
const pinAt = (design().pinAt ??= {})
if ((next && want >= next.dy) || (prevRow && want <= prevRow.dy)) {
// Onto or past a neighbour: the pins change order. The others stay where they are, this one goes where it is dragged.
const others = d.rows.filter((_, i) => i !== d.index)
const at = others.filter(r => r.dy < want || (r.dy === want && want > row.dy)).length
const order = [...others.slice(0, at), row, ...others.slice(at)].map(r => r.key)
const keep = (design().pinOrder ?? []).filter(k => !d.rows.some(r => r.key === k))
design().pinOrder = [...keep, ...order]
for (const r of others) pinAt[r.key] = r.dy
pinAt[row.key] = want
return
}
// 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 ??= {})
const delta = Math.max(Math.round(p.y - d.start), prev + 1 - row.dy)
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)
@ -171,16 +261,27 @@ function onMove(e: PointerEvent) {
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 }
const dx = p.x - d.start.x
const dy = p.y - d.start.y
for (const [id, o] of d.origs) putAt(id, snap(o.x + dx), snap(o.y + dy))
return
}
if (d.type === 'box') {
d.cur = p
return
}
if (d.type === 'scale') {
// Grown from its top left corner, as far as the pointer is pulled.
const it = items.value.find(x => x.key === d.key)
if (!it) return
const turned = it.rotate === 90 || it.rotate === 270
const kx = (p.x - it.x) / (turned ? it.h : it.w)
const ky = (p.y + top.value - it.y) / (turned ? it.w : it.h)
const k = Math.min(4, Math.max(0.25, Math.round(Math.max(kx, ky) * 20) / 20))
const des = design()
des.scale ??= {}
if (k === 1) delete des.scale[d.key]
else des.scale[d.key] = k
return
}
const s = shapes.value.find(sh => sh.id === d.id)
@ -201,6 +302,21 @@ function onUp() {
const d = drag.value
drag.value = null
if (!d) return
if (d.type === 'box') {
// Everything the box touches is picked.
const x0 = Math.min(d.start.x, d.cur.x)
const x1 = Math.max(d.start.x, d.cur.x)
const y0 = Math.min(d.start.y, d.cur.y)
const y1 = Math.max(d.start.y, d.cur.y)
if (x1 - x0 < 0.2 && y1 - y0 < 0.2) return
const ids = [...shapes.value.map(sh => sh.id), ...items.value.map(it => it.key), ...(nameBox.value ? ['name'] : [])].filter(id => {
const a = areaOf(id)
return a && a.x < x1 && a.x + a.w > x0 && a.y < y1 && a.y + a.h > y0
})
group.value = d.add ? [...new Set([...group.value, ...ids])] : ids
sel.value = group.value.at(-1) ?? null
return
}
if (d.type === 'create') {
const s = shapes.value.find(x => x.id === d.id)
// A click without dragging draws nothing.
@ -215,9 +331,62 @@ function onUp() {
}
function remove() {
if (!selShape.value) return
design().shapes = shapes.value.filter(s => s !== selShape.value)
sel.value = null
const gone = new Set(group.value.filter(id => shapes.value.some(s => s.id === id)))
if (selShape.value) gone.add(selShape.value.id)
if (!gone.size) return
design().shapes = shapes.value.filter(s => !gone.has(s.id))
pick(null)
ed.commit(false)
}
/** Moves everything picked a step (a quarter square; Shift: a whole one). */
function nudge(dx: number, dy: number) {
const ids = group.value.length ? group.value : sel.value ? [sel.value] : []
let moved = false
for (const id of ids) {
const o = origOf(id)
if (!o) continue
putAt(id, snap(o.x + dx), snap(o.y + dy))
moved = true
}
if (moved) ed.commit(false)
}
// ── Screens pixel by pixel ──────────────────────────────────────────
/** The screen of the selected item, when it is a whole screen (to split) or one of its pixels (to join). */
const selScreen = computed(() => {
const it = selItem.value
if (!it || it.kind !== 'screen') return null
if (it.screenOf) return { key: it.screenOf, split: true }
return (it.pixels?.length ?? 0) > 1 ? { key: it.key, split: false } : null
})
/** Splits a screen into pixels placed one by one (each where it sat), or joins them into one screen again. */
function toggleSplit(key: string, split: boolean) {
const d = design()
const set = new Set(d.split ?? [])
if (split) set.add(key)
else {
set.delete(key)
// The pixels' own places go; the screen keeps the place it had.
const it = items.value.find(x => x.screenOf === key)
for (const p of items.value.filter(x => x.screenOf === key)) delete d.place?.[p.key]
if (it && !d.place?.[key]) d.place![key] = { x: it.x, y: it.y - top.value }
}
if (set.size) d.split = [...set]
else delete d.split
pick(split ? pixelKey(items.value.find(x => x.key === key)?.pixels?.[0]?.id ?? '') : key)
ed.commit(false)
}
/** Fitted: the box is as big as what is on it. Off: it keeps the width and height set. */
function toggleFit() {
const d = design()
if (d.fit) {
delete d.fit
d.w = body.value.w
d.h = body.value.h
} else d.fit = true
ed.commit(false)
}
@ -236,8 +405,18 @@ function setShown(key: string, nested: boolean, on: boolean) {
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
if (!on && sel.value === key) pick(null)
ed.commit(false)
if (on && nested) {
nextTick(() => {
const it = items.value.find(x => x.key === key)
if (it && !d.place?.[key]) {
d.place![key] = { x: it.x, y: it.y - top.value }
pick(key)
ed.commit(false)
}
})
}
}
/** Grows or shrinks the selected item (steps of a quarter), or the size of a text. */
@ -250,7 +429,7 @@ function grow(by: number) {
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))
const next = Math.min(4, Math.max(0.25, Math.round(((d.scale?.[key] ?? selItem.value.scale ?? 1) + by) * 4) / 4))
d.scale ??= {}
if (next === 1) delete d.scale[key]
else d.scale[key] = next
@ -303,7 +482,14 @@ function toggleFill() {
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))
const d = design()
// A size typed in: the box keeps it (and what it shows can still make it bigger).
if (d.fit) {
delete d.fit
d.w = body.value.w
d.h = body.value.h
}
d[axis] = Math.min(120, Math.max(2, Math.round(v * 2) / 2))
ed.commit(false)
}
@ -320,9 +506,20 @@ const textInput = ref<HTMLInputElement>()
onMounted(() => window.addEventListener('keydown', onKey))
onBeforeUnmount(() => window.removeEventListener('keydown', onKey))
const ARROW: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
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) {
const arrow = ARROW[e.key]
if (arrow && (sel.value || group.value.length)) {
e.preventDefault()
const step = e.shiftKey ? 1 : 0.25
nudge(arrow[0] * step, arrow[1] * step)
} else if (e.key === 'Escape' && group.value.length) {
e.preventDefault()
e.stopPropagation()
pick(null)
} else if ((e.key === 'Delete' || e.key === 'Backspace') && (selShape.value || group.value.some(id => shapes.value.some(s => s.id === id)))) {
e.preventDefault()
remove()
} else if (e.key === 'r' || e.key === 'R') turn(e.shiftKey ? -90 : 90)
@ -345,10 +542,27 @@ const grips = computed(() => {
]
})
const kindName = (it: FaceItem) => (it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
const kindName = (it: FaceItem) => (it.screenOf ? 'Pixel' : it.kind === 'screen' ? 'Screen' : it.kind === 'hex' ? 'Display' : 'Lamp')
/** What a thing on the box is, and where from when it is a display of a part inside. */
const tipOf = (it: FaceItem) => `${it.label || kindName(it)}${it.from ? ` from ${it.from}` : ''}`
/** The size grip of the item picked alone: its bottom right corner, sized and turned with it. */
const scaleGrip = computed(() => {
const it = selItem.value
if (!it || group.value.length > 1) return null
return { it, x: (it.x + it.w) * G, y: (it.y + it.h) * G, r: 3.5 / (it.scale ?? 1) }
})
/** The box being dragged around things, in grid units from the box's top left. */
const pickBox = computed(() => {
const d = drag.value
if (d?.type !== 'box') return null
return { x: Math.min(d.start.x, d.cur.x), y: Math.min(d.start.y, d.cur.y), w: Math.abs(d.cur.x - d.start.x), h: Math.abs(d.cur.y - d.start.y) }
})
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 (group.value.length > 1) return `${group.value.length} things`
if (selItem.value) return `${kindName(selItem.value)}${selItem.value.label ? ` ${selItem.value.label}` : ''}${selItem.value.from ? ` from ${selItem.value.from}` : ''}`
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 ''
@ -387,6 +601,9 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
<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>
<button class="btn-sm" :class="{ on: def.design?.fit }" title="The box is as big as what is on it (pins, name, displays, drawings). Off: it keeps the width and height set" @click="toggleFit">
<Icon name="lucide:scan" class="size-3.5" /> Fit
</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">
@ -423,9 +640,23 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
:height="it.h * G + 4"
rx="3"
class="face-thing"
:class="{ sel: sel === it.key }"
:class="{ sel: isSel(it.key), nested: !!it.from }"
:data-face="it.key"
/>
>
<title>{{ tipOf(it) }}</title>
</rect>
<!-- Its size grip, picked alone: drag to make it bigger or smaller -->
<circle
v-if="scaleGrip?.it.key === it.key"
:cx="scaleGrip.x"
:cy="scaleGrip.y"
:r="scaleGrip.r"
class="face-grip scale"
:data-face="it.key"
data-handle="scale"
>
<title>Drag to size</title>
</circle>
</g>
<rect
v-if="nameBox"
@ -435,7 +666,7 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
:height="nameBox.h * G"
rx="3"
class="face-thing"
:class="{ sel: sel === 'name' }"
:class="{ sel: isSel('name') }"
data-face="name"
/>
<rect
@ -449,7 +680,9 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
class="face-thing face-pinbox"
:class="{ sel: sel === `pin:${p.key}` }"
:data-face="`pin:${p.key}`"
/>
>
<title>Drag up or down; past another pin, they swap</title>
</rect>
<g :transform="`translate(0 ${body.y * G})`">
<g v-for="s in shapes" :key="s.id" :transform="shapeTransform(s)">
<line
@ -459,7 +692,7 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
:x2="(s.x + s.w) * G"
:y2="(s.y + s.h) * G"
class="face-hit"
:class="{ sel: sel === s.id }"
:class="{ sel: isSel(s.id) }"
:data-face="s.id"
/>
<rect
@ -470,15 +703,16 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
: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 }"
:class="{ sel: isSel(s.id) }"
:data-face="s.id"
/>
</g>
<g v-if="selShape" :transform="shapeTransform(selShape)">
<g v-if="selShape && group.length <= 1" :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>
<rect v-if="pickBox" :x="PAD + pickBox.x * G * k" :y="PAD + pickBox.y * G * k" :width="pickBox.w * G * k" :height="pickBox.h * G * k" class="face-pickbox" />
</svg>
<aside class="face-side">
@ -521,27 +755,31 @@ const ICON: Record<string, string> = { lamp: 'lucide:lightbulb', hex: 'lucide:bi
<div class="face-props">
<template v-if="sel && selLabel">
<span class="font-semibold">{{ selLabel }}</span>
<template v-if="selShape || selItem">
<button v-if="selScreen && group.length <= 1" class="btn-sm" :title="selScreen.split ? 'Back into one screen' : 'Each pixel on its own, to place one by one'" @click="toggleSplit(selScreen.key, !selScreen.split)">
<Icon :name="selScreen.split ? 'lucide:grid-2x2' : 'lucide:grid-2x2-plus'" class="size-3.5" /> {{ selScreen.split ? 'Join pixels' : 'Split into pixels' }}
</button>
<template v-if="(selShape || selItem) && group.length <= 1">
<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>
<span class="tabular-nums text-xs">{{ Math.round(((selShape ? selShape.size : (def.design?.scale?.[sel] ?? selItem?.scale)) ?? 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)">
<span v-if="group.length > 1" class="hint">Drag one to move them all, or use the arrow keys (Shift: a whole square).</span>
<button v-if="selShape || group.some(id => shapes.some(x => x.id === id))" class="btn-sm danger ml-auto" @click="remove"><Icon name="lucide:trash-2" class="size-3.5" /> Delete</button>
<button v-else-if="selItem && group.length <= 1" 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>
<span v-else class="hint">Drag things on the box; Shift + click or a box around them picks several. The corner of a picked thing sizes it. R turns, + and − size, Delete removes a drawing.</span>
</div>
</div>
</div>

View File

@ -240,6 +240,7 @@ const title = computed(() => {
class="chip-name"
>{{ chipDef?.name ?? 'Missing' }}</text>
<g v-for="f in shape.face" :key="f.id" :transform="faceTransform(f)">
<title v-if="f.from">{{ f.label || (f.kind === 'screen' ? 'Screen' : f.kind === 'hex' ? 'Display' : 'Lamp') }} from {{ f.from }}</title>
<template v-if="f.kind === 'screen'">
<rect :x="f.x * G - 2" :y="f.y * G - 2" :width="f.w * G + 4" :height="f.h * G + 4" rx="2" class="screen-bg" />
<rect

View File

@ -54,6 +54,8 @@ export interface FaceItem {
rotate?: number
/** A display of a component inside: that component's name. */
from?: string
/** A pixel shown on its own: the key of the screen it is part of. */
screenOf?: string
kind: 'lamp' | 'hex' | 'screen'
/** Screen only: its pixels and the size of one, in grid units. */
pixels?: ScreenPixel[]
@ -242,10 +244,16 @@ function shownItems(def: ComponentDef, get: DefLookup, depth: number): FaceItem[
if (def.face === false || depth > 4) return []
const d = def.design
const hide = new Set(d?.hide ?? [])
const own = ownFaceItems(def).filter(it => !hide.has(it.key))
// As its own box shows them: turned and sized the same, screens split into pixels where it does.
const looks = (it: FaceItem): FaceItem => ({
...it,
...(d?.scale?.[it.key] ? { scale: d.scale[it.key] } : {}),
...(d?.rotate?.[it.key] ? { rotate: d.rotate[it.key] } : {}),
})
const own = splitScreens(ownFaceItems(def), new Set(d?.split ?? [])).filter(it => !hide.has(it.key)).map(looks)
if (!d?.show?.length) return own
const show = new Set(d.show)
return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key))]
return [...own, ...nestedItems(def, get, depth).filter(it => show.has(it.key)).map(looks)]
}
/**
@ -260,6 +268,49 @@ export function faceCandidates(def: ComponentDef, get: DefLookup): { key: string
return [...own, ...nested]
}
/** The key of one pixel of a screen shown pixel by pixel. */
export const pixelKey = (pixelId: string) => `px:${pixelId}`
/**
* Screens listed in `split` shown pixel by pixel: each pixel its own item,
* where it sat in the screen (sized and turned as the screen was, `looks`),
* so splitting moves nothing.
*/
export function splitScreens(items: FaceItem[], split: Set<string>, looks: (key: string) => { scale?: number; rotate?: number } = () => ({})): FaceItem[] {
if (!split.size) return items
return items.flatMap(it => {
if (it.kind !== 'screen' || !split.has(it.key) || !it.pixels || !it.px) return [it]
const { scale, rotate } = { scale: it.scale, rotate: it.rotate, ...looks(it.key) }
const k = scale ?? 1
const px = it.px!
// The screen's middle; each pixel's middle turned around it.
const cx = it.x + (it.w * k) / 2
const cy = it.y + (it.h * k) / 2
const turn = (((rotate ?? 0) % 360) + 360) % 360
return it.pixels.map(p => {
let dx = (p.col + 0.5) * px * k - (it.w * k) / 2
let dy = (p.row + 0.5) * px * k - (it.h * k) / 2
for (let a = 0; a < turn; a += 90) [dx, dy] = [-dy, dx]
const item: FaceItem = {
...it,
id: p.id,
key: pixelKey(p.id),
label: '',
x: cx + dx - (px * k) / 2,
y: cy + dy - (px * k) / 2,
w: px,
h: px,
pixels: [{ ...p, col: 0, row: 0 }],
screenOf: it.key,
}
delete item.rotate
if (k !== 1) item.scale = k
else delete item.scale
return item
})
})
}
/** A box item's size and turn, as an SVG transform: grown from its top left corner, turned around its middle. */
export function faceTransform(f: FaceItem): string | undefined {
if (!f.scale && !f.rotate) return undefined
@ -381,14 +432,18 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
const top = auto.body.y
const hide = new Set(d.hide ?? [])
const place = d.place ?? {}
// Pins on each edge, top to bottom: where they were put, the others one row under the pin above.
// Pins on each edge, top to bottom (in the order set, else as they come): where they were put, the others one row under the pin above.
const order = new Map((d.pinOrder ?? []).map((k, i) => [k, i]))
const rank = (p: PinInfo) => order.get(p.key) ?? 1e6 + p.dy
const placePins = (list: PinInfo[]) => {
let prev = -Infinity
// The first pin takes the edge's first row, whichever pin that is.
const first = Math.min(...list.map(p => p.dy))
return list
.sort((a, b) => a.dy - b.dy)
.sort((a, b) => rank(a) - rank(b) || a.dy - b.dy)
.map(p => {
const want = d.pinAt?.[p.key]
const dy = Math.max(want ?? (prev === -Infinity ? p.dy : prev + 1), prev + 1, 0)
const dy = Math.max(want ?? (prev === -Infinity ? first : prev + 1), prev + 1, 0)
prev = dy
return [p.key, dy] as const
})
@ -397,32 +452,67 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
const rightPins = edgePins.filter(p => p.dx > 0)
const rows = new Map([...placePins(edgePins.filter(p => p.dx === 0)), ...placePins(rightPins)])
const lowest = Math.max(0, ...rightPins.map(p => d.pinAt?.[p.key] ?? p.dy))
const w = Math.max(2, d.w)
const bottom = Math.max(lowest, ...rows.values())
const h = Math.max(d.h, bottom - top + 0.5, 2)
// Own items where auto layout put them unless placed; displays of parts inside only when shown.
// Fitted: as wide as its pin names and its name need, as high as its pins; what it shows makes it bigger.
const longest = (ps: PinInfo[]) => ps.reduce((m, p) => Math.max(m, p.label.length), 0)
const labels = Math.ceil(longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + longest(rightPins) * LABEL_CHAR + (hide.has('name') || place.name ? 0 : def.name.length * NAME_CHAR) + 1.5)
const w = d.fit ? Math.max(2, labels) : Math.max(2, d.w)
const h = d.fit ? Math.max(bottom - top + 0.5, 2) : Math.max(d.h, bottom - top + 0.5, 2)
// Own items where the automatic layout put them unless placed; displays of parts inside only when shown,
// each in the first free spot unless placed. Screens split into pixels where asked: each pixel where it
// sat in the screen as placed, unless placed on its own.
const show = new Set(d.show ?? [])
const nested = nestedItems(def, get).filter(it => show.has(it.key))
let below = (auto.face ?? []).reduce((m, it) => Math.max(m, it.y + it.h), auto.body.y + auto.body.h - 0.6) + 0.3
const items = [
...(auto.face ?? []),
...nested.map(it => {
const at = { ...it, x: 0.6, y: below }
below += it.h + 0.3
return at
}),
]
const shown = items
const split = new Set(d.split ?? [])
const placed = (it: FaceItem): FaceItem => (place[it.key] ? { ...it, x: place[it.key]!.x, y: top + place[it.key]!.y } : it)
const sized = (it: FaceItem) => {
const k = d.scale?.[it.key] ?? it.scale ?? 1
const turned = (d.rotate?.[it.key] ?? it.rotate) === 90 || (d.rotate?.[it.key] ?? it.rotate) === 270
return { w: (turned ? it.h : it.w) * k, h: (turned ? it.w : it.h) * k }
}
const own = (auto.face ?? []).filter(it => !hide.has(it.key)).map(placed)
const nestedAll = nestedItems(def, get).filter(it => show.has(it.key) && !hide.has(it.key))
const taken: { x: number; y: number; w: number; h: number }[] = own.map(it => ({ x: it.x, y: it.y, ...sized(it) }))
// The name, where it shows.
if (!hide.has('name')) {
const nw = def.name.length * NAME_CHAR + 0.4
const c = place.name ? { x: place.name.x, y: top + place.name.y } : { x: w / 2, y: auto.nameY ?? 0 }
taken.push({ x: c.x - nw / 2, y: c.y - 0.55, w: nw, h: 1.1 })
}
for (const it of nestedAll) if (place[it.key]) taken.push({ x: place[it.key]!.x, y: top + place[it.key]!.y, ...sized(it) })
const labelL = longest(edgePins.filter(p => p.dx === 0)) * LABEL_CHAR + 0.6
const labelR = longest(rightPins) * LABEL_CHAR + 0.6
const nested = nestedAll.map(it => {
if (place[it.key]) return placed(it)
const spot = freeSpot(taken, sized(it), { x0: labelL, x1: Math.max(w - labelR, labelL + sized(it).w), y0: top + 0.3 })
taken.push({ ...spot, ...sized(it) })
return { ...it, ...spot }
})
const looks = (key: string) => ({ ...(d.scale?.[key] ? { scale: d.scale[key] } : {}), ...(d.rotate?.[key] ? { rotate: d.rotate[key] } : {}) })
const items = splitScreens([...own, ...nested], split, looks)
.filter(it => !hide.has(it.key))
.map(it => {
const at = place[it.key]
const scale = d.scale?.[it.key]
const rotate = d.rotate?.[it.key]
return { ...it, ...(at ? { x: at.x, y: top + at.y } : {}), ...(scale ? { scale } : {}), ...(rotate ? { rotate } : {}) }
})
// The box is never smaller than what it shows (sized and turned as shown).
.map(it => (it.screenOf ? placed(it) : it))
// Sized and turned as this box says, else as the part inside shows it.
const shown = items.map(it => {
const out: FaceItem = { ...it }
const scale = d.scale?.[it.key] ?? it.scale
const rotate = d.rotate?.[it.key] ?? it.rotate
if (scale) out.scale = scale
else delete out.scale
if (rotate) out.rotate = rotate
else delete out.rotate
return out
})
// The box is never smaller than what it shows (sized and turned as shown), its name and, fitted, its drawings.
let right = w
let floor = top + h
if (d.fit) {
for (const sh of d.shapes ?? []) {
const tw = sh.kind === 'text' ? (sh.text?.length ?? 1) * 0.42 * (sh.size ?? 1) : 0
right = Math.max(right, sh.x + Math.max(sh.w, 0, tw) + 0.3)
floor = Math.max(floor, top + sh.y + Math.max(sh.h, 0, sh.kind === 'text' ? (sh.size ?? 1) : 0) + 0.3)
}
if (place.name && !hide.has('name')) right = Math.max(right, place.name.x + (def.name.length * NAME_CHAR) / 2 + 0.3)
}
for (const it of shown) {
const k = it.scale ?? 1
const turned = it.rotate === 90 || it.rotate === 270
@ -446,6 +536,20 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
}
}
/**
* The first spot for a thing of size `s`, going along rows from the top
* left, that keeps clear of everything taken; below them all when none is.
*/
function freeSpot(taken: { x: number; y: number; w: number; h: number }[], s: { w: number; h: number }, area: { x0: number; x1: number; y0: number }): { x: number; y: number } {
const gap = 0.3
const clear = (x: number, y: number) => taken.every(t => x + s.w + gap <= t.x || x >= t.x + t.w + gap || y + s.h + gap <= t.y || y >= t.y + t.h + gap)
const lowest = taken.reduce((m, t) => Math.max(m, t.y + t.h), area.y0)
for (let y = area.y0; y <= lowest; y += 0.25) {
for (let x = area.x0; x + s.w <= area.x1 + 1e-9; x += 0.25) if (clear(x, y)) return { x, y }
}
return { x: area.x0, y: lowest + gap }
}
/** A pin on one edge of a component's box, and whether a signal goes in or comes out there. */
interface EdgePin {
pin: Omit<PinInfo, 'dx' | 'dy'>

View File

@ -86,6 +86,8 @@ function cleanDesign(d: ComponentDef) {
if (f.rotate !== undefined) f.rotate = nums(f.rotate, v => [0, 90, 180, 270].includes(v))
if (f.pinAt !== undefined) f.pinAt = nums(f.pinAt, v => Number.isInteger(v) && v >= 0 && v <= 1000)
for (const k of ['scale', 'rotate', 'pinAt'] as const) if (f[k] === undefined) delete f[k]
for (const k of ['pinOrder', 'split'] as const) if (f[k] !== undefined && !(Array.isArray(f[k]) && f[k]!.every(v => typeof v === 'string'))) delete f[k]
if (f.fit !== undefined && f.fit !== true) delete f.fit
if (f.shapes !== undefined) {
f.shapes = Array.isArray(f.shapes)
? f.shapes

View File

@ -186,6 +186,12 @@ export interface FaceDesign {
rotate?: Record<string, number>
/** Row of a pin on its edge (by pin key); pins without one follow the pin above. */
pinAt?: Record<string, number>
/** Pins in this order down their edges (keys); pins not listed come after, in their usual order. */
pinOrder?: string[]
/** Screens shown pixel by pixel, each pixel placed on its own (screen keys, as in place). */
split?: string[]
/** The box takes the size its pins, name and things on it need, instead of w and h. */
fit?: boolean
shapes?: FaceShape[]
}

View File

@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { faceCandidates, screenLayouts, shapeOf } from '../app/lib/logic/geometry'
import { faceCandidates, pixelKey, screenLayouts, shapeOf, splitScreens } from '../app/lib/logic/geometry'
import { matchScore } from '../app/lib/match'
import { createProject, lookup } from '../app/lib/logic/ops'
import { toProject } from '../app/lib/logic/project'
@ -159,3 +159,86 @@ describe('finding parts', () => {
expect(matchScore('Lamp', 'xyz')).toBe(0)
})
})
describe('the box designer, more', () => {
/** A 2×2 screen of pixels and two inputs, in a component placed once in another. */
function screened() {
const p = createProject({ examples: false })
const inner: ComponentDef = {
id: 'inner',
name: 'Scr',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 1, label: 'B' },
{ id: 'p1', kind: 'pixel', x: 6, y: 0 },
{ id: 'p2', kind: 'pixel', x: 8, y: 0 },
{ id: 'p3', kind: 'pixel', x: 6, y: 2 },
{ id: 'p4', kind: 'pixel', x: 8, y: 2 },
],
wires: [],
}
p.components.push(inner)
return { p, inner, get: lookup(p), node: { id: 'c', kind: 'chip' as const, chip: 'inner', x: 0, y: 0 } }
}
it('splitting a screen into pixels moves nothing, also sized and turned', () => {
const [screen] = screenLayouts(screened().inner)
for (const rotate of [undefined, 90, 180, 270]) {
const it = { ...screen!, x: 1, y: 1, scale: 2, ...(rotate ? { rotate } : {}) }
const pixels = splitScreens([it], new Set([it.key]))
expect(pixels).toHaveLength(4)
// The four pixels cover exactly the screen's turned square: 2 × 2 pixels of 1 × 2 = a 4 × 4 square at 1, 1.
const xs = pixels.map(px => px.x).sort((a, b) => a - b)
const ys = pixels.map(px => px.y).sort((a, b) => a - b)
expect([xs[0], xs[3], ys[0], ys[3]]).toEqual([1, 3, 1, 3])
expect(pixels.every(px => px.scale === 2 && px.w === 1 && px.key === pixelKey(px.id) && px.screenOf === it.key)).toBe(true)
}
// Turned a quarter, the top left pixel goes to the top right.
const turned = splitScreens([{ ...screen!, x: 0, y: 0, rotate: 90 }], new Set([screen!.key]))
expect(turned.find(px => px.id === 'p1')).toMatchObject({ x: 1, y: 0 })
})
it('pins can change order on their edge', () => {
const { inner, get, node } = screened()
const before = shapeOf(node, get).inputs.map(p => [p.key, p.dy])
inner.design = { w: 6, h: 4, pinOrder: ['b', 'a'] }
const after = shapeOf(node, get).inputs
expect(after.find(p => p.key === 'b')!.dy).toBe(before[0]![1])
expect(after.find(p => p.key === 'a')!.dy).toBe(before[1]![1])
})
it('a fitted box grows and shrinks with what is on it; a set one keeps its size', () => {
const { inner, get, node } = screened()
inner.design = { w: 20, h: 20, fit: true, place: { screen: { x: 1, y: 1 } } }
const small = shapeOf(node, get).body
expect(small.w).toBeLessThan(20)
inner.design.place!.screen = { x: 12, y: 1 }
expect(shapeOf(node, get).body.w).toBeGreaterThan(small.w + 8)
delete inner.design.fit
inner.design.place!.screen = { x: 1, y: 1 }
expect(shapeOf(node, get).body.w).toBe(20)
})
it('a display of a part inside shows in a free spot inside the box, not below it', () => {
const { p } = screened()
const outer: ComponentDef = {
id: 'outer',
name: 'Outer',
symbol: 'box',
nodes: [
{ id: 'x', kind: 'chip', chip: 'inner', x: 0, y: 0 },
...['i0', 'i1', 'i2', 'i3', 'i4', 'i5'].map((id, k) => ({ id, kind: 'input' as const, x: -6, y: k, label: id })),
],
wires: [],
design: { w: 10, h: 7, fit: true, show: ['x/screen'] },
}
p.components.push(outer)
const shape = shapeOf({ id: 'o', kind: 'chip', chip: 'outer', x: 0, y: 0 }, lookup(p))
const scr = shape.face!.find(f => f.key === 'x/screen')!
expect(scr.y + scr.h).toBeLessThanOrEqual(shape.body.y + shape.body.h)
// The six inputs make it six rows high; the screen fits beside their names.
expect(shape.body.h).toBeLessThan(7)
expect(scr.from).toBe('Scr')
})
})