feat(signage): Slides library, widgets placed on the preview, blank slides, slide editor rework

- Slides library (Alembic 0044, /api/signage/library): slides kept with a name and a
  description, added to playlists as copies ("Add a slide" → Your slides, "Keep in Slides"),
  or shown alone as a screen's default (device config `slide`, played as "slide:<id>",
  also as a schedule's fallback). Signage → Slides: gallery + a two-pane editor.
- Widgets moved and sized by hand on the preview (WidgetCanvas: handles, snapping, arrow
  keys): position/size "custom" with a box the TV draws the same; alignment per widget.
- Blank slides (background + widgets); menu boards narrower and placed left/centre/right.
- Slide editor reworked: name | show, transition effect | seconds; sections; text look on
  one row with ready colours; one card per widget, settings on one row.
- Questions inside the page (@xenia/ui ConfirmDialog/useConfirm), Switch boxed, Segmented
  fill; the timeline's drop line; schedule lines run on weekdays or smart days, not both;
  the playlist editor stays within 1080p with a long timeline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 07:53:27 +02:00
co-authored by Claude Opus 5.5
parent 60e6a16217
commit 83551714f7
46 changed files with 1934 additions and 431 deletions
+3
View File
@@ -57,6 +57,9 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) | | A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) |
| A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline | | A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline |
| Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` | | Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` |
| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component |
| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right |
| Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` |
| A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` | | A side drawer | `Sheet side="right"` (`size="wide"`: 600 px) | the permissions editor is `wide` |
| Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box | | Something that stays at the top of a dialog or drawer | `toolbar` (Dialog / Sheet) | under the title, doesn't scroll: the permissions' search box |
| A control beside a dialog's close button | `headerEnd` (Dialog / Sheet) | the product editor's language picker | | A control beside a dialog's close button | `headerEnd` (Dialog / Sheet) | the product editor's language picker |
@@ -55,6 +55,9 @@ def _ref_exists(source: str, value: int, db) -> bool:
if source == "signage_playlists": if source == "signage_playlists":
from models.signage import SignagePlaylist from models.signage import SignagePlaylist
return db.get(SignagePlaylist, value) is not None return db.get(SignagePlaylist, value) is not None
if source == "signage_slides":
from models.signage import SignageSavedSlide
return db.get(SignageSavedSlide, value) is not None
if source == "tables": if source == "tables":
from models.table import Table from models.table import Table
t = db.get(Table, value) t = db.get(Table, value)
@@ -0,0 +1,46 @@
"""The signage Slides library (owner 2026-11-21): slides kept with a name and a description, added
to playlists as copies or shown alone as a screen's default (device config `slide`).
Revision ID: 0044_signage_saved_slides
Revises: 0043_scenes_and_schedule_items
Create Date: 2026-11-21 22:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0044_signage_saved_slides'
down_revision = '0043_scenes_and_schedule_items'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
'signage_saved_slides',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('orientation', sa.String(), nullable=False),
sa.Column('kind', sa.String(), nullable=False),
sa.Column('duration_s', sa.Integer(), nullable=False),
sa.Column('transition', sa.String(), nullable=True),
sa.Column('video_to_end', sa.Boolean(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.Column('days', sa.JSON(), nullable=True),
sa.Column('time_from', sa.String(), nullable=True),
sa.Column('time_to', sa.String(), nullable=True),
sa.Column('date_from', sa.String(), nullable=True),
sa.Column('date_to', sa.String(), nullable=True),
sa.Column('content', sa.JSON(), nullable=False),
sa.Column('created_at', UTCDateTime(), nullable=False),
sa.Column('updated_at', UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_signage_saved_slides_id', 'signage_saved_slides', ['id'])
def downgrade() -> None:
op.drop_index('ix_signage_saved_slides_id', table_name='signage_saved_slides')
op.drop_table('signage_saved_slides')
+1 -1
View File
@@ -40,7 +40,7 @@ import models.fees # noqa: F401 DeliveryArea, FeeRule (phase 3S, S.3)
import models.refund # noqa: F401 Refund, RefundItem (step 3.3e) import models.refund # noqa: F401 Refund, RefundItem (step 3.3e)
import models.media # noqa: F401 Media (media library, step 5.1) import models.media # noqa: F401 Media (media library, step 5.1)
import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3) import models.display_look # noqa: F401 DisplayLook (customer display looks, step 5.3)
import models.signage # noqa: F401 SignagePlaylist, SignageSlide (signage, step 5.4a) import models.signage # noqa: F401 SignagePlaylist, SignageSlide, SignageSavedSlide (signage, 5.4a; library 2026-11-21)
import models.scene # noqa: F401 Scene (2026-11-21) import models.scene # noqa: F401 Scene (2026-11-21)
import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6) import models.tablet_order # noqa: F401 TabletOrder (ordering from a menu tablet, step 6.6)
import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8) import models.floor_plan # noqa: F401 FloorPlan, FloorItem (the table map, step 6.8)
+26
View File
@@ -78,3 +78,29 @@ class SignageScheduleItem(Base):
position = Column(Integer, nullable=False, default=0) position = Column(Integer, nullable=False, default=0)
created_at = Column(UTCDateTime, default=utcnow, nullable=False) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
class SignageSavedSlide(Base):
"""A slide kept in the Slides library (owner 2026-11-21): built once, with a name and a short
description, then added to playlists (a copy goes in) or shown alone on a screen that has it
as its default (device config `slide`). The same fields as a playlist's slide, plus the shape
it is built for (its preview and the picture-fit warnings)."""
__tablename__ = "signage_saved_slides"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
description = Column(String, nullable=True)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
kind = Column(String, nullable=False) # menu | image | video | text | blank
duration_s = Column(Integer, nullable=False, default=10)
transition = Column(String, nullable=True)
video_to_end = Column(Boolean, nullable=False, default=False)
enabled = Column(Boolean, nullable=False, default=True)
days = Column(JSON, nullable=True)
time_from = Column(String, nullable=True)
time_to = Column(String, nullable=True)
date_from = Column(String, nullable=True)
date_to = Column(String, nullable=True)
content = Column(JSON, nullable=False, default=dict)
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
@@ -27,6 +27,8 @@ MODULE = Module(
device_app=DeviceApp(login_modes=('none',), scope=(), config=( device_app=DeviceApp(login_modes=('none',), scope=(), config=(
# What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape # What it plays and how the TV hangs (5.4a); the editor builds for the screen's shape
ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'), ConfigField('playlist', 'ref', default=None, choices_from='signage_playlists'),
# ... or a library slide shown alone (owner 2026-11-21; a playlist wins when both are set)
ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
)), )),
+242 -18
View File
@@ -12,8 +12,14 @@ Manager side (signage.manage):
PUT /api/signage/slides/{id} change it PUT /api/signage/slides/{id} change it
DELETE /api/signage/slides/{id} DELETE /api/signage/slides/{id}
POST /api/signage/slides/{id}/duplicate a copy right after it POST /api/signage/slides/{id}/duplicate a copy right after it
GET /api/signage/screens the paired screens: playlist, orientation, rotation GET /api/signage/library the Slides library (2026-11-21): kept slides
PUT /api/signage/screens/{id} {playlist_id, orientation, rotation} POST /api/signage/library {name, description, orientation, kind, …slide fields}
GET /api/signage/library/{id} one (a menu board resolved for its preview)
PUT /api/signage/library/{id} change it (a screen showing it is told)
DELETE /api/signage/library/{id} screens that had it as their default show nothing
POST /api/signage/library/{id}/duplicate a copy
GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation
PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation}
The screen (a paired device running `signage`, no sign-in): The screen (a paired device running `signage`, no sign-in):
GET /api/signage/screen its playlist resolved for playing GET /api/signage/screen its playlist resolved for playing
@@ -29,13 +35,13 @@ import json
from typing import Dict, List, Literal, Optional from typing import Dict, List, Literal, Optional
from fastapi import APIRouter, Depends, Response from fastapi import APIRouter, Depends, Response
from pydantic import BaseModel, ConfigDict, Field, field_validator from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.access.deps import require, require_device from core.access.deps import require, require_device
from core.errors import XeniaError from core.errors import XeniaError
from database import get_db from database import get_db
from models.signage import SignagePlaylist, SignageScheduleItem, SignageSlide from models.signage import SignagePlaylist, SignageSavedSlide, SignageScheduleItem, SignageSlide
from services import media as media_store from services import media as media_store
from services import video as video_store from services import video as video_store
from services.ws_bus import broadcast_sync from services.ws_bus import broadcast_sync
@@ -66,14 +72,34 @@ class Background(_Strict):
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"] WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"]
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar"] Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
class Box(_Strict):
"""Where a widget moved by hand sits (2026-11-21): % of the slide's width / height."""
x: float = Field(ge=0, le=100)
y: float = Field(ge=0, le=100)
w: float = Field(ge=2, le=100)
h: float = Field(ge=2, le=100)
@model_validator(mode="after")
def _inside(self):
# kept on the slide: a box never runs past its right or bottom edge
self.w = round(min(self.w, 100), 2)
self.h = round(min(self.h, 100), 2)
self.x = round(min(self.x, 100 - self.w), 2)
self.y = round(min(self.y, 100 - self.h), 2)
return self
class Widget(_Strict): class Widget(_Strict):
"""Something small on a menu or text slide (5.4c), in a corner or a bar.""" """Something small on a menu, text or blank slide (5.4c), in a corner or a bar, or (moved and
sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom"."""
kind: WidgetKind kind: WidgetKind
position: Position = "top-right" position: Position = "top-right"
size: Literal["small", "medium", "large"] = "medium" size: Literal["small", "medium", "large", "custom"] = "medium"
box: Optional[Box] = None # position "custom"
align: Literal["auto", "left", "center", "right"] = "auto" # inside its place; auto: by its corner / box
media_id: Optional[int] = None # logo: a picture media_id: Optional[int] = None # logo: a picture
text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's text: Optional[str] = Field(default=None, max_length=200) # message: this text instead of the venue's
date_style: Literal["short", "long"] = "long" date_style: Literal["short", "long"] = "long"
@@ -83,6 +109,18 @@ class Widget(_Strict):
qr_caption: Optional[str] = Field(default=None, max_length=80) qr_caption: Optional[str] = Field(default=None, max_length=80)
weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days weather_days: int = Field(default=1, ge=1, le=3) # today, or today + the next days
@model_validator(mode="after")
def _place(self):
if self.position == "custom":
if self.box is None:
raise ValueError("a widget placed by hand needs its box")
self.size = "custom"
else:
self.box = None
if self.size == "custom":
self.size = "medium"
return self
@field_validator("qr_url") @field_validator("qr_url")
@classmethod @classmethod
def _url(cls, v): def _url(cls, v):
@@ -118,6 +156,12 @@ class TextContent(_Strict):
widgets: List[Widget] = Field(default_factory=list, max_length=10) widgets: List[Widget] = Field(default_factory=list, max_length=10)
class BlankContent(_Strict):
"""A blank slide (2026-11-21): only its background and its widgets."""
background: Background = Field(default_factory=Background)
widgets: List[Widget] = Field(default_factory=list, max_length=10)
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"] Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
@@ -143,6 +187,8 @@ class MenuContent(_Strict):
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# how it's laid out (the player pages through what doesn't fit, 5.5b) # how it's laid out (the player pages through what doesn't fit, 5.5b)
columns: int = Field(default=2, ge=1, le=3) columns: int = Field(default=2, ge=1, le=3)
board_width: int = Field(default=100, ge=40, le=100) # % of the screen the list takes (2026-11-21)
board_align: Literal["left", "center", "right"] = "left" # where a narrower list sits, and its title
page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit
page_seconds: int = Field(default=10, ge=3, le=120) page_seconds: int = Field(default=10, ge=3, le=120)
font: Font = "sans" font: Font = "sans"
@@ -168,8 +214,8 @@ class MenuContent(_Strict):
return v return v
CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent} CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent, "blank": BlankContent}
Kind = Literal["menu", "image", "video", "text"] Kind = Literal["menu", "image", "video", "text", "blank"]
# ── requests ─────────────────────────────────────────────────────────────────── # ── requests ───────────────────────────────────────────────────────────────────
@@ -254,8 +300,16 @@ class SchedulesBody(BaseModel):
lines: List[ScheduleLine] = Field(default_factory=list, max_length=200) lines: List[ScheduleLine] = Field(default_factory=list, max_length=200)
class SavedSlideBody(SlideFields):
"""A library slide: its name and description, the shape it is built for, its kind (new ones)."""
kind: Optional[Kind] = None
description: Optional[str] = Field(default=None, max_length=300)
orientation: Optional[Orientation] = None
class ScreenBody(BaseModel): class ScreenBody(BaseModel):
playlist_id: Optional[int] = None # its default playlist playlist_id: Optional[int] = None # its default playlist
slide_id: Optional[int] = None # … or a library slide (one or the other)
orientation: Optional[Orientation] = None orientation: Optional[Orientation] = None
rotation: Optional[Literal[0, 90, 180, 270]] = None rotation: Optional[Literal[0, 90, 180, 270]] = None
@@ -367,6 +421,24 @@ def _screen_config(dev) -> dict:
return effective(for_app("signage"), dev.config) return effective(for_app("signage"), dev.config)
def slide_key(slide_id: int) -> str:
"""A library slide shown alone, where a playlist id goes (a screen's default, 2026-11-21)."""
return f"slide:{slide_id}"
def default_of(cfg: dict):
"""A screen's default: its playlist's id, else "slide:<id>" for its library slide, else None."""
if cfg.get("playlist"):
return cfg["playlist"]
if cfg.get("slide"):
return slide_key(cfg["slide"])
return None
def _screens_showing_slide(db, slide_id: int) -> list[int]:
return [d.id for d in _screens(db) if not _screen_config(d).get("playlist") and _screen_config(d).get("slide") == slide_id]
def _screen_playlists(db, d) -> set: def _screen_playlists(db, d) -> set:
"""Every playlist a screen may play: its default and those of its schedule lines.""" """Every playlist a screen may play: its default and those of its schedule lines."""
from services.signage_schedule import lines_for from services.signage_schedule import lines_for
@@ -440,6 +512,14 @@ def _uses(db, media_id: int) -> list:
media_store.register_usage("signage_slide", _uses) media_store.register_usage("signage_slide", _uses)
def _saved_uses(db, media_id: int) -> list:
return [{"id": s.id, "name": s.name} for s in db.query(SignageSavedSlide).order_by(SignageSavedSlide.name)
if media_id in media_ids(s.content or {})]
media_store.register_usage("signage_saved_slide", _saved_uses)
def _video_done(db, media_id: int) -> None: def _video_done(db, media_id: int) -> None:
"""A video's playable version is ready (services/video.py): the screens playing it switch to it.""" """A video's playable version is ready (services/video.py): the screens playing it switch to it."""
playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video") playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video")
@@ -458,10 +538,11 @@ def tell_all_screens(db) -> None:
def menu_changed(db) -> None: def menu_changed(db) -> None:
"""Products, categories or prices changed (main.py, the same requests that push the online menu): """Products, categories or prices changed (main.py, the same requests that push the online menu):
the screens with a menu board on their playlist read it again.""" the screens with a menu board on their playlist (or as their default slide) read it again."""
playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")} playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")}
if playlists: boards = {slide_key(sid) for (sid,) in db.query(SignageSavedSlide.id).filter(SignageSavedSlide.kind == "menu")}
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists]) if playlists or boards:
_tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists or default_of(_screen_config(d)) in boards])
# ── playlists ────────────────────────────────────────────────────────────────── # ── playlists ──────────────────────────────────────────────────────────────────
@@ -607,6 +688,112 @@ def duplicate_slide(slide_id: int, db: Session = Depends(get_db), user=Depends(r
return _slide_out(copy) return _slide_out(copy)
# ── the Slides library (owner 2026-11-21) ──────────────────────────────────────
def _saved(db, sid: int) -> SignageSavedSlide:
s = db.get(SignageSavedSlide, sid)
if s is None:
raise XeniaError("signage.slide_unknown", slide_id=sid)
return s
def _saved_out(s: SignageSavedSlide, db=None) -> dict:
out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "kind": s.kind,
"duration_s": s.duration_s, "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled),
"days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to,
"content": s.content or {}}
if db is not None:
if s.kind == "menu":
from services.signage_menu import resolve
out["menu"] = resolve(db, out["content"])
showing = set(_screens_showing_slide(db, s.id))
out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing]
return out
def _saved_name(body) -> str:
name = (body.name or "").strip()
if not name:
raise XeniaError("signage.content_invalid", field="name", reason="required")
return name
@router.get("/library")
def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Every kept slide, with its menu resolved (the gallery's previews) and the media they show."""
rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all()
return {"slides": [_saved_out(s, db) for s in rows],
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})])}
@router.post("/library", status_code=201)
def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
if body.kind is None:
raise XeniaError("signage.content_invalid", field="kind", reason="required")
name = _saved_name(body)
s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True,
video_to_end=body.kind == "video", content=_content(db, body.kind, None))
_apply(db, s, body)
s.name = name
s.description = (body.description or "").strip() or None
db.add(s)
db.commit()
db.refresh(s)
return _saved_out(s, db)
@router.get("/library/{slide_id}")
def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {}))
return out
@router.put("/library/{slide_id}")
def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
if body.kind is not None and body.kind != s.kind:
raise XeniaError("signage.content_invalid", field="kind", reason="a slide keeps its kind")
name = _saved_name(body) if "name" in body.model_fields_set else s.name
_apply(db, s, body)
s.name = name
if "description" in body.model_fields_set:
s.description = (body.description or "").strip() or None
if body.orientation is not None:
s.orientation = body.orientation
db.commit()
db.refresh(s)
_tell(_screens_showing_slide(db, s.id))
return _saved_out(s, db)
@router.delete("/library/{slide_id}", status_code=204)
def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
showing = _screens_showing_slide(db, s.id)
for d in _screens(db):
if (d.config or {}).get("slide") == s.id:
d.config = {**(d.config or {}), "slide": None}
db.delete(s)
db.commit()
_tell(showing)
return Response(status_code=204)
@router.post("/library/{slide_id}/duplicate", status_code=201)
def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id)
copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, kind=s.kind,
duration_s=s.duration_s, transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled,
days=s.days, time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to,
content=json.loads(json.dumps(s.content or {})))
db.add(copy)
db.commit()
db.refresh(copy)
return _saved_out(copy, db)
# ── screens ──────────────────────────────────────────────────────────────────── # ── screens ────────────────────────────────────────────────────────────────────
def _screen_out(db, d) -> dict: def _screen_out(db, d) -> dict:
@@ -614,13 +801,20 @@ def _screen_out(db, d) -> dict:
from services.signage_schedule import now_for from services.signage_schedule import now_for
cfg = _screen_config(d) cfg = _screen_config(d)
p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None p = db.get(SignagePlaylist, cfg["playlist"]) if cfg.get("playlist") else None
sl = db.get(SignageSavedSlide, cfg["slide"]) if cfg.get("slide") and not p else None
now_id, scheduled = now_for(db, d) now_id, scheduled = now_for(db, d)
if isinstance(now_id, str):
now = {"id": now_id, "name": sl.name, "scheduled": False, "slide": True} if sl else None
else:
now_p = db.get(SignagePlaylist, now_id) if now_id else None now_p = db.get(SignagePlaylist, now_id) if now_id else None
now = {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None
ids = _screen_playlists(db, d) ids = _screen_playlists(db, d)
shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set() shapes = {x.orientation for x in db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids))} if ids else set()
if sl:
shapes.add(sl.orientation)
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None, return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
"orientation": cfg["orientation"], "rotation": cfg["rotation"], "slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None,
"now": {"id": now_p.id, "name": now_p.name, "scheduled": scheduled} if now_p else None, "orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now,
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)} "orientation_mismatch": any(o != cfg["orientation"] for o in shapes)}
@@ -638,7 +832,12 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
raise XeniaError("signage.not_a_screen", device_id=device_id) raise XeniaError("signage.not_a_screen", device_id=device_id)
cfg = dict(d.config or {}) cfg = dict(d.config or {})
for key in body.model_fields_set: for key in body.model_fields_set:
cfg[{"playlist_id": "playlist"}.get(key, key)] = getattr(body, key) cfg[{"playlist_id": "playlist", "slide_id": "slide"}.get(key, key)] = getattr(body, key)
# the default is a playlist or a library slide, never both
if "playlist_id" in body.model_fields_set and body.playlist_id is not None:
cfg["slide"] = None
if "slide_id" in body.model_fields_set and body.slide_id is not None:
cfg["playlist"] = None
d.config = validate(for_app("signage"), cfg, db) d.config = validate(for_app("signage"), cfg, db)
db.commit() db.commit()
broadcast_sync("device.updated", {}, device_ids=[d.id]) broadcast_sync("device.updated", {}, device_ids=[d.id])
@@ -663,6 +862,30 @@ def _resolved(db, p: SignagePlaylist) -> dict:
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])} "media": _media_map(db, [i for s in slides for i in media_ids(s["content"])])}
def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
"""A library slide shown alone as a screen's default: a playlist of that one slide."""
from services.signage_menu import resolve
one = _saved_out(s)
one["transition"] = one["transition"] or "fade"
if one["kind"] == "menu":
one["menu"] = resolve(db, one["content"])
for w in one["content"].get("widgets") or []:
if w["kind"] == "qr":
w["link"] = _qr_link(w)
slides = [one] if s.enabled else []
return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides,
"media": _media_map(db, media_ids(one["content"]))}
def _default_resolved(db, cfg: dict):
d = default_of(cfg)
if isinstance(d, str):
s = db.get(SignageSavedSlide, cfg["slide"])
return d, (_resolved_slide(db, s, cfg["orientation"]) if s else None)
p = db.get(SignagePlaylist, d) if d else None
return d, (_resolved(db, p) if p else None)
@router.get("/screen") @router.get("/screen")
def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))): def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))):
"""What this screen plays: its settings and its playlist with every slide and media address. """What this screen plays: its settings and its playlist with every slide and media address.
@@ -678,19 +901,20 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
cfg = _screen_config(dev) cfg = _screen_config(dev)
lines = lines_for(db, dev.id) lines = lines_for(db, dev.id)
schedule, playlists, playlist = None, None, None schedule, playlists, playlist = None, None, None
default = cfg.get("playlist") default, fallback = _default_resolved(db, cfg)
if lines: if lines:
ids = _screen_playlists(db, dev) ids = _screen_playlists(db, dev)
playlists = {str(p.id): _resolved(db, p) for p in playlists = {str(p.id): _resolved(db, p) for p in
(db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])} (db.query(SignagePlaylist).filter(SignagePlaylist.id.in_(ids)).all() if ids else [])}
if isinstance(default, str) and fallback:
playlists[default] = fallback # its library slide, under "slide:<id>"
scenes = sorted(active_ids(db)) scenes = sorted(active_ids(db))
entries = [entry_of(i) for i in lines] entries = [entry_of(i) for i in lines]
now_id = pick(entries, default, venue_now(), scenes) now_id = pick(entries, default, venue_now(), scenes)
playlist = playlists.get(str(now_id)) if now_id else None playlist = playlists.get(str(now_id)) if now_id else None
schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key} schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key}
else: else:
p = db.get(SignagePlaylist, default) if default else None playlist = fallback
playlist = _resolved(db, p) if p is not None else None
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]}, out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
"playlist": playlist, "schedule": schedule, "playlists": playlists, "playlist": playlist, "schedule": schedule, "playlists": playlists,
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old) # for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
+3 -3
View File
@@ -98,14 +98,14 @@ def lines_for(db, screen_id: int) -> list:
.order_by(SignageScheduleItem.position, SignageScheduleItem.id) if not i.screen_ids or screen_id in i.screen_ids] .order_by(SignageScheduleItem.position, SignageScheduleItem.id) if not i.screen_ids or screen_id in i.screen_ids]
def now_for(db, dev, local: datetime | None = None, scenes=None) -> tuple[int | None, bool]: def now_for(db, dev, local: datetime | None = None, scenes=None) -> tuple[int | str | None, bool]:
"""(the playlist a screen plays now, whether a schedule line picked it).""" """(the playlist a screen plays now, whether a schedule line picked it)."""
from core.timeutil import venue_now from core.timeutil import venue_now
from routers.signage import _screen_config from routers.signage import _screen_config, default_of
from services.scenes import active_ids from services.scenes import active_ids
local = local or venue_now() local = local or venue_now()
scenes = active_ids(db) if scenes is None else scenes scenes = active_ids(db) if scenes is None else scenes
default = _screen_config(dev).get("playlist") default = default_of(_screen_config(dev)) # a playlist id, or "slide:<id>" (a library slide)
got = pick([entry_of(i) for i in lines_for(db, dev.id)], None, local, scenes) got = pick([entry_of(i) for i in lines_for(db, dev.id)], None, local, scenes)
return (got, True) if got is not None else (default, False) return (got, True) if got is not None else (default, False)
@@ -0,0 +1,96 @@
"""The signage Slides library and what came with it (owner 2026-11-21): slides kept with a name and a
description, added to playlists as copies, shown alone as a screen's default (also behind a
schedule); blank slides (a background and widgets); widgets moved and sized by hand (their own
box); a menu board narrower than the screen, placed left / centre / right."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_media import jpeg, media_dir, up # noqa: F401 (fixture + helpers)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
def keep(client, h, **body):
r = client.post("/api/signage/library", headers=h, json={"name": "Logo", "kind": "blank", **body})
assert r.status_code == 201, r.text
return r.json()
def test_the_library_keeps_slides(client, owner_h):
s = keep(client, owner_h, description=" Our logo, big ", orientation="portrait", duration_s=15,
content={"background": {"kind": "colour", "colour": "#102030"}, "widgets": [{"kind": "name", "position": "top-center"}]})
assert s["kind"] == "blank" and s["orientation"] == "portrait" and s["description"] == "Our logo, big" and s["duration_s"] == 15
assert s["content"]["widgets"][0]["size"] == "medium" and s["screens"] == []
r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"name": "Logo 2", "description": "", "days": [5, 6]})
assert r.json()["name"] == "Logo 2" and r.json()["description"] is None and r.json()["days"] == [5, 6]
assert err(client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"kind": "text"})) == "signage.content_invalid"
assert err(client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"name": " "})) == "signage.content_invalid"
assert err(client.post("/api/signage/library", headers=owner_h, json={"name": "x"})) == "signage.content_invalid" # no kind
copy = client.post(f"/api/signage/library/{s['id']}/duplicate", headers=owner_h).json()
assert copy["name"] == "Logo 2 (2)" and copy["content"] == r.json()["content"]
listed = client.get("/api/signage/library", headers=owner_h).json()
assert [x["name"] for x in listed["slides"]] == ["Logo 2", "Logo 2 (2)"] and listed["media"] == {}
assert client.delete(f"/api/signage/library/{copy['id']}", headers=owner_h).status_code == 204
assert err(client.get(f"/api/signage/library/{copy['id']}", headers=owner_h)) == "signage.slide_unknown"
def test_a_library_slide_protects_its_pictures(client, owner_h, media_dir):
pic = up(client, owner_h, jpeg(800, 800)).json()
keep(client, owner_h, kind="image", name="Promo", content={"media_id": pic["id"]})
r = client.delete(f"/api/media/{pic['id']}", headers=owner_h)
assert r.status_code == 409, r.text
def test_a_screen_shows_a_library_slide_when_nothing_else_plays(client, owner_h, screens, sent):
s = keep(client, owner_h, content={"widgets": [{"kind": "qr", "position": "bottom-right"}]})
tv = screens[1]
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"slide_id": s["id"]})
assert r.status_code == 200, r.text
assert r.json()["slide_id"] == s["id"] and r.json()["playlist_id"] is None
assert r.json()["now"] == {"id": f"slide:{s['id']}", "name": "Logo", "scheduled": False, "slide": True}
got = client.get("/api/signage/screen", headers=tv["h"]).json()
pl = got["playlist"]
assert pl["id"] == f"slide:{s['id']}" and [x["id"] for x in pl["slides"]] == [s["id"]]
assert pl["slides"][0]["content"]["widgets"][0]["link"] # the QR's address, as in a playlist
# a change to it reaches that screen only
sent.clear()
client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"duration_s": 20})
assert sent == [("signage.changed", [tv["id"]])]
# behind a schedule: the slide is the fallback, under its own key
p = playlist(client, owner_h, "Lunch")
slide(client, owner_h, p["id"], "text", content={"title": "Lunch"})
client.put("/api/signage/schedules", headers=owner_h, json={"lines": [
{"playlist_id": p["id"], "screen_ids": [tv["id"]], "date_from": "2000-01-01", "date_to": "2000-01-02"}]})
got = client.get("/api/signage/screen", headers=tv["h"]).json()
assert got["schedule"]["fallback_playlist_id"] == f"slide:{s['id']}" and f"slide:{s['id']}" in got["playlists"]
assert got["playlist"]["id"] == f"slide:{s['id']}"
# a playlist as the default takes its place (one or the other)
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
assert r.json()["playlist_id"] == p["id"] and r.json()["slide_id"] is None
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"slide_id": s["id"]})
assert r.json()["playlist_id"] is None and r.json()["slide_id"] == s["id"]
# deleting the slide: the screen shows nothing and is told
sent.clear()
client.delete(f"/api/signage/library/{s['id']}", headers=owner_h)
assert ("signage.changed", [tv["id"]]) in sent
assert client.get("/api/signage/screens", headers=owner_h).json()[0]["slide_id"] is None
def test_blank_slides_and_widgets_placed_by_hand(client, owner_h):
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "clock", "position": "custom", "box": {"x": 90, "y": 5, "w": 20, "h": 10}, "align": "right"},
{"kind": "date", "position": "top-left", "size": "custom", "box": {"x": 1, "y": 1, "w": 5, "h": 5}}]})
clock, date = s["content"]["widgets"]
assert clock["size"] == "custom" and clock["box"] == {"x": 80, "y": 5, "w": 20, "h": 10} and clock["align"] == "right" # kept on the slide
assert date["size"] == "medium" and date["box"] is None # a corner: no box, a real size
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"widgets": [{"kind": "clock", "position": "custom"}]}})
assert err(r) == "signage.content_invalid" # placed by hand needs its box
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"title": "x"}})
assert err(r) == "signage.content_invalid" # a blank slide has no title
def test_a_menu_board_narrower_than_the_screen(client, owner_h):
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "menu", content={"select": "all", "board_width": 60, "board_align": "center"})
assert s["content"]["board_width"] == 60 and s["content"]["board_align"] == "center"
assert slide(client, owner_h, p["id"], "menu")["content"]["board_width"] == 100
r = client.put(f"/api/signage/slides/{s['id']}", headers=owner_h, json={"content": {"board_width": 20}})
assert err(r) == "signage.content_invalid"
@@ -10,7 +10,7 @@ import client from '../../api/client'
import { configGroups, configValue, refOptions } from './devicesLogic' import { configGroups, configValue, refOptions } from './devicesLogic'
// Where a `ref` field's choices come from (the device list is passed in) // Where a `ref` field's choices come from (the device list is passed in)
const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers', display_looks: '/api/display/looks', signage_playlists: '/api/signage/playlists', signage_schedules: '/api/signage/schedules', tables: '/api/tables/' } const REF_URLS = { prep_zones: '/api/prep-zones', categories: '/api/products/categories', printers: '/api/system/printers', display_looks: '/api/display/looks', signage_playlists: '/api/signage/playlists', signage_slides: '/api/signage/library', signage_schedules: '/api/signage/schedules', tables: '/api/tables/' }
export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) { export default function DeviceConfigFields({ appKey, fields = [], value, onChange, devices = [], selfId = null }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -30,6 +30,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
const printers = lists.printers ?? [] const printers = lists.printers ?? []
const looks = lists.display_looks ?? [] const looks = lists.display_looks ?? []
const playlists = lists.signage_playlists ?? [] const playlists = lists.signage_playlists ?? []
const slides = lists.signage_slides?.slides ?? [] // the Slides library answers { slides, media }
const schedules = lists.signage_schedules ?? [] const schedules = lists.signage_schedules ?? []
const tables = lists.tables ?? [] const tables = lists.tables ?? []
@@ -57,7 +58,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
<Field key={f.key} label={label} hint={hint}> <Field key={f.key} label={label} hint={hint}>
<Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key} <Select value={v == null ? '' : String(v)} onChange={e => set(f, e.target.value)} data-config={f.key}
options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) }, options={[{ value: '', label: t(`${base(f.key)}.none`, { defaultValue: t('devices.form.none') }) },
...refOptions(f, { zones, categories, printers, looks, playlists, schedules, tables, devices, selfId })]} /> ...refOptions(f, { zones, categories, printers, looks, playlists, slides, schedules, tables, devices, selfId })]} />
</Field> </Field>
) )
} }
@@ -86,10 +86,11 @@ export function configGroups(fields = []) {
} }
/** Options of a `ref` field: prep zones, categories, printers, customer display looks, or live devices of one app ("devices:<app>"). */ /** Options of a `ref` field: prep zones, categories, printers, customer display looks, or live devices of one app ("devices:<app>"). */
export function refOptions(field, { zones = [], categories = [], printers = [], looks = [], playlists = [], schedules = [], tables = [], devices = [], selfId = null } = {}) { export function refOptions(field, { zones = [], categories = [], printers = [], looks = [], playlists = [], slides = [], schedules = [], tables = [], devices = [], selfId = null } = {}) {
if (field.choices_from === 'tables') return tables.filter(x => x.is_active !== false).map(x => ({ value: String(x.id), label: x.label || String(x.number) })) if (field.choices_from === 'tables') return tables.filter(x => x.is_active !== false).map(x => ({ value: String(x.id), label: x.label || String(x.number) }))
if (field.choices_from === 'signage_schedules') return schedules.map(s => ({ value: String(s.id), label: s.name })) if (field.choices_from === 'signage_schedules') return schedules.map(s => ({ value: String(s.id), label: s.name }))
if (field.choices_from === 'signage_playlists') return playlists.map(p => ({ value: String(p.id), label: p.name })) if (field.choices_from === 'signage_playlists') return playlists.map(p => ({ value: String(p.id), label: p.name }))
if (field.choices_from === 'signage_slides') return slides.map(p => ({ value: String(p.id), label: p.name }))
if (field.choices_from === 'display_looks') return looks.map(l => ({ value: String(l.id), label: l.name })) if (field.choices_from === 'display_looks') return looks.map(l => ({ value: String(l.id), label: l.name }))
if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name })) if (field.choices_from === 'prep_zones') return zones.map(z => ({ value: String(z.id), label: z.name }))
if (field.choices_from === 'categories') return categories.map(c => ({ value: String(c.id), label: c.name })) if (field.choices_from === 'categories') return categories.map(c => ({ value: String(c.id), label: c.name }))
@@ -0,0 +1,96 @@
// "Add a slide" (plan step 5.6a; three parts since 2026-11-21): start empty (a picture, a video,
// a text, a menu board, a blank slide or a blank one with a few widgets), a ready-made slide, or
// one of the venue's own slides from the Slides library (a copy goes in). `library` null: no
// third part (the library's own "New slide"). onPick(body) gets the new slide's fields.
import { Film, ImageIcon, LayoutDashboard, LayoutList, Square, Type } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Spinner } from '@xenia/ui'
import { BLANK_WITH_WIDGETS, mediaLookup, slideFromSaved, slideFromTemplate, TEMPLATES } from './signageLogic'
import SlidePreview from './SlidePreview'
export const KIND_ICON = { image: ImageIcon, video: Film, text: Type, menu: LayoutList, blank: Square }
const EMPTY = [
{ key: 'image', kind: 'image', content: {} }, { key: 'video', kind: 'video', content: {} }, { key: 'text', kind: 'text', content: {} },
{ key: 'menu', kind: 'menu', content: {} }, { key: 'blank', kind: 'blank', content: {} },
]
function Heading({ children, hint }) {
return (
<div className="grid gap-0.5">
<div className="flex items-center gap-3">
<span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{children}</span>
<span className="flex-1 border-t border-line" aria-hidden="true" />
</div>
{hint && <p className="text-caption text-ink-3">{hint}</p>}
</div>
)
}
export default function AddSlideDialog({ onClose, onPick, orientation = 'landscape', venue, library = null, libraryMedia = {}, title }) {
const { t } = useTranslation('manager')
const tall = orientation === 'portrait'
return (
<Dialog open size="xl" title={title || t('signage.addSlide')} onClose={onClose}
footer={<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>}>
<div className="grid gap-6" data-testid="signage-add-dialog">
<section className="grid gap-3">
<Heading>{t('signage.blank')}</Heading>
<div className="grid gap-2 grid-cols-3 sm:grid-cols-6">
{EMPTY.map(e => {
const Icon = KIND_ICON[e.kind]
return (
<button key={e.key} type="button" onClick={() => onPick({ kind: e.kind, content: {} })} data-testid={`signage-new-${e.key}`}
className="p-3 rounded-control border border-line bg-surface-2 hover:bg-surface-3 hover:border-line-strong text-left grid gap-1.5 transition-colors duration-fast">
<Icon size={18} className="text-ink-2" aria-hidden="true" />
<span className="text-label font-medium text-ink">{t(`signage.kinds.${e.kind}`)}</span>
</button>
)
})}
<button type="button" onClick={() => onPick(slideFromTemplate(BLANK_WITH_WIDGETS, t))} data-testid="signage-new-blank-widgets"
className="p-3 rounded-control border border-line bg-surface-2 hover:bg-surface-3 hover:border-line-strong text-left grid gap-1.5 transition-colors duration-fast">
<LayoutDashboard size={18} className="text-ink-2" aria-hidden="true" />
<span className="text-label font-medium text-ink">{t('signage.kinds.blankWidgets')}</span>
</button>
</div>
</section>
<section className="grid gap-3">
<Heading>{t('signage.templatesTitle')}</Heading>
<div className={`grid gap-3 ${tall ? 'grid-cols-3 sm:grid-cols-6' : 'grid-cols-2 sm:grid-cols-3'}`}>
{TEMPLATES.map(tpl => {
const sample = { id: 0, ...slideFromTemplate(tpl, t), enabled: true, menu: { groups: [] } }
return (
<button key={tpl.key} type="button" onClick={() => onPick(slideFromTemplate(tpl, t))} data-testid={`signage-template-${tpl.key}`}
className="rounded-control border border-line bg-surface-2 hover:bg-surface-3 hover:border-line-strong text-left overflow-hidden grid content-start transition-colors duration-fast">
<div className="pointer-events-none"><SlidePreview slide={sample} media={() => null} venue={venue} orientation={orientation} testid="signage-template-preview" /></div>
<span className="text-label font-medium text-ink px-2 py-1.5">{t(`signage.templates.${tpl.key}.name`)}</span>
</button>
)
})}
</div>
</section>
{library !== null && (
<section className="grid gap-3" data-testid="signage-add-library">
<Heading hint={t('signage.library.addHint')}>{t('signage.library.yours')}</Heading>
{library === undefined ? <div className="flex justify-center p-4"><Spinner /></div>
: library.length === 0 ? <p className="text-label text-ink-3 py-2">{t('signage.library.noneYet')}</p> : (
<div className={`grid gap-3 ${tall ? 'grid-cols-3 sm:grid-cols-6' : 'grid-cols-2 sm:grid-cols-3'}`}>
{library.map(s => (
<button key={s.id} type="button" onClick={() => onPick(slideFromSaved(s))} data-testid="signage-add-saved" data-name={s.name}
className="rounded-control border border-line bg-surface-2 hover:bg-surface-3 hover:border-line-strong text-left overflow-hidden grid content-start transition-colors duration-fast">
<div className="pointer-events-none"><SlidePreview slide={s} media={mediaLookup(libraryMedia)} venue={venue} orientation={orientation} testid="signage-saved-preview" /></div>
<span className="grid px-2 py-1.5 min-w-0">
<span className="text-label font-medium text-ink truncate">{s.name}</span>
{s.description && <span className="text-caption text-ink-3 truncate">{s.description}</span>}
</span>
</button>
))}
</div>
)}
</section>
)}
</div>
</Dialog>
)
}
@@ -3,18 +3,21 @@
// (arrows on what the board shows), badges, prices of a sales point, photos / descriptions, sold-out // (arrows on what the board shows), badges, prices of a sales point, photos / descriptions, sold-out
// style, columns and pages, the look, and the widgets. `slide.menu` is the server's resolution of // style, columns and pages, the look, and the widgets. `slide.menu` is the server's resolution of
// the draft (PlaylistEditor asks for it as you change things). // the draft (PlaylistEditor asks for it as you change things).
// 2026-11-21 (owner review): sections with titles; what each line shows in fewer rows (the four
// switches on one); the layout: columns, how wide the list is and where it sits (left / centre /
// right), products per page, seconds per page.
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { ArrowDown, ArrowUp, EyeOff, X } from 'lucide-react' import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, EyeOff, X } from 'lucide-react'
import { MENU_LANGUAGES, SALES_POINTS } from '@xenia/access' import { MENU_LANGUAGES, SALES_POINTS } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Field, IconButton, Input, Select, Switch } from '@xenia/ui' import { Dropdown, Field, IconButton, Input, Segmented, Select, Switch } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { BADGES, boardOrder, moveGroup, moveItem, toggled } from './signageLogic' import { BADGES, boardOrder, moveGroup, moveItem, toggled } from './signageLogic'
import { BackgroundField, ColourField } from './SignageFields' import { BackgroundField, ColourField, Range, Section } from './SignageFields'
import { TextLook } from './SlideEditor' import { TextLook } from './SlideEditor'
import WidgetsEditor from './WidgetsEditor' import WidgetsEditor from './WidgetsEditor'
export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [] }) { export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [], widget = null, onWidget }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const c = slide.content || {} const c = slide.content || {}
@@ -34,19 +37,22 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
const found = q.trim().length < 1 ? [] : products.filter(p => p.name.toLowerCase().includes(q.trim().toLowerCase()) && !shown.has(p.id)).slice(0, 8) const found = q.trim().length < 1 ? [] : products.filter(p => p.name.toLowerCase().includes(q.trim().toLowerCase()) && !shown.has(p.id)).slice(0, 8)
const reorder = next => setC(boardOrder(next)) const reorder = next => setC(boardOrder(next))
const badges = c.badges || {} const badges = c.badges || {}
const digits = v => Number(String(v).replace(/\D/g, ''))
return ( return (
<div className="grid gap-4" data-testid="signage-menu-editor"> <div className="grid gap-7" data-testid="signage-menu-editor">
<Field label={t('signage.title')}><Input value={c.title || ''} maxLength={120} onChange={e => setC({ title: e.target.value })} data-testid="signage-menu-title" /></Field>
{/* what it lists */} {/* what it lists */}
<fieldset className="grid gap-3 rounded-control border border-line p-3"> <Section title={t('signage.menu.what')}>
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.menu.what')}</legend> <div className="grid gap-4 md:grid-cols-2 items-end">
<Select value={c.select || 'custom'} onChange={e => setC({ select: e.target.value })} aria-label={t('signage.menu.what')} data-testid="signage-menu-select" <Field label={t('signage.title')}><Input value={c.title || ''} maxLength={120} onChange={e => setC({ title: e.target.value })} data-testid="signage-menu-title" /></Field>
<Field label={t('signage.menu.which')}>
<Dropdown value={c.select || 'custom'} onChange={v => setC({ select: v })} data-testid="signage-menu-select"
options={[{ value: 'all', label: t('signage.menu.all') }, { value: 'custom', label: t('signage.menu.custom') }]} /> options={[{ value: 'all', label: t('signage.menu.all') }, { value: 'custom', label: t('signage.menu.custom') }]} />
</Field>
</div>
{c.select !== 'all' && <> {c.select !== 'all' && <>
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<span className="text-label text-ink-2">{t('signage.menu.categories')}</span> <span className="text-label font-medium text-ink">{t('signage.menu.categories')}</span>
<p className="text-caption text-ink-3">{t('signage.menu.categoriesHint')}</p> <p className="text-caption text-ink-3">{t('signage.menu.categoriesHint')}</p>
<div className="flex flex-wrap gap-1.5" data-testid="signage-menu-categories"> <div className="flex flex-wrap gap-1.5" data-testid="signage-menu-categories">
{top.flatMap(cat => [cat, ...subsOf(cat.id)]).map(cat => { {top.flatMap(cat => [cat, ...subsOf(cat.id)]).map(cat => {
@@ -63,7 +69,7 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
</div> </div>
</div> </div>
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<span className="text-label text-ink-2">{t('signage.menu.products')}</span> <span className="text-label font-medium text-ink">{t('signage.menu.products')}</span>
{(c.product_ids || []).length > 0 && ( {(c.product_ids || []).length > 0 && (
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{(c.product_ids || []).map(id => ( {(c.product_ids || []).map(id => (
@@ -91,7 +97,7 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
</>} </>}
{(c.exclude_ids || []).length > 0 && ( {(c.exclude_ids || []).length > 0 && (
<div className="grid gap-1.5"> <div className="grid gap-1.5">
<span className="text-label text-ink-2">{t('signage.menu.hidden')}</span> <span className="text-label font-medium text-ink">{t('signage.menu.hidden')}</span>
<div className="flex flex-wrap gap-1.5"> <div className="flex flex-wrap gap-1.5">
{(c.exclude_ids || []).map(id => ( {(c.exclude_ids || []).map(id => (
<button key={id} type="button" onClick={() => setC({ exclude_ids: (c.exclude_ids || []).filter(x => x !== id) })} <button key={id} type="button" onClick={() => setC({ exclude_ids: (c.exclude_ids || []).filter(x => x !== id) })}
@@ -102,13 +108,12 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
</div> </div>
</div> </div>
)} )}
</fieldset> </Section>
{/* the board's own order, badges, hiding */} {/* the board's own order, badges, hiding */}
<fieldset className="grid gap-2 rounded-control border border-line p-3"> <Section title={t('signage.menu.onTheBoard', { count: slide.menu?.count ?? 0 })}>
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.menu.onTheBoard', { count: slide.menu?.count ?? 0 })}</legend> <p className="text-caption text-ink-3 -mt-1">{t('signage.menu.orderHint')}</p>
<p className="text-caption text-ink-3">{t('signage.menu.orderHint')}</p> <div className="grid gap-3 max-h-[28rem] overflow-auto pr-1 rounded-control border border-line bg-surface-2 p-3" data-testid="signage-menu-board">
<div className="grid gap-3 max-h-[28rem] overflow-auto pr-1" data-testid="signage-menu-board">
{groups.map((g, gi) => ( {groups.map((g, gi) => (
<div key={`${g.category?.id ?? 'all'}`} className="grid gap-1" data-testid="signage-menu-group" data-name={g.category?.name ?? ''}> <div key={`${g.category?.id ?? 'all'}`} className="grid gap-1" data-testid="signage-menu-group" data-name={g.category?.name ?? ''}>
{g.category && ( {g.category && (
@@ -120,7 +125,7 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
)} )}
<ul className="grid gap-0.5"> <ul className="grid gap-0.5">
{g.items.map((it, ii) => ( {g.items.map((it, ii) => (
<li key={it.id} className="flex items-center gap-1.5 pl-2 rounded-control hover:bg-surface-2" data-testid="signage-menu-row" data-id={it.id}> <li key={it.id} className="flex items-center gap-1.5 pl-2 rounded-control hover:bg-surface" data-testid="signage-menu-row" data-id={it.id}>
<span className={`flex-1 min-w-0 truncate text-label ${it.available ? 'text-ink' : 'text-ink-3 line-through'}`}>{it.name}</span> <span className={`flex-1 min-w-0 truncate text-label ${it.available ? 'text-ink' : 'text-ink-3 line-through'}`}>{it.name}</span>
{it.price != null && <span className="text-caption text-ink-2 tabular-nums">{formatMoney(it.price)}</span>} {it.price != null && <span className="text-caption text-ink-2 tabular-nums">{formatMoney(it.price)}</span>}
<Select size="sm" value={badges[String(it.id)] || ''} aria-label={t('signage.menu.badge')} data-testid="signage-menu-badge" <Select size="sm" value={badges[String(it.id)] || ''} aria-label={t('signage.menu.badge')} data-testid="signage-menu-badge"
@@ -142,47 +147,62 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
))} ))}
{groups.length === 0 && <p className="text-label text-ink-3">{t('signage.menu.empty')}</p>} {groups.length === 0 && <p className="text-label text-ink-3">{t('signage.menu.empty')}</p>}
</div> </div>
</fieldset> </Section>
{/* what each line shows, and the pages */} {/* what each line shows: the four switches on one row, then the rest (2026-11-21) */}
<fieldset className="grid gap-3 rounded-control border border-line p-3 sm:grid-cols-2"> <Section title={t('signage.menu.options')}>
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.menu.options')}</legend> <div className="grid gap-3 grid-cols-2 xl:grid-cols-4">
<Switch checked={c.group_by_category !== false} onChange={on => setC({ group_by_category: on })} label={t('signage.menu.group')} data-testid="signage-menu-group-switch" /> <Switch boxed checked={c.group_by_category !== false} onChange={on => setC({ group_by_category: on })} label={t('signage.menu.group')} data-testid="signage-menu-group-switch" />
<Switch checked={c.category_titles !== false} onChange={on => setC({ category_titles: on })} label={t('signage.menu.headings')} /> <Switch boxed checked={c.category_titles !== false} onChange={on => setC({ category_titles: on })} label={t('signage.menu.headings')} />
<Switch checked={!!c.show_photos} onChange={on => setC({ show_photos: on })} label={t('signage.menu.photos')} data-testid="signage-menu-photos" /> <Switch boxed checked={!!c.show_photos} onChange={on => setC({ show_photos: on })} label={t('signage.menu.photos')} data-testid="signage-menu-photos" />
<Switch checked={!!c.show_descriptions} onChange={on => setC({ show_descriptions: on })} label={t('signage.menu.descriptions')} /> <Switch boxed checked={!!c.show_descriptions} onChange={on => setC({ show_descriptions: on })} label={t('signage.menu.descriptions')} />
</div>
<div className="grid gap-4 md:grid-cols-3 items-start">
<Field label={t('signage.menu.prices')}> <Field label={t('signage.menu.prices')}>
<Select value={c.sales_point ?? ''} onChange={e => setC({ sales_point: e.target.value || null })} data-testid="signage-menu-prices" <Dropdown value={c.sales_point ?? ''} onChange={v => setC({ sales_point: v || null })} data-testid="signage-menu-prices"
options={[{ value: '', label: t('signage.menu.noPrices') }, ...SALES_POINTS.map(sp => ({ value: sp, label: t(`common:salesPoints.${sp}.name`) }))]} /> options={[{ value: '', label: t('signage.menu.noPrices') }, ...SALES_POINTS.map(sp => ({ value: sp, label: t(`common:salesPoints.${sp}.name`) }))]} />
</Field> </Field>
<Field label={t('signage.menu.language')} hint={t('signage.menu.languageHint')}> <Field label={t('signage.menu.language')} hint={t('signage.menu.languageHint')}>
<Select value={c.language ?? ''} onChange={e => setC({ language: e.target.value || null })} data-testid="signage-menu-language" <Dropdown value={c.language ?? ''} onChange={v => setC({ language: v || null })} data-testid="signage-menu-language"
options={[{ value: '', label: t('signage.menu.asTyped') }, ...MENU_LANGUAGES.map(l => ({ value: l, label: t(`products.editor.lang.${l}`) }))]} /> options={[{ value: '', label: t('signage.menu.asTyped') }, ...MENU_LANGUAGES.map(l => ({ value: l, label: t(`products.editor.lang.${l}`) }))]} />
</Field> </Field>
<Field label={t('signage.menu.soldOut')}> <Field label={t('signage.menu.soldOut')}>
<Select value={c.sold_out || 'strike'} onChange={e => setC({ sold_out: e.target.value })} <Dropdown value={c.sold_out || 'strike'} onChange={v => setC({ sold_out: v })}
options={[{ value: 'strike', label: t('signage.menu.strike') }, { value: 'hide', label: t('signage.menu.hideSoldOut') }]} /> options={[{ value: 'strike', label: t('signage.menu.strike') }, { value: 'hide', label: t('signage.menu.hideSoldOut') }]} />
</Field> </Field>
</div>
</Section>
{/* the layout: columns, how wide the list is and where it sits, the pages (2026-11-21) */}
<Section title={t('signage.menu.layout')}>
<div className="grid gap-4 grid-cols-2 xl:grid-cols-5 items-start">
<Field label={t('signage.columns')}> <Field label={t('signage.columns')}>
<Select value={String(c.columns || 2)} onChange={e => setC({ columns: Number(e.target.value) })} data-testid="signage-columns" <Segmented value={String(c.columns || 2)} onChange={v => setC({ columns: Number(v) })} data-testid="signage-columns" fill
options={[1, 2, 3].map(n => ({ value: String(n), label: String(n) }))} /> options={[1, 2, 3].map(n => ({ value: String(n), label: String(n), testId: `signage-columns-${n}` }))} />
</Field>
<Range label={t('signage.menu.width')} value={c.board_width || 100} min={40} max={100} step={5} suffix="%"
onChange={v => setC({ board_width: v })} testid="signage-menu-width" />
<Field label={t('signage.menu.place')} hint={(c.board_width || 100) >= 100 ? t('signage.menu.placeHint') : undefined}>
<Segmented value={c.board_align || 'left'} onChange={v => setC({ board_align: v })} data-testid="signage-menu-align" fill
options={[['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.aligns.${v}`), testId: `signage-menu-align-${v}` }))} />
</Field> </Field>
<Field label={t('signage.menu.perPage')} hint={t('signage.menu.perPageHint')}> <Field label={t('signage.menu.perPage')} hint={t('signage.menu.perPageHint')}>
<Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={t('signage.menu.auto')} <Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={t('signage.menu.auto')}
onChange={e => { const n = Number(e.target.value.replace(/\D/g, '')); setC({ page_size: n ? Math.min(60, Math.max(3, n)) : null }) }} /> onChange={e => { const n = digits(e.target.value); setC({ page_size: n ? Math.min(60, Math.max(3, n)) : null }) }} />
</Field> </Field>
<Field label={t('signage.menu.pageSeconds')}> <Field label={t('signage.menu.pageSeconds')}>
<Input inputMode="numeric" value={String(c.page_seconds || 10)} onChange={e => setC({ page_seconds: Math.min(120, Math.max(3, Number(e.target.value.replace(/\D/g, '')) || 3)) })} /> <Input inputMode="numeric" value={String(c.page_seconds || 10)} onChange={e => setC({ page_seconds: Math.min(120, Math.max(3, digits(e.target.value) || 3)) })} />
</Field> </Field>
</fieldset>
<div className="grid gap-3 sm:grid-cols-2">
<ColourField label={t('signage.accent')} value={c.accent_colour || '#f59e0b'} onChange={v => setC({ accent_colour: v })} testid="signage-accent" />
</div> </div>
<TextLook c={c} setC={setC} align={false} /> </Section>
<TextLook c={c} setC={setC} align={false}>
<ColourField label={t('signage.accent')} value={c.accent_colour || '#f59e0b'} onChange={v => setC({ accent_colour: v })} testid="signage-accent" />
</TextLook>
<BackgroundField value={c.background} onChange={background => setC({ background })} media={media} onMedia={onMedia} <BackgroundField value={c.background} onChange={background => setC({ background })} media={media} onMedia={onMedia}
misfit={misfit.includes(c.background?.media_id)} /> misfit={misfit.includes(c.background?.media_id)} />
<WidgetsEditor widgets={c.widgets || []} onChange={widgets => setC({ widgets })} media={media} onMedia={onMedia} /> <WidgetsEditor widgets={c.widgets || []} onChange={widgets => setC({ widgets })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} />
</div> </div>
) )
} }
@@ -1,25 +1,27 @@
// One playlist (plan step 5.6a; reworked 2026-11-21): its name, orientation and default transition // One playlist (plan step 5.6a; reworked 2026-11-21): its name, orientation and default transition
// (the toolbar); a horizontal timeline of slides, like a video editor's (cards of one size that // (the toolbar); a horizontal timeline of slides, like a video editor's (cards of one size that
// scroll sideways: drag or ← → to reorder, duplicate, remove); under it the picked slide's basics // scroll sideways: drag them, with a line where the slide will land, or ← → to reorder; duplicate,
// (name, seconds, on / off, transition, when it shows) beside its live preview, the same height; // remove); under it the picked slide's basics (name, show it, transition, seconds, when it shows)
// then what the slide shows. New slides blank or from a template; a warning on slides whose // beside its live preview, the same height, where its widgets can be picked, moved and sized
// picture or video doesn't fit the orientation. A slide's "when it shows" narrows its playlist's // (WidgetCanvas); then what the slide shows. New slides empty, ready-made or from the Slides
// schedule: outside both, it doesn't play. // library; a slide can be kept in the library too. Questions (leave unsaved changes, remove a
// slide) are asked inside the page. A warning on slides whose picture or video doesn't fit the
// orientation. A slide's "when it shows" narrows its playlist's schedule.
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { AlertTriangle, ArrowLeft, ArrowRight, Copy, Film, ImageIcon, LayoutList, Plus, Trash2, Type } from 'lucide-react' import { AlertTriangle, ArrowLeft, ArrowRight, BookmarkPlus, Copy, ImageIcon, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, Input, Select, Spinner } from '@xenia/ui' import { Button, Dialog, Dropdown, Field, IconButton, Input, Spinner, Textarea, useConfirm } from '@xenia/ui'
import * as api from './signageApi' import * as api from './signageApi'
import { mediaEntry, mediaLookup, misfits, moved, slideBody, slideFromTemplate, TEMPLATES, totalSeconds, TRANSITIONS, windowParts } from './signageLogic' import { mediaEntry, mediaLookup, misfits, moved, slideBody, totalSeconds, TRANSITIONS, windowParts } from './signageLogic'
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog'
import SlideEditor, { SlideBasics } from './SlideEditor' import SlideEditor, { SlideBasics } from './SlideEditor'
import SlidePreview from './SlidePreview' import SlidePreview from './SlidePreview'
import { useMenuPreview, useWidgetEditor } from './useSlideDraft'
const KIND_ICON = { image: ImageIcon, video: Film, text: Type, menu: LayoutList }
/** The preview as big as its box allows (the box is as tall as the basics beside it). */ /** The preview as big as its box allows (the box is as tall as the basics beside it). */
function FitPreview({ orientation, children }) { export function FitPreview({ orientation, children }) {
const box = useRef(null) const box = useRef(null)
const [size, setSize] = useState({ w: 0, h: 0 }) const [size, setSize] = useState({ w: 0, h: 0 })
useLayoutEffect(() => { useLayoutEffect(() => {
@@ -32,7 +34,7 @@ function FitPreview({ orientation, children }) {
const ratio = orientation === 'portrait' ? 9 / 16 : 16 / 9 const ratio = orientation === 'portrait' ? 9 / 16 : 16 / 9
const width = Math.max(0, Math.min(size.w, size.h * ratio)) const width = Math.max(0, Math.min(size.w, size.h * ratio))
return ( return (
<div ref={box} className="h-full min-h-[16rem] grid place-items-center" data-testid="signage-preview-box"> <div ref={box} className="h-full min-h-[16rem] min-w-0 grid place-items-center" data-testid="signage-preview-box">
{width > 0 && <div style={{ width }}>{children}</div>} {width > 0 && <div style={{ width }}>{children}</div>}
</div> </div>
) )
@@ -46,10 +48,14 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
const [selected, setSelected] = useState(null) const [selected, setSelected] = useState(null)
const [draft, setDraft] = useState(null) const [draft, setDraft] = useState(null)
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [adding, setAdding] = useState(false) const [adding, setAdding] = useState(null) // the library's slides while the dialog is open (undefined: loading)
const [libMedia, setLibMedia] = useState({})
const [keeping, setKeeping] = useState(false)
const [confirmDelete, setConfirmDelete] = useState(false) const [confirmDelete, setConfirmDelete] = useState(false)
const [dragFrom, setDragFrom] = useState(null) const [drag, setDrag] = useState(null) // { from, at }: the card dragged and where it would land
const [name, setName] = useState('') const [name, setName] = useState('')
const [confirm, confirmDialog] = useConfirm()
const { widget, setWidget, editor } = useWidgetEditor(setDraft, selected, t('signage.widgets.canvas'))
const load = useCallback(async (select) => { const load = useCallback(async (select) => {
try { try {
@@ -66,19 +72,10 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
load().then(p => { if (p?.slides?.length) { setSelected(p.slides[0].id); setDraft(structuredClone(p.slides[0])) } }) load().then(p => { if (p?.slides?.length) { setSelected(p.slides[0].id); setDraft(structuredClone(p.slides[0])) } })
api.previewVenue().then(setVenue).catch(() => {}) api.previewVenue().then(setVenue).catch(() => {})
}, [load]) }, [load])
useMenuPreview(draft, setDraft)
const saved = pl?.slides.find(s => s.id === selected) const saved = pl?.slides.find(s => s.id === selected)
const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved]) const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved])
// a menu board's draft: its products resolved by the server for the preview
const menuKey = draft?.kind === 'menu' ? JSON.stringify(draft.content) : null
useEffect(() => {
if (!menuKey) return undefined
const h = setTimeout(() => {
api.previewMenu(JSON.parse(menuKey)).then(r => setDraft(d => (d && d.kind === 'menu' ? { ...d, menu: r.menu } : d))).catch(() => {})
}, 400)
return () => clearTimeout(h)
}, [menuKey])
const bad = useMemo(() => misfits(pl?.slides, media, pl?.orientation), [pl, media]) const bad = useMemo(() => misfits(pl?.slides, media, pl?.orientation), [pl, media])
const draftBad = useMemo(() => (draft ? misfits([draft], media, pl?.orientation)[draft.id] || [] : []), [draft, media, pl]) const draftBad = useMemo(() => (draft ? misfits([draft], media, pl?.orientation)[draft.id] || [] : []), [draft, media, pl])
if (!pl) return <div className="flex justify-center p-8"><Spinner /></div> if (!pl) return <div className="flex justify-center p-8"><Spinner /></div>
@@ -89,62 +86,89 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
catch (err) { toast.error(errorMessage(err, t)); return null } catch (err) { toast.error(errorMessage(err, t)); return null }
finally { setBusy(false) } finally { setBusy(false) }
} }
const pick = s => { const leave = async () => !dirty || confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', testId: 'signage-discard' })
if (dirty && !window.confirm(t('signage.discard'))) return const pick = async s => {
if (s.id === selected || !(await leave())) return
setSelected(s.id) setSelected(s.id)
setDraft(structuredClone(s)) setDraft(structuredClone(s))
} }
const remove = async s => {
const ok = await confirm({ title: t('signage.deleteSlideTitle', { name: s.name || t(`signage.kinds.${s.kind}`) }), body: t('signage.deleteSlide'),
confirmLabel: t('fees.delete'), tone: 'danger', testId: 'signage-slide-delete-confirm' })
if (ok) run(() => api.deleteSlide(s.id), t('signage.removed'), s.id === selected ? null : selected)
}
const reorder = (from, to) => { const reorder = (from, to) => {
if (from === to) return
const ids = moved(pl.slides.map(s => s.id), from, to) const ids = moved(pl.slides.map(s => s.id), from, to)
setPl(p => ({ ...p, slides: ids.map(id => p.slides.find(s => s.id === id)) })) setPl(p => ({ ...p, slides: ids.map(id => p.slides.find(s => s.id === id)) }))
run(() => api.orderSlides(pl.id, ids)) run(() => api.orderSlides(pl.id, ids))
} }
// dragging a card: where it lands is before or after the card under the pointer
const over = (e, i) => {
if (!drag) return
e.preventDefault()
const r = e.currentTarget.getBoundingClientRect()
const at = e.clientX < r.left + r.width / 2 ? i : i + 1
if (at !== drag.at) setDrag(d => ({ ...d, at }))
}
const drop = () => {
if (drag && drag.at != null) reorder(drag.from, drag.at > drag.from ? drag.at - 1 : drag.at)
setDrag(null)
}
const savePlaylist = patch => run(() => api.updatePlaylist(pl.id, patch), t('settings.saved')) const savePlaylist = patch => run(() => api.updatePlaylist(pl.id, patch), t('settings.saved'))
const addFrom = async tpl => { const openAdd = async () => {
setAdding(false) if (!(await leave())) return
const made = await run(() => api.addSlide(pl.id, slideFromTemplate(tpl, t)), t('signage.added')) setAdding(undefined)
if (made) { await load(made.id) } api.listSaved().then(r => { setAdding(r.slides); setLibMedia(r.media) }).catch(() => setAdding([]))
}
const addSlide = async body => {
setAdding(null)
const made = await run(() => api.addSlide(pl.id, body), t('signage.added'))
if (made) await load(made.id)
} }
const total = totalSeconds(pl.slides, media) const total = totalSeconds(pl.slides, media)
const marker = i => drag && drag.at === i && drag.at !== drag.from && drag.at !== drag.from + 1
return ( return (
<div className="grid gap-4" data-testid="signage-playlist" data-id={pl.id}> <div className="grid gap-4 grid-cols-[minmax(0,1fr)]" data-testid="signage-playlist" data-id={pl.id}>
<header className="flex flex-wrap items-end gap-2"> <header className="flex flex-wrap items-end gap-2">
<Field label={t('signage.playlistName')} className="flex-1 min-w-[12rem]"> <Field label={t('signage.playlistName')} className="flex-1 min-w-[12rem]">
<Input value={name} maxLength={80} onChange={e => setName(e.target.value)} data-testid="signage-playlist-name" <Input value={name} maxLength={80} onChange={e => setName(e.target.value)} data-testid="signage-playlist-name"
onBlur={() => name.trim() && name.trim() !== pl.name && savePlaylist({ name: name.trim() })} onBlur={() => name.trim() && name.trim() !== pl.name && savePlaylist({ name: name.trim() })}
onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} /> onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
</Field> </Field>
<Field label={t('signage.orientation')}> <Field label={t('signage.orientation')} className="w-52">
<Select value={pl.orientation} onChange={e => savePlaylist({ orientation: e.target.value })} data-testid="signage-orientation" <Dropdown value={pl.orientation} onChange={v => savePlaylist({ orientation: v })} data-testid="signage-orientation"
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} /> options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} />
</Field> </Field>
<Field label={t('signage.defaultTransition')}> <Field label={t('signage.defaultTransition')} className="w-44">
<Select value={pl.transition} onChange={e => savePlaylist({ transition: e.target.value })} <Dropdown value={pl.transition} onChange={v => savePlaylist({ transition: v })}
options={TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} /> options={TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} />
</Field> </Field>
<IconButton variant="secondary" label={t('signage.duplicatePlaylist')} disabled={busy} <IconButton tone="info" label={t('signage.duplicatePlaylist')} disabled={busy}
onClick={() => run(() => api.duplicatePlaylist(pl.id), t('signage.duplicated')).then(() => onChanged?.())}><Copy size={16} /></IconButton> onClick={() => run(() => api.duplicatePlaylist(pl.id), t('signage.duplicated')).then(() => onChanged?.())}><Copy size={16} /></IconButton>
<IconButton variant="ghost" label={t('fees.delete')} disabled={busy} onClick={() => setConfirmDelete(true)} data-testid="signage-playlist-delete"><Trash2 size={16} /></IconButton> <IconButton tone="danger" label={t('fees.delete')} disabled={busy} onClick={() => setConfirmDelete(true)} data-testid="signage-playlist-delete"><Trash2 size={16} /></IconButton>
</header> </header>
<p className="text-label text-ink-3"> <p className="text-label text-ink-3">
{t('signage.summary', { count: pl.slides.length, minutes: Math.floor(total / 60), seconds: String(total % 60).padStart(2, '0') })} {t('signage.summary', { count: pl.slides.length, minutes: Math.floor(total / 60), seconds: String(total % 60).padStart(2, '0') })}
{pl.screens.length > 0 && <> · {t('signage.playingOn', { names: pl.screens.map(s => s.name).join(', ') })}</>} {pl.screens.length > 0 && <> · {t('signage.playingOn', { names: pl.screens.map(s => s.name).join(', ') })}</>}
</p> </p>
{/* the timeline: cards of one size, scrolling sideways (2026-11-21) */} {/* the timeline: cards of one size, scrolling sideways; a line shows where a dragged card lands */}
<section className="rounded-card border border-line bg-surface-2 p-3" aria-label={t('signage.timeline')}> <section className="min-w-0 rounded-card border border-line bg-surface-2 p-3" aria-label={t('signage.timeline')}>
<ol className="flex gap-3 overflow-x-auto pb-2 snap-x" data-testid="signage-timeline"> <ol className="flex gap-3 overflow-x-auto px-2 pb-2 snap-x" data-testid="signage-timeline" onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDrag(d => (d ? { ...d, at: null } : d)) }}>
{pl.slides.map((s, i) => { {pl.slides.map((s, i) => {
const Icon = KIND_ICON[s.kind] || ImageIcon const Icon = KIND_ICON[s.kind] || ImageIcon
const parts = windowParts(s) const parts = windowParts(s)
return ( return (
<li key={s.id} draggable onDragStart={() => setDragFrom(i)} onDragOver={e => e.preventDefault()} <li key={s.id} draggable onDragStart={e => { e.dataTransfer.effectAllowed = 'move'; setDrag({ from: i, at: null }) }} onDragEnd={() => setDrag(null)}
onDrop={() => { if (dragFrom != null) reorder(dragFrom, i); setDragFrom(null) }} onDragOver={e => over(e, i)} onDrop={e => { e.preventDefault(); drop() }}
data-testid="signage-slide-card" data-id={s.id} data-kind={s.kind} data-testid="signage-slide-card" data-id={s.id} data-kind={s.kind}
className={`w-52 shrink-0 snap-start rounded-card border bg-surface grid gap-2 p-2 cursor-pointer transition-colors duration-fast className={`relative w-52 shrink-0 snap-start rounded-card border bg-surface grid gap-2 p-2 cursor-pointer transition-[border-color,opacity] duration-fast
${s.id === selected ? 'border-accent ring-2 ring-accent' : 'border-line hover:border-line-strong'} ${s.enabled ? '' : 'opacity-60'}`} ${s.id === selected ? 'border-accent ring-2 ring-accent' : 'border-line hover:border-line-strong'} ${s.enabled ? '' : 'opacity-60'} ${drag?.from === i ? 'opacity-40' : ''}`}
onClick={() => pick(s)}> onClick={() => pick(s)}>
{marker(i) && <DropLine side="left" />}
{marker(i + 1) && i === pl.slides.length - 1 && <DropLine side="right" />}
<div className="pointer-events-none h-28 grid place-items-center rounded-control bg-surface-2"> <div className="pointer-events-none h-28 grid place-items-center rounded-control bg-surface-2">
<div style={{ width: pl.orientation === 'portrait' ? 63 : '100%' }}> <div style={{ width: pl.orientation === 'portrait' ? 63 : '100%' }}>
<SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} testid="signage-card-preview" /> <SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} testid="signage-card-preview" />
@@ -169,13 +193,13 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
<IconButton size="sm" tone="info" className="!w-full" label={t('signage.duplicateSlide')} disabled={busy} <IconButton size="sm" tone="info" className="!w-full" label={t('signage.duplicateSlide')} disabled={busy}
onClick={() => run(() => api.duplicateSlide(s.id), t('signage.duplicated'))}><Copy size={16} /></IconButton> onClick={() => run(() => api.duplicateSlide(s.id), t('signage.duplicated'))}><Copy size={16} /></IconButton>
<IconButton size="sm" tone="danger" className="!w-full" label={t('fees.delete')} disabled={busy} data-testid="signage-slide-delete" <IconButton size="sm" tone="danger" className="!w-full" label={t('fees.delete')} disabled={busy} data-testid="signage-slide-delete"
onClick={() => window.confirm(t('signage.deleteSlide')) && run(() => api.deleteSlide(s.id), t('signage.removed'), s.id === selected ? null : selected)}><Trash2 size={16} /></IconButton> onClick={() => remove(s)}><Trash2 size={16} /></IconButton>
</div> </div>
</li> </li>
) )
})} })}
<li className="w-52 shrink-0 snap-start"> <li className="w-52 shrink-0 snap-start">
<button type="button" onClick={() => setAdding(true)} data-testid="signage-add-slide" <button type="button" onClick={openAdd} data-testid="signage-add-slide"
className="w-full h-full min-h-[12rem] rounded-card border-2 border-dashed border-line-strong text-ink-2 hover:text-accent-ink hover:border-accent grid place-items-center gap-1 text-label font-medium transition-colors duration-fast"> className="w-full h-full min-h-[12rem] rounded-card border-2 border-dashed border-line-strong text-ink-2 hover:text-accent-ink hover:border-accent grid place-items-center gap-1 text-label font-medium transition-colors duration-fast">
<span className="grid justify-items-center gap-1"><Plus size={20} aria-hidden="true" />{t('signage.addSlide')}</span> <span className="grid justify-items-center gap-1"><Plus size={20} aria-hidden="true" />{t('signage.addSlide')}</span>
</button> </button>
@@ -185,61 +209,31 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
{/* the picked slide: its basics beside its preview (one height), then what it shows */} {/* the picked slide: its basics beside its preview (one height), then what it shows */}
{draft ? <> {draft ? <>
<section className="grid gap-4 lg:grid-cols-2 items-stretch rounded-card border border-line bg-surface shadow-raised p-card" data-testid="signage-slide-top"> <section className="grid gap-6 lg:grid-cols-2 items-stretch rounded-card border border-line bg-surface shadow-raised p-card min-w-0" data-testid="signage-slide-top">
<SlideBasics slide={draft} onChange={setDraft} /> <SlideBasics slide={draft} onChange={setDraft} />
<FitPreview orientation={pl.orientation}> <FitPreview orientation={pl.orientation}>
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} playing /> <SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} playing editor={editor} />
</FitPreview> </FitPreview>
</section> </section>
<section className="rounded-card border border-line bg-surface shadow-raised p-card"> <section className="rounded-card border border-line bg-surface shadow-raised p-card min-w-0">
<SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))} <SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))}
misfit={draftBad} /> misfit={draftBad} widget={widget} onWidget={setWidget} />
</section> </section>
<div className="flex gap-2 items-center sticky bottom-0 bg-canvas py-2 z-10"> <div className="flex flex-wrap gap-2 items-center sticky bottom-0 bg-canvas py-2 z-10">
<Button loading={busy} disabled={!dirty} onClick={() => run(() => api.updateSlide(draft.id, slideBody(draft)), t('settings.saved'))} <Button loading={busy} disabled={!dirty} onClick={() => run(() => api.updateSlide(draft.id, slideBody(draft)), t('settings.saved'))}
data-testid="signage-slide-save">{t('fees.save')}</Button> data-testid="signage-slide-save">{t('fees.save')}</Button>
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setDraft(structuredClone(saved))}>{t('signage.undo')}</Button> <Button variant="secondary" disabled={!dirty || busy} onClick={() => setDraft(structuredClone(saved))}>{t('signage.undo')}</Button>
{dirty && <span className="text-label text-ink-3">{t('display.looks.unsaved')}</span>} {dirty && <span className="text-label text-ink-3">{t('display.looks.unsaved')}</span>}
<span className="flex-1" />
<Button variant="ghost" icon={<BookmarkPlus size={16} />} onClick={() => setKeeping(true)} data-testid="signage-keep-slide">{t('signage.library.keep')}</Button>
</div> </div>
</> : <p className="text-body text-ink-3 p-6 text-center">{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}</p>} </> : <p className="text-body text-ink-3 p-6 text-center">{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}</p>}
{adding && ( {adding !== null && (
<Dialog open size="lg" title={t('signage.addSlide')} onClose={() => setAdding(false)} <AddSlideDialog onClose={() => setAdding(null)} onPick={addSlide} orientation={pl.orientation} venue={venue} library={adding} libraryMedia={libMedia} />
footer={<Button variant="secondary" onClick={() => setAdding(false)}>{t('fees.cancel')}</Button>}>
<div className="grid gap-4" data-testid="signage-add-dialog">
<div className="grid gap-2">
<span className="text-label font-medium text-ink-2">{t('signage.blank')}</span>
<div className="grid gap-2 grid-cols-2 sm:grid-cols-4">
{['image', 'video', 'text', 'menu'].map(k => {
const Icon = KIND_ICON[k]
return (
<button key={k} type="button" onClick={() => addFrom({ key: k, kind: k, content: {} })} data-testid={`signage-new-${k}`}
className="p-3 rounded-control border border-line bg-surface-2 hover:bg-surface-3 text-left grid gap-1">
<Icon size={18} className="text-ink-2" aria-hidden="true" />
<span className="text-label font-medium text-ink">{t(`signage.kinds.${k}`)}</span>
</button>
)
})}
</div>
</div>
<div className="grid gap-2">
<span className="text-label font-medium text-ink-2">{t('signage.templatesTitle')}</span>
<div className="grid gap-3 grid-cols-2 sm:grid-cols-3">
{TEMPLATES.map(tpl => {
const sample = { id: 0, ...slideFromTemplate(tpl, t), enabled: true, menu: { groups: [] } }
return (
<button key={tpl.key} type="button" onClick={() => addFrom(tpl)} data-testid={`signage-template-${tpl.key}`}
className="rounded-control border border-line bg-surface-2 hover:bg-surface-3 text-left overflow-hidden grid">
<div className="pointer-events-none"><SlidePreview slide={sample} media={() => null} venue={venue} orientation={pl.orientation} testid="signage-template-preview" /></div>
<span className="text-label font-medium text-ink px-2 py-1.5">{t(`signage.templates.${tpl.key}.name`)}</span>
</button>
)
})}
</div>
</div>
</div>
</Dialog>
)} )}
{keeping && draft && <KeepDialog draft={draft} orientation={pl.orientation} onClose={() => setKeeping(false)} />}
{confirmDialog}
{confirmDelete && ( {confirmDelete && (
<Dialog open size="sm" title={t('signage.deletePlaylistTitle', { name: pl.name })} onClose={() => setConfirmDelete(false)} <Dialog open size="sm" title={t('signage.deletePlaylistTitle', { name: pl.name })} onClose={() => setConfirmDelete(false)}
@@ -254,3 +248,39 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
</div> </div>
) )
} }
/** The line where a dragged slide will land: at a card's left side, or after the last one. */
function DropLine({ side }) {
return <span aria-hidden="true" data-testid="signage-drop-line"
className={`absolute top-1 bottom-1 w-1 rounded-full bg-accent pointer-events-none ${side === 'left' ? '-left-2' : '-right-2'}`} />
}
/** Keep the slide (as it is now, saved or not) in the Slides library, with a name and a description. */
function KeepDialog({ draft, orientation, onClose }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(draft.name || '')
const [description, setDescription] = useState('')
const [busy, setBusy] = useState(false)
const keep = async () => {
setBusy(true)
try {
await api.createSaved({ ...slideBody(draft), kind: draft.kind, name: name.trim(), description: description.trim() || null, orientation })
toast.success(t('signage.library.kept'))
onClose()
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
return (
<Dialog open size="sm" title={t('signage.library.keepTitle')} onClose={onClose}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>
<Button loading={busy} disabled={!name.trim()} onClick={keep} data-testid="signage-keep-confirm">{t('signage.library.keepYes')}</Button>
</>}>
<div className="grid gap-3">
<p className="text-label text-ink-2">{t('signage.library.keepHint')}</p>
<Field label={t('signage.library.name')}><Input value={name} autoFocus maxLength={80} onChange={e => setName(e.target.value)} data-testid="signage-keep-name" /></Field>
<Field label={t('signage.library.description')}><Textarea rows={2} value={description} maxLength={300} onChange={e => setDescription(e.target.value)} /></Field>
</div>
</Dialog>
)
}
@@ -13,10 +13,10 @@ import { MONTH_DAYS } from '@xenia/signage'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, EmptyState, Field, FilterChip, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui' import { Button, Dropdown, EmptyState, Field, FilterChip, IconButton, InfoTip, Input, Spinner, Switch } from '@xenia/ui'
import * as api from './signageApi' import * as api from './signageApi'
import { DAY_SHORTCUTS, setDayShortcut, shortcutOf, toggleMonthDay, toggleWeekday } from './signageLogic'
import { listScenes } from '../scenes/scenesApi' import { listScenes } from '../scenes/scenesApi'
const DAYS = [0, 1, 2, 3, 4, 5, 6] const DAYS = [0, 1, 2, 3, 4, 5, 6]
const SHORTCUTS = { everyday: [], weekdays: [0, 1, 2, 3, 4], weekend: [5, 6] }
const KEYS = ['id', 'name', 'playlist_id', 'screen_ids', 'priority', 'enabled', 'days', 'month_days', 'time_from', 'time_to', 'date_from', 'date_to', 'scene_id'] const KEYS = ['id', 'name', 'playlist_id', 'screen_ids', 'priority', 'enabled', 'days', 'month_days', 'time_from', 'time_to', 'date_from', 'date_to', 'scene_id']
const bodyOf = lines => lines.map(l => Object.fromEntries(KEYS.map(k => [k, l[k] ?? (k === 'screen_ids' || k === 'days' || k === 'month_days' ? [] : null)]))) const bodyOf = lines => lines.map(l => Object.fromEntries(KEYS.map(k => [k, l[k] ?? (k === 'screen_ids' || k === 'days' || k === 'month_days' ? [] : null)])))
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
@@ -75,7 +75,7 @@ function Line({ line: l, set, playlists, screens, scenes, onRemove }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const days = l.days || [] const days = l.days || []
const md = l.month_days || [] const md = l.month_days || []
const shortcut = Object.entries(SHORTCUTS).find(([, v]) => same(v, days))?.[0] const shortcut = shortcutOf(l) // days or smart days, not both (owner 2026-11-21)
return ( return (
<li className={`rounded-card border border-line bg-surface shadow-raised p-card grid gap-4 ${l.enabled ? '' : 'opacity-70'}`} data-testid="signage-schedule-entry"> <li className={`rounded-card border border-line bg-surface shadow-raised p-card grid gap-4 ${l.enabled ? '' : 'opacity-70'}`} data-testid="signage-schedule-entry">
{/* playlist · screens · priority · delete: one height, one line (2026-11-21) */} {/* playlist · screens · priority · delete: one height, one line (2026-11-21) */}
@@ -100,18 +100,19 @@ function Line({ line: l, set, playlists, screens, scenes, onRemove }) {
<div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.days')}> <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.days')}>
{DAYS.map(d => ( {DAYS.map(d => (
<FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} data-testid={`signage-entry-day-${d}`} <FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} data-testid={`signage-entry-day-${d}`}
onClick={() => set({ days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort() })}>{t(`signage.weekdays.${d}`)}</FilterChip> onClick={() => set(toggleWeekday(l, d))}>{t(`signage.weekdays.${d}`)}</FilterChip>
))} ))}
<span className="w-px h-6 bg-line mx-1" aria-hidden="true" /> <span className="w-px h-6 bg-line mx-1" aria-hidden="true" />
{Object.entries(SHORTCUTS).map(([k, v]) => ( {Object.keys(DAY_SHORTCUTS).map(k => (
<FilterChip key={k} size="sm" tone="info" pressed={shortcut === k} onClick={() => set({ days: v })} data-testid={`signage-entry-${k}`}>{t(`signage.schedules.shortcuts.${k}`)}</FilterChip> <FilterChip key={k} size="sm" tone="info" pressed={shortcut === k} onClick={() => set(setDayShortcut(k))} data-testid={`signage-entry-${k}`}>{t(`signage.schedules.shortcuts.${k}`)}</FilterChip>
))} ))}
</div> </div>
<div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.schedules.smartDays')}> <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('signage.schedules.smartDays')}>
<span className="text-caption text-ink-3 mr-1">{t('signage.schedules.smartDays')}</span> <span className="text-caption text-ink-3 mr-1">{t('signage.schedules.smartDays')}</span>
<InfoTip>{t('signage.schedules.smartDaysHint')}</InfoTip>
{MONTH_DAYS.map(k => ( {MONTH_DAYS.map(k => (
<FilterChip key={k} size="sm" tone={k === 'not_holiday' ? 'warning' : 'success'} pressed={md.includes(k)} data-testid={`signage-entry-md-${k}`} <FilterChip key={k} size="sm" tone={k === 'not_holiday' ? 'warning' : 'success'} pressed={md.includes(k)} data-testid={`signage-entry-md-${k}`}
onClick={() => set({ month_days: md.includes(k) ? md.filter(x => x !== k) : [...md, k] })}>{t(`signage.schedules.monthDays.${k}`)}</FilterChip> onClick={() => set(toggleMonthDay(l, k))}>{t(`signage.schedules.monthDays.${k}`)}</FilterChip>
))} ))}
</div> </div>
</div> </div>
@@ -1,5 +1,6 @@
// Signage → Screens (plan step 5.6c; 2026-11-21): every paired signage TV with its default playlist, // Signage → Screens (plan step 5.6c; 2026-11-21): every paired signage TV with its default (a
// its shape and how its picture is turned, and what plays on it now. A schedule line for a screen // playlist, or one slide from the Slides library shown alone), its shape and how its picture is
// turned, and what plays on it now. A schedule line for a screen
// (Schedules) wins over its default while it matches. A warning when a playlist it may play was // (Schedules) wins over its default while it matches. A warning when a playlist it may play was
// made for the other shape. New TVs are paired in Devices. // made for the other shape. New TVs are paired in Devices.
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
@@ -15,10 +16,11 @@ export default function ScreensTab() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [screens, setScreens] = useState(null) const [screens, setScreens] = useState(null)
const [playlists, setPlaylists] = useState([]) const [playlists, setPlaylists] = useState([])
const [slides, setSlides] = useState([])
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
const [s, p] = await Promise.all([api.listScreens(), api.listPlaylists()]) const [s, p, l] = await Promise.all([api.listScreens(), api.listPlaylists(), api.listSaved().catch(() => ({ slides: [] }))])
setScreens(s); setPlaylists(p) setScreens(s); setPlaylists(p); setSlides(l.slides)
} catch (err) { toast.error(errorMessage(err, t)) } } catch (err) { toast.error(errorMessage(err, t)) }
}, [t]) }, [t])
useEffect(() => { load() }, [load]) useEffect(() => { load() }, [load])
@@ -50,12 +52,15 @@ export default function ScreensTab() {
</div> </div>
<p className="text-label text-ink-2 flex items-center gap-1.5" data-testid="signage-screen-now"> <p className="text-label text-ink-2 flex items-center gap-1.5" data-testid="signage-screen-now">
{s.now?.scheduled && <CalendarClock size={14} className="text-accent-ink" aria-hidden="true" />} {s.now?.scheduled && <CalendarClock size={14} className="text-accent-ink" aria-hidden="true" />}
{s.now ? t(s.now.scheduled ? 'signage.screens.nowScheduled' : 'signage.screens.nowDefault', { name: s.now.name }) : t('signage.screens.nowNothing')} {s.now ? t(s.now.scheduled ? 'signage.screens.nowScheduled' : s.now.slide ? 'signage.screens.nowSlide' : 'signage.screens.nowDefault', { name: s.now.name }) : t('signage.screens.nowNothing')}
</p> </p>
<div className="grid gap-3 sm:grid-cols-3"> <div className="grid gap-3 sm:grid-cols-3">
<Field label={t('signage.screens.defaultPlaylist')}> <Field label={t('signage.screens.default')} hint={t('signage.screens.defaultHint')}>
<Dropdown value={s.playlist_id ?? ''} data-testid="signage-screen-playlist" onChange={v => save(s.id, { playlist_id: v === '' ? null : Number(v) })} <Dropdown value={s.playlist_id ? `p:${s.playlist_id}` : s.slide_id ? `s:${s.slide_id}` : ''} data-testid="signage-screen-playlist"
options={[{ value: '', label: t('signage.screens.nothing') }, ...playlists.map(p => ({ value: p.id, label: p.name }))]} /> onChange={v => save(s.id, v.startsWith('s:') ? { slide_id: Number(v.slice(2)) } : { playlist_id: v ? Number(v.slice(2)) : null, slide_id: null })}
options={[{ value: '', label: t('signage.screens.nothing') },
...playlists.map(p => ({ value: `p:${p.id}`, label: p.name, hint: t('signage.screens.aPlaylist') })),
...slides.map(x => ({ value: `s:${x.id}`, label: x.name, hint: t('signage.screens.aSlide') }))]} />
</Field> </Field>
<Field label={t('signage.screens.shape')}> <Field label={t('signage.screens.shape')}>
<Dropdown value={s.orientation} onChange={v => save(s.id, { orientation: v })} data-testid="signage-screen-orientation" <Dropdown value={s.orientation} onChange={v => save(s.id, { orientation: v })} data-testid="signage-screen-orientation"
@@ -1,10 +1,39 @@
// Small editors the signage slide editor is built from (plan step 5.6a): a picture / video from the // Small editors the signage slide editor is built from (plan step 5.6a; reworked 2026-11-21): a
// library, a colour, a background (colour or photo with darkening). // section with its title, a picture / video from the library, a colour (ready ones + the picker),
// a background (colour or photo with darkening), a slider with its value.
import { useState } from 'react' import { useState } from 'react'
import { AlertTriangle, Film, ImageIcon, X } from 'lucide-react' import { AlertTriangle, Film, ImageIcon, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, IconButton, Select } from '@xenia/ui' import { Button, Dropdown, Field, IconButton } from '@xenia/ui'
import MediaPicker from '../media/MediaPicker' import MediaPicker from '../media/MediaPicker'
import { COLOUR_PRESETS } from './signageLogic'
/** A part of the slide editor: its title over a thin line, then its fields (DESIGN.md §3). */
export function Section({ title, aside, children, testid, className = '' }) {
return (
<section className={`grid gap-3 content-start ${className}`} data-testid={testid}>
<div className="flex items-center gap-3 min-h-[1.75rem]">
<span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{title}</span>
<span className="flex-1 border-t border-line" aria-hidden="true" />
{aside}
</div>
{children}
</section>
)
}
/** A slider with its label and value, as tall as the fields beside it. */
export function Range({ label, value, min, max, step = 1, onChange, suffix = '', testid }) {
return (
<Field label={label}>
<span className="h-control flex items-center gap-3">
<input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(Number(e.target.value))}
className="flex-1 min-w-0 accent-accent" aria-label={label} data-testid={testid} />
<span className="text-label text-ink-2 tabular-nums w-12 text-right">{value}{suffix}</span>
</span>
</Field>
)
}
/** Pick a picture or a video from the library; `entry` is the media map's item for `value`. */ /** Pick a picture or a video from the library; `entry` is the media map's item for `value`. */
export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, misfit, label, testid }) { export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, misfit, label, testid }) {
@@ -12,7 +41,7 @@ export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, mi
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
return ( return (
<div className="grid gap-1.5" data-testid={testid}> <div className="grid gap-1.5" data-testid={testid}>
{label && <span className="text-label font-medium text-ink-2">{label}</span>} {label && <span className="text-label font-medium text-ink">{label}</span>}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="w-24 h-14 rounded-control border border-line bg-surface-3 overflow-hidden flex items-center justify-center shrink-0"> <div className="w-24 h-14 rounded-control border border-line bg-surface-3 overflow-hidden flex items-center justify-center shrink-0">
{entry?.thumb ? <img src={entry.thumb} alt="" className="w-full h-full object-cover" /> {entry?.thumb ? <img src={entry.thumb} alt="" className="w-full h-full object-cover" />
@@ -38,17 +67,24 @@ export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, mi
) )
} }
/** A colour the venue chooses for its TV (stored as #rrggbb: data, not a theme colour). */ /** A colour the venue chooses for its TV (stored as #rrggbb: data, not a theme colour): a few
export function ColourField({ label, value, onChange, testid }) { * ready colours with one click, and the picker for any other (2026-11-21). */
export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS }) {
const v = (value || '#000000').toLowerCase()
return ( return (
<label className="grid gap-1.5 text-label font-medium text-ink-2"> <div className="grid gap-1.5" role="group" aria-label={label}>
{label} <span className="text-label font-medium text-ink">{label}</span>
<span className="flex items-center gap-2"> <span className="min-h-control flex flex-wrap items-center gap-1.5">
<input type="color" value={value || '#000000'} onChange={e => onChange(e.target.value)} data-testid={testid} {presets.map(c => (
className="w-10 h-10 rounded-control border border-line bg-surface cursor-pointer p-0.5" /> <button key={c} type="button" onClick={() => onChange(c)} aria-label={c} aria-pressed={v === c} title={c}
<span className="text-caption text-ink-3 font-mono">{value}</span> className={`w-7 h-7 rounded-full border border-line-strong shrink-0 transition-transform duration-fast ${v === c ? 'ring-2 ring-accent ring-offset-2 ring-offset-surface' : 'hover:scale-110'}`}
style={{ background: c }} data-testid={testid ? `${testid}-preset` : undefined} />
))}
<input type="color" value={v} onChange={e => onChange(e.target.value)} data-testid={testid} aria-label={label}
className="w-9 h-9 rounded-control border border-line bg-surface cursor-pointer p-0.5 ml-1" />
<span className="text-caption text-ink-3 font-mono">{v}</span>
</span> </span>
</label> </div>
) )
} }
@@ -58,22 +94,26 @@ export function BackgroundField({ value, onChange, media, onMedia, misfit, testi
const bg = value || { kind: 'colour', colour: '#111827', media_id: null, dim: 0, fit: 'cover' } const bg = value || { kind: 'colour', colour: '#111827', media_id: null, dim: 0, fit: 'cover' }
const set = patch => onChange({ ...bg, ...patch }) const set = patch => onChange({ ...bg, ...patch })
return ( return (
<fieldset className="grid gap-3 rounded-control border border-line p-3" data-testid={testid}> <Section title={t('signage.background')} testid={testid}>
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.background')}</legend> <div className="grid gap-4 md:grid-cols-[14rem_minmax(0,1fr)] items-start">
<Select value={bg.kind} onChange={e => set({ kind: e.target.value })} aria-label={t('signage.background')} data-testid={`${testid}-kind`} <Field label={t('signage.bgKind')}>
<Dropdown value={bg.kind} onChange={kind => set({ kind })} data-testid={`${testid}-kind`}
options={[{ value: 'colour', label: t('signage.bgColour') }, { value: 'media', label: t('signage.bgPhoto') }]} /> options={[{ value: 'colour', label: t('signage.bgColour') }, { value: 'media', label: t('signage.bgPhoto') }]} />
</Field>
{bg.kind === 'colour' {bg.kind === 'colour'
? <ColourField label={t('signage.colour')} value={bg.colour} onChange={colour => set({ colour })} testid={`${testid}-colour`} /> ? <ColourField label={t('signage.colour')} value={bg.colour} onChange={colour => set({ colour })} testid={`${testid}-colour`} />
: <> : (
<div className="grid gap-4 sm:grid-cols-[auto_minmax(0,1fr)_12rem] items-end">
<MediaPick kind="image" value={bg.media_id} entry={media?.[String(bg.media_id)]} misfit={misfit} testid={`${testid}-photo`} <MediaPick kind="image" value={bg.media_id} entry={media?.[String(bg.media_id)]} misfit={misfit} testid={`${testid}-photo`}
onChange={item => { onMedia(item); set({ media_id: item.id }) }} onRemove={() => set({ media_id: null })} /> onChange={item => { onMedia(item); set({ media_id: item.id }) }} onRemove={() => set({ media_id: null })} />
<label className="grid gap-1 text-label text-ink-2"> <Range label={t('signage.dimLabel')} value={bg.dim} min={0} max={80} step={5} suffix="%" onChange={dim => set({ dim })} testid={`${testid}-dim`} />
{t('signage.dim', { value: bg.dim })} <Field label={t('signage.fit')}>
<input type="range" min={0} max={80} step={5} value={bg.dim} onChange={e => set({ dim: Number(e.target.value) })} data-testid={`${testid}-dim`} /> <Dropdown value={bg.fit} onChange={fit => set({ fit })}
</label>
<Select value={bg.fit} onChange={e => set({ fit: e.target.value })} aria-label={t('signage.fit')}
options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} /> options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} />
</>} </Field>
</fieldset> </div>
)}
</div>
</Section>
) )
} }
@@ -1,21 +1,24 @@
// Signage (plan steps 5.6a-c; 2026-11-21): the screens (each one's default playlist, shape and // Signage (plan steps 5.6a-c; 2026-11-21): the screens (each one's default playlist, shape and
// turn), the playlists (pick one to edit its timeline and slides; make a new one for a landscape or // turn), the playlists (pick one to edit its timeline and slides; make a new one for a landscape or
// a portrait screen), the schedules (which playlist plays when on which screens, scenes), the // a portrait screen), the schedules (which playlist plays when on which screens, scenes), the
// slides library (single slides to reuse, coming next), the message of the day and the weather's // Slides library (single slides to reuse in playlists or show alone on a screen, 2026-11-21; the
// town: one tab each, in that order; the tab is in the address (?tab=). // slide being edited is ?slide= and the page then fits the screen, its two halves scrolling on
// their own), the message of the day and the weather's town: one tab each, in that order; the
// tab is in the address (?tab=).
// Backend: /api/signage (routers/signage.py). // Backend: /api/signage (routers/signage.py).
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { Layers, Monitor, Plus, Smartphone } from 'lucide-react' import { Monitor, Plus, Smartphone } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, Input, Page, PageHeader, Select, Spinner, Tabs } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, Field, Input, Page, PageHeader, Spinner, Tabs } from '@xenia/ui'
import * as api from './signageApi' import * as api from './signageApi'
import PlaylistEditor from './PlaylistEditor' import PlaylistEditor from './PlaylistEditor'
import SchedulesTab from './SchedulesTab' import SchedulesTab from './SchedulesTab'
import ScreensTab from './ScreensTab' import ScreensTab from './ScreensTab'
import SignageSettingsTab from './SignageSettingsTab' import SignageSettingsTab from './SignageSettingsTab'
import SlidesTab from './SlidesTab'
const TABS = ['screens', 'playlists', 'schedules', 'slides', 'settings'] const TABS = ['screens', 'playlists', 'schedules', 'slides', 'settings']
@@ -26,7 +29,9 @@ export default function SignagePage() {
const [creating, setCreating] = useState(false) const [creating, setCreating] = useState(false)
const [params, setParams] = useSearchParams() const [params, setParams] = useSearchParams()
const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'screens' const tab = TABS.includes(params.get('tab')) ? params.get('tab') : 'screens'
const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); return n }, { replace: true }) const setTab = v => setParams(p => { const n = new URLSearchParams(p); n.set('tab', v); n.delete('slide'); return n }, { replace: true })
const slide = tab === 'slides' && Number(params.get('slide')) > 0 ? Number(params.get('slide')) : null
const openSlide = id => setParams(p => { const n = new URLSearchParams(p); if (id) n.set('slide', String(id)); else n.delete('slide'); return n })
const load = useCallback(async () => { const load = useCallback(async () => {
try { const l = await api.listPlaylists(); setList(l); return l } catch (err) { toast.error(errorMessage(err, t)); return null } try { const l = await api.listPlaylists(); setList(l); return l } catch (err) { toast.error(errorMessage(err, t)); return null }
@@ -34,15 +39,15 @@ export default function SignagePage() {
useEffect(() => { load().then(l => { if (l?.length) setCurrent(c => c ?? l[0].id) }) }, [load]) useEffect(() => { load().then(l => { if (l?.length) setCurrent(c => c ?? l[0].id) }) }, [load])
return ( return (
<Page testId="signage-page" header={<PageHeader title={t('signage.pageTitle')} subtitle={t('signage.intro')} />} <Page testId="signage-page" fit={!!slide} header={<PageHeader title={t('signage.pageTitle')} subtitle={t('signage.intro')} />}
top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('signage.pageTitle')} top={<Tabs size="lg" value={tab} onChange={setTab} aria-label={t('signage.pageTitle')}
tabs={TABS.map(k => ({ id: k, label: t(`signage.tabs.${k}`), testId: `signage-tab-${k}` }))} />}> tabs={TABS.map(k => ({ id: k, label: t(`signage.tabs.${k}`), testId: `signage-tab-${k}` }))} />}>
{tab === 'screens' && <ScreensTab />} {tab === 'screens' && <ScreensTab />}
{tab === 'slides' && <EmptyState icon={<Layers size={28} />} title={t('signage.slidesTab.title')} description={t('signage.slidesTab.body')} />} {tab === 'slides' && <SlidesTab open={slide} onOpen={openSlide} />}
{tab === 'schedules' && <SchedulesTab />} {tab === 'schedules' && <SchedulesTab />}
{tab === 'settings' && <SignageSettingsTab />} {tab === 'settings' && <SignageSettingsTab />}
{tab !== 'playlists' ? null : !list ? <div className="flex justify-center p-6"><Spinner /></div> : ( {tab !== 'playlists' ? null : !list ? <div className="flex justify-center p-6"><Spinner /></div> : (
<div className="grid gap-5 xl:grid-cols-[14rem_1fr]"> <div className="grid gap-5 xl:grid-cols-[14rem_minmax(0,1fr)]">
<nav className="grid gap-2 content-start" aria-label={t('signage.playlists')}> <nav className="grid gap-2 content-start" aria-label={t('signage.playlists')}>
<span className="text-label font-medium text-ink-2">{t('signage.playlists')}</span> <span className="text-label font-medium text-ink-2">{t('signage.playlists')}</span>
<ul className="grid gap-1.5" data-testid="signage-playlists"> <ul className="grid gap-1.5" data-testid="signage-playlists">
@@ -93,7 +98,7 @@ function NewPlaylist({ onClose, onCreate }) {
<Input value={name} autoFocus maxLength={80} onChange={e => setName(e.target.value)} placeholder={t('signage.playlistPlaceholder')} data-testid="signage-new-name" /> <Input value={name} autoFocus maxLength={80} onChange={e => setName(e.target.value)} placeholder={t('signage.playlistPlaceholder')} data-testid="signage-new-name" />
</Field> </Field>
<Field label={t('signage.orientation')} hint={t('signage.orientationHint')}> <Field label={t('signage.orientation')} hint={t('signage.orientationHint')}>
<Select value={orientation} onChange={e => setOrientation(e.target.value)} data-testid="signage-new-orientation" <Dropdown value={orientation} onChange={setOrientation} data-testid="signage-new-orientation"
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} /> options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} />
</Field> </Field>
</div> </div>
@@ -2,49 +2,54 @@
// may show (days, hours, dates), and what it shows (picture, video, text, menu board's look). // may show (days, hours, dates), and what it shows (picture, video, text, menu board's look).
// The parent keeps the draft and saves it; the preview follows every change. // The parent keeps the draft and saves it; the preview follows every change.
// 2026-11-21: in two parts: SlideBasics (beside the preview) and SlideEditor (what it shows, below). // 2026-11-21: in two parts: SlideBasics (beside the preview) and SlideEditor (what it shows, below).
// Reworked 2026-11-21 (owner review): name | show this slide, transition effect | seconds; the
// text's look on one row (alignment, height, font, size) and its colour with ready colours under
// it; sections with a title and a line; blank slides (a background and widgets).
import { AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Dropdown, Field, FilterChip, Input, Select, Switch, Textarea } from '@xenia/ui' import { Dropdown, Field, FilterChip, Input, Segmented, Switch, Textarea } from '@xenia/ui'
import { FONT_KEYS, TRANSITIONS } from './signageLogic' import { FONT_KEYS, TRANSITIONS } from './signageLogic'
import { BackgroundField, ColourField, MediaPick } from './SignageFields' import { BackgroundField, ColourField, MediaPick, Range, Section } from './SignageFields'
import MenuEditor from './MenuEditor' import MenuEditor from './MenuEditor'
import WidgetsEditor from './WidgetsEditor' import WidgetsEditor from './WidgetsEditor'
/** The slide's basics, beside its preview: name, seconds on screen, on / off, transition, when it shows. */ /**
export function SlideBasics({ slide, onChange }) { * The slide's basics: name (unless `showName` is off: the Slides library has its own), show it or
* not, its transition, seconds on screen (or a video to its end), and when it shows.
*/
export function SlideBasics({ slide, onChange, showName = true }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const set = patch => onChange({ ...slide, ...patch }) const set = patch => onChange({ ...slide, ...patch })
const days = slide.days || [] const days = slide.days || []
const toggleDay = d => set({ days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort() }) const toggleDay = d => set({ days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort() })
const toEnd = slide.kind === 'video' && slide.video_to_end
return ( return (
<div className="grid gap-4 content-start" data-testid="signage-slide-basics"> <div className="grid gap-5 content-start" data-testid="signage-slide-basics">
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2 items-end">
{showName && (
<Field label={t('signage.slideName')}> <Field label={t('signage.slideName')}>
<Input value={slide.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-slide-name" /> <Input value={slide.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-slide-name" />
</Field> </Field>
{!(slide.kind === 'video' && slide.video_to_end) ? ( )}
<Field label={t('signage.duration')}> <Switch boxed checked={!!slide.enabled} onChange={on => set({ enabled: on })} label={t('signage.enabled')} data-testid="signage-slide-enabled" />
<Input inputMode="numeric" value={String(slide.duration_s ?? 10)} data-testid="signage-duration"
onChange={e => set({ duration_s: Math.min(3600, Number(e.target.value.replace(/\D/g, '')) || 0) })} />
</Field>
) : <span />}
<Field label={t('signage.transition')}> <Field label={t('signage.transition')}>
<Dropdown value={slide.transition || ''} onChange={v => set({ transition: v || null })} data-testid="signage-transition" <Dropdown value={slide.transition || ''} onChange={v => set({ transition: v || null })} data-testid="signage-transition"
options={[{ value: '', label: t('signage.transitionDefault') }, ...TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))]} /> options={[{ value: '', label: t('signage.transitionDefault') }, ...TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))]} />
</Field> </Field>
<div className="flex items-end pb-2.5"> {!toEnd && (
<Switch checked={!!slide.enabled} onChange={on => set({ enabled: on })} label={t('signage.enabled')} data-testid="signage-slide-enabled" /> <Field label={t('signage.duration')}>
</div> <Input inputMode="numeric" value={String(slide.duration_s ?? 10)} data-testid="signage-duration"
onChange={e => set({ duration_s: Math.min(3600, Number(e.target.value.replace(/\D/g, '')) || 0) })} />
</Field>
)}
{slide.kind === 'video' && ( {slide.kind === 'video' && (
<div className="sm:col-span-2"> <Switch boxed className="sm:col-span-2" checked={!!slide.video_to_end} onChange={on => set({ video_to_end: on })} label={t('signage.videoToEnd')}
<Switch checked={!!slide.video_to_end} onChange={on => set({ video_to_end: on })} label={t('signage.videoToEnd')}
description={t('signage.videoToEndHint')} data-testid="signage-video-to-end" /> description={t('signage.videoToEndHint')} data-testid="signage-video-to-end" />
</div>
)} )}
</div> </div>
<fieldset className="grid gap-3 rounded-control border border-line p-3"> <Section title={t('signage.when')}>
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.when')}</legend> <p className="text-caption text-ink-3 -mt-1">{t('signage.whenHint')}</p>
<p className="text-caption text-ink-3">{t('signage.whenHint')}</p>
<div className="flex flex-wrap gap-1.5" role="group" aria-label={t('signage.days')}> <div className="flex flex-wrap gap-1.5" role="group" aria-label={t('signage.days')}>
{[0, 1, 2, 3, 4, 5, 6].map(d => ( {[0, 1, 2, 3, 4, 5, 6].map(d => (
<FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} onClick={() => toggleDay(d)} data-testid={`signage-day-${d}`}> <FilterChip key={d} size="sm" tone="accent" pressed={days.includes(d)} onClick={() => toggleDay(d)} data-testid={`signage-day-${d}`}>
@@ -52,95 +57,114 @@ export function SlideBasics({ slide, onChange }) {
</FilterChip> </FilterChip>
))} ))}
</div> </div>
<div className="grid gap-3 grid-cols-2"> <div className="grid gap-3 grid-cols-2 xl:grid-cols-4">
<Field label={t('signage.timeFrom')}><Input type="time" value={slide.time_from || ''} onChange={e => set({ time_from: e.target.value || null })} data-testid="signage-time-from" /></Field> <Field label={t('signage.timeFrom')}><Input type="time" value={slide.time_from || ''} onChange={e => set({ time_from: e.target.value || null })} data-testid="signage-time-from" /></Field>
<Field label={t('signage.timeTo')}><Input type="time" value={slide.time_to || ''} onChange={e => set({ time_to: e.target.value || null })} data-testid="signage-time-to" /></Field> <Field label={t('signage.timeTo')}><Input type="time" value={slide.time_to || ''} onChange={e => set({ time_to: e.target.value || null })} data-testid="signage-time-to" /></Field>
<Field label={t('signage.dateFrom')}><Input type="date" value={slide.date_from || ''} onChange={e => set({ date_from: e.target.value || null })} data-testid="signage-date-from" /></Field> <Field label={t('signage.dateFrom')}><Input type="date" value={slide.date_from || ''} onChange={e => set({ date_from: e.target.value || null })} data-testid="signage-date-from" /></Field>
<Field label={t('signage.dateTo')}><Input type="date" value={slide.date_to || ''} onChange={e => set({ date_to: e.target.value || null })} data-testid="signage-date-to" /></Field> <Field label={t('signage.dateTo')}><Input type="date" value={slide.date_to || ''} onChange={e => set({ date_to: e.target.value || null })} data-testid="signage-date-to" /></Field>
</div> </div>
</fieldset> </Section>
</div> </div>
) )
} }
/** What the slide shows (below the basics and the preview): picture, video, text, menu board. */ /**
export default function SlideEditor({ slide, onChange, media, onMedia, misfit = [] }) { * What the slide shows: picture, video, text, menu board or blank. `widget` / `onWidget`: the
* widget picked on the preview (its card is highlighted).
*/
export default function SlideEditor({ slide, onChange, media, onMedia, misfit = [], widget = null, onWidget }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const set = patch => onChange({ ...slide, ...patch }) const set = patch => onChange({ ...slide, ...patch })
const c = slide.content || {} const c = slide.content || {}
const setC = patch => set({ content: { ...c, ...patch } }) const setC = patch => set({ content: { ...c, ...patch } })
const bad = id => misfit.includes(id) const bad = id => misfit.includes(id)
const widgets = <WidgetsEditor widgets={c.widgets || []} onChange={ws => setC({ widgets: ws })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} />
return ( const fit = (
<div className="grid gap-5" data-testid="signage-slide-editor" data-kind={slide.kind}>
{slide.kind === 'image' && (
<div className="grid gap-3">
<MediaPick kind="image" label={t('signage.picture')} value={c.media_id} entry={media[String(c.media_id)]} misfit={bad(c.media_id)}
onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-picture" />
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('signage.fit')}> <Field label={t('signage.fit')}>
<Select value={c.fit || 'cover'} onChange={e => setC({ fit: e.target.value })} <Dropdown value={c.fit || 'cover'} onChange={v => setC({ fit: v })}
options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} /> options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} />
</Field> </Field>
)
return (
<div className="grid gap-7" data-testid="signage-slide-editor" data-kind={slide.kind}>
{slide.kind === 'image' && (
<Section title={t('signage.picture')}>
<MediaPick kind="image" value={c.media_id} entry={media[String(c.media_id)]} misfit={bad(c.media_id)}
onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-picture" />
<div className="grid gap-4 md:grid-cols-[16rem_minmax(0,1fr)] items-start">
{fit}
<ColourField label={t('signage.around')} value={c.background_colour || '#000000'} onChange={v => setC({ background_colour: v })} /> <ColourField label={t('signage.around')} value={c.background_colour || '#000000'} onChange={v => setC({ background_colour: v })} />
</div> </div>
</div> </Section>
)} )}
{slide.kind === 'video' && ( {slide.kind === 'video' && (
<div className="grid gap-3"> <Section title={t('signage.video')}>
<MediaPick kind="video" label={t('signage.video')} value={c.media_id} entry={media[String(c.media_id)]} misfit={bad(c.media_id)} <MediaPick kind="video" value={c.media_id} entry={media[String(c.media_id)]} misfit={bad(c.media_id)}
onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-video" /> onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-video" />
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2 items-end">
<Field label={t('signage.fit')}> {fit}
<Select value={c.fit || 'cover'} onChange={e => setC({ fit: e.target.value })} <Switch boxed checked={c.muted !== false} onChange={on => setC({ muted: on })} label={t('signage.muted')} />
options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} />
</Field>
<div className="flex items-end pb-1"><Switch checked={c.muted !== false} onChange={on => setC({ muted: on })} label={t('signage.muted')} /></div>
</div>
</div> </div>
</Section>
)} )}
{slide.kind === 'text' && ( {slide.kind === 'text' && <>
<div className="grid gap-3"> <Section title={t('signage.textTitle')}>
<Field label={t('signage.title')}><Input value={c.title || ''} maxLength={120} onChange={e => setC({ title: e.target.value })} data-testid="signage-text-title" /></Field> <Field label={t('signage.title')}><Input value={c.title || ''} maxLength={120} onChange={e => setC({ title: e.target.value })} data-testid="signage-text-title" /></Field>
<Field label={t('signage.body')}><Textarea rows={3} value={c.body || ''} maxLength={1000} onChange={e => setC({ body: e.target.value })} data-testid="signage-text-body" /></Field> <Field label={t('signage.body')}><Textarea rows={3} value={c.body || ''} maxLength={1000} onChange={e => setC({ body: e.target.value })} data-testid="signage-text-body" /></Field>
</Section>
<TextLook c={c} setC={setC} /> <TextLook c={c} setC={setC} />
<BackgroundField value={c.background} onChange={background => setC({ background })} media={media} onMedia={onMedia} <BackgroundField value={c.background} onChange={background => setC({ background })} media={media} onMedia={onMedia}
misfit={bad(c.background?.media_id)} /> misfit={bad(c.background?.media_id)} />
<WidgetsEditor widgets={c.widgets || []} onChange={widgets => setC({ widgets })} media={media} onMedia={onMedia} /> {widgets}
</div> </>}
)}
{slide.kind === 'menu' && <MenuEditor slide={slide} onChange={onChange} media={media} onMedia={onMedia} misfit={misfit} />} {slide.kind === 'blank' && <>
<BackgroundField value={c.background} onChange={background => setC({ background })} media={media} onMedia={onMedia}
misfit={bad(c.background?.media_id)} />
{widgets}
</>}
{slide.kind === 'menu' && <MenuEditor slide={slide} onChange={onChange} media={media} onMedia={onMedia} misfit={misfit} widget={widget} onWidget={onWidget} />}
</div> </div>
) )
} }
/** Alignment, font, colour and size of a text slide. */ /**
export function TextLook({ c, setC, align = true }) { * The look of a text: alignment, height, font and size on one row, its colour (ready colours and
* the picker) under them. A menu board (`align` off) has no alignment / height; it passes its
* accent colour as `children`, beside the text's colour.
*/
export function TextLook({ c, setC, align = true, children }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
return ( return (
<div className="grid gap-3 sm:grid-cols-2"> <Section title={t('signage.textLook')} testid="signage-text-look">
<div className={`grid gap-4 items-end ${align ? 'grid-cols-2 xl:grid-cols-4' : 'sm:grid-cols-2'}`}>
{align && <> {align && <>
<Field label={t('signage.align')}> <Field label={t('signage.align')}>
<Select value={c.align || 'center'} onChange={e => setC({ align: e.target.value })} <Segmented value={c.align || 'center'} onChange={v => setC({ align: v })} data-testid="signage-align" fill
options={['left', 'center', 'right'].map(x => ({ value: x, label: t(`signage.aligns.${x}`) }))} /> options={[['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.aligns.${v}`), testId: `signage-align-${v}` }))} />
</Field> </Field>
<Field label={t('signage.vertical')}> <Field label={t('signage.vertical')}>
<Select value={c.vertical || 'middle'} onChange={e => setC({ vertical: e.target.value })} <Segmented value={c.vertical || 'middle'} onChange={v => setC({ vertical: v })} data-testid="signage-vertical" fill
options={['top', 'middle', 'bottom'].map(x => ({ value: x, label: t(`signage.verticals.${x}`) }))} /> options={[['top', AlignVerticalJustifyStart], ['middle', AlignVerticalJustifyCenter], ['bottom', AlignVerticalJustifyEnd]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.verticals.${v}`), testId: `signage-vertical-${v}` }))} />
</Field> </Field>
</>} </>}
<Field label={t('signage.font')}> <Field label={t('signage.font')}>
<Select value={c.font || 'sans'} onChange={e => setC({ font: e.target.value })} data-testid="signage-font" <Dropdown value={c.font || 'sans'} onChange={v => setC({ font: v })} data-testid="signage-font"
options={FONT_KEYS.map(x => ({ value: x, label: t(`signage.fonts.${x}`) }))} /> options={FONT_KEYS.map(x => ({ value: x, label: t(`signage.fonts.${x}`) }))} />
</Field> </Field>
<ColourField label={t('signage.textColour')} value={c.text_colour || '#ffffff'} onChange={v => setC({ text_colour: v })} testid="signage-text-colour" /> <Range label={t('signage.textSizeLabel')} value={c.text_size || 100} min={50} max={250} step={10} suffix="%"
<label className="grid gap-1 text-label font-medium text-ink-2 sm:col-span-2"> onChange={v => setC({ text_size: v })} testid="signage-text-size" />
{t('signage.textSize', { value: c.text_size || 100 })}
<input type="range" min={50} max={250} step={10} value={c.text_size || 100} onChange={e => setC({ text_size: Number(e.target.value) })} data-testid="signage-text-size" />
</label>
</div> </div>
<div className={`grid gap-4 ${children ? 'lg:grid-cols-2' : ''}`}>
<ColourField label={t('signage.textColour')} value={c.text_colour || '#ffffff'} onChange={v => setC({ text_colour: v })} testid="signage-text-colour" />
{children}
</div>
</Section>
) )
} }
@@ -1,13 +1,16 @@
// A slide drawn exactly as the TV draws it (@xenia/signage), in a box of the playlist's shape // A slide drawn exactly as the TV draws it (@xenia/signage), in a box of the playlist's shape
// (plan step 5.6a). The slide is laid out on a full-size 1920 × 1080 (or 1080 × 1920) frame and // (plan step 5.6a). The slide is laid out on a full-size 1920 × 1080 (or 1080 × 1920) frame and
// scaled down to the box, so text, rows and menu pages match a real TV, not a small window. // scaled down to the box, so text, rows and menu pages match a real TV, not a small window.
// `editor` = { selected, onSelect, onPlace, label } (2026-11-21): the widgets can be picked, moved
// and sized on it (WidgetCanvas).
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { boardPages, SlideView } from '@xenia/signage' import { boardPages, SlideView, WIDGET_HOSTS } from '@xenia/signage'
import WidgetCanvas from './WidgetCanvas'
const LONG = 1920 const LONG = 1920
const SHORT = 1080 const SHORT = 1080
export default function SlidePreview({ slide, media, venue, orientation = 'landscape', page = 0, playing = false, className = '', testid = 'signage-preview' }) { export default function SlidePreview({ slide, media, venue, orientation = 'landscape', page = 0, playing = false, className = '', testid = 'signage-preview', editor = null }) {
const [now, setNow] = useState(() => new Date()) const [now, setNow] = useState(() => new Date())
const box = useRef(null) const box = useRef(null)
const [scale, setScale] = useState(0) const [scale, setScale] = useState(0)
@@ -29,13 +32,20 @@ export default function SlidePreview({ slide, media, venue, orientation = 'lands
}, [w]) }, [w])
const pages = slide?.kind === 'menu' ? boardPages(slide, 0, w, h) : null const pages = slide?.kind === 'menu' ? boardPages(slide, 0, w, h) : null
return ( return (
<div ref={box} className={`relative overflow-hidden rounded-control bg-black ${className}`} data-testid={testid} data-orientation={orientation} <div ref={box} className={`relative rounded-control ${className}`} data-testid={testid} data-orientation={orientation}
style={{ aspectRatio: tall ? '9 / 16' : '16 / 9' }}> style={{ aspectRatio: tall ? '9 / 16' : '16 / 9' }}>
{/* the slide is clipped to its frame; the editor's handles may stick out of it */}
<div className="absolute inset-0 overflow-hidden rounded-control bg-black">
{slide && scale > 0 && ( {slide && scale > 0 && (
<div style={{ position: 'absolute', top: 0, left: 0, width: w, height: h, transform: `scale(${scale})`, transformOrigin: 'top left', containerType: 'size' }}> <div style={{ position: 'absolute', top: 0, left: 0, width: w, height: h, transform: `scale(${scale})`, transformOrigin: 'top left', containerType: 'size' }}>
<SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={Math.min(page, (pages?.length || 1) - 1)} playing={playing} /> <SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={Math.min(page, (pages?.length || 1) - 1)} playing={playing} />
</div> </div>
)} )}
</div> </div>
{editor && slide && scale > 0 && WIDGET_HOSTS.includes(slide.kind) && (
<WidgetCanvas boxRef={box} widgets={slide.content?.widgets || []} selected={editor.selected} onSelect={editor.onSelect}
onPlace={editor.onPlace} label={editor.label} />
)}
</div>
) )
} }
@@ -0,0 +1,171 @@
// Signage → Slides (owner 2026-11-21): the venue's own slides, built once and kept with a name and
// a short description, to add to any playlist (a copy goes in: "Add a slide" → Your slides) or to
// show alone on a screen (Screens → its default). The gallery shows each one drawn as the TV
// draws it; opening one splits the page in two halves that scroll on their own: its preview (the
// widgets can be moved and sized on it), name, description and shape on the left, every setting
// on the right. The slide being edited is in the address (?slide=).
import { useCallback, useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { ArrowLeft, Copy, Layers, Monitor, Pencil, Plus, Smartphone, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, IconButton, Input, Pane, Segmented, Spinner, Textarea, useConfirm } from '@xenia/ui'
import * as api from './signageApi'
import { mediaEntry, mediaLookup, misfits, savedBody } from './signageLogic'
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog'
import SlideEditor, { SlideBasics } from './SlideEditor'
import SlidePreview from './SlidePreview'
import { useMenuPreview, useWidgetEditor } from './useSlideDraft'
export default function SlidesTab({ open, onOpen }) {
const { t } = useTranslation('manager')
const [list, setList] = useState(null)
const [media, setMedia] = useState({})
const [venue, setVenue] = useState(null)
const [creating, setCreating] = useState(false)
const [confirm, confirmDialog] = useConfirm()
const load = useCallback(async () => {
try { const r = await api.listSaved(); setList(r.slides); setMedia(r.media) } catch (err) { toast.error(errorMessage(err, t)) }
}, [t])
useEffect(() => { load(); api.previewVenue().then(setVenue).catch(() => {}) }, [load])
if (open) return <SavedSlideEditor id={open} venue={venue} onClose={() => { onOpen(null); load() }} />
if (!list) return <div className="flex justify-center p-6"><Spinner /></div>
const create = async body => {
setCreating(false)
try {
const s = await api.createSaved({ ...body, name: t('signage.library.newName', { kind: t(`signage.kinds.${body.kind}`) }), orientation: 'landscape' })
onOpen(s.id)
} catch (err) { toast.error(errorMessage(err, t)) }
}
const remove = async s => {
const ok = await confirm({ title: t('signage.library.deleteTitle', { name: s.name }), tone: 'danger', confirmLabel: t('fees.delete'), testId: 'signage-saved-delete-confirm',
body: s.screens?.length ? t('signage.library.deleteUsed', { names: s.screens.map(x => x.name).join(', ') }) : t('signage.library.deleteBody') })
if (!ok) return
try { await api.deleteSaved(s.id); toast.success(t('signage.removed')); load() } catch (err) { toast.error(errorMessage(err, t)) }
}
const duplicate = async s => {
try { await api.duplicateSaved(s.id); toast.success(t('signage.duplicated')); load() } catch (err) { toast.error(errorMessage(err, t)) }
}
return (
<div className="grid gap-4" data-testid="signage-slides">
<div className="flex flex-wrap items-center gap-3">
<p className="text-label text-ink-2 max-w-3xl flex-1">{t('signage.library.intro')}</p>
<Button icon={<Plus size={16} />} onClick={() => setCreating(true)} data-testid="signage-saved-new">{t('signage.library.new')}</Button>
</div>
{list.length === 0
? <EmptyState icon={<Layers size={28} />} title={t('signage.library.none')} description={t('signage.library.noneHint')} />
: (
<ul className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]" data-testid="signage-saved-list">
{list.map(s => {
const Icon = KIND_ICON[s.kind]
const Shape = s.orientation === 'portrait' ? Smartphone : Monitor
return (
<li key={s.id} className="rounded-card border border-line bg-surface shadow-raised overflow-hidden grid content-start" data-testid="signage-saved" data-name={s.name}>
<button type="button" onClick={() => onOpen(s.id)} className="block bg-surface-2 p-3" aria-label={t('signage.library.edit', { name: s.name })}>
<div className="pointer-events-none mx-auto" style={{ width: s.orientation === 'portrait' ? '40%' : '100%' }}>
<SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={s.orientation} testid="signage-saved-preview" />
</div>
</button>
<div className="p-card grid gap-1 min-w-0">
<span className="flex items-center gap-1.5 min-w-0">
<Icon size={15} className="text-ink-2 shrink-0" aria-hidden="true" />
<span className="text-body font-semibold text-ink truncate">{s.name}</span>
<Shape size={14} className="text-ink-3 shrink-0 ml-auto" aria-label={t(`signage.orientations.${s.orientation}`)} />
</span>
<span className="text-caption text-ink-3 line-clamp-2 min-h-[2.2em]">{s.description || t(`signage.kinds.${s.kind}`)}</span>
{s.screens?.length > 0 && <span className="text-caption text-success-ink truncate">{t('signage.library.onScreens', { names: s.screens.map(x => x.name).join(', ') })}</span>}
<div className="flex gap-1 pt-2 justify-end">
<IconButton size="sm" tone="accent" label={t('signage.library.edit', { name: s.name })} onClick={() => onOpen(s.id)} data-testid="signage-saved-edit"><Pencil size={15} /></IconButton>
<IconButton size="sm" tone="info" label={t('signage.duplicateSlide')} onClick={() => duplicate(s)} data-testid="signage-saved-duplicate"><Copy size={15} /></IconButton>
<IconButton size="sm" tone="danger" label={t('fees.delete')} onClick={() => remove(s)} data-testid="signage-saved-delete"><Trash2 size={15} /></IconButton>
</div>
</div>
</li>
)
})}
</ul>
)}
{creating && <AddSlideDialog title={t('signage.library.new')} onClose={() => setCreating(false)} onPick={create} venue={venue} />}
{confirmDialog}
</div>
)
}
/** One library slide: preview and its name / description / shape on the left, its settings on the right. */
function SavedSlideEditor({ id, venue, onClose }) {
const { t } = useTranslation('manager')
const [saved, setSaved] = useState(null)
const [draft, setDraft] = useState(null)
const [media, setMedia] = useState({})
const [busy, setBusy] = useState(false)
const [confirm, confirmDialog] = useConfirm()
const { widget, setWidget, editor } = useWidgetEditor(setDraft, id, t('signage.widgets.canvas'))
useEffect(() => {
api.getSaved(id).then(s => { setSaved(s); setDraft(structuredClone(s)); setMedia(s.media || {}) })
.catch(err => { toast.error(errorMessage(err, t)); onClose() })
}, [id]) // eslint-disable-line react-hooks/exhaustive-deps
useMenuPreview(draft, setDraft)
const dirty = useMemo(() => !!(draft && saved && JSON.stringify(savedBody(draft)) !== JSON.stringify(savedBody(saved))), [draft, saved])
const draftBad = useMemo(() => (draft ? misfits([draft], media, draft.orientation)[draft.id] || [] : []), [draft, media])
if (!draft) return <div className="flex justify-center p-6"><Spinner /></div>
const set = patch => setDraft(d => ({ ...d, ...patch }))
const save = async () => {
setBusy(true)
try { const s = await api.updateSaved(id, savedBody(draft)); setSaved(s); setDraft(d => ({ ...structuredClone(s), menu: d.menu })); toast.success(t('settings.saved')) }
catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
const back = async () => {
if (dirty && !(await confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', testId: 'signage-discard' }))) return
onClose()
}
const tall = draft.orientation === 'portrait'
return (
<div className="x-page__fill grid gap-5 lg:grid-cols-2" data-testid="signage-saved-editor" data-id={id}>
<Pane header={
<div className="flex items-center gap-2 px-card py-card-y">
<IconButton variant="ghost" label={t('signage.library.back')} onClick={back} data-testid="signage-saved-back"><ArrowLeft size={18} /></IconButton>
<h2 className="text-body-lg font-semibold text-ink truncate flex-1 min-w-0">{draft.name || t('signage.library.untitled')}</h2>
{dirty && <span className="text-label text-ink-3 hidden xl:inline">{t('display.looks.unsaved')}</span>}
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setDraft(d => ({ ...structuredClone(saved), menu: d.menu }))}>{t('signage.undo')}</Button>
<Button loading={busy} disabled={!dirty || !draft.name?.trim()} onClick={save} data-testid="signage-saved-save">{t('fees.save')}</Button>
</div>
}>
<div className="p-card grid gap-6 content-start">
<div className="mx-auto w-full" style={{ maxWidth: tall ? '22rem' : undefined }}>
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={draft.orientation} playing editor={editor} testid="signage-saved-live" />
</div>
<div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_auto] items-end">
<Field label={t('signage.library.name')}>
<Input value={draft.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-saved-name" />
</Field>
<Field label={t('signage.orientation')}>
<Segmented value={draft.orientation} onChange={v => set({ orientation: v })} data-testid="signage-saved-orientation"
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`), icon: o === 'portrait' ? <Smartphone size={15} aria-hidden="true" /> : <Monitor size={15} aria-hidden="true" /> }))} />
</Field>
</div>
<Field label={t('signage.library.description')} hint={t('signage.library.descriptionHint')}>
<Textarea rows={3} value={draft.description || ''} maxLength={300} onChange={e => set({ description: e.target.value })} data-testid="signage-saved-description" />
</Field>
<p className="text-caption text-ink-3">
{t('signage.library.kindIs', { kind: t(`signage.kinds.${draft.kind}`) })}
{saved.screens?.length > 0 && <> · {t('signage.library.onScreens', { names: saved.screens.map(x => x.name).join(', ') })}</>}
</p>
</div>
</Pane>
<Pane header={<h3 className="px-card py-card-y text-body font-semibold text-ink">{t('signage.library.settings')}</h3>}>
<div className="p-card grid gap-7 content-start">
<SlideBasics slide={draft} onChange={setDraft} showName={false} />
<SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))}
misfit={draftBad} widget={widget} onWidget={setWidget} />
</div>
</Pane>
{confirmDialog}
</div>
)
}
@@ -0,0 +1,111 @@
// 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).
import { useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from '@xenia/i18n'
import { boxFromRect, moveBox, resizeBox, snapBox } 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
export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPlace, label }) {
const { t } = useTranslation('manager')
const [rects, setRects] = useState({})
const [guides, setGuides] = useState([])
const last = useRef('')
// where each widget is drawn now (the clock ticks, texts change): measured after every render
// (on purpose without deps; it only sets state when something moved)
// 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]')) {
const r = el.getBoundingClientRect()
out[el.getAttribute('data-widget')] = boxFromRect(r, frame)
}
const key = JSON.stringify(out)
if (key !== last.current) { last.current = key; setRects(out) }
})
const start = (e, i, handle = null) => {
e.preventDefault()
e.stopPropagation()
onSelect(i)
e.currentTarget.closest('[data-testid="signage-canvas"]')?.focus({ preventScroll: true })
const box = boxRef.current
const w = widgets[i]
const base = w?.position === 'custom' && w.box ? w.box : rects[i]
if (!box || !base) return
const { width, height } = box.getBoundingClientRect()
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 next = handle ? resizeBox(base, handle, dx, dy) : moveBox(base, dx, dy)
const snapped = snapBox(next, handle)
setGuides(snapped.guides)
onPlace(i, snapped.box)
}
const up = () => {
window.removeEventListener('pointermove', move)
window.removeEventListener('pointerup', up)
setGuides([])
}
window.addEventListener('pointermove', move)
window.addEventListener('pointerup', up)
}
const key = e => {
if (selected == null) return
if (e.key === 'Escape') { onSelect(null); 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 w = widgets[selected]
const base = w?.position === 'custom' && w.box ? w.box : rects[selected]
if (base) onPlace(selected, moveBox(base, d[0], d[1]))
}
const sel = selected != null ? (widgets[selected]?.position === 'custom' && widgets[selected].box) || rects[selected] : null
return (
<div className="absolute inset-0 outline-none" tabIndex={0} onKeyDown={key} onPointerDown={() => onSelect(null)}
role="application" aria-label={label} data-testid="signage-canvas">
{widgets.map((w, i) => rects[i] && (
<div key={i} className={`absolute cursor-move rounded-sm ${selected === i ? '' : 'hover:outline hover:outline-2 hover:outline-accent/60'}`}
style={{ left: `${rects[i].x}%`, top: `${rects[i].y}%`, width: `${rects[i].w}%`, height: `${rects[i].h}%` }}
onPointerDown={e => start(e, i)} data-testid="signage-canvas-widget" data-index={i} 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 }} />
})}
{sel && (
<div className="absolute pointer-events-none outline outline-2 outline-accent" data-testid="signage-canvas-selected"
style={{ left: `${sel.x}%`, top: `${sel.y}%`, width: `${sel.w}%`, height: `${sel.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 ${sel.y < 8 ? 'top-full mt-2' : 'bottom-full mb-2'}`}>
{t(`signage.widgets.kinds.${widgets[selected]?.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, selected, h)} />
))}
</div>
)}
</div>
)
}
@@ -1,77 +1,130 @@
// The widgets of a text or menu slide (plan step 5.6b): logo, name, date, clock, message of the // The widgets of a text, menu or blank slide (plan step 5.6b; reworked 2026-11-21): logo, name,
// day, QR code, weather; each in a corner or a bar, small / medium / large, with its own options. // date, clock, message of the day, QR code, weather. Each in its own card: its name first, then
// its settings on one row (where, size, alignment, its own options). Where / size read "Custom"
// once it was moved or sized by hand on the preview (WidgetCanvas); picking a corner or a bar
// puts it back. The card of the widget picked on the preview is highlighted (the page doesn't
// jump to it: the preview stays in view while you drag).
// Up to 10 (the server's limit). // Up to 10 (the server's limit).
import { Plus, Trash2 } from 'lucide-react' import { AlignCenter, AlignLeft, AlignRight, CalendarDays, Clock, CloudSun, ImageIcon, MessageSquare, Plus, QrCode, Store, Trash2 } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Field, IconButton, Input, Select, Switch } from '@xenia/ui' import { Button, Dropdown, Field, IconButton, Input, Segmented, Switch } from '@xenia/ui'
import { MediaPick } from './SignageFields' import { MediaPick, Section } from './SignageFields'
import { WIDGET_KINDS, WIDGET_POSITIONS } from './signageLogic' import { presetWidget, WIDGET_KINDS, WIDGET_POSITIONS } from './signageLogic'
export default function WidgetsEditor({ widgets = [], onChange, media, onMedia }) { const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, qr: QrCode, weather: CloudSun }
export default function WidgetsEditor({ widgets = [], onChange, media, onMedia, selected = null, onSelect }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const set = (i, patch) => onChange(widgets.map((w, j) => (j === i ? { ...w, ...patch } : w))) const set = (i, patch) => onChange(widgets.map((w, j) => (j === i ? { ...w, ...patch } : w)))
const add = kind => onChange([...widgets, { kind, position: kind === 'message' ? 'bottom-bar' : 'top-right', size: 'medium' }]) const add = kind => {
onChange([...widgets, { kind, position: kind === 'message' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto' }])
onSelect?.(widgets.length)
}
return ( return (
<fieldset className="grid gap-3 rounded-control border border-line p-3" data-testid="signage-widgets"> <Section title={t('signage.widgets.title')} testid="signage-widgets">
<legend className="px-1 text-label font-medium text-ink-2">{t('signage.widgets.title')}</legend> <p className="text-caption text-ink-3 -mt-1">{t(widgets.length ? 'signage.widgets.dragHint' : 'signage.widgets.none')}</p>
{widgets.length === 0 && <p className="text-caption text-ink-3">{t('signage.widgets.none')}</p>} {widgets.map((w, i) => {
{widgets.map((w, i) => ( const Icon = ICON[w.kind] || ImageIcon
<div key={i} className="grid gap-2 rounded-control bg-surface-2 p-2" data-testid="signage-widget" data-kind={w.kind}> const custom = w.position === 'custom'
<div className="flex flex-wrap items-end gap-2"> const on = selected === i
<span className="text-label font-medium text-ink min-w-[6rem] pb-2">{t(`signage.widgets.kinds.${w.kind}`)}</span> return (
<Field label={t('signage.widgets.position')} className="flex-1 min-w-[9rem]"> <div key={i} onPointerDown={() => onSelect?.(i)}
<Select value={w.position} onChange={e => set(i, { position: e.target.value })} data-testid="signage-widget-position" className={`grid gap-3 rounded-card border p-4 transition-colors duration-fast ${on ? 'border-accent bg-accent-soft/40 ring-1 ring-accent' : 'border-line bg-surface-2'}`}
options={WIDGET_POSITIONS.map(p => ({ value: p, label: t(`signage.widgets.positions.${p}`) }))} /> data-testid="signage-widget" data-kind={w.kind} data-selected={on ? 'true' : undefined}>
</Field> <div className="flex items-center gap-2">
<Field label={t('signage.widgets.size')}> <Icon size={16} className="text-ink-2 shrink-0" aria-hidden="true" />
<Select value={w.size || 'medium'} onChange={e => set(i, { size: e.target.value })} <span className="text-body font-semibold text-ink">{t(`signage.widgets.kinds.${w.kind}`)}</span>
options={['small', 'medium', 'large'].map(s => ({ value: s, label: t(`signage.widgets.sizes.${s}`) }))} /> <span className="flex-1" />
</Field> <IconButton size="sm" tone="danger" label={t('fees.delete')} data-testid="signage-widget-remove"
<IconButton variant="ghost" label={t('fees.delete')} onClick={() => onChange(widgets.filter((_, j) => j !== i))} data-testid="signage-widget-remove"><Trash2 size={16} /></IconButton> onClick={e => { e.stopPropagation(); onChange(widgets.filter((_, j) => j !== i)); onSelect?.(null) }}><Trash2 size={16} /></IconButton>
</div> </div>
{w.kind === 'logo' && ( <div className="flex flex-wrap items-end gap-3">
<MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo" <Field label={t('signage.widgets.position')} className="w-44">
onChange={item => { onMedia(item); set(i, { media_id: item.id }) }} /> <Dropdown value={w.position} onChange={p => p !== 'custom' && onChange(widgets.map((x, j) => (j === i ? presetWidget(x, p) : x)))}
)} data-testid="signage-widget-position"
{w.kind === 'message' && ( options={[...WIDGET_POSITIONS.map(p => ({ value: p, label: t(`signage.widgets.positions.${p}`) })),
<Field label={t('signage.widgets.ownText')} hint={t('signage.widgets.ownTextHint')}> ...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} />
<Input value={w.text || ''} maxLength={200} onChange={e => set(i, { text: e.target.value || null })} data-testid="signage-widget-text" />
</Field> </Field>
<Field label={t('signage.widgets.size')} className="w-36">
<Dropdown value={custom ? 'custom' : (w.size || 'medium')} disabled={custom} onChange={size => set(i, { size })} data-testid="signage-widget-size"
options={[...['small', 'medium', 'large'].map(s => ({ value: s, label: t(`signage.widgets.sizes.${s}`) })),
...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} />
</Field>
<Field label={t('signage.widgets.align')}>
<Segmented value={w.align || 'auto'} onChange={align => set(i, { align })} aria-label={t('signage.widgets.align')} data-testid="signage-widget-align"
options={[
{ value: 'auto', label: t('signage.widgets.alignAuto'), testId: 'signage-widget-align-auto' },
{ value: 'left', icon: <AlignLeft size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.left'), testId: 'signage-widget-align-left' },
{ value: 'center', icon: <AlignCenter size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.center'), testId: 'signage-widget-align-center' },
{ value: 'right', icon: <AlignRight size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.right'), testId: 'signage-widget-align-right' },
]} />
</Field>
<KindFields w={w} set={patch => set(i, patch)} media={media} onMedia={onMedia} />
</div>
{w.kind === 'weather' && <p className="text-caption text-ink-3">{t('signage.widgets.weatherNeedsInternet')}</p>}
</div>
)
})}
{widgets.length < 10 && (
<div className="flex flex-wrap items-center gap-1.5">
{WIDGET_KINDS.map(k => {
const Icon = ICON[k]
return (
<Button key={k} size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => add(k)} data-testid={`signage-widget-add-${k}`}>
<span className="inline-flex items-center gap-1.5"><Icon size={14} aria-hidden="true" />{t(`signage.widgets.kinds.${k}`)}</span>
</Button>
)
})}
</div>
)} )}
{w.kind === 'date' && ( </Section>
<Select value={w.date_style || 'long'} onChange={e => set(i, { date_style: e.target.value })} aria-label={t('signage.widgets.kinds.date')} )
}
/** The options only some widgets have, on the same row. */
function KindFields({ w, set, media, onMedia }) {
const { t } = useTranslation('manager')
if (w.kind === 'logo') {
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo"
onChange={item => { onMedia(item); set({ media_id: item.id }) }} />
}
if (w.kind === 'message') {
return (
<Field label={t('signage.widgets.ownText')} hint={t('signage.widgets.ownTextHint')} className="flex-1 min-w-[14rem]">
<Input value={w.text || ''} maxLength={200} onChange={e => set({ text: e.target.value || null })} data-testid="signage-widget-text" />
</Field>
)
}
if (w.kind === 'date') {
return (
<Field label={t('signage.widgets.dateStyle')} className="w-56">
<Dropdown value={w.date_style || 'long'} onChange={date_style => set({ date_style })}
options={[{ value: 'long', label: t('signage.widgets.dateLong') }, { value: 'short', label: t('signage.widgets.dateShort') }]} /> options={[{ value: 'long', label: t('signage.widgets.dateLong') }, { value: 'short', label: t('signage.widgets.dateShort') }]} />
)} </Field>
{w.kind === 'clock' && <Switch checked={!!w.clock_seconds} onChange={on => set(i, { clock_seconds: on })} label={t('signage.widgets.seconds')} />} )
{w.kind === 'qr' && ( }
<div className="grid gap-2 sm:grid-cols-2"> if (w.kind === 'clock') {
<Field label={t('display.qrTarget')}> return <Switch boxed className="w-44" checked={!!w.clock_seconds} onChange={on => set({ clock_seconds: on })} label={t('signage.widgets.seconds')} />
<Select value={w.qr_target || 'ordering'} onChange={e => set(i, { qr_target: e.target.value })} }
if (w.kind === 'qr') {
return (<>
<Field label={t('display.qrTarget')} className="w-48">
<Dropdown value={w.qr_target || 'ordering'} onChange={qr_target => set({ qr_target })}
options={['ordering', 'menu', 'custom'].map(q => ({ value: q, label: t(`display.qrTargets.${q}`) }))} /> options={['ordering', 'menu', 'custom'].map(q => ({ value: q, label: t(`display.qrTargets.${q}`) }))} />
</Field> </Field>
{w.qr_target === 'custom' && ( {w.qr_target === 'custom' && (
<Field label={t('display.qrUrl')}><Input value={w.qr_url || ''} placeholder="https://" onChange={e => set(i, { qr_url: e.target.value || null })} /></Field> <Field label={t('display.qrUrl')} className="flex-1 min-w-[12rem]"><Input value={w.qr_url || ''} placeholder="https://" onChange={e => set({ qr_url: e.target.value || null })} /></Field>
)} )}
<Field label={t('display.qrCaption')}><Input value={w.qr_caption || ''} maxLength={80} onChange={e => set(i, { qr_caption: e.target.value || null })} /></Field> <Field label={t('display.qrCaption')} className="flex-1 min-w-[10rem]"><Input value={w.qr_caption || ''} maxLength={80} onChange={e => set({ qr_caption: e.target.value || null })} /></Field>
</div> </>)
)} }
{w.kind === 'weather' && ( if (w.kind === 'weather') {
<div className="grid gap-1"> return (
<Select value={String(w.weather_days || 1)} onChange={e => set(i, { weather_days: Number(e.target.value) })} aria-label={t('signage.widgets.weatherDays')} <Field label={t('signage.widgets.weatherDays')} className="w-48">
<Dropdown value={String(w.weather_days || 1)} onChange={v => set({ weather_days: Number(v) })}
options={[1, 2, 3].map(n => ({ value: String(n), label: t('signage.widgets.days', { count: n }) }))} /> options={[1, 2, 3].map(n => ({ value: String(n), label: t('signage.widgets.days', { count: n }) }))} />
<p className="text-caption text-ink-3">{t('signage.widgets.weatherNeedsInternet')}</p> </Field>
</div>
)}
</div>
))}
{widgets.length < 10 && (
<div className="flex flex-wrap gap-1.5">
{WIDGET_KINDS.map(k => (
<Button key={k} size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => add(k)} data-testid={`signage-widget-add-${k}`}>
{t(`signage.widgets.kinds.${k}`)}</Button>
))}
</div>
)}
</fieldset>
) )
}
return null
} }
@@ -19,6 +19,14 @@ export const duplicateSlide = id => client.post(`/api/signage/slides/${id}/dupli
export const previewVenue = () => client.get('/api/signage/venue').then(data) export const previewVenue = () => client.get('/api/signage/venue').then(data)
export const previewMenu = content => client.post('/api/signage/preview/menu', { content }).then(data) export const previewMenu = content => client.post('/api/signage/preview/menu', { content }).then(data)
// the Slides library (2026-11-21)
export const listSaved = () => client.get('/api/signage/library').then(data)
export const getSaved = id => client.get(`/api/signage/library/${id}`).then(data)
export const createSaved = body => client.post('/api/signage/library', body).then(data)
export const updateSaved = (id, body) => client.put(`/api/signage/library/${id}`, body).then(data)
export const deleteSaved = id => client.delete(`/api/signage/library/${id}`)
export const duplicateSaved = id => client.post(`/api/signage/library/${id}/duplicate`).then(data)
export const listScreens = () => client.get('/api/signage/screens').then(data) export const listScreens = () => client.get('/api/signage/screens').then(data)
export const updateScreen = (id, body) => client.put(`/api/signage/screens/${id}`, body).then(data) export const updateScreen = (id, body) => client.put(`/api/signage/screens/${id}`, body).then(data)
@@ -1,6 +1,6 @@
// The signage editor's pure helpers (plan step 5.6a): unit-tested in tests/signage.test.mjs. // The signage editor's pure helpers (plan step 5.6a): unit-tested in tests/signage.test.mjs.
export const KINDS = ['image', 'video', 'text', 'menu'] export const KINDS = ['image', 'video', 'text', 'menu', 'blank'] // blank: a background and widgets (2026-11-21)
export const TRANSITIONS = ['fade', 'slide', 'zoom', 'none'] export const TRANSITIONS = ['fade', 'slide', 'zoom', 'none']
export const FONT_KEYS = ['sans', 'serif', 'rounded', 'condensed', 'display'] export const FONT_KEYS = ['sans', 'serif', 'rounded', 'condensed', 'display']
@@ -30,6 +30,12 @@ export const TEMPLATES = [
{ key: 'video', kind: 'video', video_to_end: true, content: { fit: 'cover', muted: true } }, { key: 'video', kind: 'video', video_to_end: true, content: { fit: 'cover', muted: true } },
] ]
/** A blank slide to start from: a dark background, the venue's name and the clock (2026-11-21). */
export const BLANK_WITH_WIDGETS = { key: 'blankWidgets', kind: 'blank', content: {
background: { kind: 'colour', colour: '#111827', media_id: null, dim: 0, fit: 'cover' },
widgets: [{ kind: 'name', position: 'top-left' }, { kind: 'clock', position: 'top-right' }],
} }
/** The body to create a slide from a template; `t` fills its '@' texts. */ /** The body to create a slide from a template; `t` fills its '@' texts. */
export function slideFromTemplate(tpl, t = k => k) { export function slideFromTemplate(tpl, t = k => k) {
const { key, kind, content, ...fields } = tpl const { key, kind, content, ...fields } = tpl
@@ -150,3 +156,116 @@ export function toggled(list, id) {
else set.add(id) else set.add(id)
return [...set].sort((a, b) => a - b) return [...set].sort((a, b) => a - b)
} }
// ── the Slides library (2026-11-21) ──────────────────────────────────────────
/** What a library slide sends back (PUT /api/signage/library/{id}): a slide's fields, its name, description and shape. */
export function savedBody(s) {
return { ...slideBody(s), name: (s.name || '').trim(), description: (s.description || '').trim() || null, orientation: s.orientation || 'landscape' }
}
/** A library slide added to a playlist: a copy of its fields (the playlist's slide is then its own). */
export function slideFromSaved(saved) {
return { kind: saved.kind, ...slideBody(saved), content: JSON.parse(JSON.stringify(saved.content || {})) }
}
/** Colours offered with one click beside the colour picker (the venue's TV: data, not the theme). */
export const COLOUR_PRESETS = ['#ffffff', '#111827', '#fde68a', '#f59e0b', '#ef4444', '#22c55e', '#38bdf8', '#a78bfa', '#f472b6']
// ── widgets moved and sized on the preview (2026-11-21) ──────────────────────
const round = v => Math.round(v * 10) / 10
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
export const MIN_BOX = 3 // % of the slide
/** A rendered widget's place as a box in % of the slide (its rect and the slide's, in pixels). */
export function boxFromRect(r, frame) {
return { x: round((r.left - frame.left) / frame.width * 100), y: round((r.top - frame.top) / frame.height * 100),
w: round(r.width / frame.width * 100), h: round(r.height / frame.height * 100) }
}
/** A box moved by dx, dy (%), kept on the slide. */
export function moveBox(b, dx, dy) {
return { ...b, x: round(clamp(b.x + dx, 0, 100 - b.w)), y: round(clamp(b.y + dy, 0, 100 - b.h)) }
}
/** A box resized from one of its handles (n, ne, e, se, s, sw, w, nw) by dx, dy (%), kept on the slide. */
export function resizeBox(b, handle, dx, dy, min = MIN_BOX) {
let { x, y, w, h } = b
if (handle.includes('e')) w = clamp(w + dx, min, 100 - x)
if (handle.includes('s')) h = clamp(h + dy, min, 100 - y)
if (handle.includes('w')) { const right = x + w; x = clamp(x + dx, 0, right - min); w = right - x }
if (handle.includes('n')) { const bottom = y + h; y = clamp(y + dy, 0, bottom - min); h = bottom - y }
return { x: round(x), y: round(y), w: round(w), h: round(h) }
}
/**
* A moved box pulled onto the slide's edges and middle lines when it comes within `near` %:
* → { box, guides: ['x:50', 'y:0', …] } (the lines it sits on, for the editor to draw).
* Moving keeps its size; resizing (handle) only moves the edges it drags.
*/
export function snapBox(b, handle = null, near = 1.2) {
const out = { ...b }
const guides = []
const xs = handle ? [...(handle.includes('w') ? ['l'] : []), ...(handle.includes('e') ? ['r'] : [])] : ['l', 'c', 'r']
const ys = handle ? [...(handle.includes('n') ? ['t'] : []), ...(handle.includes('s') ? ['b'] : [])] : ['t', 'm', 'b']
const lines = [0, 50, 100]
const pull = (axis, sides) => {
const [pos, size] = axis === 'x' ? ['x', 'w'] : ['y', 'h']
let best = null
for (const side of sides) {
const at = side === 'l' || side === 't' ? out[pos] : side === 'c' || side === 'm' ? out[pos] + out[size] / 2 : out[pos] + out[size]
for (const line of lines) {
const d = line - at
if (Math.abs(d) <= near && (!best || Math.abs(d) < Math.abs(best.d))) best = { d, line, side }
}
}
if (!best) return
if (!handle) out[pos] = round(out[pos] + best.d)
else if (best.side === 'l' || best.side === 't') { out[pos] = round(out[pos] + best.d); out[size] = round(out[size] - best.d) }
else out[size] = round(out[size] + best.d)
guides.push(`${axis}:${best.line}`)
}
pull('x', xs)
pull('y', ys)
return { box: out, guides }
}
/** A widget placed by hand: position and size become "custom", its box kept. */
export function placeWidget(w, box) {
return { ...w, position: 'custom', size: 'custom', box }
}
/** A widget put back in a corner or a bar: no box, a real size again. */
export function presetWidget(w, position) {
const { box: _box, ...rest } = w
return { ...rest, position, size: w.size === 'custom' || !w.size ? 'medium' : w.size }
}
// ── schedule lines: days or smart days, not both (owner 2026-11-21) ──────────
export const DAY_SHORTCUTS = { everyday: [], weekdays: [0, 1, 2, 3, 4], weekend: [5, 6] }
/** The shortcut a line's days match ("every day" only while no smart day is picked either). */
export function shortcutOf(line) {
const days = line.days || []
const hit = Object.entries(DAY_SHORTCUTS).find(([, v]) => v.length === days.length && v.every((d, i) => d === days[i]))?.[0]
return hit === 'everyday' && (line.month_days || []).length ? null : hit ?? null
}
/** A weekday picked or not: smart days are cleared (the line runs on days of the week). */
export function toggleWeekday(line, d) {
const days = line.days || []
return { days: days.includes(d) ? days.filter(x => x !== d) : [...days, d].sort((a, b) => a - b), month_days: [] }
}
/** A day shortcut (every day, weekdays, weekend): smart days are cleared. */
export function setDayShortcut(key) {
return { days: [...DAY_SHORTCUTS[key]], month_days: [] }
}
/** A smart day picked or not: weekdays are cleared (the line runs on smart days). */
export function toggleMonthDay(line, key) {
const md = line.month_days || []
return { month_days: md.includes(key) ? md.filter(x => x !== key) : [...md, key], days: [] }
}
@@ -0,0 +1,34 @@
// What the two slide editors share (a playlist's slide, a library slide; 2026-11-21): a menu
// board's draft resolved by the server for its preview, and the preview's widget handles.
import { useEffect, useState } from 'react'
import * as api from './signageApi'
import { placeWidget } from './signageLogic'
/** A menu board's products as the server resolves the draft (only what changes the list counts). */
export function useMenuPreview(draft, setDraft) {
const c = draft?.kind === 'menu' ? draft.content || {} : null
const key = c ? JSON.stringify({ ...c, widgets: undefined, background: undefined }) : null
useEffect(() => {
if (!key) return undefined
const h = setTimeout(() => {
api.previewMenu(JSON.parse(key)).then(r => setDraft(d => (d && d.kind === 'menu' ? { ...d, menu: r.menu } : d))).catch(() => {})
}, 400)
return () => clearTimeout(h)
}, [key, setDraft])
}
/**
* The widget picked on the preview and how a move / resize there changes the draft.
* → { widget, setWidget, editor } (editor: SlidePreview's `editor` prop). Picks nothing when the
* slide changes (`slideKey`).
*/
export function useWidgetEditor(setDraft, slideKey, label) {
const [state, setState] = useState({ key: slideKey, widget: null })
const widget = state.key === slideKey ? state.widget : null
const setWidget = w => setState({ key: slideKey, widget: w })
const onPlace = (i, box) => setDraft(d => {
const ws = d?.content?.widgets || []
return { ...d, content: { ...d.content, widgets: ws.map((w, j) => (j === i ? placeWidget(w, box) : w)) } }
})
return { widget, setWidget, editor: { selected: widget, onSelect: setWidget, onPlace, label } }
}
+44
View File
@@ -57,3 +57,47 @@ test('the board\'s own order from what it shows; moving categories and products;
assert.deepEqual(toggled([1, 2], 2), [1]) assert.deepEqual(toggled([1, 2], 2), [1])
assert.deepEqual(toggled(undefined, 4), [4]) assert.deepEqual(toggled(undefined, 4), [4])
}) })
test('widgets moved and sized on the preview: boxes kept on the slide, snapping, custom and back (2026-11-21)', async () => {
const { boxFromRect, moveBox, placeWidget, presetWidget, resizeBox, snapBox } = await import('../src/pages/signage/signageLogic.js')
const frame = { left: 100, top: 50, width: 800, height: 450 }
assert.deepEqual(boxFromRect({ left: 500, top: 95, width: 160, height: 45 }, frame), { x: 50, y: 10, w: 20, h: 10 })
const b = { x: 50, y: 10, w: 20, h: 10 }
assert.deepEqual(moveBox(b, 40, -20), { x: 80, y: 0, w: 20, h: 10 }) // stopped at the edges
assert.deepEqual(resizeBox(b, 'se', 5, 5), { x: 50, y: 10, w: 25, h: 15 })
assert.deepEqual(resizeBox(b, 'nw', 30, 30), { x: 67, y: 17, w: 3, h: 3 }) // never smaller than 3 %
assert.deepEqual(resizeBox(b, 'e', 90, 0), { x: 50, y: 10, w: 50, h: 10 })
const s = snapBox({ x: 40.5, y: 0.8, w: 20, h: 10 }) // its middle near 50, its top near 0
assert.deepEqual(s.box, { x: 40, y: 0, w: 20, h: 10 })
assert.deepEqual(s.guides, ['x:50', 'y:0'])
assert.deepEqual(snapBox({ x: 10, y: 10, w: 89.5, h: 10 }, 'e').box, { x: 10, y: 10, w: 90, h: 10 }) // a handle moves only its edge
const w = placeWidget({ kind: 'clock', position: 'top-right', size: 'large' }, b)
assert.deepEqual(w, { kind: 'clock', position: 'custom', size: 'custom', box: b })
assert.deepEqual(presetWidget(w, 'bottom-left'), { kind: 'clock', position: 'bottom-left', size: 'medium' })
assert.deepEqual(presetWidget({ kind: 'clock', position: 'top-right', size: 'large' }, 'top-left').size, 'large')
})
test('a schedule line runs on weekdays or on smart days, not both (2026-11-21)', async () => {
const { setDayShortcut, shortcutOf, toggleMonthDay, toggleWeekday } = await import('../src/pages/signage/signageLogic.js')
const line = { days: [0, 1], month_days: [] }
assert.deepEqual(toggleMonthDay(line, 'holiday'), { month_days: ['holiday'], days: [] })
assert.deepEqual(toggleWeekday({ days: [], month_days: ['first'] }, 3), { days: [3], month_days: [] })
assert.deepEqual(setDayShortcut('weekend'), { days: [5, 6], month_days: [] })
assert.equal(shortcutOf({ days: [], month_days: [] }), 'everyday')
assert.equal(shortcutOf({ days: [], month_days: ['last'] }), null) // a smart day: "every day" isn't lit
assert.equal(shortcutOf({ days: [0, 1, 2, 3, 4], month_days: [] }), 'weekdays')
})
test('the Slides library: what is saved, and a copy for a playlist', async () => {
const { savedBody, slideFromSaved } = await import('../src/pages/signage/signageLogic.js')
const saved = { id: 4, name: ' Logo ', description: ' ', orientation: 'portrait', kind: 'blank', duration_s: 12, enabled: true, days: [], content: { widgets: [{ kind: 'name' }] } }
const body = savedBody(saved)
assert.equal(body.name, 'Logo')
assert.equal(body.description, null)
assert.equal(body.orientation, 'portrait')
const copy = slideFromSaved(saved)
assert.equal(copy.kind, 'blank')
assert.equal(copy.duration_s, 12)
copy.content.widgets[0].kind = 'clock'
assert.equal(saved.content.widgets[0].kind, 'name') // a copy, never the kept slide
})
+1
View File
@@ -26,6 +26,7 @@
}, },
"ui": { "ui": {
"close": "Κλείσιμο", "close": "Κλείσιμο",
"cancel": "Άκυρο",
"dismiss": "Απόρριψη", "dismiss": "Απόρριψη",
"loading": "Φόρτωση", "loading": "Φόρτωση",
"moreInfo": "Περισσότερες πληροφορίες", "moreInfo": "Περισσότερες πληροφορίες",
+60 -10
View File
@@ -1270,7 +1270,9 @@
"image": "Εικόνα", "image": "Εικόνα",
"video": "Βίντεο", "video": "Βίντεο",
"text": "Κείμενο", "text": "Κείμενο",
"menu": "Μενού" "menu": "Μενού",
"blank": "Κενή",
"blankWidgets": "Κενή με widgets"
}, },
"misfit": "Αυτή η εικόνα ή το βίντεο δεν ταιριάζει στο σχήμα της λίστας: θα κοπεί ή θα έχει μπάρες.", "misfit": "Αυτή η εικόνα ή το βίντεο δεν ταιριάζει στο σχήμα της λίστας: θα κοπεί ή θα έχει μπάρες.",
"toTheEnd": "ως το τέλος", "toTheEnd": "ως το τέλος",
@@ -1291,7 +1293,7 @@
"6": "Κυρ" "6": "Κυρ"
}, },
"duplicateSlide": "Αντίγραφο της διαφάνειας", "duplicateSlide": "Αντίγραφο της διαφάνειας",
"deleteSlide": "Αφαίρεση αυτής της διαφάνειας;", "deleteSlide": "Φεύγει από αυτή τη λίστα. Οι εικόνες και τα βίντεό της μένουν στη βιβλιοθήκη πολυμέσων.",
"removed": "Η διαφάνεια αφαιρέθηκε.", "removed": "Η διαφάνεια αφαιρέθηκε.",
"addSlide": "Προσθήκη διαφάνειας", "addSlide": "Προσθήκη διαφάνειας",
"added": "Η διαφάνεια προστέθηκε.", "added": "Η διαφάνεια προστέθηκε.",
@@ -1344,7 +1346,7 @@
"videoToEndHint": "Όχι: δείχνεται για τα δευτερόλεπτα παρακάτω (και επαναλαμβάνεται αν είναι μικρότερο).", "videoToEndHint": "Όχι: δείχνεται για τα δευτερόλεπτα παρακάτω (και επαναλαμβάνεται αν είναι μικρότερο).",
"duration": "Δευτερόλεπτα στην οθόνη", "duration": "Δευτερόλεπτα στην οθόνη",
"durationMenuHint": "Ένα μεγάλο μενού γυρίζει σελίδες και μένει όσο χρειάζεται.", "durationMenuHint": "Ένα μεγάλο μενού γυρίζει σελίδες και μένει όσο χρειάζεται.",
"transition": "Μπαίνει με", "transition": "Εφέ μετάβασης",
"transitionDefault": "Τη μετάβαση της λίστας", "transitionDefault": "Τη μετάβαση της λίστας",
"when": "Πότε εμφανίζεται", "when": "Πότε εμφανίζεται",
"whenHint": "Κενό για πάντα. Διαλέξτε ημέρες, ώρες (μπορεί να περνούν τα μεσάνυχτα) ή ημερομηνίες για να εμφανίζεται μόνο τότε. Αυτό στενεύει το πρόγραμμα της λίστας: μια διαφάνεια με ώρα εκτός των ωρών που παίζει η λίστα της δεν εμφανίζεται ποτέ.", "whenHint": "Κενό για πάντα. Διαλέξτε ημέρες, ώρες (μπορεί να περνούν τα μεσάνυχτα) ή ημερομηνίες για να εμφανίζεται μόνο τότε. Αυτό στενεύει το πρόγραμμα της λίστας: μια διαφάνεια με ώρα εκτός των ωρών που παίζει η λίστα της δεν εμφανίζεται ποτέ.",
@@ -1429,7 +1431,12 @@
"pageSeconds": "Δευτερόλεπτα ανά σελίδα", "pageSeconds": "Δευτερόλεπτα ανά σελίδα",
"language": "Γλώσσα", "language": "Γλώσσα",
"languageHint": "Τα ονόματα των προϊόντων σε αυτή την οθόνη. Χωρίς μετάφραση: όπως γράφτηκαν.", "languageHint": "Τα ονόματα των προϊόντων σε αυτή την οθόνη. Χωρίς μετάφραση: όπως γράφτηκαν.",
"asTyped": "Όπως γράφτηκαν" "asTyped": "Όπως γράφτηκαν",
"which": "Προϊόντα",
"layout": "Διάταξη",
"width": "Πλάτος λίστας",
"place": "Θέση λίστας",
"placeHint": "Σε όλο το πλάτος η λίστα γεμίζει την οθόνη: στενέψτε την για να τη μετακινήσετε."
}, },
"badges": { "badges": {
"new": "Νέο", "new": "Νέο",
@@ -1477,7 +1484,13 @@
"weatherDays": "Μέρες", "weatherDays": "Μέρες",
"days_one": "Σήμερα", "days_one": "Σήμερα",
"days_other": "Σήμερα και {{count}} μέρες", "days_other": "Σήμερα και {{count}} μέρες",
"weatherNeedsInternet": "Ο καιρός χρειάζεται internet: χωρίς αυτό (ή χωρίς πόλη) το στοιχείο κρύβεται." "weatherNeedsInternet": "Ο καιρός χρειάζεται internet: χωρίς αυτό (ή χωρίς πόλη) το στοιχείο κρύβεται.",
"dragHint": "Συμβουλή: επιλέξτε ένα widget στην προεπισκόπηση, σύρετέ το για να το μετακινήσετε και από τις λαβές για να αλλάξετε το μέγεθος. Τα πεδία Θέση και Μέγεθος γράφουν τότε «Προσαρμοσμένο».",
"custom": "Προσαρμοσμένο",
"align": "Στοίχιση",
"alignAuto": "Αυτόματη",
"dateStyle": "Μορφή",
"canvas": "Τα widgets της διαφάνειας: σύρετε ένα για μετακίνηση, τις λαβές για μέγεθος, τα βέλη για μικρές κινήσεις"
}, },
"tabs": { "tabs": {
"playlists": "Λίστες", "playlists": "Λίστες",
@@ -1509,7 +1522,12 @@
"shape": "Σχήμα τηλεόρασης", "shape": "Σχήμα τηλεόρασης",
"nowScheduled": "Τώρα: {{name}} (από πρόγραμμα)", "nowScheduled": "Τώρα: {{name}} (από πρόγραμμα)",
"nowDefault": "Τώρα: {{name}} (η προεπιλογή της)", "nowDefault": "Τώρα: {{name}} (η προεπιλογή της)",
"nowNothing": "Τώρα: τίποτα (κενή οθόνη)" "nowNothing": "Τώρα: τίποτα (κενή οθόνη)",
"default": "Παίζει από προεπιλογή",
"defaultHint": "Όταν δεν ταιριάζει καμία γραμμή προγράμματος: μια λίστα ή μία διαφάνεια μόνη της.",
"aPlaylist": "Λίστα",
"aSlide": "Διαφάνεια",
"nowSlide": "Τώρα: {{name}} (η διαφάνεια προεπιλογής της)"
}, },
"schedules": { "schedules": {
"new": "Νέο πρόγραμμα", "new": "Νέο πρόγραμμα",
@@ -1549,7 +1567,8 @@
"scene": "Μόνο σε σκηνή", "scene": "Μόνο σε σκηνή",
"anyScene": "Πάντα (χωρίς σκηνή)", "anyScene": "Πάντα (χωρίς σκηνή)",
"enabled": "Ενεργή", "enabled": "Ενεργή",
"playingNow": "Παίζει τώρα σε: {{names}}" "playingNow": "Παίζει τώρα σε: {{names}}",
"smartDaysHint": "Μια γραμμή παίζει σε ημέρες της εβδομάδας ή σε έξυπνες ημέρες: η επιλογή του ενός καθαρίζει το άλλο. Για τα δύο, προσθέστε άλλη γραμμή με την ίδια λίστα."
}, },
"settings": { "settings": {
"message": "Μήνυμα ημέρας", "message": "Μήνυμα ημέρας",
@@ -1571,9 +1590,40 @@
"refresh": "Ενημέρωση τώρα", "refresh": "Ενημέρωση τώρα",
"forget": "Αφαίρεση πόλης" "forget": "Αφαίρεση πόλης"
}, },
"slidesTab": { "discardTitle": "Αλλαγές χωρίς αποθήκευση",
"title": "Έρχονται διαφάνειες για επαναχρησιμοποίηση", "discardYes": "Έξοδος χωρίς αποθήκευση",
"body": "Εδώ θα φτιάχνετε μεμονωμένες διαφάνειες, θα τις κρατάτε και θα τις προσθέτετε σε όποια λίστα θέλετε." "deleteSlideTitle": "Αφαίρεση «{{name}}»;",
"bgKind": "Είδος",
"dimLabel": "Σκούρεμα φωτογραφίας",
"textTitle": "Κείμενο",
"textLook": "Εμφάνιση κειμένου",
"textSizeLabel": "Μέγεθος κειμένου",
"library": {
"intro": "Διαφάνειες που φτιάχνετε μία φορά και κρατάτε: προσθέστε τες σε όποια λίστα θέλετε (Προσθήκη διαφάνειας → Οι διαφάνειές σας) ή δείξτε μία μόνη της σε μια οθόνη (Οθόνες).",
"new": "Νέα διαφάνεια",
"none": "Δεν έχετε κρατήσει διαφάνειες ακόμα.",
"noneHint": "Φτιάξτε μια διαφάνεια εδώ ή κρατήστε μία από μια λίστα (Κράτηση στις Διαφάνειες, κάτω από τις ρυθμίσεις της).",
"edit": "Επεξεργασία «{{name}}»",
"onScreens": "Προβάλλεται σε {{names}}",
"deleteTitle": "Διαγραφή «{{name}}»;",
"deleteBody": "Όσες λίστες πήραν αντίγραφό της το κρατούν.",
"deleteUsed": "Προβάλλεται σε {{names}}: αυτές οι οθόνες δεν θα δείχνουν τίποτα μέχρι να επιλέξετε κάτι άλλο. Οι λίστες κρατούν τα αντίγραφά τους.",
"newName": "{{kind}} (νέα)",
"back": "Πίσω στις διαφάνειες",
"untitled": "Διαφάνεια χωρίς όνομα",
"name": "Όνομα",
"description": "Σύντομη περιγραφή",
"descriptionHint": "Για να την ξεχωρίζετε: τι δείχνει και πότε τη χρησιμοποιείτε.",
"kindIs": "Είδος: {{kind}}",
"settings": "Ρυθμίσεις",
"yours": "Οι διαφάνειές σας",
"addHint": "Από την καρτέλα Διαφάνειες: ένα αντίγραφο μπαίνει σε αυτή τη λίστα.",
"noneYet": "Δεν έχετε κρατήσει διαφάνειες: φτιάξτε τες στην καρτέλα Διαφάνειες ή κρατήστε μία από μια λίστα.",
"keep": "Κράτηση στις Διαφάνειες",
"keepTitle": "Κράτηση αυτής της διαφάνειας",
"keepHint": "Ένα αντίγραφο της διαφάνειας όπως είναι τώρα πηγαίνει στην καρτέλα Διαφάνειες, για άλλες λίστες ή για να προβάλλεται μόνη της σε μια οθόνη.",
"keepYes": "Κράτηση",
"kept": "Κρατήθηκε στις Διαφάνειες."
} }
}, },
"overview": { "overview": {
+5
View File
@@ -550,6 +550,11 @@
"hint": "Τι παίζει αυτή η οθόνη (Προβολή).", "hint": "Τι παίζει αυτή η οθόνη (Προβολή).",
"none": "Τίποτα (κενή οθόνη)" "none": "Τίποτα (κενή οθόνη)"
}, },
"slide": {
"label": "Διαφάνεια",
"hint": "Ή μία διαφάνεια από τη βιβλιοθήκη Διαφάνειες, όταν δεν έχει επιλεγεί λίστα προβολής.",
"none": "Καμία"
},
"orientation": { "orientation": {
"label": "Προσανατολισμός", "label": "Προσανατολισμός",
"hint": "Πώς κρέμεται η τηλεόραση: οι διαφάνειες φτιάχνονται για αυτό το σχήμα.", "hint": "Πώς κρέμεται η τηλεόραση: οι διαφάνειες φτιάχνονται για αυτό το σχήμα.",
+1
View File
@@ -26,6 +26,7 @@
}, },
"ui": { "ui": {
"close": "Close", "close": "Close",
"cancel": "Cancel",
"dismiss": "Dismiss", "dismiss": "Dismiss",
"loading": "Loading", "loading": "Loading",
"moreInfo": "More info", "moreInfo": "More info",
+60 -10
View File
@@ -1270,7 +1270,9 @@
"image": "Picture", "image": "Picture",
"video": "Video", "video": "Video",
"text": "Text", "text": "Text",
"menu": "Menu board" "menu": "Menu board",
"blank": "Blank",
"blankWidgets": "Blank with widgets"
}, },
"misfit": "This picture or video doesn't fit the playlist's shape: it will be cropped or have bars.", "misfit": "This picture or video doesn't fit the playlist's shape: it will be cropped or have bars.",
"toTheEnd": "to the end", "toTheEnd": "to the end",
@@ -1291,7 +1293,7 @@
"6": "Sun" "6": "Sun"
}, },
"duplicateSlide": "Duplicate the slide", "duplicateSlide": "Duplicate the slide",
"deleteSlide": "Remove this slide?", "deleteSlide": "It goes from this playlist. Its pictures and videos stay in the media library.",
"removed": "Slide removed.", "removed": "Slide removed.",
"addSlide": "Add a slide", "addSlide": "Add a slide",
"added": "Slide added.", "added": "Slide added.",
@@ -1344,7 +1346,7 @@
"videoToEndHint": "Off: it shows for the seconds below (and repeats if it is shorter).", "videoToEndHint": "Off: it shows for the seconds below (and repeats if it is shorter).",
"duration": "Seconds on screen", "duration": "Seconds on screen",
"durationMenuHint": "A long menu turns its pages and stays as long as it needs.", "durationMenuHint": "A long menu turns its pages and stays as long as it needs.",
"transition": "Comes in with", "transition": "Transition effect",
"transitionDefault": "The playlist's transition", "transitionDefault": "The playlist's transition",
"when": "When it shows", "when": "When it shows",
"whenHint": "Leave empty for always. Pick days, hours (they may pass midnight) or dates to show it only then. This narrows the playlist's schedule: a slide whose time is outside the hours its playlist plays never shows.", "whenHint": "Leave empty for always. Pick days, hours (they may pass midnight) or dates to show it only then. This narrows the playlist's schedule: a slide whose time is outside the hours its playlist plays never shows.",
@@ -1429,7 +1431,12 @@
"pageSeconds": "Seconds per page", "pageSeconds": "Seconds per page",
"language": "Language", "language": "Language",
"languageHint": "The products' names on this board. Not translated: as typed.", "languageHint": "The products' names on this board. Not translated: as typed.",
"asTyped": "As typed" "asTyped": "As typed",
"which": "Products",
"layout": "Layout",
"width": "Width of the list",
"place": "Where the list sits",
"placeHint": "At the full width the list fills the screen: make it narrower to place it."
}, },
"badges": { "badges": {
"new": "New", "new": "New",
@@ -1477,7 +1484,13 @@
"weatherDays": "Days", "weatherDays": "Days",
"days_one": "Today", "days_one": "Today",
"days_other": "Today and {{count}} days", "days_other": "Today and {{count}} days",
"weatherNeedsInternet": "The weather needs internet: without it (or without a town set) the widget is hidden." "weatherNeedsInternet": "The weather needs internet: without it (or without a town set) the widget is hidden.",
"dragHint": "Tip: pick a widget on the preview, drag it to move it and its handles to size it. Where and size then read \"Custom\".",
"custom": "Custom",
"align": "Alignment",
"alignAuto": "Auto",
"dateStyle": "Style",
"canvas": "The slide's widgets: drag one to move it, its handles to size it, arrow keys to nudge it"
}, },
"tabs": { "tabs": {
"playlists": "Playlists", "playlists": "Playlists",
@@ -1509,7 +1522,12 @@
"shape": "TV shape", "shape": "TV shape",
"nowScheduled": "Now: {{name}} (by a schedule)", "nowScheduled": "Now: {{name}} (by a schedule)",
"nowDefault": "Now: {{name}} (its default)", "nowDefault": "Now: {{name}} (its default)",
"nowNothing": "Now: nothing (a blank screen)" "nowNothing": "Now: nothing (a blank screen)",
"default": "Plays by default",
"defaultHint": "When no schedule line matches: a playlist, or one slide shown alone.",
"aPlaylist": "Playlist",
"aSlide": "Slide",
"nowSlide": "Now: {{name}} (its default slide)"
}, },
"schedules": { "schedules": {
"new": "New schedule", "new": "New schedule",
@@ -1549,7 +1567,8 @@
"scene": "Only during a scene", "scene": "Only during a scene",
"anyScene": "Always (no scene)", "anyScene": "Always (no scene)",
"enabled": "On", "enabled": "On",
"playingNow": "Playing now on {{names}}" "playingNow": "Playing now on {{names}}",
"smartDaysHint": "A line runs on weekdays or on smart days: picking one clears the other. For both, add another line with the same playlist."
}, },
"settings": { "settings": {
"message": "Message of the day", "message": "Message of the day",
@@ -1571,9 +1590,40 @@
"refresh": "Fetch now", "refresh": "Fetch now",
"forget": "Remove the town" "forget": "Remove the town"
}, },
"slidesTab": { "discardTitle": "Unsaved changes",
"title": "Slides to reuse are coming", "discardYes": "Leave without saving",
"body": "Here you will make single slides, keep them, and add them to any playlist." "deleteSlideTitle": "Remove \"{{name}}\"?",
"bgKind": "Kind",
"dimLabel": "Darken the photo",
"textTitle": "Text",
"textLook": "Text look",
"textSizeLabel": "Text size",
"library": {
"intro": "Slides you build once and keep: add them to any playlist (Add a slide → Your slides), or show one alone on a screen (Screens).",
"new": "New slide",
"none": "No slides kept yet.",
"noneHint": "Build a slide here, or keep one from a playlist (Keep in Slides, under its settings).",
"edit": "Edit \"{{name}}\"",
"onScreens": "Shown on {{names}}",
"deleteTitle": "Delete \"{{name}}\"?",
"deleteBody": "Playlists that got a copy of it keep their copy.",
"deleteUsed": "It is shown on {{names}}: those screens will show nothing until you pick something else. Playlists keep their copies.",
"newName": "{{kind}} (new)",
"back": "Back to the slides",
"untitled": "A slide without a name",
"name": "Name",
"description": "Short description",
"descriptionHint": "To tell it apart later: what it shows and when you use it.",
"kindIs": "Kind: {{kind}}",
"settings": "Settings",
"yours": "Your slides",
"addHint": "From the Slides tab: a copy goes into this playlist.",
"noneYet": "No slides kept yet: build them in the Slides tab, or keep one from a playlist.",
"keep": "Keep in Slides",
"keepTitle": "Keep this slide",
"keepHint": "A copy of the slide as it is now goes to the Slides tab, to reuse in other playlists or show alone on a screen.",
"keepYes": "Keep it",
"kept": "Kept in Slides."
} }
}, },
"overview": { "overview": {
+5
View File
@@ -550,6 +550,11 @@
"hint": "What this screen plays (Signage).", "hint": "What this screen plays (Signage).",
"none": "Nothing (a blank screen)" "none": "Nothing (a blank screen)"
}, },
"slide": {
"label": "Slide",
"hint": "Or a single slide from the Slides library, shown when no playlist is picked.",
"none": "None"
},
"orientation": { "orientation": {
"label": "Orientation", "label": "Orientation",
"hint": "How the TV hangs: slides are built for this shape.", "hint": "How the TV hangs: slides are built for this shape.",
+1
View File
@@ -29,6 +29,7 @@ export function useUiLabels() {
const language = i18n.resolvedLanguage || i18n.language const language = i18n.resolvedLanguage || i18n.language
return useMemo(() => ({ return useMemo(() => ({
close: t('ui.close'), close: t('ui.close'),
cancel: t('ui.cancel'),
dismiss: t('ui.dismiss'), dismiss: t('ui.dismiss'),
loading: t('ui.loading'), loading: t('ui.loading'),
moreInfo: t('ui.moreInfo'), moreInfo: t('ui.moreInfo'),
+3 -2
View File
@@ -1,8 +1,8 @@
// One slide as a TV shows it (plan step 5.6a): picture, video, text or menu board. Used by the // One slide as a TV shows it (plan step 5.6a): picture, video, text, menu board or blank (2026-11-21). Used by the
// player (terminal) and the manager's previews. Needs a parent with `container-type: size`. // player (terminal) and the manager's previews. Needs a parent with `container-type: size`.
// media(id) → { src, url, kind, width, height } | null (src: the address or the TV's kept copy) // media(id) → { src, url, kind, width, height } | null (src: the address or the TV's kept copy)
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import { MenuSlide, TextSlide } from './Slides.jsx' import { BlankSlide, MenuSlide, TextSlide } from './Slides.jsx'
export function SlideView({ slide, media, venue, now, pages, page, onEnded, playing = true }) { export function SlideView({ slide, media, venue, now, pages, page, onEnded, playing = true }) {
return ( return (
@@ -10,6 +10,7 @@ export function SlideView({ slide, media, venue, now, pages, page, onEnded, play
{slide.kind === 'image' && <ImageSlide content={slide.content || {}} media={media} />} {slide.kind === 'image' && <ImageSlide content={slide.content || {}} media={media} />}
{slide.kind === 'video' && <VideoSlide slide={slide} media={media} onEnded={onEnded} playing={playing} />} {slide.kind === 'video' && <VideoSlide slide={slide} media={media} onEnded={onEnded} playing={playing} />}
{slide.kind === 'text' && <TextSlide content={slide.content || {}} media={media} venue={venue} now={now} />} {slide.kind === 'text' && <TextSlide content={slide.content || {}} media={media} venue={venue} now={now} />}
{slide.kind === 'blank' && <BlankSlide 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} />} {slide.kind === 'menu' && <MenuSlide slide={slide} media={media} venue={venue} now={now} pages={pages || []} page={page || 0} />}
</> </>
) )
+96 -30
View File
@@ -5,7 +5,7 @@
import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react' import { Cloud, CloudFog, CloudLightning, CloudMoon, CloudRain, CloudSnow, CloudSun, Moon, Sun } from 'lucide-react'
import { QRCodeSVG } from 'qrcode.react' import { QRCodeSVG } from 'qrcode.react'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { FONTS, weatherIcon } from './logic' import { fitUnit, FONTS, textWidth, weatherIcon, widgetAlign } from './logic'
/** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */ /** A slide's background: a colour, or a photo (cover / contain) with a darkening layer. */
export function Background({ bg, media }) { export function Background({ bg, media }) {
@@ -19,6 +19,7 @@ export function Background({ bg, media }) {
} }
const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' } const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' }
const BOARD_ALIGN = { left: 'flex-start', center: 'center', right: 'flex-end' }
const hasBar = (c, where) => (c.widgets || []).some(w => w.position === where) const hasBar = (c, where) => (c.widgets || []).some(w => w.position === where)
export function TextSlide({ content: c, media, venue, now }) { export function TextSlide({ content: c, media, venue, now }) {
@@ -38,6 +39,16 @@ export function TextSlide({ content: c, media, venue, now }) {
) )
} }
/** A blank slide (2026-11-21): its background and its widgets, nothing else. */
export function BlankSlide({ content: c, media, venue, now }) {
return (
<div className="absolute inset-0" data-testid="signage-blank">
<Background bg={c.background} media={media} />
<Widgets widgets={c.widgets} media={media} venue={venue} now={now} />
</div>
)
}
/** A menu board (5.5b): its page of items (pages flip on their own), photos, descriptions, badges, sold out. */ /** 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 }) { export function MenuSlide({ slide, media, venue, now, page, pages }) {
const { t } = useTranslation('terminal') const { t } = useTranslation('terminal')
@@ -52,7 +63,11 @@ export function MenuSlide({ slide, media, venue, now, page, pages }) {
<div className="absolute inset-0 flex flex-col" <div className="absolute inset-0 flex flex-col"
style={{ padding: `${hasBar(c, 'top-bar') ? 12 : 5}cqmin 5cqmin ${hasBar(c, 'bottom-bar') ? 12 : 5}cqmin` }} style={{ padding: `${hasBar(c, 'top-bar') ? 12 : 5}cqmin 5cqmin ${hasBar(c, 'bottom-bar') ? 12 : 5}cqmin` }}
data-testid="signage-menu" data-page={page} data-pages={pages.length}> data-testid="signage-menu" data-page={page} data-pages={pages.length}>
{c.title && <h1 style={{ fontSize: `${7 * scale}cqmin`, fontWeight: 800, margin: '0 0 2cqmin', color: accent, lineHeight: 1.1 }}>{c.title}</h1>} {/* the list: the whole width, or narrower and placed left / centre / right (2026-11-21) */}
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', width: `${c.board_width || 100}%`,
alignSelf: BOARD_ALIGN[c.board_align] || 'flex-start' }} data-testid="signage-menu-board" data-align={c.board_align || 'left'}>
{c.title && <h1 style={{ fontSize: `${7 * scale}cqmin`, fontWeight: 800, margin: '0 0 2cqmin', color: accent, lineHeight: 1.1,
textAlign: c.board_align || 'left' }}>{c.title}</h1>}
<div style={{ columnCount: c.columns || 2, columnGap: '5cqmin', fontSize: `${3.2 * scale}cqmin`, flex: 1, columnFill: 'auto' }}> <div style={{ columnCount: c.columns || 2, columnGap: '5cqmin', fontSize: `${3.2 * scale}cqmin`, flex: 1, columnFill: 'auto' }}>
{groups.map((g, i) => ( {groups.map((g, i) => (
<div key={`${g.category?.id ?? 'all'}-${i}`} style={{ marginBottom: '1.6cqmin' }}> <div key={`${g.category?.id ?? 'all'}-${i}`} style={{ marginBottom: '1.6cqmin' }}>
@@ -92,12 +107,13 @@ export function MenuSlide({ slide, media, venue, now, page, pages }) {
</div> </div>
)} )}
</div> </div>
</div>
<Widgets widgets={c.widgets} media={media} venue={venue} now={now} colour={c.text_colour} /> <Widgets widgets={c.widgets} media={media} venue={venue} now={now} colour={c.text_colour} />
</div> </div>
) )
} }
// ── widgets (5.5b) ────────────────────────────────────────────────────────── // ── widgets (5.5b; placed by hand on the editor's preview, owner 2026-11-21) ────
const SIZE = { small: 0.75, medium: 1, large: 1.4 } const SIZE = { small: 0.75, medium: 1, large: 1.4 }
const CORNER = { const CORNER = {
@@ -108,11 +124,19 @@ const CORNER = {
'bottom-center': { bottom: '3cqmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' }, 'bottom-center': { bottom: '3cqmin', left: '50%', transform: 'translateX(-50%)', alignItems: 'center' },
'bottom-right': { bottom: '3cqmin', right: '3cqmin', alignItems: 'flex-end' }, 'bottom-right': { bottom: '3cqmin', right: '3cqmin', alignItems: 'flex-end' },
} }
const SELF = { left: 'flex-start', center: 'center', right: 'flex-end' }
/** The widgets of a slide, in their corners and bars. One that has nothing to show is left out. */ /**
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position
* "custom") each in its own box, scaled to fill it. One that has nothing to show is left out.
* Each carries `data-widget` = its index in the slide's list (the editor's handles find it so).
*/
export function Widgets({ widgets, media, venue, now, colour }) { export function Widgets({ widgets, media, venue, now, colour }) {
const fmt = useFormat()
if (!widgets?.length) return null if (!widgets?.length) return null
const bar = where => widgets.filter(w => w.position === where) const ctx = { media, venue, now, fmt }
const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, w.position === 'custom' && !!w.box)]).filter(([, , body]) => body)
const bar = where => shown.filter(([w]) => w.position === where)
const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]] const bars = [['top-bar', { top: 0 }], ['bottom-bar', { bottom: 0 }]]
return ( return (
<> <>
@@ -120,59 +144,99 @@ export function Widgets({ widgets, media, venue, now, colour }) {
<div key={where} className="absolute inset-x-0" data-testid={`signage-${where}`} <div key={where} className="absolute inset-x-0" data-testid={`signage-${where}`}
style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '3cqmin', padding: '2cqmin 4cqmin', style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '3cqmin', padding: '2cqmin 4cqmin',
background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: '9cqmin' }}> background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: '9cqmin' }}>
{bar(where).map((w, i) => <Widget key={i} w={w} media={media} venue={venue} now={now} />)} {bar(where).map(([w, i, body]) => (
<div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w) }}>{body}</div>
))}
</div> </div>
))} ))}
{widgets.filter(w => CORNER[w.position]).map((w, i) => ( {shown.filter(([w]) => CORNER[w.position]).map(([w, i, body]) => {
<div key={`c${i}`} className="absolute" style={{ ...CORNER[w.position], display: 'flex', flexDirection: 'column', color: colour || '#fff' }}> const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {}
<Widget w={w} media={media} venue={venue} now={now} /> return (
<div key={`c${i}`} data-widget={i} className="absolute" style={{ ...CORNER[w.position], ...own, display: 'flex', flexDirection: 'column', color: colour || '#fff' }}>
{body}
</div>
)
})}
{shown.filter(([w]) => w.position === 'custom' && w.box).map(([w, i, body]) => (
<div key={`b${i}`} data-widget={i} className="absolute" data-testid="signage-w-box"
style={{ left: `${w.box.x}%`, top: `${w.box.y}%`, width: `${w.box.w}%`, height: `${w.box.h}%`, containerType: 'size', color: colour || '#fff' }}>
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: SELF[widgetAlign(w)], textAlign: widgetAlign(w) }}>
{body}
</div>
</div> </div>
))} ))}
</> </>
) )
} }
const ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning } const OBJECT_POSITION = { left: 'left center', center: 'center', right: 'right center' }
function Widget({ w, media, venue, now }) { /**
const { formatDate, formatTime } = useFormat() * What one widget shows, or null when it has nothing to show. Sizes are "usual units" (cqmin of
* the slide at size medium); `fit`: the widget fills its own box instead (fitUnit).
*/
function widgetBody(w, { media, venue, now, fmt }, fit) {
const { formatDate, formatTime } = fmt
const s = SIZE[w.size] || 1 const s = SIZE[w.size] || 1
const text = { fontSize: `${3.4 * s}cqmin`, fontWeight: 700, lineHeight: 1.15, textShadow: '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)' } const unit = (height, width) => (fit ? fitUnit(height, width) : n => `${+(n * s).toFixed(3)}cqmin`)
const text = (u, size, weight = 700) => ({ fontSize: u(size), fontWeight: weight, lineHeight: 1.15,
textShadow: '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)', whiteSpace: fit ? 'nowrap' : undefined })
if (w.kind === 'logo') { if (w.kind === 'logo') {
const m = media(w.media_id) const m = media(w.media_id)
return m ? <img src={m.src} alt="" style={{ height: `${9 * s}cqmin`, maxWidth: `${30 * s}cqmin`, objectFit: 'contain' }} data-testid="signage-w-logo" /> : null if (!m) return null
return fit
? <img src={m.src} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', objectPosition: OBJECT_POSITION[widgetAlign(w)] }} data-testid="signage-w-logo" />
: <img src={m.src} alt="" style={{ height: `${9 * s}cqmin`, maxWidth: `${30 * s}cqmin`, objectFit: 'contain' }} data-testid="signage-w-logo" />
}
if (w.kind === 'name') {
if (!venue?.name) return null
const u = unit(4.2 * 1.15, textWidth(venue.name.length, 4.2))
return <span style={text(u, 4.2)} data-testid="signage-w-name">{venue.name}</span>
}
if (w.kind === 'date') {
const str = formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong')
const u = unit(3.4 * 1.15, textWidth(str.length, 3.4))
return <span style={text(u, 3.4)} data-testid="signage-w-date">{str}</span>
}
if (w.kind === 'clock') {
const u = unit(4.6 * 1.15, textWidth(w.clock_seconds ? 8 : 5, 4.6)) // its usual width: the size stays as the minutes turn
return <span style={{ ...text(u, 4.6), fontVariantNumeric: 'tabular-nums' }} data-testid="signage-w-clock">{formatTime(now, w.clock_seconds ? 'timeSeconds' : 'time')}</span>
} }
if (w.kind === 'name') return venue?.name ? <span style={{ ...text, fontSize: `${4.2 * s}cqmin` }} 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}cqmin`, fontVariantNumeric: 'tabular-nums' }} data-testid="signage-w-clock">{formatTime(now, w.clock_seconds ? 'timeSeconds' : 'time')}</span>
if (w.kind === 'message') { if (w.kind === 'message') {
const msg = w.text || venue?.message const msg = w.text || venue?.message
return msg ? <span style={{ ...text, fontWeight: 600 }} data-testid="signage-w-message">{msg}</span> : null if (!msg) return null
const u = unit(3.4 * 1.15, textWidth(msg.length, 3.4))
return <span style={text(u, 3.4, 600)} data-testid="signage-w-message">{msg}</span>
} }
if (w.kind === 'qr') { if (w.kind === 'qr') {
return w.link ? ( if (!w.link) return null
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.8cqmin' }} data-testid="signage-w-qr" data-link={w.link}> const caption = w.qr_caption ? 2.4 * 1.15 + 0.8 : 0
<div style={{ background: '#fff', padding: '1cqmin', borderRadius: '1cqmin', lineHeight: 0 }}> const u = unit(16 + caption, Math.max(16, w.qr_caption ? textWidth(w.qr_caption.length, 2.4) : 0))
<QRCodeSVG value={w.link} size={256} style={{ width: `${14 * s}cqmin`, height: `${14 * s}cqmin` }} /> return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: u(0.8) }} data-testid="signage-w-qr" data-link={w.link}>
<div style={{ background: '#fff', padding: u(1), borderRadius: u(1), lineHeight: 0 }}>
<QRCodeSVG value={w.link} size={256} style={{ width: u(14), height: u(14) }} />
</div> </div>
{w.qr_caption && <span style={{ ...text, fontSize: `${2.4 * s}cqmin` }}>{w.qr_caption}</span>} {w.qr_caption && <span style={text(u, 2.4)}>{w.qr_caption}</span>}
</div> </div>
) : null )
} }
if (w.kind === 'weather') { if (w.kind === 'weather') {
const wx = venue?.weather const wx = venue?.weather
if (!wx || wx.temperature == null) return null // no internet / no place: hidden (5.4c) 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 Icon = ICONS[weatherIcon(wx.code, wx.is_day)] || Cloud
const deg = wx.units === 'fahrenheit' ? '°F' : '°C' const deg = wx.units === 'fahrenheit' ? '°F' : '°C'
const days = (w.weather_days || 1) > 1 ? (wx.days || []).slice(1, w.weather_days) : []
const u = unit(6, 6 + 1.5 + textWidth(4, 4.4) + days.length * (1.5 + 3.4 + textWidth(12, 2.4)))
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: '1.5cqmin' }} data-testid="signage-w-weather"> <div style={{ display: 'flex', alignItems: 'center', gap: u(1.5) }} data-testid="signage-w-weather">
<Icon style={{ width: `${6 * s}cqmin`, height: `${6 * s}cqmin` }} aria-hidden="true" /> <Icon style={{ width: u(6), height: u(6), flexShrink: 0 }} aria-hidden="true" />
<span style={{ ...text, fontSize: `${4.4 * s}cqmin` }}>{Math.round(wx.temperature)}{deg}</span> <span style={text(u, 4.4)}>{Math.round(wx.temperature)}{deg}</span>
{(w.weather_days || 1) > 1 && (wx.days || []).slice(1, w.weather_days).map(d => { {days.map(d => {
const DayIcon = ICONS[weatherIcon(d.code, true)] || Cloud const DayIcon = ICONS[weatherIcon(d.code, true)] || Cloud
return ( return (
<span key={d.date} style={{ display: 'flex', alignItems: 'center', gap: '0.6cqmin', ...text, fontSize: `${2.4 * s}cqmin`, fontWeight: 600 }}> <span key={d.date} style={{ display: 'flex', alignItems: 'center', gap: u(0.6), ...text(u, 2.4, 600) }}>
{formatDate(`${d.date}T12:00:00Z`, 'weekday').slice(0, 3)} <DayIcon style={{ width: `${3.4 * s}cqmin`, height: `${3.4 * s}cqmin` }} aria-hidden="true" /> {formatDate(`${d.date}T12:00:00Z`, 'weekday').slice(0, 3)} <DayIcon style={{ width: u(3.4), height: u(3.4) }} aria-hidden="true" />
{Math.round(d.max)}° / {Math.round(d.min)}° {Math.round(d.max)}° / {Math.round(d.min)}°
</span> </span>
) )
@@ -182,3 +246,5 @@ function Widget({ w, media, venue, now }) {
} }
return null return null
} }
const ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning }
+1 -1
View File
@@ -2,5 +2,5 @@
// player (terminal/src/apps/signage) and in the manager's live previews. Sizes are container // player (terminal/src/apps/signage) and in the manager's live previews. Sizes are container
// units (cqmin): put a slide inside an element with `container-type: size` (frameStyle() does). // units (cqmin): put a slide inside an element with `container-type: size` (frameStyle() does).
export * from './logic.js' export * from './logic.js'
export { Background, MenuSlide, TextSlide, Widgets } from './Slides.jsx' export { Background, BlankSlide, MenuSlide, TextSlide, Widgets } from './Slides.jsx'
export { SlideView } from './SlideView.jsx' export { SlideView } from './SlideView.jsx'
+32
View File
@@ -248,3 +248,35 @@ export function boardPages(slide, rotation, w, h) {
const per = c.page_size || rows * (c.columns || 2) const per = c.page_size || rows * (c.columns || 2)
return menuPages(slide.menu?.groups || [], per, c.category_titles !== false) return menuPages(slide.menu?.groups || [], per, c.category_titles !== false)
} }
// ── widgets placed by hand (owner 2026-11-21) ─────────────────────────────────
/** The slide kinds that carry widgets. */
export const WIDGET_HOSTS = ['text', 'menu', 'blank']
/** How a widget lines up inside its place: its own choice, else by its corner / its box's side. */
export function widgetAlign(w) {
if (w?.align && w.align !== 'auto') return w.align
if (w?.position === 'custom' && w.box) {
const mid = w.box.x + w.box.w / 2
return mid < 100 / 3 ? 'left' : mid > 200 / 3 ? 'right' : 'center'
}
const p = w?.position || ''
return p.endsWith('left') ? 'left' : p.endsWith('right') ? 'right' : p.endsWith('center') ? 'center' : 'left'
}
/**
* A size unit for a widget that fills its own box: `n` units of its usual size (cqmin at "medium")
* scaled so the whole widget, `height` × `width` usual units, fits the box (inside an element with
* `container-type: size`). → n → CSS length.
*/
export function fitUnit(height, width) {
const byH = 100 / Math.max(0.1, height)
const byW = 100 / Math.max(0.1, width)
return n => `calc(${+n.toFixed(3)} * min(${+byH.toFixed(4)}cqh, ${+byW.toFixed(4)}cqw))`
}
/** A line of `chars` characters at `size` usual units: about how wide it is (bold sans). */
export function textWidth(chars, size) {
return Math.max(1, chars) * size * 0.6
}
+19
View File
@@ -136,3 +136,22 @@ test('smart days and scenes, the same dates as the server (owner 2026-11-21)', a
assert.equal(pick(entries, 99, sat, [1]), 50) assert.equal(pick(entries, 99, sat, [1]), 50)
assert.ok(!matches({ scene_id: 2 }, sat, [1])) assert.ok(!matches({ scene_id: 2 }, sat, [1]))
}) })
test('widgets placed by hand: how they line up, and a unit that fills their box (2026-11-21)', async () => {
const { fitUnit, textWidth, widgetAlign } = await import('../src/logic.js')
assert.equal(widgetAlign({ position: 'top-right' }), 'right')
assert.equal(widgetAlign({ position: 'bottom-center' }), 'center')
assert.equal(widgetAlign({ position: 'top-bar' }), 'left')
assert.equal(widgetAlign({ position: 'top-left', align: 'center' }), 'center') // its own choice
assert.equal(widgetAlign({ position: 'custom', box: { x: 70, y: 0, w: 25, h: 10 } }), 'right') // by its box's side
assert.equal(widgetAlign({ position: 'custom', box: { x: 40, y: 0, w: 20, h: 10 } }), 'center')
assert.equal(fitUnit(5, 20)(2.5), 'calc(2.5 * min(20cqh, 5cqw))')
assert.equal(textWidth(5, 4), 12)
})
test('a screen whose default is a library slide plays it when no line matches', () => {
const one = { id: 'slide:3', slides: [{ id: 3 }] }
const data = { schedule: { entries: [{ playlist_id: 1, date_from: '2000-01-01', date_to: '2000-01-01' }], fallback_playlist_id: 'slide:3', scenes: [], timezone: 'Europe/Athens' },
playlists: { 1: { id: 1, slides: [] }, 'slide:3': one } }
assert.equal(playlistNow(data, new Date('2026-11-21T12:00:00Z')), one)
})
+10
View File
@@ -342,6 +342,13 @@
.x-switch-row__label { display: block; font-size: var(--x-text-body); line-height: var(--x-leading-body); font-weight: var(--x-weight-medium); color: var(--x-ink); cursor: pointer; } .x-switch-row__label { display: block; font-size: var(--x-text-body); line-height: var(--x-leading-body); font-weight: var(--x-weight-medium); color: var(--x-ink); cursor: pointer; }
.x-switch-row__description { margin-top: var(--x-space-0-5); font-size: var(--x-text-label); line-height: var(--x-leading-label); color: var(--x-ink-2); } .x-switch-row__description { margin-top: var(--x-space-0-5); font-size: var(--x-text-label); line-height: var(--x-leading-label); color: var(--x-ink-2); }
.x-switch-row--disabled .x-switch-row__label { cursor: not-allowed; opacity: 0.6; } .x-switch-row--disabled .x-switch-row__label { cursor: not-allowed; opacity: 0.6; }
/* boxed (2026-11-21): a switch in a row of fields, as tall and as framed as an input beside it */
.x-switch-row--boxed {
box-sizing: border-box; min-height: var(--x-control-md); padding: var(--x-space-2) var(--x-space-3);
background: var(--x-surface); border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control);
}
.x-switch-row--boxed .x-switch-row__label { font-size: var(--x-text-label); }
.x-confirm__body { font-size: var(--x-text-body); line-height: var(--x-leading-body); color: var(--x-ink-2); }
/* ── ReasonPicker ───────────────────────────────────────────────────────────── */ /* ── ReasonPicker ───────────────────────────────────────────────────────────── */
.x-reasons { display: grid; gap: var(--x-space-2); } .x-reasons { display: grid; gap: var(--x-space-2); }
@@ -514,6 +521,9 @@
border: var(--x-border-width) solid var(--x-line-strong); border-radius: var(--x-radius-control); background: var(--x-surface-2); border: var(--x-border-width) solid var(--x-line-strong); border-radius: var(--x-radius-control); background: var(--x-surface-2);
} }
.x-segmented--sm { min-height: var(--x-control-sm); } .x-segmented--sm { min-height: var(--x-control-sm); }
/* fill (2026-11-21): as wide as its column, the options sharing the width */
.x-segmented--fill { display: flex; width: 100%; }
.x-segmented--fill > .x-segmented__item { flex: 1 1 0; justify-content: center; }
.x-segmented__item { .x-segmented__item {
display: inline-flex; align-items: center; gap: var(--x-space-1-5); padding: 0 var(--x-space-3); display: inline-flex; align-items: center; gap: var(--x-space-1-5); padding: 0 var(--x-space-3);
border: 0; border-radius: calc(var(--x-radius-control) - 3px); background: transparent; color: var(--x-ink-2); border: 0; border-radius: calc(var(--x-radius-control) - 3px); background: transparent; color: var(--x-ink-2);
@@ -0,0 +1,41 @@
import { useCallback, useState } from 'react'
import { Button } from './Button.jsx'
import { Dialog } from './Dialog.jsx'
import { useLabels } from './labels.js'
/**
* Asks before doing something: a small dialog inside the page, never the browser's confirm()
* (2026-11-21). tone 'danger' for deleting / throwing work away.
* <ConfirmDialog open title="Delete this slide?" confirmLabel="Delete" tone="danger"
* onConfirm={remove} onCancel={close}>It goes from the playlist.</ConfirmDialog>
*/
export function ConfirmDialog({ open, title, children, confirmLabel, cancelLabel, tone = 'primary', onConfirm, onCancel, busy = false, testId }) {
const labels = useLabels()
return (
<Dialog open={open} size="sm" title={title} onClose={onCancel}
footer={<>
<Button variant="secondary" onClick={onCancel} data-testid={testId ? `${testId}-cancel` : 'confirm-cancel'}>{cancelLabel ?? labels.cancel}</Button>
<Button variant={tone === 'danger' ? 'danger' : 'primary'} loading={busy} onClick={onConfirm}
data-testid={testId ? `${testId}-ok` : 'confirm-ok'}>{confirmLabel ?? labels.submit}</Button>
</>}>
{children && <div className="x-confirm__body">{children}</div>}
</Dialog>
)
}
/**
* The same as a hook that answers with a promise:
* const [confirm, confirmDialog] = useConfirm()
* if (!(await confirm({ title, body, confirmLabel, tone: 'danger' }))) return
* …render {confirmDialog} somewhere in the component.
*/
export function useConfirm() {
const [ask, setAsk] = useState(null)
const confirm = useCallback(opts => new Promise(resolve => setAsk({ ...opts, resolve })), [])
const answer = value => { ask?.resolve(value); setAsk(null) }
const dialog = ask ? (
<ConfirmDialog open title={ask.title} confirmLabel={ask.confirmLabel} cancelLabel={ask.cancelLabel} tone={ask.tone} testId={ask.testId}
onConfirm={() => answer(true)} onCancel={() => answer(false)}>{ask.body}</ConfirmDialog>
) : null
return [confirm, dialog]
}
+5 -4
View File
@@ -42,15 +42,16 @@ export function FilterChip({ pressed = false, tone = 'neutral', count, size = 'm
} }
/** /**
* A few mutually exclusive views (List / Map). options: [{ value, label, icon? }]. * A few mutually exclusive views (List / Map). options: [{ value, label, icon?, ariaLabel? }]
* (ariaLabel: the name of an option shown as an icon only). fill: as wide as its column, the options sharing it.
* <Segmented value={view} onChange={setView} options={[…]} aria-label="View" /> * <Segmented value={view} onChange={setView} options={[…]} aria-label="View" />
*/ */
export function Segmented({ options = [], value, onChange, size = 'md', className, ...rest }) { export function Segmented({ options = [], value, onChange, size = 'md', fill = false, className, ...rest }) {
return ( return (
<div role="group" className={cx('x-segmented', `x-segmented--${size}`, className)} {...rest}> <div role="group" className={cx('x-segmented', `x-segmented--${size}`, fill && 'x-segmented--fill', className)} {...rest}>
{options.map(o => ( {options.map(o => (
<button key={o.value} type="button" aria-pressed={o.value === value} className={cx('x-segmented__item', o.value === value && 'x-segmented__item--on')} <button key={o.value} type="button" aria-pressed={o.value === value} className={cx('x-segmented__item', o.value === value && 'x-segmented__item--on')}
onClick={() => onChange?.(o.value)} data-testid={o.testId}> onClick={() => onChange?.(o.value)} data-testid={o.testId} aria-label={o.ariaLabel} title={o.ariaLabel}>
{o.icon}{o.label} {o.icon}{o.label}
</button> </button>
))} ))}
+3 -2
View File
@@ -7,8 +7,9 @@ import { cx } from '../internal/cx.js'
* onChange receives the new boolean. Without `label`, pass aria-label. * onChange receives the new boolean. Without `label`, pass aria-label.
* The whole row (label + description) is clickable. * The whole row (label + description) is clickable.
* info: an element right after the label (an <InfoTip>), not after the switch. * info: an element right after the label (an <InfoTip>), not after the switch.
* boxed: framed and as tall as an input, the text left and the switch right (a switch in a row of fields).
*/ */
export function Switch({ checked, onChange, label, description, info, disabled = false, id, className, ...rest }) { export function Switch({ checked, onChange, label, description, info, disabled = false, boxed = false, id, className, ...rest }) {
const auto = useId() const auto = useId()
const switchId = id || auto const switchId = id || auto
const descId = `${switchId}-desc` const descId = `${switchId}-desc`
@@ -31,7 +32,7 @@ export function Switch({ checked, onChange, label, description, info, disabled =
if (!label && !description) return <span className={cx('x-switch-bare', className)}>{control}</span> if (!label && !description) return <span className={cx('x-switch-bare', className)}>{control}</span>
return ( return (
<div className={cx('x-switch-row', disabled && 'x-switch-row--disabled', className)}> <div className={cx('x-switch-row', boxed && 'x-switch-row--boxed', disabled && 'x-switch-row--disabled', className)}>
<div className="x-switch-row__text"> <div className="x-switch-row__text">
{label && ( {label && (
<span className="x-switch-row__head"> <span className="x-switch-row__head">
+1
View File
@@ -7,6 +7,7 @@ import { createContext, createElement, useContext } from 'react'
export const DEFAULT_LABELS = { export const DEFAULT_LABELS = {
close: 'Close', close: 'Close',
cancel: 'Cancel',
dismiss: 'Dismiss', dismiss: 'Dismiss',
loading: 'Loading', loading: 'Loading',
moreInfo: 'More info', moreInfo: 'More info',
+1
View File
@@ -11,6 +11,7 @@
export { Button, IconButton } from './components/Button.jsx' export { Button, IconButton } from './components/Button.jsx'
export { Dialog } from './components/Dialog.jsx' export { Dialog } from './components/Dialog.jsx'
export { ConfirmDialog, useConfirm } from './components/ConfirmDialog.jsx'
export { Sheet } from './components/Sheet.jsx' export { Sheet } from './components/Sheet.jsx'
export { PrintArea, PrintSheet } from './components/PrintArea.jsx' export { PrintArea, PrintSheet } from './components/PrintArea.jsx'
export { ToastProvider } from './components/Toast.jsx' export { ToastProvider } from './components/Toast.jsx'
+45 -1
View File
@@ -265,7 +265,8 @@ try {
await mgr.getByTestId('signage-add-slide').click() await mgr.getByTestId('signage-add-slide').click()
await mgr.getByTestId('signage-template-menuBoard').click() await mgr.getByTestId('signage-template-menuBoard').click()
await mgr.getByTestId('signage-menu-editor').waitFor({ timeout: 10_000 }) await mgr.getByTestId('signage-menu-editor').waitFor({ timeout: 10_000 })
await mgr.getByTestId('signage-menu-select').selectOption('custom') await mgr.getByTestId('signage-menu-select').click()
await mgr.getByRole('option', { name: 'Chosen categories and products' }).click()
await mgr.locator(`[data-testid="signage-menu-category"][data-name="${catA.name}"]`).click() await mgr.locator(`[data-testid="signage-menu-category"][data-name="${catA.name}"]`).click()
await mgr.locator(`[data-testid="signage-menu-category"][data-name="${catB.name}"]`).click() await mgr.locator(`[data-testid="signage-menu-category"][data-name="${catB.name}"]`).click()
await mgr.getByTestId('signage-menu-search').fill(extra.name.slice(0, 4)) await mgr.getByTestId('signage-menu-search').fill(extra.name.slice(0, 4))
@@ -301,6 +302,43 @@ try {
&& !menuSlide.menu.groups.flatMap(g => g.items).some(i => i.id === hiddenId) && menuSlide.menu.groups[0].category?.id === catB.id, && !menuSlide.menu.groups.flatMap(g => g.items).some(i => i.id === hiddenId) && menuSlide.menu.groups[0].category?.id === catB.id,
JSON.stringify({ select: mc.select, cats: mc.category_ids, prods: mc.product_ids, ex: mc.exclude_ids, order: mc.category_order, badges: mc.badges })) JSON.stringify({ select: mc.select, cats: mc.category_ids, prods: mc.product_ids, ex: mc.exclude_ids, order: mc.category_order, badges: mc.badges }))
await mgr.screenshot({ path: path.join(OUT, 'signage-menu-editor.png') }) await mgr.screenshot({ path: path.join(OUT, 'signage-menu-editor.png') })
// ── 2026-11-21: a widget moved and sized on the preview; the slide kept in the Slides library ──
await mgr.getByTestId('signage-preview-box').scrollIntoViewIfNeeded()
await sleep(300)
const handle = mgr.getByTestId('signage-canvas-widget').last()
const hb = await handle.boundingBox()
await mgr.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2)
await mgr.mouse.down()
await mgr.mouse.move(hb.x - 200, hb.y + 120, { steps: 6 })
await mgr.mouse.up()
const se = await mgr.getByTestId('signage-handle-se').boundingBox()
await mgr.mouse.move(se.x + 7, se.y + 7)
await mgr.mouse.down()
await mgr.mouse.move(se.x + 60, se.y + 30, { steps: 5 })
await mgr.mouse.up()
r.check('2026-11-21: a widget dragged on the preview reads "Custom" in its card',
(await mgr.locator('[data-testid="signage-widget"][data-selected="true"]').getByTestId('signage-widget-position').textContent()).includes('Custom'))
await mgr.getByTestId('signage-slide-save').click()
await sleep(900)
const moved = (await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.find(x => x.kind === 'menu').content.widgets.find(w => w.position === 'custom')
r.check('2026-11-21: …saved with its own box', moved?.position === 'custom' && moved.size === 'custom' && moved.box?.w > 0 && moved.box?.h > 0, JSON.stringify(moved))
await mgr.getByTestId('signage-keep-slide').click()
await mgr.getByTestId('signage-keep-name').fill('Board to keep')
await mgr.getByTestId('signage-keep-confirm').click()
await sleep(800)
const kept = (await api('GET', '/api/signage/library', { token: boss })).slides.find(x => x.name === 'Board to keep')
r.check('2026-11-21: a playlist\'s slide kept in the Slides library', kept?.kind === 'menu' && kept.content.widgets.some(w => w.position === 'custom'))
await mgr.getByTestId('signage-add-slide').click()
await mgr.locator('[data-testid="signage-add-saved"][data-name="Board to keep"]').click()
await sleep(900)
r.check('2026-11-21: …and added from "Your slides" to the playlist (a copy)',
(await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.filter(x => x.kind === 'menu').length === 2)
// removing a slide asks inside the page (not the browser)
await mgr.getByTestId('signage-slide-card').last().getByTestId('signage-slide-delete').click()
await mgr.getByTestId('signage-slide-delete-confirm-ok').click()
await sleep(900)
r.check('2026-11-21: a slide removed after the page\'s own question',
(await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.filter(x => x.kind === 'menu').length === 1)
// ── 5.6c: screens, schedules, the message of the day ───────────────────── // ── 5.6c: screens, schedules, the message of the day ─────────────────────
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
await mgr.getByTestId('signage-tab-settings').click() await mgr.getByTestId('signage-tab-settings').click()
@@ -353,6 +391,12 @@ try {
await mgr.getByTestId('signage-tab-schedules').click() await mgr.getByTestId('signage-tab-schedules').click()
await mgr.screenshot({ path: path.join(OUT, 'signage-schedules.png'), fullPage: true }) await mgr.screenshot({ path: path.join(OUT, 'signage-schedules.png'), fullPage: true })
await api('PUT', '/api/signage/schedules', { token: boss, body: { lines: [] } }) await api('PUT', '/api/signage/schedules', { token: boss, body: { lines: [] } })
// a library slide as the screen's default (2026-11-21)
await mgr.getByTestId('signage-tab-screens').click()
await card.waitFor({ timeout: 10_000 })
await choose(card, 'signage-screen-playlist', 'Board to keep')
r.check('2026-11-21: Screens: a library slide as the default plays alone on the TV',
!!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === `slide:${kept.id}`, 15_000, 300)))
await mgr.context().close() await mgr.context().close()
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300) await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)