Files
xenia-pos-local/terminal/src/apps/signage/SignageApp.jsx
T
bonaminandClaude Opus 5.5 314e9c2457 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>
2026-11-17 20:59:33 +02:00

192 lines
8.7 KiB
React

// The signage player (plan step 5.5a): a TV paired as a signage screen, no sign-in. It plays its
// playlist (or the playlist its schedule picks now) full screen: slides in order, each for its
// time (a video to its end), with its transition, only on its days / hours / dates; turned for a
// TV mounted sideways. Everything it needs is kept on the device: the last answer of
// GET /api/signage/screen in localStorage and every picture and video as an in-memory copy, so it
// keeps playing (and switching by its schedule) while the server is down, and catches up on
// `signage.changed`, a reconnect, or every few minutes (prices that change by time alone).
// Menu boards page by themselves when they don't fit (5.5b); widgets sit in corners and bars.
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, SlideView, slideMs } from '@xenia/signage'
const quiet = { xenia: { noOverride: true } }
const CACHE_KEY = 'xenia:signage:screen'
const REFRESH_MS = 5 * 60_000
const VIDEO_MAX_MS = 15 * 60_000 // a video "to its end" that never ends moves on after this
const KEEP_VIDEO_BYTES = 120 * 1024 * 1024 // bigger videos stream from the server (not kept offline)
const TRANSITION_MS = 800
function readCache() {
try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null }
}
function writeCache(data) {
try { localStorage.setItem(CACHE_KEY, JSON.stringify(data)) } catch { /* full or blocked: the memory copy still plays */ }
}
/** url → an in-memory copy (object URL) of every file the playlists need; old copies are let go. */
function useKeptMedia(urls) {
const [kept, setKept] = useState({})
const keptRef = useRef({})
const key = urls.slice().sort().join('|')
useEffect(() => {
let live = true
const wanted = key ? key.split('|') : []
;(async () => {
for (const url of wanted) {
if (keptRef.current[url]) continue
try {
const res = await fetch(url)
if (!res.ok) continue
const size = Number(res.headers.get('content-length') || 0)
if (size > KEEP_VIDEO_BYTES) continue
const blob = await res.blob()
if (!live) return
keptRef.current = { ...keptRef.current, [url]: URL.createObjectURL(blob) }
setKept(keptRef.current)
} catch { /* offline: the next answer tries again; the address still works while online */ }
}
const gone = Object.keys(keptRef.current).filter(u => !wanted.includes(u))
if (gone.length) {
const next = { ...keptRef.current }
for (const u of gone) { URL.revokeObjectURL(next[u]); delete next[u] }
keptRef.current = next
if (live) setKept(next)
}
})()
return () => { live = false }
}, [key])
useEffect(() => () => Object.values(keptRef.current).forEach(u => URL.revokeObjectURL(u)), [])
return kept
}
export default function SignageApp() {
const { t } = useTranslation('terminal')
const { offline } = useDevice()
const [data, setData] = useState(readCache)
const [now, setNow] = useState(() => new Date())
const load = useCallback(async () => {
try {
const { data: d } = await client.get('/api/signage/screen', quiet)
setData(prev => (prev?.version === d.version ? prev : d))
writeCache(d)
} catch { /* keep playing what we have */ }
}, [])
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents(['signage.changed', 'device.updated'], load)
useEffect(() => {
const id = setInterval(load, REFRESH_MS)
return () => clearInterval(id)
}, [load])
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000)
return () => clearInterval(id)
}, [])
const kept = useKeptMedia(useMemo(() => mediaUrls(data), [data]))
const playlist = playlistNow(data, now)
const tz = data?.schedule?.timezone
const screen = data?.screen
return (
<main className="fixed inset-0 overflow-hidden select-none cursor-none" style={{ background: '#000' }}
data-testid="app-signage" data-playlist={playlist?.id ?? ''} data-orientation={screen?.orientation ?? ''} data-offline={offline ? 'true' : 'false'}>
<div style={frameStyle(screen?.rotation)} data-testid="signage-frame" data-rotation={screen?.rotation ?? 0}>
{playlist?.slides?.length
? <Player key={playlist.id} playlist={playlist} kept={kept} tz={tz} venue={data?.venue} now={now} rotation={screen?.rotation} />
: <Empty text={data ? t('signage.nothing') : t('signage.starting')} />}
</div>
</main>
)
}
function Empty({ text }) {
return (
<div className="absolute inset-0 flex items-end justify-end p-4" data-testid="signage-empty">
<span style={{ color: 'rgba(255,255,255,0.25)', fontSize: '1.4vmin' }}>{text}</span>
</div>
)
}
/** Plays one playlist: the current slide, the next when its time is up, with the transition. */
function useWindowSize() {
const [size, setSize] = useState(() => ({ w: window.innerWidth, h: window.innerHeight }))
useEffect(() => {
const on = () => setSize({ w: window.innerWidth, h: window.innerHeight })
window.addEventListener('resize', on)
return () => window.removeEventListener('resize', on)
}, [])
return size
}
function Player({ playlist, kept, tz, venue, now, rotation }) {
const local = localNow(tz, now)
const slides = playlist.slides
const size = useWindowSize()
const pagesOf = useCallback(sl => (sl?.kind === 'menu' ? boardPages(sl, rotation, size.w, size.h) : null), [rotation, size])
const [cur, setCur] = useState(() => ({ index: nextSlide(slides, -1, local), at: Date.now(), n: 0 }))
const [prev, setPrev] = useState(null)
const media = id => {
const m = playlist.media?.[String(id)]
return m ? { ...m, src: kept[m.url] || m.url } : null
}
const curRef = useRef(cur)
useEffect(() => { curRef.current = cur })
const advance = useCallback(() => {
const c = curRef.current
const next = nextSlide(slides, c.index, localNow(tz, new Date()))
setPrev(c.index >= 0 ? c : null)
setCur({ index: next, at: Date.now(), n: c.n + 1 })
}, [slides, tz])
// the slide list changed (an edit): keep going from a slide that still exists
useEffect(() => {
setCur(c => (c.index >= 0 && c.index < slides.length ? c : { index: nextSlide(slides, -1, localNow(tz, new Date())), at: Date.now(), n: c.n + 1 }))
}, [slides, tz])
const slide = cur.index >= 0 ? slides[cur.index] : null
// time's up (videos to their end call advance themselves, with a safety limit)
useEffect(() => {
if (!slide) return undefined
const ms = slide.kind === 'menu' ? menuMs(slide, pagesOf(slide).length) : (slideMs(slide) ?? VIDEO_MAX_MS)
const id = setTimeout(advance, ms)
return () => clearTimeout(id)
}, [slide, cur.n, advance, pagesOf])
// a slide that may no longer show (its window ended) is skipped at once; none showing → wait
useEffect(() => {
if (cur.index < 0 && nextSlide(slides, -1, local) >= 0) advance()
}, [cur.index, slides, local.minutes, advance]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!prev) return undefined
const id = setTimeout(() => setPrev(null), TRANSITION_MS)
return () => clearTimeout(id)
}, [prev])
if (!slide) return <Empty text="" />
const transition = slide.transition || playlist.transition || 'fade'
return (
<>
{prev && slides[prev.index] && (
<Layer key={`out-${prev.n}`} slide={slides[prev.index]} media={media} venue={venue} now={now} className={`sg-out sg-out-${transition}`}
pages={pagesOf(slides[prev.index])} page={pageAt(pagesOf(slides[prev.index])?.length || 0, slides[prev.index].content?.page_seconds, cur.at - prev.at - 1)} />
)}
<Layer key={`in-${cur.n}`} slide={slide} media={media} venue={venue} now={now} onEnded={advance}
className={cur.n === 0 ? '' : `sg-in sg-in-${transition}`} current
pages={pagesOf(slide)} page={pageAt(pagesOf(slide)?.length || 0, slide.content?.page_seconds, now.getTime() - cur.at)} />
</>
)
}
function Layer({ slide, media, venue, now, onEnded, className, current = false, pages, page }) {
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}>
<SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={page} onEnded={current ? onEnded : undefined} />
</section>
)
}