refactor: @xenia/signage: the slides and the player's logic shared by the terminal and the manager (platform-v2 step 5.6a)

The signage slides (SlideView, TextSlide, MenuSlide, Widgets) and the pure
logic (schedule pick, slide windows, menu pages) move from the terminal into
packages/signage, so the manager's previews draw a slide exactly as the TV
does. Sizes are container units (cqmin) instead of viewport units: a slide
draws inside any box with container-type: size (frameStyle sets it on the
TV). Tests move with it (10). Dockerfiles copy its package.json; both apps'
Tailwind content include it; run-all runs its tests. Signage e2e and the
compose stack passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:59:33 +02:00
co-authored by Claude Opus 5.5
parent e90c2f4f8f
commit 314e9c2457
16 changed files with 146 additions and 76 deletions
+1
View File
@@ -11,6 +11,7 @@ COPY packages/ui/package.json packages/ui/
COPY packages/i18n/package.json packages/i18n/
COPY packages/api/package.json packages/api/
COPY packages/access/package.json packages/access/
COPY packages/signage/package.json packages/signage/
COPY waiter_pwa/package.json waiter_pwa/
COPY manager_dashboard/package.json manager_dashboard/
COPY terminal/package.json terminal/
+1
View File
@@ -15,6 +15,7 @@
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
"lucide-react": "^1.73.0",
+2 -29
View File
@@ -10,8 +10,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import client from '../../api/client'
import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context'
import { boardPages, frameStyle, localNow, mediaUrls, menuMs, nextSlide, pageAt, playlistNow, slideMs } from './logic'
import { MenuSlide, TextSlide } from './Slides'
import { boardPages, frameStyle, localNow, mediaUrls, menuMs, nextSlide, pageAt, playlistNow, SlideView, slideMs } from '@xenia/signage'
const quiet = { xenia: { noOverride: true } }
const CACHE_KEY = 'xenia:signage:screen'
@@ -186,33 +185,7 @@ function Layer({ slide, media, venue, now, onEnded, className, current = false,
return (
<section className={`absolute inset-0 overflow-hidden ${className}`} style={{ animationDuration: `${TRANSITION_MS}ms` }}
data-testid={current ? 'signage-slide' : 'signage-slide-out'} data-kind={slide.kind} data-slide={slide.id}>
{slide.kind === 'image' && <ImageSlide content={slide.content} media={media} />}
{slide.kind === 'video' && <VideoSlide slide={slide} media={media} onEnded={current ? onEnded : undefined} />}
{slide.kind === 'text' && <TextSlide content={slide.content} media={media} venue={venue} now={now} />}
{slide.kind === 'menu' && <MenuSlide slide={slide} media={media} venue={venue} now={now} pages={pages || []} page={page || 0} />}
<SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={page} onEnded={current ? onEnded : undefined} />
</section>
)
}
function ImageSlide({ content, media }) {
const m = media(content.media_id)
return (
<div className="absolute inset-0" style={{ background: content.background_colour || '#000' }}>
{m && <img src={m.src} alt="" className="w-full h-full" style={{ objectFit: content.fit || 'cover' }} data-testid="signage-image" />}
</div>
)
}
function VideoSlide({ slide, media, onEnded }) {
const c = slide.content
const m = media(c.media_id)
const ref = useRef(null)
useEffect(() => { ref.current?.play?.().catch(() => {}) }, [m?.src])
return (
<div className="absolute inset-0" style={{ background: c.background_colour || '#000' }}>
{m && <video ref={ref} src={m.src} autoPlay muted={c.muted !== false} playsInline loop={!slide.video_to_end}
onEnded={slide.video_to_end ? onEnded : undefined} onError={slide.video_to_end ? onEnded : undefined}
className="w-full h-full" style={{ objectFit: c.fit || 'cover' }} data-testid="signage-video" />}
</div>
)
}
-184
View File
@@ -1,184 +0,0 @@
// Text and menu slides of the signage player, and their widgets (plan steps 5.5a, 5.5b). Colours,
// 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 (vmin), so a slide looks the
// same on any TV.
import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react'
import { QRCodeSVG } from 'qrcode.react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { FONTS, weatherIcon } from './logic'
/** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */
export function Background({ bg, media }) {
const m = bg?.kind === 'media' ? media(bg.media_id) : null
return (
<div className="absolute inset-0" style={{ background: bg?.colour || '#111827' }} data-testid="signage-background">
{m && <img src={m.src} alt="" className="absolute inset-0 w-full h-full" style={{ objectFit: bg.fit || 'cover' }} />}
{m && bg.dim > 0 && <div className="absolute inset-0" style={{ background: `rgba(0,0,0,${bg.dim / 100})` }} />}
</div>
)
}
const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' }
const hasBar = (c, where) => (c.widgets || []).some(w => w.position === where)
export function TextSlide({ content: c, media, venue, now }) {
const scale = (c.text_size || 100) / 100
return (
<div className="absolute inset-0" style={{ color: c.text_colour || '#fff', fontFamily: FONTS[c.font] || FONTS.sans }}>
<Background bg={c.background} media={media} />
<div className="absolute inset-0 flex flex-col" style={{
justifyContent: JUSTIFY[c.vertical] || 'center', textAlign: c.align || 'center',
padding: `${hasBar(c, 'top-bar') ? 14 : 8}vmin 8vmin ${hasBar(c, 'bottom-bar') ? 14 : 8}vmin`, gap: `${3 * scale}vmin`,
}}>
{c.title && <h1 style={{ fontSize: `${9 * scale}vmin`, lineHeight: 1.1, fontWeight: 800, margin: 0 }} data-testid="signage-title">{c.title}</h1>}
{c.body && <p style={{ fontSize: `${4.5 * scale}vmin`, lineHeight: 1.35, margin: 0, whiteSpace: 'pre-line' }} data-testid="signage-body">{c.body}</p>}
</div>
<Widgets widgets={c.widgets} media={media} venue={venue} now={now} colour={c.text_colour} />
</div>
)
}
/** A menu board (5.5b): its page of items (pages flip on their own), photos, descriptions, badges, sold out. */
export function MenuSlide({ slide, media, venue, now, page, pages }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const c = slide.content
const scale = (c.text_size || 100) / 100
const accent = c.accent_colour || '#f59e0b'
const groups = pages[page] || []
return (
<div className="absolute inset-0" style={{ color: c.text_colour || '#fff', fontFamily: FONTS[c.font] || FONTS.sans }}>
<Background bg={c.background} media={media} />
<div className="absolute inset-0 flex flex-col"
style={{ padding: `${hasBar(c, 'top-bar') ? 12 : 5}vmin 5vmin ${hasBar(c, 'bottom-bar') ? 12 : 5}vmin` }}
data-testid="signage-menu" data-page={page} data-pages={pages.length}>
{c.title && <h1 style={{ fontSize: `${7 * scale}vmin`, fontWeight: 800, margin: '0 0 2vmin', color: accent, lineHeight: 1.1 }}>{c.title}</h1>}
<div style={{ columnCount: c.columns || 2, columnGap: '5vmin', fontSize: `${3.2 * scale}vmin`, flex: 1, columnFill: 'auto' }}>
{groups.map((g, i) => (
<div key={`${g.category?.id ?? 'all'}-${i}`} style={{ marginBottom: '1.6vmin' }}>
{g.category && c.category_titles !== false && (
<h2 style={{ fontSize: '1.15em', color: accent, margin: '0 0 0.6vmin', fontWeight: 700, breakAfter: 'avoid' }}
data-testid="signage-menu-heading">{g.category.name}</h2>
)}
{g.items.map(it => (
<div key={it.id} data-testid="signage-menu-item" data-id={it.id} data-available={it.available ? 'true' : 'false'}
style={{ display: 'flex', alignItems: 'center', gap: '1.5vmin', breakInside: 'avoid', padding: '0.5vmin 0',
opacity: it.available ? 1 : 0.5 }}>
{c.show_photos && (it.image
? <img src={it.image} alt="" style={{ width: '7vmin', height: '7vmin', objectFit: 'cover', borderRadius: '1vmin', flexShrink: 0 }} />
: <span style={{ width: '7vmin', height: '7vmin', flexShrink: 0 }} />)}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: '1vmin' }}>
<span style={{ textDecoration: it.available ? 'none' : 'line-through', fontWeight: 600 }}>{it.name}</span>
{it.badge && (
<span style={{ background: accent, color: '#111', fontSize: '0.55em', fontWeight: 800, padding: '0.2vmin 0.9vmin', borderRadius: '99vmin',
textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }} data-testid="signage-badge">{t(`signage.badges.${it.badge}`)}</span>
)}
{!it.available && <span style={{ fontSize: '0.6em', whiteSpace: 'nowrap' }} data-testid="signage-sold-out">{t('signage.soldOut')}</span>}
<span style={{ flex: 1, borderBottom: '0.25vmin dotted currentColor', opacity: 0.35, minWidth: '2vmin' }} />
{it.price != null && <span style={{ color: accent, fontVariantNumeric: 'tabular-nums', fontWeight: 700, whiteSpace: 'nowrap' }}
data-testid="signage-menu-price">{formatMoney(it.price)}</span>}
</div>
{it.description && <div style={{ fontSize: '0.7em', opacity: 0.75, lineHeight: 1.25 }}>{it.description}</div>}
</div>
</div>
))}
</div>
))}
</div>
{pages.length > 1 && (
<div style={{ display: 'flex', gap: '1vmin', justifyContent: 'center', paddingTop: '1vmin' }} aria-hidden="true">
{pages.map((_, i) => <span key={i} style={{ width: '1.2vmin', height: '1.2vmin', borderRadius: '50%', background: i === page ? accent : 'currentColor', opacity: i === page ? 1 : 0.3 }} />)}
</div>
)}
</div>
<Widgets widgets={c.widgets} media={media} venue={venue} now={now} colour={c.text_colour} />
</div>
)
}
// ── widgets (5.5b) ──────────────────────────────────────────────────────────
const SIZE = { small: 0.75, medium: 1, large: 1.4 }
const CORNER = {
'top-left': { top: '3vmin', left: '3vmin', alignItems: 'flex-start' },
'top-center': { top: '3vmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' },
'top-right': { top: '3vmin', right: '3vmin', alignItems: 'flex-end' },
'bottom-left': { bottom: '3vmin', left: '3vmin', alignItems: 'flex-start' },
'bottom-center': { bottom: '3vmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' },
'bottom-right': { bottom: '3vmin', right: '3vmin', alignItems: 'flex-end' },
}
/** The widgets of a slide, in their corners and bars. One that has nothing to show is left out. */
export function Widgets({ widgets, media, venue, now, colour }) {
if (!widgets?.length) return null
const bar = where => widgets.filter(w => w.position === where)
const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]]
return (
<>
{bars.map(([where, pos]) => bar(where).length > 0 && (
<div key={where} className="absolute inset-x-0" data-testid={`signage-${where}`}
style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '3vmin', padding: '2vmin 4vmin',
background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: '9vmin' }}>
{bar(where).map((w, i) => <Widget key={i} w={w} media={media} venue={venue} now={now} />)}
</div>
))}
{widgets.filter(w => CORNER[w.position]).map((w, i) => (
<div key={`c${i}`} className="absolute" style={{ ...CORNER[w.position], display: 'flex', flexDirection: 'column', color: colour || '#fff' }}>
<Widget w={w} media={media} venue={venue} now={now} />
</div>
))}
</>
)
}
const ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning }
function Widget({ w, media, venue, now }) {
const { formatDate, formatTime } = useFormat()
const s = SIZE[w.size] || 1
const text = { fontSize: `${3.4 * s}vmin`, fontWeight: 700, lineHeight: 1.15, textShadow: '0 0.2vmin 0.8vmin rgba(0,0,0,0.35)' }
if (w.kind === 'logo') {
const m = media(w.media_id)
return m ? <img src={m.src} alt="" style={{ height: `${9 * s}vmin`, maxWidth: `${30 * s}vmin`, objectFit: 'contain' }} data-testid="signage-w-logo" /> : null
}
if (w.kind === 'name') return venue?.name ? <span style={{ ...text, fontSize: `${4.2 * s}vmin` }} data-testid="signage-w-name">{venue.name}</span> : null
if (w.kind === 'date') return <span style={text} data-testid="signage-w-date">{formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong')}</span>
if (w.kind === 'clock') return <span style={{ ...text, fontSize: `${4.6 * s}vmin`, fontVariantNumeric: 'tabular-nums' }} data-testid="signage-w-clock">{formatTime(now, w.clock_seconds ? 'timeSeconds' : 'time')}</span>
if (w.kind === 'message') {
const msg = w.text || venue?.message
return msg ? <span style={{ ...text, fontWeight: 600 }} data-testid="signage-w-message">{msg}</span> : null
}
if (w.kind === 'qr') {
return w.link ? (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.8vmin' }} data-testid="signage-w-qr" data-link={w.link}>
<div style={{ background: '#fff', padding: '1vmin', borderRadius: '1vmin', lineHeight: 0 }}>
<QRCodeSVG value={w.link} size={256} style={{ width: `${14 * s}vmin`, height: `${14 * s}vmin` }} />
</div>
{w.qr_caption && <span style={{ ...text, fontSize: `${2.4 * s}vmin` }}>{w.qr_caption}</span>}
</div>
) : null
}
if (w.kind === 'weather') {
const wx = venue?.weather
if (!wx || wx.temperature == null) return null // no internet / no place: hidden (5.4c)
const Icon = ICONS[weatherIcon(wx.code, wx.is_day)] || Cloud
const deg = wx.units === 'fahrenheit' ? '°F' : '°C'
return (
<div style={{ display: 'flex', alignItems: 'center', gap: '1.5vmin' }} data-testid="signage-w-weather">
<Icon style={{ width: `${6 * s}vmin`, height: `${6 * s}vmin` }} aria-hidden="true" />
<span style={{ ...text, fontSize: `${4.4 * s}vmin` }}>{Math.round(wx.temperature)}{deg}</span>
{(w.weather_days || 1) > 1 && (wx.days || []).slice(1, w.weather_days).map(d => {
const DayIcon = ICONS[weatherIcon(d.code, true)] || Cloud
return (
<span key={d.date} style={{ display: 'flex', alignItems: 'center', gap: '0.6vmin', ...text, fontSize: `${2.4 * s}vmin`, fontWeight: 600 }}>
{formatDate(`${d.date}T12:00:00Z`, 'weekday').slice(0, 3)} <DayIcon style={{ width: `${3.4 * s}vmin`, height: `${3.4 * s}vmin` }} aria-hidden="true" />
{Math.round(d.max)}° / {Math.round(d.min)}°
</span>
)
})}
</div>
)
}
return null
}
-202
View File
@@ -1,202 +0,0 @@
// The signage player's logic (plan step 5.5a). Pure: unit-tested in Node (tests/signage.test.mjs).
// The schedule rules are the server's (local_backend/services/signage_schedule.py) so a screen
// switches playlists by itself while the server is down; the same cases are tested on both sides.
/** The venue's local clock at `date`: { weekday (0 = Monday), minutes, date: "YYYY-MM-DD" }. */
export function localNow(timeZone, date = new Date()) {
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', {
timeZone: timeZone || undefined, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit',
weekday: 'short', hourCycle: 'h23',
}).formatToParts(date).map(p => [p.type, p.value]))
const weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(parts.weekday)
return { weekday, minutes: Number(parts.hour) * 60 + Number(parts.minute), date: `${parts.year}-${parts.month}-${parts.day}` }
}
/** The day before a local moment (for windows that pass midnight). */
function yesterday(local) {
const d = new Date(`${local.date}T12:00:00Z`)
d.setUTCDate(d.getUTCDate() - 1)
return { weekday: (local.weekday + 6) % 7, minutes: local.minutes, date: d.toISOString().slice(0, 10) }
}
const mins = hhmm => {
if (!hhmm) return null
const [h, m] = hhmm.split(':').map(Number)
return h * 60 + m
}
function dayOk(w, local) {
const days = w.days || []
return (!days.length || days.includes(local.weekday)) &&
(!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to)
}
/** Does a window (days, time_from / time_to that may pass midnight, date_from / date_to) cover `local`? */
export function matches(w, local) {
let start = mins(w.time_from)
let end = mins(w.time_to)
if (start == null && end == null) return dayOk(w, local)
start = start ?? 0
end = end ?? 24 * 60
if (start < end) return local.minutes >= start && local.minutes < end && dayOk(w, local)
if (local.minutes >= start) return dayOk(w, local)
if (local.minutes < end) return dayOk(w, yesterday(local))
return false
}
const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + (e.days?.length ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0)
/** The playlist a schedule plays at `local`: highest priority, then the most specific, then the later entry. */
export function pick(entries, fallback, local) {
let best = null
let bestKey = null
;(entries || []).forEach((e, i) => {
if (e.playlist_id == null || !matches(e, local)) return
const key = [e.priority || 0, specific(e), i]
if (!bestKey || key[0] > bestKey[0] || (key[0] === bestKey[0] && (key[1] > bestKey[1] || (key[1] === bestKey[1] && key[2] > bestKey[2])))) {
best = e.playlist_id
bestKey = key
}
})
return best ?? fallback ?? null
}
/** The playlist to play now from the screen's answer (GET /api/signage/screen). */
export function playlistNow(data, now = new Date()) {
if (!data) return null
if (!data.schedule) return data.playlist || null
const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now))
return id != null ? data.playlists?.[String(id)] ?? null : null
}
/** A slide may show now: its own window (days / hours / dates), in venue time. */
export function slideShows(slide, local) {
return matches({ days: slide.days, time_from: slide.time_from, time_to: slide.time_to, date_from: slide.date_from, date_to: slide.date_to }, local)
}
/** The index of the next slide that may show after `current` (wrapping), or -1 when none may. */
export function nextSlide(slides, current, local) {
const n = slides?.length || 0
for (let step = 1; step <= n; step++) {
const i = (((current ?? -1) + step) % n + n) % n
if (slideShows(slides[i], local)) return i
}
return -1
}
/** How long a slide stays, in ms; null = until its video ends (with a safety limit in the player). */
export function slideMs(slide) {
if (slide.kind === 'video' && slide.video_to_end) return null
return Math.max(2, slide.duration_s || 10) * 1000
}
/** The frame's size and turn for a screen: CSS for the box that holds the slides. */
export function frameStyle(rotation) {
const r = Number(rotation) || 0
if (r === 90 || r === 270) {
return { width: '100vh', height: '100vw', transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', position: 'absolute' }
}
return { width: '100vw', height: '100vh', transform: r === 180 ? 'rotate(180deg)' : undefined, top: 0, left: 0, position: 'absolute' }
}
/** Every media address a playlist (or a schedule's playlists) needs, to keep on the device. */
export function mediaUrls(data) {
if (!data) return []
const lists = data.schedule ? Object.values(data.playlists || {}) : (data.playlist ? [data.playlist] : [])
const out = new Set()
for (const p of lists) for (const m of Object.values(p.media || {})) if (m.url) out.add(m.url)
return [...out]
}
/** The fonts a slide can choose (all on the device: nothing to download, works offline). */
export const FONTS = {
sans: 'system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
serif: 'Georgia, "Times New Roman", serif',
rounded: 'ui-rounded, "SF Pro Rounded", "Arial Rounded MT Bold", system-ui, sans-serif',
condensed: '"Arial Narrow", "Roboto Condensed", "Helvetica Neue", sans-serif',
display: 'Impact, "Arial Black", system-ui, sans-serif',
}
// ── menu boards (5.5b) ───────────────────────────────────────────────────────
/** The frame's height in vmin (its shorter side is 100) for a screen w × h: 100 when wide, ~178 when tall (16:9). */
export function frameHeightVmin(rotation, w = 16, h = 9) {
const turned = Number(rotation) === 90 || Number(rotation) === 270
const frameTall = turned ? w > h : h > w // the screen's sides, swapped when the picture is turned
return frameTall ? (100 * Math.max(w, h)) / Math.min(w, h) : 100
}
/**
* How many rows fit in one column of a menu board: rows are items (taller with a photo or a
* description) and group headings. Sizes in vmin, as the board draws them.
*/
export function rowsPerColumn({ heightVmin = 100, textSize = 100, photos = false, descriptions = false, title = false, bars = 0 }) {
const s = (textSize || 100) / 100
const row = (photos ? 8 : descriptions ? 7 : 4.8) * s
const used = 10 + (title ? 11 * s : 0) + bars * 9 // padding, the title, top / bottom bars of widgets
return Math.max(3, Math.floor((heightVmin - used) / row))
}
/**
* The board's pages: groups split into pages of at most `perPage` rows (a heading counts as a
* row; a group cut in two repeats its heading on the next page). → [[{category, items}], …]
*/
export function menuPages(groups, perPage, headings = true) {
const per = Math.max(1, perPage | 0)
const pages = []
let page = []
let used = 0
const flush = () => { if (page.length) pages.push(page); page = []; used = 0 }
for (const g of groups || []) {
let items = [...(g.items || [])]
if (!items.length) continue
while (items.length) {
const head = headings && g.category ? 1 : 0
if (used + head + 1 > per) flush()
const room = per - used - head
const take = items.slice(0, Math.max(1, room))
page.push({ category: g.category, items: take })
used += head + take.length
items = items.slice(take.length)
if (items.length) flush()
}
}
flush()
return pages
}
/** A menu slide's time: every page for its seconds, at least the slide's own time. */
export function menuMs(slide, pageCount) {
const per = Math.max(3, slide.content?.page_seconds || 10) * 1000
return Math.max(slideMs(slide), pageCount > 1 ? pageCount * per : 0)
}
/** The page on screen `elapsedMs` into the slide (the pages go round while the slide lasts). */
export function pageAt(pageCount, pageSeconds, elapsedMs) {
if (pageCount <= 1 || !(elapsedMs > 0)) return 0 // the clock's last tick may be just before the slide began
return Math.floor(elapsedMs / (Math.max(3, pageSeconds || 10) * 1000)) % pageCount // round and round while the slide lasts
}
/** A weather code (WMO, as Open-Meteo sends it) → an icon name for the widget. */
export function weatherIcon(code, isDay = true) {
if (code == null) return 'cloud'
if (code === 0) return isDay ? 'sun' : 'moon'
if (code <= 2) return isDay ? 'cloud-sun' : 'cloud-moon'
if (code === 3) return 'cloud'
if (code === 45 || code === 48) return 'fog'
if ((code >= 51 && code <= 67) || (code >= 80 && code <= 82)) return 'rain'
if ((code >= 71 && code <= 77) || code === 85 || code === 86) return 'snow'
if (code >= 95) return 'storm'
return 'cloud'
}
/** A menu slide's pages for this screen (w × h pixels, turned by `rotation`). */
export function boardPages(slide, rotation, w, h) {
const c = slide.content || {}
const widgets = c.widgets || []
const bars = ['top-bar', 'bottom-bar'].filter(p => widgets.some(x => x.position === p)).length
const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: c.text_size, photos: c.show_photos,
descriptions: c.show_descriptions, title: !!c.title, bars })
const per = c.page_size || rows * (c.columns || 2)
return menuPages(slide.menu?.groups || [], per, c.category_titles !== false)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import xenia from '@xenia/ui/tailwind-preset'
export default {
// Shared design tokens only (bg-surface, text-ink-2, rounded-control…), CS-16
presets: [xenia],
content: ['./index.html', './src/**/*.{js,jsx}'],
content: ['./index.html', './src/**/*.{js,jsx}', '../packages/signage/src/**/*.{js,jsx}'], // signage slides use a few utilities (5.6a)
theme: { extend: {} },
plugins: [],
}
-119
View File
@@ -1,119 +0,0 @@
// The signage player's logic (plan step 5.5a): the same schedule cases as the server's
// local_backend/tests/test_signage_schedule.py, slide windows, the next slide, the frame.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { boardPages, frameHeightVmin, frameStyle, localNow, matches, mediaUrls, menuMs, menuPages, nextSlide, pageAt, pick, playlistNow, rowsPerColumn, slideMs, weatherIcon } from '../src/apps/signage/logic.js'
const at = (date, hhmm) => {
const d = new Date(`${date}T12:00:00Z`)
const [h, m] = hhmm.split(':').map(Number)
return { weekday: (d.getUTCDay() + 6) % 7, minutes: h * 60 + m, date }
}
const MON_10 = at('2026-11-16', '10:00')
const MON_13 = at('2026-11-16', '13:00')
const SAT_13 = at('2026-11-21', '13:00')
const SAT_23 = at('2026-11-21', '23:30')
const SUN_01 = at('2026-11-22', '01:00')
const MON_01 = at('2026-11-16', '01:00')
test('the venue clock in its own time zone', () => {
const l = localNow('Europe/Athens', new Date('2026-11-16T22:30:00Z')) // 00:30 on Tuesday in Athens
assert.deepEqual(l, { weekday: 1, minutes: 30, date: '2026-11-17' })
})
test('which windows match (the server\'s cases)', () => {
const lunch = { time_from: '12:00', time_to: '15:00' }
assert.ok(matches(lunch, MON_13) && !matches(lunch, MON_10))
const night = { days: [5], time_from: '22:00', time_to: '02:00' }
assert.ok(matches(night, SAT_23) && matches(night, SUN_01) && !matches(night, MON_01))
const xmas = { date_from: '2026-12-20', date_to: '2026-12-27' }
assert.ok(matches(xmas, at('2026-12-24', '20:00')) && !matches(xmas, at('2026-12-28', '09:00')))
assert.ok(matches({}, MON_10))
assert.ok(matches({ time_from: '18:00' }, at('2026-11-16', '23:59')))
})
test('the schedule\'s winner (the server\'s cases)', () => {
const entries = [{ playlist_id: 10, time_from: '12:00', time_to: '15:00' }, { playlist_id: 20, days: [5, 6] },
{ playlist_id: 30, days: [5, 6], time_from: '12:00', time_to: '15:00' },
{ playlist_id: 40, date_from: '2026-11-21', date_to: '2026-11-21', priority: 5 }]
assert.equal(pick(entries, 99, MON_10), 99)
assert.equal(pick(entries, 99, MON_13), 10)
assert.equal(pick(entries, 99, at('2026-11-22', '13:00')), 30)
assert.equal(pick(entries, 99, SAT_13), 40)
assert.equal(pick(entries, null, MON_10), null)
})
test('the playlist now, alone or from a schedule', () => {
assert.equal(playlistNow({ playlist: { id: 1 } }).id, 1)
const data = { schedule: { timezone: 'Europe/Athens', entries: [{ playlist_id: 2, time_from: '12:00', time_to: '15:00' }], fallback_playlist_id: 3 },
playlists: { 2: { id: 2 }, 3: { id: 3 } } }
assert.equal(playlistNow(data, new Date('2026-11-16T11:00:00Z')).id, 2) // 13:00 in Athens
assert.equal(playlistNow(data, new Date('2026-11-16T08:00:00Z')).id, 3)
assert.equal(playlistNow(null), null)
})
test('the next slide skips the ones outside their window, and wraps', () => {
const slides = [{ id: 1 }, { id: 2, time_from: '12:00', time_to: '15:00' }, { id: 3, days: [0] }]
assert.equal(nextSlide(slides, -1, MON_10), 0)
assert.equal(nextSlide(slides, 0, MON_10), 2) // 2 is a lunch slide
assert.equal(nextSlide(slides, 2, MON_10), 0)
assert.equal(nextSlide(slides, 0, MON_13), 1)
assert.equal(nextSlide([{ id: 1, days: [6] }], -1, MON_10), -1)
assert.equal(nextSlide([], -1, MON_10), -1)
})
test('how long a slide stays; the frame for a turned TV; what to keep on the device', () => {
assert.equal(slideMs({ kind: 'text', duration_s: 8 }), 8000)
assert.equal(slideMs({ kind: 'video', video_to_end: true, duration_s: 8 }), null)
assert.equal(slideMs({ kind: 'image' }), 10000)
assert.equal(frameStyle(90).width, '100vh')
assert.equal(frameStyle(0).width, '100vw')
assert.equal(frameStyle(180).transform, 'rotate(180deg)')
const data = { schedule: {}, playlists: { 1: { media: { 5: { url: '/a' } } }, 2: { media: { 6: { url: '/b' }, 5: { url: '/a' } } } } }
assert.deepEqual(mediaUrls(data).sort(), ['/a', '/b'])
assert.deepEqual(mediaUrls({ playlist: null }), [])
})
test('a menu board in pages: headings count, a cut group repeats its heading', () => {
const g = [{ category: { id: 1, name: 'A' }, items: [1, 2, 3, 4, 5, 6, 7].map(id => ({ id })) }, { category: { id: 2, name: 'B' }, items: [{ id: 9 }] }]
const pages = menuPages(g, 4)
assert.deepEqual(pages.map(p => p.map(x => [x.category.name, x.items.length])), [[['A', 3]], [['A', 3]], [['A', 1], ['B', 1]]])
assert.deepEqual(menuPages(g, 4, false).map(p => p.reduce((n, x) => n + x.items.length, 0)), [4, 4])
assert.deepEqual(menuPages([], 4), [])
assert.equal(menuPages([{ category: null, items: [{ id: 1 }] }], 10).length, 1)
})
test('rows that fit: taller screens and smaller text fit more, photos fewer', () => {
assert.equal(frameHeightVmin(0, 1920, 1080), 100)
assert.ok(Math.abs(frameHeightVmin(0, 1080, 1920) - 177.8) < 0.1)
assert.ok(Math.abs(frameHeightVmin(90, 1920, 1080) - 177.8) < 0.1) // a wide TV turned: a tall frame
const base = rowsPerColumn({ heightVmin: 100 })
assert.ok(rowsPerColumn({ heightVmin: 178 }) > base && rowsPerColumn({ heightVmin: 100, textSize: 70 }) > base)
assert.ok(rowsPerColumn({ heightVmin: 100, photos: true }) < base && rowsPerColumn({ heightVmin: 100, bars: 2 }) < base)
assert.ok(rowsPerColumn({ heightVmin: 10 }) >= 3)
const slide = { kind: 'menu', content: { columns: 1, page_size: 5 }, menu: { groups: [{ category: null, items: Array.from({ length: 12 }, (_, i) => ({ id: i })) }] } }
assert.equal(boardPages(slide, 0, 1920, 1080).length, 3)
})
test('a menu slide stays for all its pages; the page on screen', () => {
const slide = { kind: 'menu', duration_s: 10, content: { page_seconds: 8 } }
assert.equal(menuMs(slide, 1), 10_000)
assert.equal(menuMs(slide, 3), 24_000)
assert.equal(pageAt(3, 8, 0), 0)
assert.equal(pageAt(3, 8, 8_100), 1)
assert.equal(pageAt(3, 8, 16_500), 2)
assert.equal(pageAt(3, 8, 24_100), 0) // round again on a long slide
assert.equal(pageAt(1, 8, 99_000), 0)
assert.equal(pageAt(3, 8, -400), 0)
})
test('weather codes → icons', () => {
assert.equal(weatherIcon(0, true), 'sun')
assert.equal(weatherIcon(0, false), 'moon')
assert.equal(weatherIcon(2), 'cloud-sun')
assert.equal(weatherIcon(61), 'rain')
assert.equal(weatherIcon(73), 'snow')
assert.equal(weatherIcon(95), 'storm')
assert.equal(weatherIcon(45), 'fog')
assert.equal(weatherIcon(null), 'cloud')
})