Files
xenia-pos-local/manager_dashboard/src/pages/signage/WidgetCanvas.jsx
T
bonaminandClaude Opus 5.5 aa8ba5d1d4 feat(signage): menus play whole rounds, seconds fields with − / +, widget limit setting, widgets as big as their content (owner review 6)
- A menu board with pages plays whole rounds (menuMs rounds its seconds up); the editor says how
  long it really plays under "Seconds on screen", the card and the playlist total use it.
- Seconds on screen / per page: shared NumberInput (− / +, may be emptied: an error under the
  field and Save blocked until filled; 1 s at least, server ge=1).
- Performance (Signage -> Message & settings): widgets per slide (signage.max_widgets, 10
  recommended, up to 50), checked by the server (signage.too_many_widgets) and the editor.
- Text, clock, date, QR, weather, logo placed by hand: the box is exactly the content (its height
  x text size sets the size, the width follows; handles scale keeping the shape; text size grows
  the box); a slide's widget may run off the slide while 5 % stays on it.
- Slider: the value as close to the slider as the frame's padding; floor and table-colour sliders
  use the shared Slider. Timeline cards' ring no longer clipped; larger playlist buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 15:11:48 +02:00

181 lines
10 KiB
React

// Widgets moved and sized right on the slide's preview (owner 2026-11-21), the way areas are on the
// floor editor: click one to pick it, drag it to move it, drag its handles (corners and sides) to
// size it; arrow keys nudge the picked one (Shift: more), Escape lets it go. It snaps to the
// slide's edges and middle lines (shown while it does). A widget moved or sized this way gets
// position and size "custom" and its own box (% of the slide), which the TV draws the same.
// It lies over SlidePreview's box and finds each widget by its `data-widget` (@xenia/signage).
// Owner review 2 (2026-11-21): the arrow keys move the picked widget wherever it was picked (here
// or on its card below), unless you are typing or using a control that takes the arrows itself;
// Delete (or Backspace) removes it (owner review 3; "Undo changes" brings it back).
// Owner review 5 (2026-11-21): widgets inside a stack's parts too. Pick the stack, then click a
// widget in it: it moves and sizes inside its place (it can't leave the stack; its box is % of its
// place). The picked widget is a path: "2", or "2.1.0" (stack 2, part 1, its first widget).
// Owner review 6: a text, clock, QR… placed by hand is exactly as big as what it shows (its box is
// its content: sized by its handles keeping its shape; its text size makes it bigger too); a slide's
// widget may be moved off the slide as long as a strip of it stays to grab it back.
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { TIGHT } from '@xenia/signage'
import { boxFromRect, moveBox, moveLoose, resizeBox, scaleBox, snapBox, stackOf, widgetAt } from './signageLogic'
const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']
const CURSOR = { n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize' }
const SIZE = 14 // a handle, px
// where the arrow keys belong to the control (typing, lists, sliders, choices)
const OWN_KEYS = 'input, textarea, select, [contenteditable="true"], [role="slider"], [role="radio"], [role="option"], [role="listbox"], [role="combobox"], [role="menu"], [role="menuitem"], [role="tab"], [role="spinbutton"], [role="dialog"] *'
export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPlace, onRemove, label }) {
const { t } = useTranslation('manager')
const [rects, setRects] = useState({})
const [guides, setGuides] = useState([])
const last = useRef('')
// where each widget (and each stack place) is drawn now (the clock ticks, texts change): measured
// after every render (on purpose without deps; it only sets state when something moved). Widgets
// of a library slide drawn inside a part are not this slide's: left out.
// eslint-disable-next-line react-hooks/exhaustive-deps
useLayoutEffect(() => {
const box = boxRef.current
if (!box) return
const frame = box.getBoundingClientRect()
const out = {}
for (const el of box.querySelectorAll('[data-widget], [data-place]')) {
if (el.closest('[data-embedded]')) continue
const r = boxFromRect(el.getBoundingClientRect(), frame)
if (el.hasAttribute('data-widget')) out[el.getAttribute('data-widget')] = r
if (el.hasAttribute('data-place')) out[`place:${el.getAttribute('data-place')}`] = r
}
const key = JSON.stringify(out)
if (key !== last.current) { last.current = key; setRects(out) }
})
const sel = selected != null ? String(selected) : null
// a widget's box in its own frame: the slide's (%), or its place's for a widget in a stack
const tight = path => TIGHT.includes(widgetAt(widgets, path)?.kind)
const own = path => {
const w = widgetAt(widgets, path)
if (w?.position === 'custom' && w.box && !tight(path)) return w.box
const r = rects[path]
const place = stackOf(path) != null ? rects[`place:${path}`] : null
if (!r || stackOf(path) == null) return r || null
if (!place) return null
return { x: (r.x - place.x) / place.w * 100, y: (r.y - place.y) / place.h * 100, w: r.w / place.w * 100, h: r.h / place.h * 100 }
}
// …and where that is on the slide (for the outline)
const onSlide = path => {
const b = own(path)
const place = stackOf(path) != null ? rects[`place:${path}`] : null
if (!b || !place) return b
return { x: place.x + b.x * place.w / 100, y: place.y + b.y * place.h / 100, w: b.w * place.w / 100, h: b.h * place.h / 100 }
}
// what is stored for a tight widget: where it sits and its height before its text size (the
// height scaled as the drawn one was, so it never creeps); others: the box as drawn
const stored = (path, from, to) => {
const w = widgetAt(widgets, path)
if (!tight(path)) return to
const ts = (w.text_size || 100) / 100
const h0 = w.position === 'custom' && w.box ? w.box.h : from.h / ts
return { ...to, h: Math.max(1, Math.round(h0 * (to.h / from.h) * 100) / 100) }
}
const start = (e, path, handle = null) => {
e.preventDefault()
e.stopPropagation()
onSelect(path)
e.currentTarget.closest('[data-testid="signage-canvas"]')?.focus({ preventScroll: true })
const box = boxRef.current
const base = own(path)
if (!box || !base) return
const inside = stackOf(path) != null
const frame = box.getBoundingClientRect()
const place = inside ? rects[`place:${path}`] : { w: 100, h: 100 }
const width = frame.width * place.w / 100
const height = frame.height * place.h / 100
const x0 = e.clientX
const y0 = e.clientY
let moved = false
const move = ev => {
if (!moved && Math.abs(ev.clientX - x0) + Math.abs(ev.clientY - y0) < 3) return
moved = true
const dx = (ev.clientX - x0) / width * 100
const dy = (ev.clientY - y0) / height * 100
const shaped = tight(path)
const next = handle ? (shaped ? scaleBox(base, handle, dx, dy) : resizeBox(base, handle, dx, dy)) : inside ? moveBox(base, dx, dy) : moveLoose(base, dx, dy)
if (inside || (handle && shaped)) { onPlace(path, stored(path, base, next)); return }
const snapped = snapBox(next, handle)
setGuides(snapped.guides)
onPlace(path, stored(path, base, snapped.box))
}
const up = () => {
window.removeEventListener('pointermove', move)
window.removeEventListener('pointerup', up)
setGuides([])
}
window.addEventListener('pointermove', move)
window.addEventListener('pointerup', up)
}
// the keys, on the whole page while a widget is picked
useEffect(() => {
if (sel == null) return undefined
const on = e => {
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return
if (e.target instanceof Element && e.target.closest(OWN_KEYS)) return
if (e.key === 'Escape') { onSelect(null); return }
if ((e.key === 'Delete' || e.key === 'Backspace') && onRemove) { e.preventDefault(); onRemove(sel); return }
const step = e.shiftKey ? 2 : 0.5
const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key]
if (!d) return
e.preventDefault()
const base = own(sel)
if (base) onPlace(sel, stored(sel, base, (stackOf(sel) != null ? moveBox : moveLoose)(base, d[0], d[1])))
}
window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on)
})
// what can be picked: the slide's widgets, and the widgets of the stack picked (or of the stack
// a picked widget sits in), drawn over it
const pickable = Object.keys(rects).filter(k => !k.startsWith('place:')).filter(k => {
const parent = stackOf(k)
return parent == null || (sel != null && (sel === parent || sel.startsWith(`${parent}.`)))
}).sort((a, b) => a.split('.').length - b.split('.').length)
const box = sel != null ? onSlide(sel) : null
const picked = widgetAt(widgets, sel)
return (
<div className="absolute inset-0 outline-none" tabIndex={0} onPointerDown={() => onSelect(null)}
role="application" aria-label={label} data-testid="signage-canvas">
{pickable.map(k => {
const w = widgetAt(widgets, k)
if (!w) return null
const r = rects[k]
return (
<div key={k} className={`absolute cursor-move rounded-sm ${sel === k ? '' : 'hover:outline hover:outline-2 hover:outline-accent/60'}`}
style={{ left: `${r.x}%`, top: `${r.y}%`, width: `${r.w}%`, height: `${r.h}%` }}
onPointerDown={e => start(e, k)} data-testid="signage-canvas-widget" data-index={k} data-kind={w.kind} />
)
})}
{guides.map(g => {
const [axis, at] = g.split(':')
return <div key={g} className="absolute bg-accent pointer-events-none" data-testid="signage-canvas-guide"
style={axis === 'x' ? { left: `${at}%`, top: 0, bottom: 0, width: 1 } : { top: `${at}%`, left: 0, right: 0, height: 1 }} />
})}
{box && picked && (
<div className="absolute pointer-events-none outline outline-2 outline-accent" data-testid="signage-canvas-selected"
style={{ left: `${box.x}%`, top: `${box.y}%`, width: `${box.w}%`, height: `${box.h}%` }}>
<span className={`absolute left-0 whitespace-nowrap rounded-sm bg-accent text-accent-fg text-caption font-semibold px-1.5 py-0.5 ${box.y < 8 ? 'top-full mt-2' : 'bottom-full mb-2'}`}>
{t(`signage.widgets.kinds.${picked.kind === 'stack' ? (picked.direction === 'column' ? 'vstack' : 'hstack') : picked.kind}`)}
</span>
{HANDLES.map(h => (
<span key={h} className="absolute pointer-events-auto bg-surface border-2 border-accent rounded-[3px]" data-testid={`signage-handle-${h}`}
style={{ width: SIZE, height: SIZE, cursor: CURSOR[h],
left: h.includes('w') ? -SIZE / 2 : h.includes('e') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)`,
top: h.includes('n') ? -SIZE / 2 : h.includes('s') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)` }}
onPointerDown={e => start(e, sel, h)} />
))}
</div>
)}
</div>
)
}