feat(signage): new widgets (shape, scrolling text, countdown, opening hours, Wi-Fi, contact details); the venue's opening hours on the server, edited on the Schedule page

Shapes: rectangle, circle, triangle, polygon, star or own corners, fill or gradient,
border. Countdown: to a time every day or a date, from now / a span before / a set
time, in venue time (the slide shows what is left right now). Opening hours, Wi-Fi
(with a join-the-network code) and contact details read the venue's identity and
opening hours (GET/PUT /api/identity/hours; Schedule -> Opening hours, shaded on its
timeline); the editor warns with a link when they're missing. Plan 6R.15, F-112.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 13:24:54 +02:00
co-authored by Claude Opus 5.5
parent 2a38602d45
commit f26e51273c
22 changed files with 1002 additions and 46 deletions
+171 -6
View File
@@ -2,12 +2,13 @@
// fonts and sizes here are the venue's own choices for its TV (slide content = data, CS-16), so
// they are inline styles, not tokens. Sizes scale with the screen (cqmin), so a slide looks the
// same on any TV.
import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { Camera, Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Globe, Lock, Mail, MapPin, MessageCircle, Moon, Music, Phone, Star, Sun, ThumbsUp, Wifi } from 'lucide-react'
import { QRCodeSVG } from 'qrcode.react'
import { BADGE_ICONS } from './badges'
import { cq, CQ_BOX } from './cq'
import { useFormat, useTranslation } from '@xenia/i18n'
import { badgeColours, badgeName, cellWidgets, TIGHT, fitUnit, FONTS, itemBadges, menuLook, menuPages, pageAt, priceChars, textWidth, visibleGroups, weatherIcon, widgetAlign } from './logic'
import { badgeColours, badgeName, cellWidgets, countdownState, countdownText, TIGHT, fitUnit, FONTS, hoursRows, itemBadges, localNow, menuLook, menuPages, pageAt, priceChars, shapePoints, textWidth, visibleGroups, weatherIcon, widgetAlign, wifiQr } from './logic'
/** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */
export function Background({ bg, media }) {
@@ -173,8 +174,8 @@ const plate = (w, pad) => ({
...(w.colour ? { color: w.colour } : {}),
...(w.background_colour ? { background: w.background_colour, borderRadius: cq(1.2), ...(pad ? { padding: `${cq(0.8)} ${cq(1.6)}` } : {}) } : {}),
})
// a menu or a stack in a corner or a bar has no box of its own: it gets one of this size (cqmin)
const BOXED = { menu: [48, 56], stack: [60, 36] }
// a menu, a stack, a shape or a scrolling text in a corner or a bar has no box of its own: it gets one of this size (cqmin)
const BOXED = { menu: [48, 56], stack: [60, 36], shape: [18, 18], ticker: [80, 7] }
/**
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position
@@ -186,8 +187,9 @@ const BOXED = { menu: [48, 56], stack: [60, 36] }
*/
export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
const fmt = useFormat()
const { t } = useTranslation('terminal')
if (!widgets?.length) return null
const ctx = { media, venue, now, fmt, extras: extras || {}, embed }
const ctx = { media, venue, now, fmt, extras: extras || {}, embed, t }
const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, placedBy(w), String(i))]).filter(([, , body]) => body)
const bar = where => shown.filter(([w]) => w.position === where)
const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]]
@@ -198,7 +200,8 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: cq(3), padding: `${cq(2)} ${cq(4)}`,
background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: cq(9) }}>
{bar(where).map(([w, i, body]) => (
<div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w, true) }}>{body}</div>
<div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w, true),
...(w.kind === 'ticker' ? { flex: 1, minWidth: 0, alignSelf: 'stretch', justifyContent: 'center' } : {}) }}>{body}</div>
))}
</div>
))}
@@ -307,9 +310,171 @@ function widgetBody(w, ctx, fit, path) {
if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate)
if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} badges={venue?.badges} />, 'menu')
if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack')
// 6R.15
if (w.kind === 'shape') return boxed(<ShapeBody w={w} id={`sg-fill-${path.replace(/\./g, '-')}`} />, 'shape')
if (w.kind === 'ticker') {
if (!w.text) return null
const inBar = (w.position || '').endsWith('-bar')
const u = fit ? fitUnit(3.4 * 1.3, 0.1) : n => cq(+(n * s).toFixed(3))
const body = <Ticker w={w} style={text(u, 3.4, 600)} />
return inBar ? body : boxed(body, 'ticker')
}
if (w.kind === 'countdown') {
const st = countdownState(w, localNow(venue?.timezone, now), now.getSeconds())
if (st.state === 'none' || (st.state === 'waiting' && w.countdown_waiting === 'hide')) return null
if (st.state === 'done') return w.countdown_done_hide || !w.countdown_done ? null : line(w.countdown_done, 'signage-w-countdown-done', 700)
const digits = countdownText(st.left)
const label = w.text || ''
const u = unit((label ? 2.4 * 1.15 + 0.4 : 0) + 6 * 1.1, Math.max(textWidth(digits.length, 6) * 0.9, label ? textWidth(label.length, 2.4) : 0))
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'inherit', gap: u(0.4) }} data-testid="signage-w-countdown" data-state={st.state} data-left={st.left}>
{label && <span style={text(u, 2.4, 600)}>{label}</span>}
<span style={{ ...text(u, 6, 800), lineHeight: 1.1, fontVariantNumeric: 'tabular-nums' }}>{digits}</span>
</div>
)
}
if (w.kind === 'hours') return hoursBody(w, ctx, unit, text)
if (w.kind === 'wifi') return wifiBody(w, venue?.identity?.wifi, unit, text)
if (w.kind === 'contact') return contactBody(w, venue?.identity?.contact, unit, text)
return null
}
/** A shape (6R.15) filling its box: a rectangle (rounded corners) or circle as a box, the others as SVG corners; a fill or a gradient, a border. */
function ShapeBody({ w, id }) {
const fill = w.fill || '#f59e0b'
const angle = w.fill_angle ?? 180
const border = w.stroke && w.stroke_width ? cq(+(w.stroke_width / 2).toFixed(2)) : null // ½ % of its shorter side a step
const pts = shapePoints(w)
if (!pts) {
return (
<div style={{ width: '100%', height: '100%', boxSizing: 'border-box', background: w.fill_to ? `linear-gradient(${angle}deg, ${fill}, ${w.fill_to})` : fill,
borderRadius: w.shape === 'circle' ? '50%' : cq(w.radius || 0), ...(border ? { border: `${border} solid ${w.stroke}` } : {}) }}
data-testid="signage-w-shape" data-shape={w.shape || 'rectangle'} />
)
}
const rad = (angle * Math.PI) / 180
const dx = Math.sin(rad) / 2
const dy = -Math.cos(rad) / 2
return (
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: '100%', height: '100%', overflow: 'visible', display: 'block' }}
data-testid="signage-w-shape" data-shape={w.shape} aria-hidden="true">
{w.fill_to && (
<defs>
<linearGradient id={id} x1={0.5 - dx} y1={0.5 - dy} x2={0.5 + dx} y2={0.5 + dy}>
<stop offset="0" stopColor={fill} /><stop offset="1" stopColor={w.fill_to} />
</linearGradient>
</defs>
)}
<polygon points={pts} fill={w.fill_to ? `url(#${id})` : fill} vectorEffect="non-scaling-stroke"
style={border ? { stroke: w.stroke, strokeWidth: border, strokeLinejoin: 'round' } : undefined} />
</svg>
)
}
/** A scrolling text (6R.15): one line moving across its place, round and round; its speed follows its height. */
function Ticker({ w, style }) {
const box = useRef(null)
const run = useRef(null)
const [size, setSize] = useState(null)
useEffect(() => {
const el = box.current
if (!el || typeof ResizeObserver === 'undefined') return undefined
const ro = new ResizeObserver(() => setSize(s => (s && s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight })))
ro.observe(el)
return () => ro.disconnect()
}, [])
useEffect(() => {
const r = run.current
if (!size || !r?.animate) return undefined
const T = r.scrollWidth
const left = (w.ticker_direction || 'left') === 'left'
const pxPerS = (w.ticker_speed || 4) * Math.max(8, r.offsetHeight) * 0.9
const a = r.animate([{ transform: `translateX(${left ? size.w : -T}px)` }, { transform: `translateX(${left ? -T : size.w}px)` }],
{ duration: ((size.w + T) / pxPerS) * 1000, iterations: Infinity })
return () => a.cancel()
}, [size, w.text, w.ticker_speed, w.ticker_direction, style.fontSize])
return (
<div ref={box} style={{ width: '100%', height: '100%', overflow: 'hidden', display: 'flex', alignItems: 'center', position: 'relative' }} data-testid="signage-w-ticker">
<span ref={run} style={{ ...style, whiteSpace: 'nowrap', display: 'inline-block', willChange: 'transform' }}>{w.text}</span>
</div>
)
}
const MONDAY = '2026-11-16' // a Monday: day names from the venue's language
const dayShort = (fmt, i) => fmt.formatDate(`2026-11-${16 + i}T12:00:00Z`, 'weekday').slice(0, 3)
/** The opening hours (6R.15): the week (days with the same hours on one line) or today; today stands out. */
function hoursBody(w, ctx, unit, text) {
const { venue, now, fmt, t } = ctx
const hours = venue?.hours
if (!hours?.set) return null
const today = localNow(venue?.timezone, now).weekday
const rows = hoursRows(hours, { group: w.hours_group !== false, today, only: w.hours_style === 'today' ? today : null })
const daysText = r => (r.days.length > 1 ? `${dayShort(fmt, r.days[0])}–${dayShort(fmt, r.days[r.days.length - 1])}` : dayShort(fmt, r.days[0]))
const spansText = r => (r.spans.length ? r.spans.map(x => `${x.from}–${x.to}`).join(', ') : t('signage.closed'))
const widest = Math.max(...rows.map(r => daysText(r).length + 2 + spansText(r).length), w.text ? w.text.length : 0)
const u = unit((rows.length + (w.text ? 1.3 : 0)) * 3 * 1.35, textWidth(widest, 3))
return (
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', columnGap: u(2), rowGap: u(0.4), alignItems: 'baseline', textAlign: 'left' }}
data-testid="signage-w-hours" data-rows={rows.length} data-start={MONDAY}>
{w.text && <span style={{ ...text(u, 3.4, 800), gridColumn: '1 / -1' }}>{w.text}</span>}
{rows.map(r => (
<span key={r.days.join()} style={{ display: 'contents' }} data-today={r.today ? 'true' : undefined}>
<span style={{ ...text(u, 3, r.today ? 800 : 600), opacity: r.today || w.hours_style === 'today' ? 1 : 0.85 }}>{daysText(r)}</span>
<span style={{ ...text(u, 3, r.today ? 800 : 500), fontVariantNumeric: 'tabular-nums' }}>{spansText(r)}</span>
</span>
))}
</div>
)
}
/** The guests' Wi-Fi (6R.15, from the identity): its code to join, the network and the password. */
function wifiBody(w, wifi, unit, text) {
if (!wifi?.ssid) return null
const qr = w.wifi_qr !== false ? wifiQr(wifi) : ''
const pw = w.wifi_password !== false && wifi.security !== 'nopass' && wifi.password ? wifi.password : ''
const lines = [wifi.ssid, pw, wifi.note].filter(Boolean)
const chars = Math.max(...lines.map(l => l.length)) + 2
const u = unit(Math.max(qr ? 13 : 0, lines.length * 3.4 * 1.35), (qr ? 14.5 : 0) + textWidth(chars, 3.4))
const icon = { width: u(3), height: u(3), flexShrink: 0 }
return (
<div style={{ display: 'flex', alignItems: 'center', gap: u(1.5), textAlign: 'left' }} data-testid="signage-w-wifi">
{qr && (
<div style={{ background: w.qr_background || '#fff', padding: u(0.7), borderRadius: u(0.8), lineHeight: 0 }}>
<QRCodeSVG value={qr} size={256} fgColor={w.qr_colour || '#000000'} bgColor={w.qr_background || '#ffffff'} style={{ width: u(11.5), height: u(11.5) }} />
</div>
)}
<div style={{ display: 'grid', gap: u(0.5) }}>
<span style={{ display: 'flex', alignItems: 'center', gap: u(0.8), ...text(u, 3.4, 800) }}><Wifi style={icon} aria-hidden="true" />{wifi.ssid}</span>
{pw && <span style={{ display: 'flex', alignItems: 'center', gap: u(0.8), ...text(u, 3.4, 600) }}><Lock style={icon} aria-hidden="true" />{pw}</span>}
{wifi.note && <span style={{ ...text(u, 2.6, 500), opacity: 0.85 }}>{wifi.note}</span>}
</div>
</div>
)
}
const CONTACT_ICONS = { phone: Phone, phone2: Phone, email: Mail, address: MapPin, website: Globe, google: MapPin, facebook: ThumbsUp,
instagram: Camera, tiktok: Music, tripadvisor: Star, whatsapp: MessageCircle, viber: MessageCircle }
/** The venue's contact details (6R.15, from the identity): the chosen ones that are set, one a line with an icon. */
function contactBody(w, contact, unit, text) {
const rows = (w.contact_fields || ['phone', 'website', 'instagram']).filter(k => contact?.[k]).map(k => [k, contact[k]])
if (!rows.length) return null
const u = unit(rows.length * 3.2 * 1.4, textWidth(Math.max(...rows.map(([, v]) => v.length)) + 2, 3.2))
return (
<div style={{ display: 'grid', gap: u(0.6), textAlign: 'left' }} data-testid="signage-w-contact" data-rows={rows.length}>
{rows.map(([k, v]) => {
const Icon = CONTACT_ICONS[k] || Globe
return (
<span key={k} style={{ display: 'flex', alignItems: 'center', gap: u(0.9), ...text(u, 3.2, 600) }} data-key={k}>
<Icon style={{ width: u(3), height: u(3), flexShrink: 0 }} aria-hidden="true" />{v}
</span>
)
})}
</div>
)
}
/** The weather: now or a day of the forecast (today, tomorrow, the day after), and the next days;
* its picture and degrees, only the picture or only the degrees (2026-11-21). */
function weatherBody(w, wx, unit, text, formatDate) {
+87 -1
View File
@@ -275,7 +275,7 @@ export function visibleGroups(groups) {
/** Widgets whose box, placed by hand, is exactly their content (owner review 6): its height (× the
* widget's text size) sets the size, its width follows. A menu or a stack fills its box. */
export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather']
export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'countdown', 'hours', 'wifi', 'contact']
/** The slide kinds that carry widgets. */
export const WIDGET_HOSTS = ['text', 'menu', 'blank']
@@ -519,3 +519,89 @@ export function wifiQr(wifi) {
const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : ''
return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};`
}
// ── widgets of 6R.15: countdown, opening hours, shapes ───────────────────────
const minOf = hhmm => { const [h, m] = hhmm.split(':').map(Number); return h * 60 + m }
const dayNo = date => Date.UTC(+date.slice(0, 4), +date.slice(5, 7) - 1, +date.slice(8, 10)) / 86_400_000
/** A countdown's moment ("HH:MM" = that time today; "YYYY-MM-DDTHH:MM") in minutes from the venue's local midnight today. */
function momentMin(when, local) {
if (!when) return null
if (when.length === 5) return minOf(when)
return (dayNo(when.slice(0, 10)) - dayNo(local.date)) * 1440 + minOf(when.slice(11))
}
/**
* Where a countdown stands (6R.15) at venue time `local` ({ date, minutes }) and `seconds` past the
* minute: 'none' (no end set), 'waiting' (before it starts: `left` = its whole span), 'running'
* (`left` = seconds to the end), 'done' (the end has passed, today or for good).
*/
export function countdownState(w, local, seconds = 0) {
const end = momentMin(w?.countdown_to, local)
if (end == null) return { state: 'none', left: 0 }
const nowS = local.minutes * 60 + seconds
const endS = end * 60
let startS = null
if (w.countdown_start === 'before') startS = endS - (w.countdown_before || 120) * 60
else if (w.countdown_start === 'at') {
const at = momentMin(w.countdown_at, local)
if (at != null) startS = at * 60
}
if (nowS >= endS) return { state: 'done', left: 0 }
if (startS != null && nowS < startS) return { state: 'waiting', left: endS - startS }
return { state: 'running', left: endS - nowS }
}
/** Seconds as "1:30:00", "05:09" under an hour, "3d 04:10:00" over a day. */
export function countdownText(left) {
const s = Math.max(0, Math.floor(left))
const d = Math.floor(s / 86400)
const h = Math.floor((s % 86400) / 3600)
const m = Math.floor((s % 3600) / 60)
const two = n => String(n).padStart(2, '0')
if (d) return `${d}d ${two(h)}:${two(m)}:${two(s % 60)}`
return h ? `${h}:${two(m)}:${two(s % 60)}` : `${two(m)}:${two(s % 60)}`
}
/**
* The opening hours as lines (6R.15): [{ days: [0…6] (Monday 0), spans: [{from, to}] ([] closed),
* today }]; with `group`, days next to each other with the same hours share a line ("Mon–Fri").
* `only`: one weekday (the "today" style).
*/
export function hoursRows(hours, { group = true, today = -1, only = null } = {}) {
const days = hours?.days || []
if (days.length !== 7) return []
const key = i => JSON.stringify(days[i] || [])
const rows = []
for (let i = 0; i < 7; i++) {
if (only != null && i !== only) continue
const last = rows[rows.length - 1]
if (group && only == null && last && key(last.days[last.days.length - 1]) === key(i) && last.days[last.days.length - 1] === i - 1) last.days.push(i)
else rows.push({ days: [i], spans: days[i] || [] })
}
return rows.map(r => ({ ...r, today: r.days.includes(today) }))
}
/** A shape's corners as SVG points in a 100 × 100 box (polygon, star, triangle, custom "x,y x,y"); null for rectangle / circle. */
export function shapePoints(w) {
const kind = w?.shape || 'rectangle'
const ring = (n, r, turn = 0) => Array.from({ length: n }, (_, i) => {
const a = -Math.PI / 2 + turn + (i * 2 * Math.PI) / n
return [50 + r * Math.cos(a), 50 + r * Math.sin(a)]
})
let pts = null
if (kind === 'triangle') pts = [[50, 0], [100, 100], [0, 100]]
else if (kind === 'polygon') pts = ring(w.shape_sides || 6, 50)
else if (kind === 'star') {
const n = w.shape_sides || 5
const outer = ring(n, 50)
const inner = ring(n, 50 * (w.shape_inner || 45) / 100, Math.PI / n)
pts = outer.flatMap((p, i) => [p, inner[i]])
} else if (kind === 'custom') {
pts = String(w.shape_points || '').trim().split(/\s+/).map(p => p.split(',').map(Number))
.filter(p => p.length === 2 && p.every(Number.isFinite)).map(([x, y]) => [Math.min(100, Math.max(0, x)), Math.min(100, Math.max(0, y))])
if (pts.length < 3) pts = null
}
return pts ? pts.map(([x, y]) => `${+x.toFixed(2)},${+y.toFixed(2)}`).join(' ') : null
}
+38
View File
@@ -277,3 +277,41 @@ test('a Wi-Fi QR code: escaped, open networks without a password, hidden ones (6
assert.equal(wifiQr({ ssid: 'Open', password: 'x', security: 'nopass', hidden: true }), 'WIFI:T:nopass;S:Open;H:true;;')
assert.equal(wifiQr({ password: 'x' }), '')
})
test('a countdown: from a span before, waiting, running, done; a date; the text (6R.15)', async () => {
const { countdownState, countdownText } = await import('../src/logic.js')
const w = { countdown_to: '17:00', countdown_start: 'before', countdown_before: 120 }
const at = (hhmm, date = '2026-11-22') => ({ date, minutes: Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3)) })
// the owner's case: ends at 5, starts 2 h before, the slide shows at 3:30 → 1:30:00 left
assert.deepEqual(countdownState(w, at('15:30')), { state: 'running', left: 5400 })
assert.equal(countdownText(5400), '1:30:00')
assert.deepEqual(countdownState(w, at('14:00')), { state: 'waiting', left: 7200 })
assert.equal(countdownState(w, at('17:00')).state, 'done')
assert.equal(countdownState({ countdown_to: '17:00' }, at('09:00')).left, 8 * 3600)
assert.equal(countdownState({ countdown_to: '17:00', countdown_start: 'at', countdown_at: '16:00' }, at('15:00')).state, 'waiting')
const ny = countdownState({ countdown_to: '2026-12-31T23:59' }, at('23:59', '2026-12-30'), 30)
assert.equal(ny.left, 86400 - 30)
assert.equal(countdownText(ny.left), '23:59:30')
assert.equal(countdownText(2 * 86400 + 61), '2d 00:01:01')
assert.equal(countdownText(309), '05:09')
assert.equal(countdownState({}, at('10:00')).state, 'none')
})
test('opening hours in lines: same hours grouped, today marked; shapes as points (6R.15)', async () => {
const { hoursRows, shapePoints } = await import('../src/logic.js')
const lunch = [{ from: '12:00', to: '23:00' }]
const hours = { days: [lunch, lunch, lunch, lunch, [{ from: '12:00', to: '01:00' }], [], lunch] }
const rows = hoursRows(hours, { today: 1 })
assert.deepEqual(rows.map(r => r.days), [[0, 1, 2, 3], [4], [5], [6]])
assert.equal(rows[0].today, true)
assert.deepEqual(rows[2].spans, [])
assert.equal(hoursRows(hours, { group: false }).length, 7)
assert.deepEqual(hoursRows(hours, { only: 5 }).map(r => r.days), [[5]])
assert.deepEqual(hoursRows({ days: [] }), [])
assert.equal(shapePoints({ shape: 'triangle' }), '50,0 100,100 0,100')
assert.equal(shapePoints({ shape: 'star', shape_sides: 5 }).split(' ').length, 10)
assert.equal(shapePoints({ shape: 'polygon', shape_sides: 6 }).split(' ').length, 6)
assert.equal(shapePoints({ shape: 'custom', shape_points: '0,0 100,0 50,120' }), '0,0 100,0 50,100')
assert.equal(shapePoints({ shape: 'custom', shape_points: '1,1' }), null)
assert.equal(shapePoints({ shape: 'rectangle' }), null)
})