feat(signage): stacks, menu and text widgets, widget order (owner review 2)

- Stacks: horizontal / vertical, 2-6 parts with % shares; each part shows
  a widget, a stack one level deep, or a whole Slides-library slide
- Menu widget (a board's list in its box), text widget, weather for
  tomorrow / the day after and in picture / degrees / both styles
- Widgets' order (arrows, drag with a drop line), drawn in list order;
  arrow keys move the picked widget from its card too
- Server: extras by widget path (QR links, menus, embedded slides),
  POST /preview/slide, resolve(keep_hidden) so hidden products stay
  greyed in the editor's list; screens told when an embedded slide changes
- Editor rows tidied: framed sliders, colours as fields, text look on one
  row, Switch boxed toggles from its whole frame

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 09:44:23 +02:00
co-authored by Claude Opus 5.5
parent 83551714f7
commit 1b993e4573
23 changed files with 1231 additions and 377 deletions
+1 -1
View File
@@ -58,7 +58,7 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| 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 | | 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 | | A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right; a click anywhere in the frame toggles it |
| Two or three choices that fill a form column (alignment…) | `Segmented fill` | options share the width; icon-only options pass `ariaLabel` | | 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 |
+216 -65
View File
@@ -71,10 +71,59 @@ class Background(_Strict):
fit: Literal["cover", "contain"] = "cover" fit: Literal["cover", "contain"] = "cover"
WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"] WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather", "text", "menu", "stack"]
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"] Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "custom"]
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"]
class MenuList(_Strict):
"""What a menu board lists and how its lines look (5.4b): services/signage_menu.py resolves it.
A menu slide (MenuContent) adds its background, widgets and width; a menu widget (2026-11-21)
carries one as its `board`."""
title: Optional[str] = Field(default=None, max_length=120)
# what it lists
select: Literal["all", "custom"] = "custom"
category_ids: List[int] = Field(default_factory=list, max_length=200) # whole categories (live)
product_ids: List[int] = Field(default_factory=list, max_length=1000) # single products
exclude_ids: List[int] = Field(default_factory=list, max_length=1000)
group_by_category: bool = True
category_titles: bool = True # a heading over each group
category_order: List[int] = Field(default_factory=list, max_length=200) # the board's own order
product_order: List[int] = Field(default_factory=list, max_length=1000)
# what each line shows
sales_point: Optional[str] = "in_store" # whose prices; None = no prices
show_photos: bool = False
show_descriptions: bool = False
badges: Dict[str, Badge] = Field(default_factory=dict) # product id → badge
sold_out: Literal["strike", "hide"] = "strike"
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# pages (the player pages through what doesn't fit, 5.5b)
columns: int = Field(default=2, ge=1, le=3)
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)
font: Font = "sans"
text_colour: str = Field(default="#ffffff", pattern=HEX)
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
text_size: int = Field(default=100, ge=50, le=250)
@field_validator("sales_point")
@classmethod
def _point(cls, v):
from core import sales_points
if v is not None and v not in sales_points.ALL:
raise ValueError(f"one of {', '.join(sales_points.ALL)}")
return v
@field_validator("badges")
@classmethod
def _badge_keys(cls, v):
if any(not k.isdigit() for k in v):
raise ValueError("badges are keyed by product id")
return v
class Box(_Strict): class Box(_Strict):
"""Where a widget moved by hand sits (2026-11-21): % of the slide's width / height.""" """Where a widget moved by hand sits (2026-11-21): % of the slide's width / height."""
x: float = Field(ge=0, le=100) x: float = Field(ge=0, le=100)
@@ -92,9 +141,28 @@ class Box(_Strict):
return self return self
class Cell(_Strict):
"""A part of a stack (2026-11-21): its share of the stack (the parts' shares are weights; the
editor keeps them adding up to 100) and what it shows: a widget (another stack too, one level
deep) or a slide of the Slides library, drawn whole inside the part; or nothing."""
share: float = Field(default=50, ge=1, le=100)
widget: Optional["Widget"] = None
slide_id: Optional[int] = None
@model_validator(mode="after")
def _one(self):
if self.widget is not None and self.slide_id is not None:
raise ValueError("a part shows a widget or a slide, not both")
self.share = round(self.share, 2)
return self
class Widget(_Strict): class Widget(_Strict):
"""Something small on a menu, text or blank slide (5.4c), in a corner or a bar, or (moved and """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".""" sized by hand on the editor's preview, 2026-11-21) in its own box: position and size "custom".
2026-11-21: a text of its own, a menu (a board's list in the widget's place) and stacks: parts
side by side (direction "row") or one over the other ("column"), each showing a widget or a
whole library slide."""
kind: WidgetKind kind: WidgetKind
position: Position = "top-right" position: Position = "top-right"
size: Literal["small", "medium", "large", "custom"] = "medium" size: Literal["small", "medium", "large", "custom"] = "medium"
@@ -107,7 +175,12 @@ class Widget(_Strict):
qr_target: Literal["ordering", "menu", "custom"] = "ordering" qr_target: Literal["ordering", "menu", "custom"] = "ordering"
qr_url: Optional[str] = Field(default=None, max_length=300) qr_url: Optional[str] = Field(default=None, max_length=300)
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) # how many days, from weather_from
weather_from: int = Field(default=0, ge=0, le=2) # 0 today (now), 1 tomorrow, 2 the day after
weather_style: Literal["both", "icon", "text"] = "both" # picture and degrees, the picture, the degrees
board: Optional[MenuList] = None # menu: what it lists and how
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
cells: List[Cell] = Field(default_factory=list, max_length=6)
@model_validator(mode="after") @model_validator(mode="after")
def _place(self): def _place(self):
@@ -121,6 +194,20 @@ class Widget(_Strict):
self.size = "medium" self.size = "medium"
return self return self
@model_validator(mode="after")
def _kind_fields(self):
if self.kind == "stack" and not self.cells:
raise ValueError("a stack has at least one part")
if self.kind != "stack":
self.cells = []
if self.kind == "menu" and self.board is None:
self.board = MenuList(select="all", columns=1)
if self.kind != "menu":
self.board = None
if self.weather_from + self.weather_days > 3:
self.weather_days = 3 - self.weather_from # the forecast has three days
return self
@field_validator("qr_url") @field_validator("qr_url")
@classmethod @classmethod
def _url(cls, v): def _url(cls, v):
@@ -131,6 +218,9 @@ class Widget(_Strict):
return v return v
Cell.model_rebuild()
class ImageContent(_Strict): class ImageContent(_Strict):
media_id: Optional[int] = None # a picture media_id: Optional[int] = None # a picture
fit: Literal["cover", "contain"] = "cover" fit: Literal["cover", "contain"] = "cover"
@@ -162,57 +252,15 @@ class BlankContent(_Strict):
widgets: List[Widget] = Field(default_factory=list, max_length=10) widgets: List[Widget] = Field(default_factory=list, max_length=10)
Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"] class MenuContent(MenuList):
class MenuContent(_Strict):
"""A menu board (5.4b): which products (services/signage_menu.py resolves them), in the board's """A menu board (5.4b): which products (services/signage_menu.py resolves them), in the board's
own order, with a sales point's live prices, and how it looks.""" own order, with a sales point's live prices, and how it looks (MenuList), on its background
title: Optional[str] = Field(default=None, max_length=120) with its widgets."""
# what it lists
select: Literal["all", "custom"] = "custom"
category_ids: List[int] = Field(default_factory=list, max_length=200) # whole categories (live)
product_ids: List[int] = Field(default_factory=list, max_length=1000) # single products
exclude_ids: List[int] = Field(default_factory=list, max_length=1000)
group_by_category: bool = True
category_titles: bool = True # a heading over each group
category_order: List[int] = Field(default_factory=list, max_length=200) # the board's own order
product_order: List[int] = Field(default_factory=list, max_length=1000)
# what each line shows
sales_point: Optional[str] = "in_store" # whose prices; None = no prices
show_photos: bool = False
show_descriptions: bool = False
badges: Dict[str, Badge] = Field(default_factory=dict) # product id → badge
sold_out: Literal["strike", "hide"] = "strike"
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)
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_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 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_seconds: int = Field(default=10, ge=3, le=120)
font: Font = "sans"
text_colour: str = Field(default="#ffffff", pattern=HEX)
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # prices, headings, badges
text_size: int = Field(default=100, ge=50, le=250)
background: Background = Field(default_factory=Background) background: Background = Field(default_factory=Background)
widgets: List[Widget] = Field(default_factory=list, max_length=10) widgets: List[Widget] = Field(default_factory=list, max_length=10)
@field_validator("sales_point")
@classmethod
def _point(cls, v):
from core import sales_points
if v is not None and v not in sales_points.ALL:
raise ValueError(f"one of {', '.join(sales_points.ALL)}")
return v
@field_validator("badges")
@classmethod
def _badge_keys(cls, v):
if any(not k.isdigit() for k in v):
raise ValueError("badges are keyed by product id")
return v
CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent, "blank": BlankContent} CONTENT = {"image": ImageContent, "video": VideoContent, "text": TextContent, "menu": MenuContent, "blank": BlankContent}
Kind = Literal["menu", "image", "video", "text", "blank"] Kind = Literal["menu", "image", "video", "text", "blank"]
@@ -367,6 +415,60 @@ def media_ids(value) -> list[int]:
return out return out
def walk_widgets(widgets, prefix: str = ""):
"""Every widget of a slide, inside stacks too, with its path ("2", "2.0", "2.1.1": the widget's
index, then its part's): → (path, widget, None), and (path, None, slide id) for a part that
shows a library slide. The editor and the player find a widget's extras by its path."""
for i, w in enumerate(widgets or []):
yield from _walk_one(w, f"{prefix}{i}")
def _walk_one(w: dict, path: str):
yield path, w, None
for j, c in enumerate(w.get("cells") or []):
cp = f"{path}.{j}"
if c.get("widget"):
yield from _walk_one(c["widget"], cp)
elif c.get("slide_id"):
yield cp, None, c["slide_id"]
def embedded_ids(content: dict) -> set:
"""The library slides a slide's stacks show."""
return {sid for _, _, sid in walk_widgets((content or {}).get("widgets")) if sid}
def _needs_menu(kind: str, content: dict) -> bool:
"""Does a slide show products (a menu board, a menu widget, a library slide inside a stack)?"""
return kind == "menu" or any((w and w.get("kind") == "menu") or sid for _, w, sid in walk_widgets((content or {}).get("widgets")))
def extras(db, content: dict, keep_hidden: bool = False, depth: int = 0):
"""What a slide's widgets need beyond what is stored (2026-11-21), by widget path: a QR code's
link, a menu widget's products (`menu`), a part's library slide (`slide`: its kind, content,
menu and extras; slides inside it don't show further slides). → (extras, media ids they show)."""
from services.signage_menu import resolve
out, mids = {}, []
for path, w, sid in walk_widgets((content or {}).get("widgets")):
if w is not None:
if w.get("kind") == "qr":
out[path] = {"link": _qr_link(w)}
elif w.get("kind") == "menu":
out[path] = {"menu": resolve(db, w.get("board") or {}, keep_hidden=keep_hidden)}
elif depth == 0:
s = db.get(SignageSavedSlide, sid)
if s is None:
continue
inner, inner_media = extras(db, s.content or {}, depth=1)
one = {"id": s.id, "name": s.name, "kind": s.kind, "content": s.content or {}, "extras": inner,
"orientation": s.orientation}
if s.kind == "menu":
one["menu"] = resolve(db, one["content"])
out[path] = {"slide": one}
mids += media_ids(one["content"]) + inner_media
return out, mids
def _content(db, kind: str, raw: dict | None) -> dict: def _content(db, kind: str, raw: dict | None) -> dict:
"""The content as stored: typed for its kind, every media id an existing file of the right kind.""" """The content as stored: typed for its kind, every media id an existing file of the right kind."""
from pydantic import ValidationError from pydantic import ValidationError
@@ -389,9 +491,16 @@ def _content(db, kind: str, raw: dict | None) -> dict:
raise XeniaError("signage.not_a_video") raise XeniaError("signage.not_a_video")
if kind != "video" and m.kind != "image": if kind != "video" and m.kind != "image":
raise XeniaError("media.not_a_picture") raise XeniaError("media.not_a_picture")
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for w in data.get("widgets") or []] found = list(walk_widgets(data.get("widgets")))
pictures = [(data.get("background") or {}).get("media_id")] + [w.get("media_id") for _, w, _ in found if w]
if any(i is not None and db.get(Media, i).kind != "image" for i in pictures): if any(i is not None and db.get(Media, i).kind != "image" for i in pictures):
raise XeniaError("media.not_a_picture") raise XeniaError("media.not_a_picture")
for path, w, sid in found:
# a stack inside a stack, not deeper (2026-11-21)
if w and w.get("kind") == "stack" and path.count(".") > 1:
raise XeniaError("signage.content_invalid", field=f"widgets.{path}", reason="a stack goes at most one stack deep")
if sid and db.get(SignageSavedSlide, sid) is None:
raise XeniaError("signage.slide_unknown", slide_id=sid)
return data return data
@@ -472,10 +581,13 @@ def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict:
if slides: if slides:
from services.signage_menu import resolve from services.signage_menu import resolve
out["slides"] = [_slide_out(s) for s in p.slides] out["slides"] = [_slide_out(s) for s in p.slides]
more = []
for s in out["slides"]: for s in out["slides"]:
if s["kind"] == "menu": if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # the editor's preview (5.6a) s["menu"] = resolve(db, s["content"], keep_hidden=True) # the editor's preview (5.6a)
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})]) s["extras"], m = extras(db, s["content"], keep_hidden=True)
more += m
out["media"] = _media_map(db, [i for s in p.slides for i in media_ids(s.content or {})] + more)
return out return out
@@ -539,8 +651,8 @@ 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 (or as their default slide) 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 = {x.playlist_id for x in db.query(SignageSlide) if _needs_menu(x.kind, x.content)}
boards = {slide_key(sid) for (sid,) in db.query(SignageSavedSlide.id).filter(SignageSavedSlide.kind == "menu")} boards = {slide_key(x.id) for x in db.query(SignageSavedSlide) if _needs_menu(x.kind, x.content)}
if playlists or boards: 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]) _tell([d.id for d in _screens(db) if _screen_playlists(db, d) & playlists or default_of(_screen_config(d)) in boards])
@@ -705,12 +817,29 @@ def _saved_out(s: SignageSavedSlide, db=None) -> dict:
if db is not None: if db is not None:
if s.kind == "menu": if s.kind == "menu":
from services.signage_menu import resolve from services.signage_menu import resolve
out["menu"] = resolve(db, out["content"]) out["menu"] = resolve(db, out["content"], keep_hidden=True)
out["extras"], out["extra_media"] = extras(db, out["content"], keep_hidden=True)
showing = set(_screens_showing_slide(db, s.id)) 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] out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing]
return out return out
def _saved_one(db, s: SignageSavedSlide) -> dict:
"""One library slide for the editor, with the media it shows (its own and its stacks')."""
out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
return out
def _embedding_screens(db, sid: int) -> list[int]:
"""The screens that may show a library slide inside a stack (of a playlist's slide, or of a
library slide that is a screen's default): told when it changes."""
playlists = {x.playlist_id for x in db.query(SignageSlide) if sid in embedded_ids(x.content)}
saved = {x.id for x in db.query(SignageSavedSlide) if sid in embedded_ids(x.content)}
return [d.id for d in _screens(db) if _screen_playlists(db, d) & playlists
or (not _screen_config(d).get("playlist") and _screen_config(d).get("slide") in saved)]
def _saved_name(body) -> str: def _saved_name(body) -> str:
name = (body.name or "").strip() name = (body.name or "").strip()
if not name: if not name:
@@ -722,8 +851,9 @@ def _saved_name(body) -> str:
def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))): 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.""" """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() rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all()
return {"slides": [_saved_out(s, db) for s in rows], 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 {})])} return {"slides": slides,
"media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})] + [i for x in slides for i in x.pop("extra_media")])}
@router.post("/library", status_code=201) @router.post("/library", status_code=201)
@@ -739,14 +869,14 @@ def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depen
db.add(s) db.add(s)
db.commit() db.commit()
db.refresh(s) db.refresh(s)
return _saved_out(s, db) return _saved_one(db, s)
@router.get("/library/{slide_id}") @router.get("/library/{slide_id}")
def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id) s = _saved(db, slide_id)
out = _saved_out(s, db) out = _saved_out(s, db)
out["media"] = _media_map(db, media_ids(s.content or {})) out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media"))
return out return out
@@ -764,14 +894,14 @@ def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_
s.orientation = body.orientation s.orientation = body.orientation
db.commit() db.commit()
db.refresh(s) db.refresh(s)
_tell(_screens_showing_slide(db, s.id)) _tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id))
return _saved_out(s, db) return _saved_one(db, s)
@router.delete("/library/{slide_id}", status_code=204) @router.delete("/library/{slide_id}", status_code=204)
def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id) s = _saved(db, slide_id)
showing = _screens_showing_slide(db, s.id) showing = _screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)
for d in _screens(db): for d in _screens(db):
if (d.config or {}).get("slide") == s.id: if (d.config or {}).get("slide") == s.id:
d.config = {**(d.config or {}), "slide": None} d.config = {**(d.config or {}), "slide": None}
@@ -791,7 +921,7 @@ def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(r
db.add(copy) db.add(copy)
db.commit() db.commit()
db.refresh(copy) db.refresh(copy)
return _saved_out(copy, db) return _saved_one(db, copy)
# ── screens ──────────────────────────────────────────────────────────────────── # ── screens ────────────────────────────────────────────────────────────────────
@@ -851,15 +981,18 @@ def _resolved(db, p: SignagePlaylist) -> dict:
"""A playlist as a screen plays it: enabled slides, transitions filled in, menus, QR links, media.""" """A playlist as a screen plays it: enabled slides, transitions filled in, menus, QR links, media."""
from services.signage_menu import resolve from services.signage_menu import resolve
slides = [_slide_out(s) for s in p.slides if s.enabled] slides = [_slide_out(s) for s in p.slides if s.enabled]
more = []
for s in slides: for s in slides:
s["transition"] = s["transition"] or p.transition s["transition"] = s["transition"] or p.transition
if s["kind"] == "menu": if s["kind"] == "menu":
s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b) s["menu"] = resolve(db, s["content"]) # live prices and availability (5.4b)
s["extras"], m = extras(db, s["content"]) # menus, library slides inside stacks, links (2026-11-21)
more += m
for w in s["content"].get("widgets") or []: for w in s["content"].get("widgets") or []:
if w["kind"] == "qr": if w["kind"] == "qr":
w["link"] = _qr_link(w) w["link"] = _qr_link(w)
return {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides, return {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides,
"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"])] + more)}
def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict: def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
@@ -869,12 +1002,13 @@ def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
one["transition"] = one["transition"] or "fade" one["transition"] = one["transition"] or "fade"
if one["kind"] == "menu": if one["kind"] == "menu":
one["menu"] = resolve(db, one["content"]) one["menu"] = resolve(db, one["content"])
one["extras"], more = extras(db, one["content"])
for w in one["content"].get("widgets") or []: for w in one["content"].get("widgets") or []:
if w["kind"] == "qr": if w["kind"] == "qr":
w["link"] = _qr_link(w) w["link"] = _qr_link(w)
slides = [one] if s.enabled else [] slides = [one] if s.enabled else []
return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides, return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides,
"media": _media_map(db, media_ids(one["content"]))} "media": _media_map(db, media_ids(one["content"]) + more)}
def _default_resolved(db, cfg: dict): def _default_resolved(db, cfg: dict):
@@ -1079,9 +1213,26 @@ def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))):
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)} return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)}
class SlidePreviewBody(BaseModel):
kind: Kind
content: dict = Field(default_factory=dict)
@router.post("/preview/slide")
def preview_slide(body: SlidePreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""A slide not saved yet, as the editor's preview needs it (2026-11-21): a menu board's
products (hidden ones kept, marked), the extras of its widgets (menus, library slides inside
stacks, QR links) and the media they show."""
from services.signage_menu import resolve
content = _content(db, body.kind, body.content)
ex, more = extras(db, content, keep_hidden=True)
return {"menu": resolve(db, content, keep_hidden=True) if body.kind == "menu" else None, "extras": ex,
"media": _media_map(db, more)}
@router.post("/preview/menu") @router.post("/preview/menu")
def preview_menu(body: MenuPreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))): def preview_menu(body: MenuPreviewBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""A menu board not saved yet, resolved like a screen gets it (the editor's live preview).""" """A menu board not saved yet, resolved like a screen gets it (the editor's live preview)."""
from services.signage_menu import resolve from services.signage_menu import resolve
content = _content(db, "menu", body.content) content = _content(db, "menu", body.content)
return {"content": content, "menu": resolve(db, content)} return {"content": content, "menu": resolve(db, content, keep_hidden=True)}
+8 -4
View File
@@ -34,8 +34,11 @@ def _rank(order: list[int]):
return lambda v: (0, pos[v]) if v in pos else (1, 0) return lambda v: (0, pos[v]) if v in pos else (1, 0)
def resolve(db, content: dict, now=None) -> dict: def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
"""{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.""" """{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.
keep_hidden (the editor's list, 2026-11-21): products hidden from the board (`exclude_ids`) stay
in the list marked `"hidden": true` (greyed there, shown again with a click); `count` and the
TV leave them out."""
from models.product import Category, Product, ProductCategory from models.product import Category, Product, ProductCategory
from services import media as media_store from services import media as media_store
from services.pos_cart import unit_prices from services.pos_cart import unit_prices
@@ -55,6 +58,7 @@ def resolve(db, content: dict, now=None) -> dict:
ids = in_cats | set(content.get("product_ids") or []) ids = in_cats | set(content.get("product_ids") or [])
products = q.filter(Product.id.in_(ids)).all() if ids else [] products = q.filter(Product.id.in_(ids)).all() if ids else []
excluded = set(content.get("exclude_ids") or []) excluded = set(content.get("exclude_ids") or [])
if not keep_hidden:
products = [p for p in products if p.id not in excluded] products = [p for p in products if p.id not in excluded]
point = content.get("sales_point") point = content.get("sales_point")
@@ -89,7 +93,7 @@ def resolve(db, content: dict, now=None) -> dict:
"description": text(p, p.digital_description or p.description or None, "description") if content.get("show_descriptions") else None, "description": text(p, p.digital_description or p.description or None, "description") if content.get("show_descriptions") else None,
"price": round(prices[p.id], 2) if p.id in prices else None, "price": round(prices[p.id], 2) if p.id in prices else None,
"available": bool(p.is_available), "image": image["card"] if image else None, "available": bool(p.is_available), "image": image["card"] if image else None,
"badge": badges.get(p.id)} "badge": badges.get(p.id), **({"hidden": True} if p.id in excluded else {})}
if content.get("group_by_category", True): if content.get("group_by_category", True):
groups: dict = {} groups: dict = {}
@@ -101,4 +105,4 @@ def resolve(db, content: dict, now=None) -> dict:
else: else:
ordered = sorted(products, key=lambda p: (prod_rank(p.id), cat_key(p.primary_category_id), prod_key(p))) ordered = sorted(products, key=lambda p: (prod_rank(p.id), cat_key(p.primary_category_id), prod_key(p)))
out = [{"category": None, "items": [item(p) for p in ordered]}] if ordered else [] out = [{"category": None, "items": [item(p) for p in ordered]}] if ordered else []
return {"groups": out, "count": len(products)} return {"groups": out, "count": len([p for p in products if p.id not in excluded])}
@@ -0,0 +1,97 @@
"""Signage widgets, owner review 2026-11-21: a text of its own, a menu widget (a board's list in the
widget's place), stacks (parts side by side or one over the other, each with a widget, another
stack one level deep, or a whole library slide), weather for tomorrow / the day after and in three
styles; products hidden from a board stay in the editor's list (greyed), never on the TV."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
from tests.test_signage_menu import menu, names # noqa: F401 (fixture + helper)
BOX = {"x": 5, "y": 10, "w": 90, "h": 80}
def stack(*cells, direction="row"):
return {"kind": "stack", "direction": direction, "position": "custom", "box": BOX, "cells": list(cells)}
def keep(client, h, **body):
r = client.post("/api/signage/library", headers=h, json={"name": "Promo", "kind": "text", **body})
assert r.status_code == 201, r.text
return r.json()
def test_text_weather_and_stack_widgets_are_checked(client, owner_h):
p = playlist(client, owner_h)
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "text", "text": "Happy hour 18-20"},
{"kind": "weather", "weather_from": 1, "weather_days": 3, "weather_style": "icon"},
stack({"share": 30, "widget": {"kind": "clock"}}, {"share": 70, "widget": stack({"share": 50}, {"share": 50}, direction="column")}),
]})
ws = s["content"]["widgets"]
assert ws[0]["text"] == "Happy hour 18-20"
assert ws[1]["weather_from"] == 1 and ws[1]["weather_days"] == 2 and ws[1]["weather_style"] == "icon" # the forecast has 3 days
assert [c["share"] for c in ws[2]["cells"]] == [30, 70] and ws[2]["cells"][1]["widget"]["direction"] == "column"
assert ws[0]["cells"] == [] and ws[0]["board"] is None
url = f"/api/signage/playlists/{p['id']}/slides"
bad = [
stack(), # no parts
stack({"share": 50, "widget": {"kind": "clock"}, "slide_id": 1}), # a widget and a slide
stack({"share": 50, "widget": stack({"share": 50, "widget": stack({"share": 100})})}), # three stacks deep
stack(*[{"share": 10}] * 7), # more than 6 parts
]
for w in bad:
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [w]}})) == "signage.content_invalid", w
assert err(client.post(url, headers=owner_h, json={"kind": "blank", "content": {"widgets": [stack({"share": 100, "slide_id": 999})]}})) == "signage.slide_unknown"
def test_a_stack_shows_a_library_slide_and_a_menu_widget(client, owner_h, screens, sent, menu, db):
promo = keep(client, owner_h, content={"title": "Fresh fish", "widgets": [{"kind": "qr", "position": "bottom-right"}]})
p = playlist(client, owner_h, "Split")
tv = screens[1]
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
board = {"kind": "menu", "board": {"category_ids": [menu["cats"]["drinks"]], "exclude_ids": [menu["beer"].id], "columns": 1}}
s = slide(client, owner_h, p["id"], "blank", content={"widgets": [
{"kind": "qr", "position": "top-left"},
stack({"share": 25, "widget": board}, {"share": 75, "slide_id": promo["id"]}),
]})
# the screen: extras by widget path (the QR's link, the menu's products, the slide inside the part)
got = client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]
ex = got["extras"]
assert ex["0"]["link"] and got["content"]["widgets"][0]["link"] == ex["0"]["link"]
assert names(ex["1.0"]["menu"]) == [] and ex["1.0"]["menu"]["count"] == 0 # Beer hidden; Wine: delivery only
inner = ex["1.1"]["slide"]
assert inner["id"] == promo["id"] and inner["kind"] == "text" and inner["content"]["title"] == "Fresh fish"
assert inner["extras"]["0"]["link"] # its own widgets' extras
# the editor: the hidden product stays in the list, marked
ed = client.get(f"/api/signage/playlists/{p['id']}", headers=owner_h).json()["slides"][0]["extras"]["1.0"]["menu"]
assert [(i["name"], i.get("hidden", False)) for g in ed["groups"] for i in g["items"]] == [("Beer", True)] and ed["count"] == 0
# a change to the library slide reaches the screens that show it inside a stack
sent.clear()
client.put(f"/api/signage/library/{promo['id']}", headers=owner_h, json={"content": {"title": "Fresh octopus"}})
assert sent == [("signage.changed", [tv["id"]])]
assert client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]["1.1"]["slide"]["content"]["title"] == "Fresh octopus"
# products change: a slide with a menu widget is told too
import routers.signage as sg
sent.clear()
sg.menu_changed(db)
assert sent == [("signage.changed", [tv["id"]])]
# the library slide deleted: the part shows nothing, the screen is told
sent.clear()
client.delete(f"/api/signage/library/{promo['id']}", headers=owner_h)
assert sent == [("signage.changed", [tv["id"]])]
assert "1.1" not in client.get("/api/signage/screen", headers=tv["h"]).json()["playlist"]["slides"][0]["extras"]
assert s["content"]["widgets"][1]["cells"][1]["slide_id"] == promo["id"]
def test_the_editor_previews_any_slide(client, owner_h, menu):
promo = keep(client, owner_h, content={"title": "Inside"})
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "blank", "content": {"widgets": [
stack({"share": 50, "widget": {"kind": "menu", "board": {"product_ids": [menu["steak"].id], "exclude_ids": [menu["steak"].id]}}},
{"share": 50, "slide_id": promo["id"]})]}})
assert r.status_code == 200, r.text
got = r.json()
assert [i.get("hidden") for g in got["extras"]["0.0"]["menu"]["groups"] for i in g["items"]] == [True]
assert got["extras"]["0.1"]["slide"]["content"]["title"] == "Inside" and got["menu"] is None and got["media"] == {}
r = client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "menu", "content": {"select": "all", "exclude_ids": [menu["beer"].id]}})
m = r.json()["menu"]
assert "Beer" in [i["name"] for g in m["groups"] for i in g["items"] if i.get("hidden")] and m["count"] == 3
assert err(client.post("/api/signage/preview/slide", headers=owner_h, json={"kind": "text", "content": {"widgets": [stack()]}})) == "signage.content_invalid"
@@ -2,12 +2,16 @@
// up to date, single products, minus hidden ones), the board's own order of categories and products // up to date, single products, minus hidden ones), the board's own order of categories and products
// (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 (the editor asks for it as you change things).
// 2026-11-21 (owner review): sections with titles; what each line shows in fewer rows (the four // 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 / // switches on one); the layout: columns, how wide the list is and where it sits (left / centre /
// right), products per page, seconds per page. // right), products per page, seconds per page.
// Owner review 2 (2026-11-21): a product hidden from the board stays in the list, greyed, with a red
// crossed eye (a green eye on the ones shown): a click shows / hides it; seconds per page explained;
// the text's look on one row. `board` mode: the same editor for a menu widget's list (no background,
// widgets, width or place; its own products per page).
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, EyeOff, X } from 'lucide-react' import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, Eye, 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 { Dropdown, Field, IconButton, Input, Segmented, Select, Switch } from '@xenia/ui' import { Dropdown, Field, IconButton, Input, Segmented, Select, Switch } from '@xenia/ui'
@@ -17,30 +21,40 @@ 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 = [], widget = null, onWidget }) { let catalogue = null // categories and products, read once for every menu editor on the page
function useCatalogue() {
const [data, setData] = useState(catalogue || { cats: [], products: [] })
useEffect(() => {
if (catalogue) return
Promise.all([client.get('/api/products/categories'), client.get('/api/products/')]).then(([c, p]) => {
catalogue = { cats: c.data, products: p.data.filter(x => x.lifecycle_status === 'active' && !x.is_service_item) }
setData(catalogue)
}).catch(() => {})
}, [])
return data
}
export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [], widget = null, onWidget, extras, board = false, testid = 'signage-menu-editor' }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const c = slide.content || {} const c = slide.content || {}
const setC = patch => onChange({ ...slide, content: { ...c, ...patch } }) const setC = patch => onChange({ ...slide, content: { ...c, ...patch } })
const [cats, setCats] = useState([]) const { cats, products } = useCatalogue()
const [products, setProducts] = useState([])
const [q, setQ] = useState('') const [q, setQ] = useState('')
useEffect(() => {
client.get('/api/products/categories').then(r => setCats(r.data)).catch(() => {})
client.get('/api/products/').then(r => setProducts(r.data.filter(p => p.lifecycle_status === 'active' && !p.is_service_item))).catch(() => {})
}, [])
const byId = useMemo(() => Object.fromEntries(products.map(p => [p.id, p])), [products]) const byId = useMemo(() => Object.fromEntries(products.map(p => [p.id, p])), [products])
const top = cats.filter(x => !x.parent_id) const top = cats.filter(x => !x.parent_id)
const subsOf = id => cats.filter(x => x.parent_id === id) const subsOf = id => cats.filter(x => x.parent_id === id)
const groups = slide.menu?.groups || [] const groups = slide.menu?.groups || []
const shown = new Set(groups.flatMap(g => g.items.map(i => i.id))) const listed = new Set(groups.flatMap(g => g.items.map(i => i.id)))
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()) && !listed.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, '')) const digits = v => Number(String(v).replace(/\D/g, ''))
const hidden = new Set(c.exclude_ids || [])
return ( return (
<div className="grid gap-7" data-testid="signage-menu-editor"> <div className="grid gap-7" data-testid={testid}>
{/* what it lists */} {/* what it lists */}
<Section title={t('signage.menu.what')}> <Section title={t('signage.menu.what')}>
<div className="grid gap-4 md:grid-cols-2 items-end"> <div className="grid gap-4 md:grid-cols-2 items-end">
@@ -75,7 +89,8 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
{(c.product_ids || []).map(id => ( {(c.product_ids || []).map(id => (
<span key={id} className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-control bg-surface-2 text-label text-ink"> <span key={id} className="inline-flex items-center gap-1 pl-2.5 pr-1 py-0.5 rounded-control bg-surface-2 text-label text-ink">
{byId[id]?.name ?? `#${id}`} {byId[id]?.name ?? `#${id}`}
<IconButton size="sm" variant="ghost" label={t('media.removePhoto')} onClick={() => setC({ product_ids: (c.product_ids || []).filter(x => x !== id) })}><X size={12} /></IconButton> <IconButton size="sm" variant="ghost" label={t('media.removePhoto')}
onClick={() => setC({ product_ids: (c.product_ids || []).filter(x => x !== id), exclude_ids: (c.exclude_ids || []).filter(x => x !== id) })}><X size={12} /></IconButton>
</span> </span>
))} ))}
</div> </div>
@@ -95,22 +110,9 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
)} )}
</div> </div>
</>} </>}
{(c.exclude_ids || []).length > 0 && (
<div className="grid gap-1.5">
<span className="text-label font-medium text-ink">{t('signage.menu.hidden')}</span>
<div className="flex flex-wrap gap-1.5">
{(c.exclude_ids || []).map(id => (
<button key={id} type="button" onClick={() => setC({ exclude_ids: (c.exclude_ids || []).filter(x => x !== id) })}
className="px-2.5 py-1 rounded-control border border-line bg-surface-2 text-label text-ink-2 hover:bg-surface-3" title={t('signage.menu.showAgain')}>
{byId[id]?.name ?? `#${id}`} · {t('signage.menu.showAgain')}
</button>
))}
</div>
</div>
)}
</Section> </Section>
{/* the board's own order, badges, hiding */} {/* the board's own order, badges, hiding (hidden ones stay here, greyed) */}
<Section title={t('signage.menu.onTheBoard', { count: slide.menu?.count ?? 0 })}> <Section title={t('signage.menu.onTheBoard', { count: slide.menu?.count ?? 0 })}>
<p className="text-caption text-ink-3 -mt-1">{t('signage.menu.orderHint')}</p> <p className="text-caption text-ink-3 -mt-1">{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 rounded-control border border-line bg-surface-2 p-3" data-testid="signage-menu-board">
@@ -124,11 +126,15 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
</div> </div>
)} )}
<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" data-testid="signage-menu-row" data-id={it.id}> const off = it.hidden || hidden.has(it.id)
<span className={`flex-1 min-w-0 truncate text-label ${it.available ? 'text-ink' : 'text-ink-3 line-through'}`}>{it.name}</span> return (
{it.price != null && <span className="text-caption text-ink-2 tabular-nums">{formatMoney(it.price)}</span>} <li key={it.id} className="flex items-center gap-1.5 pl-2 rounded-control hover:bg-surface"
<Select size="sm" value={badges[String(it.id)] || ''} aria-label={t('signage.menu.badge')} data-testid="signage-menu-badge" data-testid="signage-menu-row" data-id={it.id} data-hidden={off ? 'true' : undefined}>
<span className={`flex-1 min-w-0 truncate text-label ${off ? 'text-ink-3 opacity-70' : it.available ? 'text-ink' : 'text-ink-3 line-through'}`}>{it.name}</span>
{off && <span className="text-caption text-ink-3">{t('signage.menu.hiddenTag')}</span>}
{it.price != null && <span className={`text-caption tabular-nums ${off ? 'text-ink-3 opacity-70' : 'text-ink-2'}`}>{formatMoney(it.price)}</span>}
<Select size="sm" value={badges[String(it.id)] || ''} aria-label={t('signage.menu.badge')} data-testid="signage-menu-badge" disabled={off}
onChange={e => { onChange={e => {
const next = { ...badges } const next = { ...badges }
if (e.target.value) next[String(it.id)] = e.target.value if (e.target.value) next[String(it.id)] = e.target.value
@@ -138,10 +144,13 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
options={[{ value: '', label: t('signage.menu.noBadge') }, ...BADGES.map(b => ({ value: b, label: t(`signage.badges.${b}`) }))]} /> options={[{ value: '', label: t('signage.menu.noBadge') }, ...BADGES.map(b => ({ value: b, label: t(`signage.badges.${b}`) }))]} />
<IconButton size="sm" variant="ghost" label={t('display.earlier')} disabled={ii === 0} onClick={() => reorder(moveItem(groups, gi, ii, -1))} data-testid="signage-item-up"><ArrowUp size={14} /></IconButton> <IconButton size="sm" variant="ghost" label={t('display.earlier')} disabled={ii === 0} onClick={() => reorder(moveItem(groups, gi, ii, -1))} data-testid="signage-item-up"><ArrowUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('display.later')} disabled={ii === g.items.length - 1} onClick={() => reorder(moveItem(groups, gi, ii, 1))}><ArrowDown size={14} /></IconButton> <IconButton size="sm" variant="ghost" label={t('display.later')} disabled={ii === g.items.length - 1} onClick={() => reorder(moveItem(groups, gi, ii, 1))}><ArrowDown size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('signage.menu.hide')} data-testid="signage-item-hide" <IconButton size="sm" variant="ghost" label={t(off ? 'signage.menu.showAgain' : 'signage.menu.hide')} data-testid="signage-item-hide" aria-pressed={off}
onClick={() => setC({ exclude_ids: toggled(c.exclude_ids, it.id), product_ids: (c.product_ids || []).filter(x => x !== it.id) })}><EyeOff size={14} /></IconButton> onClick={() => setC({ exclude_ids: toggled(c.exclude_ids, it.id) })}>
{off ? <EyeOff size={15} className="text-danger-ink" /> : <Eye size={15} className="text-success-ink" />}
</IconButton>
</li> </li>
))} )
})}
</ul> </ul>
</div> </div>
))} ))}
@@ -175,11 +184,12 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
{/* the layout: columns, how wide the list is and where it sits, the pages (2026-11-21) */} {/* the layout: columns, how wide the list is and where it sits, the pages (2026-11-21) */}
<Section title={t('signage.menu.layout')}> <Section title={t('signage.menu.layout')}>
<div className="grid gap-4 grid-cols-2 xl:grid-cols-5 items-start"> <div className={`grid gap-4 grid-cols-2 items-start ${board ? 'xl:grid-cols-3' : 'xl:grid-cols-5'}`}>
<Field label={t('signage.columns')}> <Field label={t('signage.columns')}>
<Segmented value={String(c.columns || 2)} onChange={v => setC({ columns: Number(v) })} data-testid="signage-columns" fill <Segmented value={String(c.columns || (board ? 1 : 2))} onChange={v => setC({ columns: Number(v) })} data-testid="signage-columns" fill
options={[1, 2, 3].map(n => ({ value: String(n), label: String(n), testId: `signage-columns-${n}` }))} /> options={[1, 2, 3].map(n => ({ value: String(n), label: String(n), testId: `signage-columns-${n}` }))} />
</Field> </Field>
{!board && <>
<Range label={t('signage.menu.width')} value={c.board_width || 100} min={40} max={100} step={5} suffix="%" <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" /> 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}> <Field label={t('signage.menu.place')} hint={(c.board_width || 100) >= 100 ? t('signage.menu.placeHint') : undefined}>
@@ -187,22 +197,26 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
options={[['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight]].map(([v, Icon]) => ( 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}` }))} /> { 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')}> </>}
<Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={t('signage.menu.auto')} <Field label={t('signage.menu.perPage')} hint={t(board ? 'signage.menu.perPageWidgetHint' : 'signage.menu.perPageHint')}>
onChange={e => { const n = digits(e.target.value); setC({ page_size: n ? Math.min(60, Math.max(3, n)) : null }) }} /> <Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={board ? '8' : t('signage.menu.auto')}
onChange={e => { const n = digits(e.target.value); setC({ page_size: n ? Math.min(60, Math.max(3, n)) : null }) }} data-testid="signage-menu-per-page" />
</Field> </Field>
<Field label={t('signage.menu.pageSeconds')}> <Field label={t('signage.menu.pageSeconds')} hint={t('signage.menu.pageSecondsHint')}>
<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)) })} /> <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>
</div> </div>
</Section> </Section>
<TextLook c={c} setC={setC} align={false}> <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" /> <ColourField compact label={t('signage.accent')} value={c.accent_colour || '#f59e0b'} onChange={v => setC({ accent_colour: v })} testid="signage-accent" />
</TextLook> </TextLook>
{!board && <>
<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} selected={widget} onSelect={onWidget} /> <WidgetsEditor widgets={c.widgets || []} onChange={widgets => setC({ widgets })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget}
extras={extras} />
</>}
</div> </div>
) )
} }
@@ -18,7 +18,7 @@ import { mediaEntry, mediaLookup, misfits, moved, slideBody, totalSeconds, TRANS
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' 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' import { useSlidePreview, useWidgetEditor } from './useSlideDraft'
/** 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). */
export function FitPreview({ orientation, children }) { export function FitPreview({ orientation, children }) {
@@ -72,7 +72,7 @@ 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) useSlidePreview(draft, setDraft, more => setMedia(m => ({ ...m, ...more })))
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])
@@ -1,7 +1,9 @@
// Small editors the signage slide editor is built from (plan step 5.6a; reworked 2026-11-21): a // Small editors the signage slide editor is built from (plan step 5.6a; reworked 2026-11-21): a
// section with its title, a picture / video from the library, a colour (ready ones + the picker), // 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. // a background (colour or photo with darkening), a slider with its value.
import { useState } from 'react' // 2026-11-21 (owner review 2): the slider framed like the fields beside it; a colour as a field
// (its swatch and code) that opens the ready colours and the picker, so it fits a row of fields.
import { useEffect, useRef, 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, Dropdown, Field, IconButton } from '@xenia/ui' import { Button, Dropdown, Field, IconButton } from '@xenia/ui'
@@ -22,11 +24,11 @@ export function Section({ title, aside, children, testid, className = '' }) {
) )
} }
/** A slider with its label and value, as tall as the fields beside it. */ /** A slider with its label and value, framed and as tall as the fields beside it. */
export function Range({ label, value, min, max, step = 1, onChange, suffix = '', testid }) { export function Range({ label, value, min, max, step = 1, onChange, suffix = '', testid }) {
return ( return (
<Field label={label}> <Field label={label}>
<span className="h-control flex items-center gap-3"> <span className="h-control flex items-center gap-3 px-3 rounded-control border border-line bg-surface">
<input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange(Number(e.target.value))} <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} /> 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 className="text-label text-ink-2 tabular-nums w-12 text-right">{value}{suffix}</span>
@@ -68,9 +70,11 @@ 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 few /** A colour the venue chooses for its TV (stored as #rrggbb: data, not a theme colour): a few
* ready colours with one click, and the picker for any other (2026-11-21). */ * ready colours with one click, and the picker for any other (2026-11-21). `compact`: a field
export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS }) { * (swatch and code) that opens them, as tall and as wide as the fields beside it. */
export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS, compact = false }) {
const v = (value || '#000000').toLowerCase() const v = (value || '#000000').toLowerCase()
if (compact) return <ColourPick label={label} value={v} onChange={onChange} testid={testid} presets={presets} />
return ( return (
<div className="grid gap-1.5" role="group" aria-label={label}> <div className="grid gap-1.5" role="group" aria-label={label}>
<span className="text-label font-medium text-ink">{label}</span> <span className="text-label font-medium text-ink">{label}</span>
@@ -88,6 +92,46 @@ export function ColourField({ label, value, onChange, testid, presets = COLOUR_P
) )
} }
function ColourPick({ label, value, onChange, testid, presets }) {
const [open, setOpen] = useState(false)
const box = useRef(null)
useEffect(() => {
if (!open) return undefined
const away = e => { if (!box.current?.contains(e.target)) setOpen(false) }
const esc = e => { if (e.key === 'Escape') setOpen(false) }
window.addEventListener('pointerdown', away)
window.addEventListener('keydown', esc)
return () => { window.removeEventListener('pointerdown', away); window.removeEventListener('keydown', esc) }
}, [open])
return (
<Field label={label}>
<div ref={box} className="relative">
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} aria-label={label} data-testid={testid ? `${testid}-open` : undefined}
className="w-full h-control flex items-center gap-2.5 px-3 rounded-control border border-line bg-surface text-label text-ink hover:border-line-strong transition-colors duration-fast">
<span className="w-6 h-6 rounded-full border border-line-strong shrink-0" style={{ background: value }} aria-hidden="true" />
<span className="font-mono text-ink-2 truncate">{value}</span>
</button>
{open && (
<div className="absolute z-30 left-0 top-full mt-1.5 grid gap-3 p-3 rounded-card border border-line bg-surface shadow-lg w-max" role="dialog" aria-label={label}>
<div className="grid grid-cols-5 gap-2">
{presets.map(c => (
<button key={c} type="button" onClick={() => { onChange(c); setOpen(false) }} aria-label={c} aria-pressed={value === c} title={c}
className={`w-8 h-8 rounded-full border border-line-strong transition-transform duration-fast ${value === c ? 'ring-2 ring-accent ring-offset-2 ring-offset-surface' : 'hover:scale-110'}`}
style={{ background: c }} data-testid={testid ? `${testid}-preset` : undefined} />
))}
</div>
<label className="flex items-center gap-2 text-label text-ink-2">
<input type="color" value={value} 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" />
<span className="font-mono">{value}</span>
</label>
</div>
)}
</div>
</Field>
)
}
/** A slide's background: a colour, or a photo (built-in or the venue's) with a darkening slider. */ /** A slide's background: a colour, or a photo (built-in or the venue's) with a darkening slider. */
export function BackgroundField({ value, onChange, media, onMedia, misfit, testid = 'signage-bg' }) { export function BackgroundField({ value, onChange, media, onMedia, misfit, testid = 'signage-bg' }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -5,6 +5,8 @@
// Reworked 2026-11-21 (owner review): name | show this slide, transition effect | seconds; the // 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 // 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). // it; sections with a title and a line; blank slides (a background and widgets).
// Owner review 2 (2026-11-21): the text's look all on one row (horizontal / vertical alignment,
// font, size in a frame, colour as a field that opens its colours).
import { AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart } from 'lucide-react' 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, Segmented, Switch, Textarea } from '@xenia/ui' import { Dropdown, Field, FilterChip, Input, Segmented, Switch, Textarea } from '@xenia/ui'
@@ -78,7 +80,7 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
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} /> const widgets = <WidgetsEditor widgets={c.widgets || []} onChange={ws => setC({ widgets: ws })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} extras={slide.extras} />
const fit = ( const fit = (
<Field label={t('signage.fit')}> <Field label={t('signage.fit')}>
<Dropdown value={c.fit || 'cover'} onChange={v => setC({ fit: v })} <Dropdown value={c.fit || 'cover'} onChange={v => setC({ fit: v })}
@@ -127,21 +129,21 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
{widgets} {widgets}
</>} </>}
{slide.kind === 'menu' && <MenuEditor slide={slide} onChange={onChange} media={media} onMedia={onMedia} misfit={misfit} widget={widget} onWidget={onWidget} />} {slide.kind === 'menu' && <MenuEditor slide={slide} onChange={onChange} media={media} onMedia={onMedia} misfit={misfit} widget={widget} onWidget={onWidget} extras={slide.extras} />}
</div> </div>
) )
} }
/** /**
* The look of a text: alignment, height, font and size on one row, its colour (ready colours and * The look of a text, all on one row (owner review 2, 2026-11-21): horizontal and vertical
* the picker) under them. A menu board (`align` off) has no alignment / height; it passes its * alignment, font, size and colour (a field that opens the ready colours and the picker). A menu
* accent colour as `children`, beside the text's colour. * board (`align` off) has no alignment; it passes its accent colour as `children`, on the same row.
*/ */
export function TextLook({ c, setC, align = true, children }) { export function TextLook({ c, setC, align = true, children }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
return ( return (
<Section title={t('signage.textLook')} testid="signage-text-look"> <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'}`}> <div className="grid gap-4 items-end grid-cols-[repeat(auto-fit,minmax(10.5rem,1fr))]">
{align && <> {align && <>
<Field label={t('signage.align')}> <Field label={t('signage.align')}>
<Segmented value={c.align || 'center'} onChange={v => setC({ align: v })} data-testid="signage-align" fill <Segmented value={c.align || 'center'} onChange={v => setC({ align: v })} data-testid="signage-align" fill
@@ -160,9 +162,7 @@ export function TextLook({ c, setC, align = true, children }) {
</Field> </Field>
<Range label={t('signage.textSizeLabel')} value={c.text_size || 100} min={50} max={250} step={10} suffix="%" <Range label={t('signage.textSizeLabel')} value={c.text_size || 100} min={50} max={250} step={10} suffix="%"
onChange={v => setC({ text_size: v })} testid="signage-text-size" /> onChange={v => setC({ text_size: v })} testid="signage-text-size" />
</div> <ColourField compact label={t('signage.textColour')} value={c.text_colour || '#ffffff'} onChange={v => setC({ text_colour: v })} testid="signage-text-colour" />
<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} {children}
</div> </div>
</Section> </Section>
@@ -15,7 +15,7 @@ import { mediaEntry, mediaLookup, misfits, savedBody } from './signageLogic'
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' 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' import { useSlidePreview, useWidgetEditor } from './useSlideDraft'
export default function SlidesTab({ open, onOpen }) { export default function SlidesTab({ open, onOpen }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -107,7 +107,7 @@ function SavedSlideEditor({ id, venue, onClose }) {
api.getSaved(id).then(s => { setSaved(s); setDraft(structuredClone(s)); setMedia(s.media || {}) }) api.getSaved(id).then(s => { setSaved(s); setDraft(structuredClone(s)); setMedia(s.media || {}) })
.catch(err => { toast.error(errorMessage(err, t)); onClose() }) .catch(err => { toast.error(errorMessage(err, t)); onClose() })
}, [id]) // eslint-disable-line react-hooks/exhaustive-deps }, [id]) // eslint-disable-line react-hooks/exhaustive-deps
useMenuPreview(draft, setDraft) useSlidePreview(draft, setDraft, more => setMedia(m => ({ ...m, ...more })))
const dirty = useMemo(() => !!(draft && saved && JSON.stringify(savedBody(draft)) !== JSON.stringify(savedBody(saved))), [draft, saved]) 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]) 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> if (!draft) return <div className="flex justify-center p-6"><Spinner /></div>
@@ -4,13 +4,17 @@
// slide's edges and middle lines (shown while it does). A widget moved or sized this way gets // 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. // 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). // It lies over SlidePreview's box and finds each widget by its `data-widget` (@xenia/signage).
import { useLayoutEffect, useRef, useState } from 'react' // Owner review 2 (2026-11-21): the arrow keys move the picked widget wherever it was picked (here
// or on its card below), unless you are typing or using a control that takes the arrows itself.
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { boxFromRect, moveBox, resizeBox, snapBox } from './signageLogic' import { boxFromRect, moveBox, resizeBox, snapBox } from './signageLogic'
const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] 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 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 const SIZE = 14 // a handle, px
// where the arrow keys belong to the control (typing, lists, sliders, choices)
const OWN_KEYS = 'input, textarea, select, [contenteditable="true"], [role="slider"], [role="radio"], [role="option"], [role="listbox"], [role="combobox"], [role="menu"], [role="menuitem"], [role="tab"], [role="spinbutton"], [role="dialog"] *'
export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPlace, label }) { export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPlace, label }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -65,8 +69,12 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl
window.addEventListener('pointerup', up) window.addEventListener('pointerup', up)
} }
const key = e => { // the keys, on the whole page while a widget is picked
if (selected == null) return useEffect(() => {
if (selected == null) return undefined
const on = e => {
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return
if (e.target instanceof Element && e.target.closest(OWN_KEYS)) return
if (e.key === 'Escape') { onSelect(null); return } if (e.key === 'Escape') { onSelect(null); return }
const step = e.shiftKey ? 2 : 0.5 const step = e.shiftKey ? 2 : 0.5
const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key] const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key]
@@ -76,10 +84,13 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl
const base = w?.position === 'custom' && w.box ? w.box : rects[selected] const base = w?.position === 'custom' && w.box ? w.box : rects[selected]
if (base) onPlace(selected, moveBox(base, d[0], d[1])) if (base) onPlace(selected, moveBox(base, d[0], d[1]))
} }
window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on)
}, [selected, widgets, rects, onPlace, onSelect])
const sel = selected != null ? (widgets[selected]?.position === 'custom' && widgets[selected].box) || rects[selected] : null const sel = selected != null ? (widgets[selected]?.position === 'custom' && widgets[selected].box) || rects[selected] : null
return ( return (
<div className="absolute inset-0 outline-none" tabIndex={0} onKeyDown={key} onPointerDown={() => onSelect(null)} <div className="absolute inset-0 outline-none" tabIndex={0} onPointerDown={() => onSelect(null)}
role="application" aria-label={label} data-testid="signage-canvas"> role="application" aria-label={label} data-testid="signage-canvas">
{widgets.map((w, i) => rects[i] && ( {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'}`} <div key={i} className={`absolute cursor-move rounded-sm ${selected === i ? '' : 'hover:outline hover:outline-2 hover:outline-accent/60'}`}
@@ -1,73 +1,125 @@
// The widgets of a text, menu or blank slide (plan step 5.6b; reworked 2026-11-21): logo, name, // The widgets of a text, menu or blank slide (plan step 5.6b; reworked 2026-11-21): logo or picture,
// date, clock, message of the day, QR code, weather. Each in its own card: its name first, then // name, date, clock, message of the day, a text of its own, QR code, weather, a menu, and stacks.
// its settings on one row (where, size, alignment, its own options). Where / size read "Custom" // Each in its own card: its name first, then its settings on one row (where, size, alignment, its
// once it was moved or sized by hand on the preview (WidgetCanvas); picking a corner or a bar // own options), what needs more room on the rows under it. Where / size read "Custom" once it was
// puts it back. The card of the widget picked on the preview is highlighted (the page doesn't // moved or sized by hand on the preview (WidgetCanvas); picking a corner or a bar puts it back. The
// jump to it: the preview stays in view while you drag). // 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).
// Owner review 2 (2026-11-21): the widgets' order (arrows, or drag a card by its handle; a later
// widget is drawn over an earlier one, and comes later in a bar); a text widget; weather for
// tomorrow / the day after and in three styles; a menu widget (a board's list in its box); stacks:
// parts side by side or one over the other, each its share (%), showing a widget, another stack (one
// level deep) or a whole slide from the Slides library.
// Up to 10 (the server's limit). // Up to 10 (the server's limit).
import { AlignCenter, AlignLeft, AlignRight, CalendarDays, Clock, CloudSun, ImageIcon, MessageSquare, Plus, QrCode, Store, Trash2 } from 'lucide-react' import { useEffect, useState } from 'react'
import {
AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical,
ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed,
} from 'lucide-react'
import { evenShares, setShare } from '@xenia/signage'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, IconButton, Input, Segmented, Switch } from '@xenia/ui' import { Button, Dropdown, Field, IconButton, Input, Segmented, Switch } from '@xenia/ui'
import * as api from './signageApi'
import MenuEditor from './MenuEditor'
import { MediaPick, Section } from './SignageFields' import { MediaPick, Section } from './SignageFields'
import { presetWidget, WIDGET_KINDS, WIDGET_POSITIONS } from './signageLogic' import {
CELL_KINDS, cellWidget, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS,
} from './signageLogic'
const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, qr: QrCode, weather: CloudSun } const ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3 }
const iconOf = w => (w.kind === 'stack' ? (w.direction === 'column' ? Rows3 : Columns3) : ICON[w.kind] || LayoutList)
const kindLabel = (t, w) => t(`signage.widgets.kinds.${w.kind === 'stack' ? (w.direction === 'column' ? 'vstack' : 'hstack') : w.kind}`)
const ROW = 'grid gap-4 items-end grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'
export default function WidgetsEditor({ widgets = [], onChange, media, onMedia, selected = null, onSelect }) { let library = null // the Slides library (for stacks' parts), read once
function useLibrary() {
const [list, setList] = useState(library || [])
useEffect(() => {
api.listSaved().then(r => { library = r.slides; setList(r.slides) }).catch(() => {})
}, [])
return list
}
export default function WidgetsEditor({ widgets = [], onChange, media, onMedia, selected = null, onSelect, extras = {} }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [drag, setDrag] = useState(null) // { from, at }: the card dragged and where it would land
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 => { const add = kind => {
onChange([...widgets, { kind, position: kind === 'message' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto' }]) onChange([...widgets, newWidget(kind)])
onSelect?.(widgets.length) onSelect?.(widgets.length)
} }
const move = (from, to) => {
if (to < 0 || to >= widgets.length || from === to) return
onChange(moved(widgets, from, to))
onSelect?.(pickedAfterMove(selected, from, to))
}
const over = (e, i) => {
if (!drag) return
e.preventDefault()
const r = e.currentTarget.getBoundingClientRect()
const at = e.clientY < r.top + r.height / 2 ? i : i + 1
if (at !== drag.at) setDrag(d => ({ ...d, at }))
}
const drop = () => {
if (drag && drag.at != null) move(drag.from, drag.at > drag.from ? drag.at - 1 : drag.at)
setDrag(null)
}
const line = i => drag && drag.at === i && drag.at !== drag.from && drag.at !== drag.from + 1 && (
<div className="h-0.5 -my-1.5 rounded-full bg-accent" data-testid="signage-widget-drop-line" aria-hidden="true" />
)
return ( return (
<Section title={t('signage.widgets.title')} testid="signage-widgets"> <Section title={t('signage.widgets.title')} testid="signage-widgets">
<p className="text-caption text-ink-3 -mt-1">{t(widgets.length ? 'signage.widgets.dragHint' : 'signage.widgets.none')}</p> <p className="text-caption text-ink-3 -mt-1">{t(widgets.length ? 'signage.widgets.dragHint' : 'signage.widgets.none')}</p>
{widgets.map((w, i) => { {widgets.map((w, i) => {
const Icon = ICON[w.kind] || ImageIcon const Icon = iconOf(w)
const custom = w.position === 'custom' const custom = w.position === 'custom'
const on = selected === i const on = selected === i
return ( return (
<div key={i} onPointerDown={() => onSelect?.(i)} <div key={i} className="grid gap-3">
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'}`} {line(i)}
data-testid="signage-widget" data-kind={w.kind} data-selected={on ? 'true' : undefined}> <div onPointerDown={() => onSelect?.(i)} onDragOver={e => over(e, i)} onDrop={drop}
className={`grid gap-4 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'}
${drag?.from === i ? 'opacity-50' : ''}`}
data-testid="signage-widget" data-kind={w.kind} data-index={i} data-selected={on ? 'true' : undefined}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span draggable onDragStart={e => { e.dataTransfer.effectAllowed = 'move'; setDrag({ from: i, at: null }) }} onDragEnd={() => setDrag(null)}
className="cursor-grab active:cursor-grabbing text-ink-3 hover:text-ink -ml-1 p-0.5 rounded" title={t('signage.widgets.dragToOrder')}
aria-hidden="true" data-testid="signage-widget-grip"><GripVertical size={16} /></span>
<Icon size={16} className="text-ink-2 shrink-0" aria-hidden="true" /> <Icon size={16} className="text-ink-2 shrink-0" aria-hidden="true" />
<span className="text-body font-semibold text-ink">{t(`signage.widgets.kinds.${w.kind}`)}</span> <span className="text-body font-semibold text-ink">{kindLabel(t, w)}</span>
<span className="flex-1" /> <span className="flex-1" />
<IconButton size="sm" label={t('signage.widgets.earlier')} disabled={i === 0} onClick={e => { e.stopPropagation(); move(i, i - 1) }}
data-testid="signage-widget-up"><ArrowUp size={16} /></IconButton>
<IconButton size="sm" label={t('signage.widgets.later')} disabled={i === widgets.length - 1} onClick={e => { e.stopPropagation(); move(i, i + 1) }}
data-testid="signage-widget-down"><ArrowDown size={16} /></IconButton>
<IconButton size="sm" tone="danger" label={t('fees.delete')} data-testid="signage-widget-remove" <IconButton size="sm" tone="danger" label={t('fees.delete')} data-testid="signage-widget-remove"
onClick={e => { e.stopPropagation(); onChange(widgets.filter((_, j) => j !== i)); onSelect?.(null) }}><Trash2 size={16} /></IconButton> onClick={e => { e.stopPropagation(); onChange(widgets.filter((_, j) => j !== i)); onSelect?.(null) }}><Trash2 size={16} /></IconButton>
</div> </div>
<div className="flex flex-wrap items-end gap-3"> <div className={ROW}>
<Field label={t('signage.widgets.position')} className="w-44"> <Field label={t('signage.widgets.position')}>
<Dropdown value={w.position} onChange={p => p !== 'custom' && onChange(widgets.map((x, j) => (j === i ? presetWidget(x, p) : x)))} <Dropdown value={w.position} onChange={p => p !== 'custom' && onChange(widgets.map((x, j) => (j === i ? presetWidget(x, p) : x)))}
data-testid="signage-widget-position" data-testid="signage-widget-position"
options={[...WIDGET_POSITIONS.map(p => ({ value: p, label: t(`signage.widgets.positions.${p}`) })), options={[...WIDGET_POSITIONS.map(p => ({ value: p, label: t(`signage.widgets.positions.${p}`) })),
...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} /> ...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} />
</Field> </Field>
<Field label={t('signage.widgets.size')} className="w-36"> <Field label={t('signage.widgets.size')}>
<Dropdown value={custom ? 'custom' : (w.size || 'medium')} disabled={custom} onChange={size => set(i, { size })} data-testid="signage-widget-size" <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}`) })), options={[...['small', 'medium', 'large'].map(s => ({ value: s, label: t(`signage.widgets.sizes.${s}`) })),
...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} /> ...(custom ? [{ value: 'custom', label: t('signage.widgets.custom') }] : [])]} />
</Field> </Field>
<Field label={t('signage.widgets.align')}> {w.kind !== 'stack' && <AlignField w={w} set={patch => set(i, patch)} />}
<Segmented value={w.align || 'auto'} onChange={align => set(i, { align })} aria-label={t('signage.widgets.align')} data-testid="signage-widget-align" <InlineFields w={w} set={patch => set(i, patch)} />
options={[ </div>
{ value: 'auto', label: t('signage.widgets.alignAuto'), testId: 'signage-widget-align-auto' }, <BelowFields w={w} set={patch => set(i, patch)} media={media} onMedia={onMedia} extras={extras} path={String(i)} depth={0} />
{ 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> </div>
{w.kind === 'weather' && <p className="text-caption text-ink-3">{t('signage.widgets.weatherNeedsInternet')}</p>}
</div> </div>
) )
})} })}
{line(widgets.length)}
{widgets.length < 10 && ( {widgets.length < 10 && (
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-wrap items-center gap-1.5">
{WIDGET_KINDS.map(k => { {[...WIDGET_KINDS, 'hstack', 'vstack'].map(k => {
const Icon = ICON[k] const Icon = ICON[k]
return ( return (
<Button key={k} size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => add(k)} data-testid={`signage-widget-add-${k}`}> <Button key={k} size="sm" variant="secondary" icon={<Plus size={14} />} onClick={() => add(k)} data-testid={`signage-widget-add-${k}`}>
@@ -81,50 +133,202 @@ export default function WidgetsEditor({ widgets = [], onChange, media, onMedia,
) )
} }
/** The options only some widgets have, on the same row. */ /** How the widget lines up in its place: auto, left, centre, right. */
function KindFields({ w, set, media, onMedia }) { function AlignField({ w, set, testid = 'signage-widget-align' }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
if (w.kind === 'logo') { return (
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-logo" <Field label={t('signage.widgets.align')}>
onChange={item => { onMedia(item); set({ media_id: item.id }) }} /> <Segmented value={w.align || 'auto'} onChange={align => set({ align })} aria-label={t('signage.widgets.align')} data-testid={testid} fill
options={[
{ value: 'auto', label: t('signage.widgets.alignAuto'), testId: `${testid}-auto` },
{ value: 'left', icon: <AlignLeft size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.left'), testId: `${testid}-left` },
{ value: 'center', icon: <AlignCenter size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.center'), testId: `${testid}-center` },
{ value: 'right', icon: <AlignRight size={16} aria-hidden="true" />, ariaLabel: t('signage.aligns.right'), testId: `${testid}-right` },
]} />
</Field>
)
} }
/** The options only some widgets have, on the same row as where / size / alignment. */
function InlineFields({ w, set }) {
const { t } = useTranslation('manager')
if (w.kind === 'message') { if (w.kind === 'message') {
return ( return (
<Field label={t('signage.widgets.ownText')} hint={t('signage.widgets.ownTextHint')} className="flex-1 min-w-[14rem]"> <Field label={t('signage.widgets.ownText')} className="col-span-2">
<Input value={w.text || ''} maxLength={200} onChange={e => set({ text: e.target.value || null })} data-testid="signage-widget-text" /> <Input value={w.text || ''} maxLength={200} placeholder={t('signage.widgets.ownTextPlaceholder')} onChange={e => set({ text: e.target.value || null })} data-testid="signage-widget-text" />
</Field>
)
}
if (w.kind === 'text') {
return (
<Field label={t('signage.widgets.theText')} className="col-span-2">
<Input value={w.text || ''} maxLength={200} onChange={e => set({ text: e.target.value || null })} data-testid="signage-widget-own-text" />
</Field> </Field>
) )
} }
if (w.kind === 'date') { if (w.kind === 'date') {
return ( return (
<Field label={t('signage.widgets.dateStyle')} className="w-56"> <Field label={t('signage.widgets.dateStyle')}>
<Dropdown value={w.date_style || 'long'} onChange={date_style => set({ date_style })} <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> </Field>
) )
} }
if (w.kind === 'clock') { if (w.kind === 'clock') {
return <Switch boxed className="w-44" checked={!!w.clock_seconds} onChange={on => set({ clock_seconds: on })} label={t('signage.widgets.seconds')} />
}
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}`) }))} />
</Field>
{w.qr_target === 'custom' && (
<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')} className="flex-1 min-w-[10rem]"><Input value={w.qr_caption || ''} maxLength={80} onChange={e => set({ qr_caption: e.target.value || null })} /></Field>
</>)
}
if (w.kind === 'weather') {
return ( return (
<Field label={t('signage.widgets.weatherDays')} className="w-48"> <Field label={t('signage.widgets.clockShows')}>
<Dropdown value={String(w.weather_days || 1)} onChange={v => set({ weather_days: Number(v) })} <Switch boxed className="h-control" checked={!!w.clock_seconds} onChange={on => set({ clock_seconds: on })} label={t('signage.widgets.seconds')} data-testid="signage-widget-seconds" />
options={[1, 2, 3].map(n => ({ value: String(n), label: t('signage.widgets.days', { count: n }) }))} />
</Field> </Field>
) )
} }
if (w.kind === 'qr') {
return (
<Field label={t('display.qrTarget')}>
<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}`) }))} />
</Field>
)
}
if (w.kind === 'weather') {
return (<>
<Field label={t('signage.widgets.weatherDays')}>
<Dropdown value={weatherChoice(w)} data-testid="signage-widget-weather-days"
onChange={v => { const [from, days] = v.split('-').map(Number); set({ weather_from: from, weather_days: days }) }}
options={WEATHER_CHOICES.map(([from, days]) => ({ value: `${from}-${days}`, label: t(`signage.widgets.weatherChoices.${from}-${days}`) }))} />
</Field>
<Field label={t('signage.widgets.weatherStyle')}>
<Dropdown value={w.weather_style || 'both'} onChange={weather_style => set({ weather_style })} data-testid="signage-widget-weather-style"
options={['both', 'icon', 'text'].map(s => ({ value: s, label: t(`signage.widgets.weatherStyles.${s}`) }))} />
</Field>
</>)
}
return null return null
} }
/** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */
function BelowFields({ w, set, media, onMedia, extras, path, depth }) {
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 <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.ownTextHint')}</p>
if (w.kind === 'weather') return <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.weatherNeedsInternet')}</p>
if (w.kind === 'qr') {
return (
<div className={ROW}>
{w.qr_target === 'custom' && (
<Field label={t('display.qrUrl')} className="col-span-2"><Input value={w.qr_url || ''} placeholder="https://" onChange={e => set({ qr_url: e.target.value || null })} /></Field>
)}
<Field label={t('display.qrCaption')} className="col-span-2"><Input value={w.qr_caption || ''} maxLength={80} onChange={e => set({ qr_caption: e.target.value || null })} /></Field>
</div>
)
}
if (w.kind === 'menu') return <MenuBoardFields w={w} set={set} extras={extras} path={path} />
if (w.kind === 'stack') return <StackFields w={w} set={set} media={media} onMedia={onMedia} extras={extras} path={path} depth={depth} />
return null
}
/** A menu widget's list and look: the menu board's editor, folded away until it is opened. */
function MenuBoardFields({ w, set, extras, path }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
const menu = extras?.[path]?.menu
return (
<div className="grid gap-4 rounded-control border border-line bg-surface p-3">
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} data-testid="signage-widget-menu-toggle"
className="flex items-center gap-2 text-left text-label font-medium text-ink">
<UtensilsCrossed size={15} className="text-ink-2" aria-hidden="true" />
<span className="flex-1">{t('signage.widgets.menuEdit', { count: menu?.count ?? 0 })}</span>
<ChevronDown size={16} className={`text-ink-3 transition-transform duration-fast ${open ? 'rotate-180' : ''}`} aria-hidden="true" />
</button>
{open && (
<MenuEditor board testid="signage-widget-menu-editor" slide={{ kind: 'menu', content: w.board || {}, menu }}
onChange={s => set({ board: s.content })} />
)}
</div>
)
}
/**
* A stack's parts: side by side or one over the other, how many (2–6), each its share (%; changing
* one gives or takes from its neighbour, "even" splits them equally) and what it shows.
*/
function StackFields({ w, set, media, onMedia, extras, path, depth }) {
const { t } = useTranslation('manager')
const slides = useLibrary()
const cells = w.cells || []
const shares = cells.map(c => Math.round(c.share || 0))
const setCells = next => set({ cells: next })
const setCell = (j, patch) => setCells(cells.map((c, k) => (k === j ? { ...c, ...patch } : c)))
const count = n => {
const even = evenShares(n)
setCells(Array.from({ length: n }, (_, k) => ({ ...(cells[k] || {}), share: even[k] })))
}
const shows = c => (c.slide_id ? 'slide' : c.widget ? (c.widget.kind === 'stack' ? (c.widget.direction === 'column' ? 'vstack' : 'hstack') : c.widget.kind) : '')
const pick = (j, v) => {
if (!v) setCell(j, { widget: null, slide_id: null })
else if (v === 'slide') setCell(j, { widget: null, slide_id: slides[0]?.id ?? null })
else setCell(j, { widget: cellWidget(v), slide_id: null })
}
const kinds = [...CELL_KINDS, ...(depth === 0 ? ['hstack', 'vstack'] : [])]
return (
<div className="grid gap-3 rounded-control border border-line bg-surface p-3" data-testid="signage-stack-editor" data-depth={depth}>
<div className={ROW}>
<Field label={t('signage.widgets.stack.direction')}>
<Segmented value={w.direction || 'row'} onChange={direction => set({ direction })} fill data-testid="signage-stack-direction"
options={[{ value: 'row', icon: <Columns3 size={16} aria-hidden="true" />, ariaLabel: t('signage.widgets.stack.row'), testId: 'signage-stack-row' },
{ value: 'column', icon: <Rows3 size={16} aria-hidden="true" />, ariaLabel: t('signage.widgets.stack.column'), testId: 'signage-stack-column' }]} />
</Field>
<Field label={t('signage.widgets.stack.parts')}>
<Segmented value={String(cells.length)} onChange={v => count(Number(v))} fill data-testid="signage-stack-count"
options={[2, 3, 4, 5, 6].map(n => ({ value: String(n), label: String(n), testId: `signage-stack-count-${n}` }))} />
</Field>
<div className="flex items-end">
<Button variant="secondary" onClick={() => count(cells.length)} data-testid="signage-stack-even">{t('signage.widgets.stack.even')}</Button>
</div>
</div>
{/* the parts as they share the stack */}
<div className={`flex ${w.direction === 'column' ? 'flex-col h-20 w-32' : 'h-8'} gap-0.5 rounded-control overflow-hidden`} aria-hidden="true">
{cells.map((c, j) => (
<span key={j} style={{ flex: `${c.share || 1} 1 0%` }}
className="grid place-items-center bg-accent-soft text-accent-ink text-caption font-semibold tabular-nums min-w-0 min-h-0">{shares[j]}%</span>
))}
</div>
{cells.map((c, j) => {
const cp = `${path}.${j}`
const v = shows(c)
return (
<div key={j} className="grid gap-3 rounded-control border border-line bg-surface-2 p-3" data-testid="signage-stack-cell-editor" data-index={j}>
<div className={ROW}>
<Field label={t('signage.widgets.stack.part', { n: j + 1 })}>
<Input inputMode="numeric" value={String(shares[j])} data-testid="signage-stack-share"
onChange={e => { const next = setShare(shares, j, e.target.value.replace(/\D/g, '')); setCells(cells.map((x, k) => ({ ...x, share: next[k] }))) }} />
</Field>
<Field label={t('signage.widgets.stack.shows')}>
<Dropdown value={v} onChange={x => pick(j, x)} data-testid="signage-stack-shows"
options={[{ value: '', label: t('signage.widgets.stack.nothing') },
...kinds.map(k => ({ value: k, label: t(`signage.widgets.kinds.${k}`) })),
{ value: 'slide', label: t('signage.widgets.stack.aSlide') }]} />
</Field>
{c.slide_id != null || v === 'slide' ? (
<Field label={t('signage.widgets.stack.slide')} className="col-span-2">
<Dropdown value={c.slide_id != null ? String(c.slide_id) : ''} onChange={x => setCell(j, { slide_id: x ? Number(x) : null })} data-testid="signage-stack-slide"
options={slides.length ? slides.map(s => ({ value: String(s.id), label: s.name }))
: [{ value: '', label: t('signage.widgets.stack.noSlides') }]} />
</Field>
) : c.widget && <>
{c.widget.kind !== 'stack' && <AlignField w={c.widget} set={patch => setCell(j, { widget: { ...c.widget, ...patch } })} testid="signage-cell-align" />}
<InlineFields w={c.widget} set={patch => setCell(j, { widget: { ...c.widget, ...patch } })} />
</>}
</div>
{c.widget && (
<BelowFields w={c.widget} set={patch => setCell(j, { widget: { ...c.widget, ...patch } })} media={media} onMedia={onMedia}
extras={extras} path={cp} depth={depth + 1} />
)}
</div>
)
})}
</div>
)
}
@@ -18,6 +18,7 @@ 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)
export const previewSlide = (kind, content) => client.post('/api/signage/preview/slide', { kind, content }).then(data)
// the Slides library (2026-11-21) // the Slides library (2026-11-21)
export const listSaved = () => client.get('/api/signage/library').then(data) export const listSaved = () => client.get('/api/signage/library').then(data)
@@ -124,7 +124,44 @@ export function mediaLookup(map) {
// ── menu boards and widgets (5.6b) ─────────────────────────────────────────── // ── menu boards and widgets (5.6b) ───────────────────────────────────────────
export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'qr', 'weather'] export const WIDGET_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu']
/** What a stack's part can show (2026-11-21): a widget, a stack one level deep, a library slide. */
export const CELL_KINDS = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather', 'menu']
/** A new widget of a kind ('hstack' / 'vstack': a stack side by side / one over the other), where it
* usually goes: a menu or a stack in a box of its own (they fill a box). */
export function newWidget(kind) {
if (kind === 'hstack' || kind === 'vstack') {
return { kind: 'stack', direction: kind === 'hstack' ? 'row' : 'column', position: 'custom', size: 'custom', align: 'auto',
box: { x: 5, y: 12, w: 90, h: 76 }, cells: [{ share: 50 }, { share: 50 }] }
}
if (kind === 'menu') {
return { kind, position: 'custom', size: 'custom', align: 'auto', box: { x: 55, y: 10, w: 40, h: 80 }, board: { select: 'all', columns: 1, sales_point: 'in_store' } }
}
return { kind, position: kind === 'message' || kind === 'text' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto',
...(kind === 'text' ? { text: '' } : {}) }
}
/** A widget put in a stack's part: only what it shows (a part has no corner, size or box). */
export function cellWidget(kind) {
if (kind === 'hstack' || kind === 'vstack') {
return { kind: 'stack', direction: kind === 'hstack' ? 'row' : 'column', align: 'auto', cells: [{ share: 50 }, { share: 50 }] }
}
return { kind, align: 'auto', ...(kind === 'menu' ? { board: { select: 'all', columns: 1, sales_point: 'in_store' } } : {}), ...(kind === 'text' ? { text: '' } : {}) }
}
/** The weather's days, as one choice: from (0 today, 1 tomorrow, 2 the day after) and how many. */
export const WEATHER_CHOICES = [[0, 1], [0, 2], [0, 3], [1, 1], [2, 1]]
export const weatherChoice = w => `${w.weather_from || 0}-${w.weather_days || 1}`
/** The picked widget's index after moving the one at `from` to `to` (the list reordered). */
export function pickedAfterMove(picked, from, to) {
if (picked == null) return picked
if (picked === from) return to
if (from < picked && to >= picked) return picked - 1
if (from > picked && to <= picked) return picked + 1
return picked
}
export const WIDGET_POSITIONS = ['top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right', 'top-bar', 'bottom-bar'] export const WIDGET_POSITIONS = ['top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right', 'top-bar', 'bottom-bar']
export const BADGES = ['new', 'chef', 'offer', 'popular', 'spicy', 'vegetarian', 'vegan'] export const BADGES = ['new', 'chef', 'offer', 'popular', 'spicy', 'vegetarian', 'vegan']
@@ -1,19 +1,35 @@
// What the two slide editors share (a playlist's slide, a library slide; 2026-11-21): a menu // What the two slide editors share (a playlist's slide, a library slide; 2026-11-21): the draft
// board's draft resolved by the server for its preview, and the preview's widget handles. // resolved by the server for its preview, and the preview's widget handles.
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { WIDGET_HOSTS } from '@xenia/signage'
import * as api from './signageApi' import * as api from './signageApi'
import { placeWidget } from './signageLogic' import { placeWidget } from './signageLogic'
/** A menu board's products as the server resolves the draft (only what changes the list counts). */ // what doesn't change what the server adds (where things sit, how they look): left out of the key
export function useMenuPreview(draft, setDraft) { const LOOK = new Set(['box', 'position', 'size', 'align', 'background', 'text_colour', 'accent_colour', 'font', 'text_size',
const c = draft?.kind === 'menu' ? draft.content || {} : null 'board_width', 'board_align', 'title', 'body', 'vertical', 'columns', 'page_seconds', 'direction', 'share', 'clock_seconds', 'date_style'])
const key = c ? JSON.stringify({ ...c, widgets: undefined, background: undefined }) : null
/**
* The draft as the server resolves it for the preview (2026-11-21): a menu board's products
* (`menu`, hidden ones kept and marked) and its widgets' extras (a menu widget's products, a
* library slide inside a stack, QR links) with the media they show (`onMedia(map)`).
*/
export function useSlidePreview(draft, setDraft, onMedia) {
const host = draft && WIDGET_HOSTS.includes(draft.kind)
const key = host ? JSON.stringify([draft.kind, draft.content || {}], (k, v) => (LOOK.has(k) ? undefined : v)) : null
useEffect(() => { useEffect(() => {
if (!key) return undefined if (!key) return undefined
const kind = draft.kind
const content = draft.content || {}
const h = setTimeout(() => { const h = setTimeout(() => {
api.previewMenu(JSON.parse(key)).then(r => setDraft(d => (d && d.kind === 'menu' ? { ...d, menu: r.menu } : d))).catch(() => {}) api.previewSlide(kind, content).then(r => {
if (r.media && Object.keys(r.media).length) onMedia?.(r.media)
setDraft(d => (d && d.kind === kind ? { ...d, extras: r.extras, ...(kind === 'menu' ? { menu: r.menu } : {}) } : d))
}).catch(() => {})
}, 400) }, 400)
return () => clearTimeout(h) return () => clearTimeout(h)
// the key holds what counts in the draft
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, setDraft]) }, [key, setDraft])
} }
+49 -11
View File
@@ -1366,13 +1366,13 @@
"muted": "Χωρίς ήχο", "muted": "Χωρίς ήχο",
"title": "Τίτλος", "title": "Τίτλος",
"body": "Κείμενο", "body": "Κείμενο",
"align": "Στοίχιση", "align": "Οριζόντια στοίχιση",
"aligns": { "aligns": {
"left": "Αριστερά", "left": "Αριστερά",
"center": "Κέντρο", "center": "Κέντρο",
"right": "Δεξιά" "right": "Δεξιά"
}, },
"vertical": "Ύψος", "vertical": "Κάθετη στοίχιση",
"verticals": { "verticals": {
"top": "Πάνω", "top": "Πάνω",
"middle": "Μέση", "middle": "Μέση",
@@ -1406,8 +1406,7 @@
"categoriesHint": "Προϊόντα που προστίθενται αργότερα σε μια επιλεγμένη κατηγορία εμφανίζονται μόνα τους. Μια κατηγορία περιλαμβάνει τις υποκατηγορίες της.", "categoriesHint": "Προϊόντα που προστίθενται αργότερα σε μια επιλεγμένη κατηγορία εμφανίζονται μόνα τους. Μια κατηγορία περιλαμβάνει τις υποκατηγορίες της.",
"products": "Μεμονωμένα προϊόντα (από οποιαδήποτε κατηγορία)", "products": "Μεμονωμένα προϊόντα (από οποιαδήποτε κατηγορία)",
"searchProduct": "Αναζήτηση προϊόντος για προσθήκη…", "searchProduct": "Αναζήτηση προϊόντος για προσθήκη…",
"hidden": "Κρυμμένα από αυτό το μενού", "showAgain": "Εμφάνιση ξανά σε αυτόν τον πίνακα",
"showAgain": "εμφάνιση ξανά",
"hide": "Απόκρυψη από αυτό το μενού", "hide": "Απόκρυψη από αυτό το μενού",
"onTheBoard_one": "Στο μενού: {{count}} προϊόν", "onTheBoard_one": "Στο μενού: {{count}} προϊόν",
"onTheBoard_other": "Στο μενού: {{count}} προϊόντα", "onTheBoard_other": "Στο μενού: {{count}} προϊόντα",
@@ -1436,7 +1435,10 @@
"layout": "Διάταξη", "layout": "Διάταξη",
"width": "Πλάτος λίστας", "width": "Πλάτος λίστας",
"place": "Θέση λίστας", "place": "Θέση λίστας",
"placeHint": "Σε όλο το πλάτος η λίστα γεμίζει την οθόνη: στενέψτε την για να τη μετακινήσετε." "placeHint": "Σε όλο το πλάτος η λίστα γεμίζει την οθόνη: στενέψτε την για να τη μετακινήσετε.",
"hiddenTag": "κρυμμένο",
"pageSecondsHint": "Όταν η λίστα δεν χωράει στην οθόνη, χωρίζεται σε σελίδες που εναλλάσσονται: κάθε σελίδα μένει τόσα δευτερόλεπτα.",
"perPageWidgetHint": "Κενό: 8. Περισσότερα γυρίζουν σελίδα."
}, },
"badges": { "badges": {
"new": "Νέο", "new": "Νέο",
@@ -1451,13 +1453,17 @@
"title": "Στοιχεία", "title": "Στοιχεία",
"none": "Κανένα στοιχείο: προσθέστε ρολόι, λογότυπο, μήνυμα ημέρας…", "none": "Κανένα στοιχείο: προσθέστε ρολόι, λογότυπο, μήνυμα ημέρας…",
"kinds": { "kinds": {
"logo": "Λογότυπο", "logo": "Λογότυπο ή εικόνα",
"name": "Όνομα καταστήματος", "name": "Όνομα καταστήματος",
"date": "Ημερομηνία", "date": "Ημερομηνία",
"clock": "Ρολόι", "clock": "Ρολόι",
"message": "Μήνυμα ημέρας", "message": "Μήνυμα ημέρας",
"qr": "Κωδικός QR", "qr": "Κωδικός QR",
"weather": "Καιρός" "weather": "Καιρός",
"text": "Κείμενο",
"menu": "Μενού",
"hstack": "Οριζόντια στοίβα",
"vstack": "Κάθετη στοίβα"
}, },
"position": "Πού", "position": "Πού",
"size": "Μέγεθος", "size": "Μέγεθος",
@@ -1482,15 +1488,47 @@
"dateShort": "17/11/2026", "dateShort": "17/11/2026",
"seconds": "Με δευτερόλεπτα", "seconds": "Με δευτερόλεπτα",
"weatherDays": "Μέρες", "weatherDays": "Μέρες",
"days_one": "Σήμερα",
"days_other": "Σήμερα και {{count}} μέρες",
"weatherNeedsInternet": "Ο καιρός χρειάζεται internet: χωρίς αυτό (ή χωρίς πόλη) το στοιχείο κρύβεται.", "weatherNeedsInternet": "Ο καιρός χρειάζεται internet: χωρίς αυτό (ή χωρίς πόλη) το στοιχείο κρύβεται.",
"dragHint": "Συμβουλή: επιλέξτε ένα widget στην προεπισκόπηση, σύρετέ το για να το μετακινήσετε και από τις λαβές για να αλλάξετε το μέγεθος. Τα πεδία Θέση και Μέγεθος γράφουν τότε «Προσαρμοσμένο».", "dragHint": "Συμβουλή: διαλέξτε ένα widget στην προεπισκόπηση ή εδώ και σύρετέ το (ή με τα βελάκια) για να το μετακινήσετε, και τις λαβές του για το μέγεθος· η θέση και το μέγεθος γράφουν τότε «Προσαρμοσμένο». Η σειρά: ένα επόμενο widget σχεδιάζεται πάνω από ένα προηγούμενο.",
"custom": "Προσαρμοσμένο", "custom": "Προσαρμοσμένο",
"align": "Στοίχιση", "align": "Στοίχιση",
"alignAuto": "Αυτόματη", "alignAuto": "Αυτόματη",
"dateStyle": "Μορφή", "dateStyle": "Μορφή",
"canvas": "Τα widgets της διαφάνειας: σύρετε ένα για μετακίνηση, τις λαβές για μέγεθος, τα βέλη για μικρές κινήσεις" "canvas": "Τα widgets της διαφάνειας: σύρετε ένα για μετακίνηση, τις λαβές για μέγεθος, τα βέλη για μικρές κινήσεις",
"earlier": "Πάνω (σχεδιάζεται κάτω από τα επόμενα)",
"later": "Κάτω (σχεδιάζεται πάνω από τα προηγούμενα)",
"dragToOrder": "Σύρετε για να αλλάξει η σειρά",
"ownTextPlaceholder": "Το μήνυμα της ημέρας",
"theText": "Κείμενο",
"clockShows": "Δείχνει",
"weatherStyle": "Δείχνει",
"weatherStyles": {
"both": "Εικόνα και βαθμούς",
"icon": "Μόνο την εικόνα",
"text": "Μόνο τους βαθμούς"
},
"weatherChoices": {
"0-1": "Σήμερα",
"0-2": "Σήμερα και αύριο",
"0-3": "Σήμερα και τις 2 επόμενες",
"1-1": "Αύριο",
"2-1": "Μεθαύριο"
},
"menuEdit_one": "Προϊόντα και εμφάνιση ({{count}} προϊόν)",
"menuEdit_other": "Προϊόντα και εμφάνιση ({{count}} προϊόντα)",
"stack": {
"direction": "Τμήματα",
"row": "Δίπλα-δίπλα",
"column": "Το ένα κάτω από το άλλο",
"parts": "Πόσα",
"even": "Ίση μοιρασιά",
"part": "Τμήμα {{n}} (%)",
"shows": "Δείχνει",
"nothing": "Τίποτα",
"aSlide": "Μια διαφάνεια από τις Διαφάνειες",
"slide": "Διαφάνεια",
"noSlides": "Δεν υπάρχουν ακόμα διαφάνειες"
}
}, },
"tabs": { "tabs": {
"playlists": "Λίστες", "playlists": "Λίστες",
+49 -11
View File
@@ -1366,13 +1366,13 @@
"muted": "Without sound", "muted": "Without sound",
"title": "Title", "title": "Title",
"body": "Text", "body": "Text",
"align": "Alignment", "align": "Horizontal alignment",
"aligns": { "aligns": {
"left": "Left", "left": "Left",
"center": "Centre", "center": "Centre",
"right": "Right" "right": "Right"
}, },
"vertical": "Height", "vertical": "Vertical alignment",
"verticals": { "verticals": {
"top": "Top", "top": "Top",
"middle": "Middle", "middle": "Middle",
@@ -1406,8 +1406,7 @@
"categoriesHint": "Products added to a chosen category later appear by themselves. A category includes its sub-categories.", "categoriesHint": "Products added to a chosen category later appear by themselves. A category includes its sub-categories.",
"products": "Single products (from any category)", "products": "Single products (from any category)",
"searchProduct": "Search a product to add…", "searchProduct": "Search a product to add…",
"hidden": "Hidden from this board", "showAgain": "Show on this board again",
"showAgain": "show again",
"hide": "Hide from this board", "hide": "Hide from this board",
"onTheBoard_one": "On the board: {{count}} product", "onTheBoard_one": "On the board: {{count}} product",
"onTheBoard_other": "On the board: {{count}} products", "onTheBoard_other": "On the board: {{count}} products",
@@ -1436,7 +1435,10 @@
"layout": "Layout", "layout": "Layout",
"width": "Width of the list", "width": "Width of the list",
"place": "Where the list sits", "place": "Where the list sits",
"placeHint": "At the full width the list fills the screen: make it narrower to place it." "placeHint": "At the full width the list fills the screen: make it narrower to place it.",
"hiddenTag": "hidden",
"pageSecondsHint": "When the list doesn't fit on the screen it is split into pages that take turns: each page stays this many seconds.",
"perPageWidgetHint": "Empty: 8. More than that turns pages."
}, },
"badges": { "badges": {
"new": "New", "new": "New",
@@ -1451,13 +1453,17 @@
"title": "Widgets", "title": "Widgets",
"none": "No widgets: add the clock, your logo, the message of the day…", "none": "No widgets: add the clock, your logo, the message of the day…",
"kinds": { "kinds": {
"logo": "Logo", "logo": "Logo or image",
"name": "Venue name", "name": "Venue name",
"date": "Date", "date": "Date",
"clock": "Clock", "clock": "Clock",
"message": "Message of the day", "message": "Message of the day",
"qr": "QR code", "qr": "QR code",
"weather": "Weather" "weather": "Weather",
"text": "Text",
"menu": "Menu",
"hstack": "Horizontal stack",
"vstack": "Vertical stack"
}, },
"position": "Where", "position": "Where",
"size": "Size", "size": "Size",
@@ -1482,15 +1488,47 @@
"dateShort": "17/11/2026", "dateShort": "17/11/2026",
"seconds": "With seconds", "seconds": "With seconds",
"weatherDays": "Days", "weatherDays": "Days",
"days_one": "Today",
"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\".", "dragHint": "Tip: pick a widget on the preview or here, then drag it (or use the arrow keys) to move it and its handles to size it; where and size then read \"Custom\". The order: a later widget is drawn over an earlier one.",
"custom": "Custom", "custom": "Custom",
"align": "Alignment", "align": "Alignment",
"alignAuto": "Auto", "alignAuto": "Auto",
"dateStyle": "Style", "dateStyle": "Style",
"canvas": "The slide's widgets: drag one to move it, its handles to size it, arrow keys to nudge it" "canvas": "The slide's widgets: drag one to move it, its handles to size it, arrow keys to nudge it",
"earlier": "Move up (drawn under the next ones)",
"later": "Move down (drawn over the earlier ones)",
"dragToOrder": "Drag to change the order",
"ownTextPlaceholder": "The message of the day",
"theText": "Text",
"clockShows": "Shows",
"weatherStyle": "Shows",
"weatherStyles": {
"both": "Picture and degrees",
"icon": "Only the picture",
"text": "Only the degrees"
},
"weatherChoices": {
"0-1": "Today",
"0-2": "Today and tomorrow",
"0-3": "Today and the next 2 days",
"1-1": "Tomorrow",
"2-1": "The day after tomorrow"
},
"menuEdit_one": "Products and look ({{count}} product)",
"menuEdit_other": "Products and look ({{count}} products)",
"stack": {
"direction": "Parts",
"row": "Side by side",
"column": "One over the other",
"parts": "How many",
"even": "Split evenly",
"part": "Part {{n}} (%)",
"shows": "Shows",
"nothing": "Nothing",
"aSlide": "A slide from Slides",
"slide": "Slide",
"noSlides": "No slides in Slides yet"
}
}, },
"tabs": { "tabs": {
"playlists": "Playlists", "playlists": "Playlists",
+33 -4
View File
@@ -1,21 +1,50 @@
// One slide as a TV shows it (plan step 5.6a): picture, video, text, menu board or blank (2026-11-21). 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' // slide.extras: what the server added to its widgets by path (QR links, menus, slides inside stacks)
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { boardPages, pageAt } from './logic.js'
import { BlankSlide, 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 }) {
const x = slide.extras
return ( return (
<> <>
{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} extras={x} embed={EmbeddedSlide} />}
{slide.kind === 'blank' && <BlankSlide content={slide.content || {}} media={media} venue={venue} now={now} />} {slide.kind === 'blank' && <BlankSlide content={slide.content || {}} media={media} venue={venue} now={now} extras={x} embed={EmbeddedSlide} />}
{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} extras={x} embed={EmbeddedSlide} />}
</> </>
) )
} }
/**
* A library slide drawn whole inside a stack's part (2026-11-21): scaled to the part (its sizes
* are the part's container units); a menu board pages by the clock for the part's own size, a
* video loops.
*/
function EmbeddedSlide({ slide, media, venue, now }) {
const ref = useRef(null)
const [size, setSize] = useState(null)
useLayoutEffect(() => {
const el = ref.current
if (!el) return undefined
const measure = () => setSize(s => (s && s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight }))
measure()
const ro = new ResizeObserver(measure)
ro.observe(el)
return () => ro.disconnect()
}, [])
const pages = slide.kind === 'menu' && size ? boardPages(slide, 0, size.w || 16, size.h || 9) : null
const page = pages ? pageAt(pages.length, slide.content?.page_seconds, now.getTime()) : 0
return (
<div ref={ref} style={{ position: 'absolute', inset: 0, overflow: 'hidden', containerType: 'size' }} data-testid="signage-embedded" data-kind={slide.kind} data-id={slide.id}>
{size && <SlideView slide={{ ...slide, video_to_end: false }} media={media} venue={venue} now={now} pages={pages} page={page} />}
</div>
)
}
function ImageSlide({ content, media }) { function ImageSlide({ content, media }) {
const m = content.media_id ? media(content.media_id) : null const m = content.media_id ? media(content.media_id) : null
return ( return (
+177 -82
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 { fitUnit, FONTS, textWidth, weatherIcon, widgetAlign } from './logic' import { fitUnit, FONTS, menuPages, pageAt, textWidth, visibleGroups, 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 }) {
@@ -22,7 +22,7 @@ const JUSTIFY = { top: 'flex-start', middle: 'center', bottom: 'flex-end' }
const BOARD_ALIGN = { left: 'flex-start', center: 'center', right: '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, extras, embed }) {
const scale = (c.text_size || 100) / 100 const scale = (c.text_size || 100) / 100
return ( return (
<div className="absolute inset-0" style={{ color: c.text_colour || '#fff', fontFamily: FONTS[c.font] || FONTS.sans }}> <div className="absolute inset-0" style={{ color: c.text_colour || '#fff', fontFamily: FONTS[c.font] || FONTS.sans }}>
@@ -34,25 +34,23 @@ export function TextSlide({ content: c, media, venue, now }) {
{c.title && <h1 style={{ fontSize: `${9 * scale}cqmin`, lineHeight: 1.1, fontWeight: 800, margin: 0 }} data-testid="signage-title">{c.title}</h1>} {c.title && <h1 style={{ fontSize: `${9 * scale}cqmin`, lineHeight: 1.1, fontWeight: 800, margin: 0 }} data-testid="signage-title">{c.title}</h1>}
{c.body && <p style={{ fontSize: `${4.5 * scale}cqmin`, lineHeight: 1.35, margin: 0, whiteSpace: 'pre-line' }} data-testid="signage-body">{c.body}</p>} {c.body && <p style={{ fontSize: `${4.5 * scale}cqmin`, lineHeight: 1.35, margin: 0, whiteSpace: 'pre-line' }} data-testid="signage-body">{c.body}</p>}
</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} extras={extras} embed={embed} />
</div> </div>
) )
} }
/** A blank slide (2026-11-21): its background and its widgets, nothing else. */ /** A blank slide (2026-11-21): its background and its widgets, nothing else. */
export function BlankSlide({ content: c, media, venue, now }) { export function BlankSlide({ content: c, media, venue, now, extras, embed }) {
return ( return (
<div className="absolute inset-0" data-testid="signage-blank"> <div className="absolute inset-0" data-testid="signage-blank">
<Background bg={c.background} media={media} /> <Background bg={c.background} media={media} />
<Widgets widgets={c.widgets} media={media} venue={venue} now={now} /> <Widgets widgets={c.widgets} media={media} venue={venue} now={now} extras={extras} embed={embed} />
</div> </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, extras, embed }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const c = slide.content const c = slide.content
const scale = (c.text_size || 100) / 100 const scale = (c.text_size || 100) / 100
const accent = c.accent_colour || '#f59e0b' const accent = c.accent_colour || '#f59e0b'
@@ -69,37 +67,7 @@ export function MenuSlide({ slide, media, venue, now, page, pages }) {
{c.title && <h1 style={{ fontSize: `${7 * scale}cqmin`, fontWeight: 800, margin: '0 0 2cqmin', color: accent, lineHeight: 1.1, {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>} 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) => ( <MenuGroups c={c} groups={groups} accent={accent} />
<div key={`${g.category?.id ?? 'all'}-${i}`} style={{ marginBottom: '1.6cqmin' }}>
{g.category && c.category_titles !== false && (
<h2 style={{ fontSize: '1.15em', color: accent, margin: '0 0 0.6cqmin', fontWeight: 700, breakAfter: 'avoid' }}
data-testid="signage-menu-heading">{g.category.name}</h2>
)}
{g.items.map(it => (
<div key={it.id} data-testid="signage-menu-item" data-id={it.id} data-available={it.available ? 'true' : 'false'}
style={{ display: 'flex', alignItems: 'center', gap: '1.5cqmin', breakInside: 'avoid', padding: '0.5cqmin 0',
opacity: it.available ? 1 : 0.5 }}>
{c.show_photos && (it.image
? <img src={it.image} alt="" style={{ width: '7cqmin', height: '7cqmin', objectFit: 'cover', borderRadius: '1cqmin', flexShrink: 0 }} />
: <span style={{ width: '7cqmin', height: '7cqmin', flexShrink: 0 }} />)}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: '1cqmin' }}>
<span style={{ textDecoration: it.available ? 'none' : 'line-through', fontWeight: 600 }}>{it.name}</span>
{it.badge && (
<span style={{ background: accent, color: '#111', fontSize: '0.55em', fontWeight: 800, padding: '0.2cqmin 0.9cqmin', borderRadius: '99cqmin',
textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }} data-testid="signage-badge">{t(`signage.badges.${it.badge}`)}</span>
)}
{!it.available && <span style={{ fontSize: '0.6em', whiteSpace: 'nowrap' }} data-testid="signage-sold-out">{t('signage.soldOut')}</span>}
<span style={{ flex: 1, borderBottom: '0.25cqmin dotted currentColor', opacity: 0.35, minWidth: '2cqmin' }} />
{it.price != null && <span style={{ color: accent, fontVariantNumeric: 'tabular-nums', fontWeight: 700, whiteSpace: 'nowrap' }}
data-testid="signage-menu-price">{formatMoney(it.price)}</span>}
</div>
{it.description && <div style={{ fontSize: '0.7em', opacity: 0.75, lineHeight: 1.25 }}>{it.description}</div>}
</div>
</div>
))}
</div>
))}
</div> </div>
{pages.length > 1 && ( {pages.length > 1 && (
<div style={{ display: 'flex', gap: '1cqmin', justifyContent: 'center', paddingTop: '1cqmin' }} aria-hidden="true"> <div style={{ display: 'flex', gap: '1cqmin', justifyContent: 'center', paddingTop: '1cqmin' }} aria-hidden="true">
@@ -108,12 +76,52 @@ export function MenuSlide({ slide, media, venue, now, page, pages }) {
)} )}
</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} extras={extras} embed={embed} />
</div> </div>
) )
} }
// ── widgets (5.5b; placed by hand on the editor's preview, owner 2026-11-21) ──── /**
* A board's groups of items (a menu slide's page, a menu widget's page). Sizes are em of the
* list's text, so the same rows fit a whole screen or a widget's box.
*/
export function MenuGroups({ c, groups, accent }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
return groups.map((g, i) => (
<div key={`${g.category?.id ?? 'all'}-${i}`} style={{ marginBottom: '0.5em' }}>
{g.category && c.category_titles !== false && (
<h2 style={{ fontSize: '1.15em', color: accent, margin: '0 0 0.19em', fontWeight: 700, breakAfter: 'avoid' }}
data-testid="signage-menu-heading">{g.category.name}</h2>
)}
{g.items.map(it => (
<div key={it.id} data-testid="signage-menu-item" data-id={it.id} data-available={it.available ? 'true' : 'false'}
style={{ display: 'flex', alignItems: 'center', gap: '0.47em', breakInside: 'avoid', padding: '0.16em 0',
opacity: it.available ? 1 : 0.5 }}>
{c.show_photos && (it.image
? <img src={it.image} alt="" style={{ width: '2.2em', height: '2.2em', objectFit: 'cover', borderRadius: '0.3em', flexShrink: 0 }} />
: <span style={{ width: '2.2em', height: '2.2em', flexShrink: 0 }} />)}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: '0.3em' }}>
<span style={{ textDecoration: it.available ? 'none' : 'line-through', fontWeight: 600 }}>{it.name}</span>
{it.badge && (
<span style={{ background: accent, color: '#111', fontSize: '0.55em', fontWeight: 800, padding: '0.1em 0.5em', borderRadius: '99em',
textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap' }} data-testid="signage-badge">{t(`signage.badges.${it.badge}`)}</span>
)}
{!it.available && <span style={{ fontSize: '0.6em', whiteSpace: 'nowrap' }} data-testid="signage-sold-out">{t('signage.soldOut')}</span>}
<span style={{ flex: 1, borderBottom: '0.08em dotted currentColor', opacity: 0.35, minWidth: '0.6em' }} />
{it.price != null && <span style={{ color: accent, fontVariantNumeric: 'tabular-nums', fontWeight: 700, whiteSpace: 'nowrap' }}
data-testid="signage-menu-price">{formatMoney(it.price)}</span>}
</div>
{it.description && <div style={{ fontSize: '0.7em', opacity: 0.75, lineHeight: 1.25 }}>{it.description}</div>}
</div>
</div>
))}
</div>
))
}
// ── widgets (5.5b; placed by hand on the editor's preview, text / menu / stacks: 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 = {
@@ -125,17 +133,22 @@ const CORNER = {
'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' } const SELF = { left: 'flex-start', center: 'center', right: 'flex-end' }
// a menu or a stack in a corner or a bar has no box of its own: it gets one of this size (cqmin)
const BOXED = { menu: [48, 56], stack: [60, 36] }
/** /**
* The widgets of a slide: in their corners and bars, or (moved and sized by hand: position * 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. * "custom") each in its own box, scaled to fill it; drawn in the list's order (a later one lies
* Each carries `data-widget` = its index in the slide's list (the editor's handles find it so). * over an earlier one). 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). `extras`: what the server added by
* widget path (QR links, a menu widget's products, a stack part's library slide); `embed`: draws a
* slide inside a stack's part (SlideView passes it).
*/ */
export function Widgets({ widgets, media, venue, now, colour }) { export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
const fmt = useFormat() const fmt = useFormat()
if (!widgets?.length) return null if (!widgets?.length) return null
const ctx = { media, venue, now, fmt } const ctx = { media, venue, now, fmt, extras: extras || {}, embed }
const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, w.position === 'custom' && !!w.box)]).filter(([, , body]) => body) const shown = widgets.map((w, i) => [w, i, widgetBody(w, ctx, w.position === 'custom' && !!w.box, String(i))]).filter(([, , body]) => body)
const bar = where => shown.filter(([w]) => w.position === where) 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 (
@@ -149,22 +162,24 @@ export function Widgets({ widgets, media, venue, now, colour }) {
))} ))}
</div> </div>
))} ))}
{shown.filter(([w]) => CORNER[w.position]).map(([w, i, body]) => { {shown.filter(([w]) => CORNER[w.position] || (w.position === 'custom' && w.box)).map(([w, i, body]) => {
const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {} if (w.position === 'custom') {
return ( return (
<div key={`c${i}`} data-widget={i} className="absolute" style={{ ...CORNER[w.position], ...own, display: 'flex', flexDirection: 'column', color: colour || '#fff' }}> <div key={i} data-widget={i} className="absolute" data-testid="signage-w-box"
{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' }}> 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) }}> <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: SELF[widgetAlign(w)], textAlign: widgetAlign(w) }}>
{body} {body}
</div> </div>
</div> </div>
))} )
}
const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {}
return (
<div key={i} data-widget={i} className="absolute" style={{ ...CORNER[w.position], ...own, display: 'flex', flexDirection: 'column', color: colour || '#fff' }}>
{body}
</div>
)
})}
</> </>
) )
} }
@@ -173,14 +188,25 @@ const OBJECT_POSITION = { left: 'left center', center: 'center', right: 'right c
/** /**
* What one widget shows, or null when it has nothing to show. Sizes are "usual units" (cqmin of * 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). * the slide at size medium); `fit`: the widget fills its own box instead (fitUnit). `path`: the
* widget's place in the slide ("2", "2.1" inside a stack), for its extras.
*/ */
function widgetBody(w, { media, venue, now, fmt }, fit) { function widgetBody(w, ctx, fit, path) {
const { media, venue, now, fmt, extras } = ctx
const { formatDate, formatTime } = fmt const { formatDate, formatTime } = fmt
const x = extras[path] || {}
const s = SIZE[w.size] || 1 const s = SIZE[w.size] || 1
const unit = (height, width) => (fit ? fitUnit(height, width) : n => `${+(n * s).toFixed(3)}cqmin`) 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, 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 }) textShadow: '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)', whiteSpace: fit ? 'nowrap' : undefined })
const line = (str, testid, weight) => {
const u = unit(3.4 * 1.15, textWidth(str.length, 3.4))
return <span style={text(u, 3.4, weight)} data-testid={testid}>{str}</span>
}
// a menu or a stack fills a box: its own, or (in a corner / bar) one of a usual size
const boxed = (body, kind) => (fit ? body : (
<div style={{ width: `${BOXED[kind][0] * s}cqmin`, height: `${BOXED[kind][1] * s}cqmin`, containerType: 'size' }}>{body}</div>
))
if (w.kind === 'logo') { if (w.kind === 'logo') {
const m = media(w.media_id) const m = media(w.media_id)
if (!m) return null if (!m) return null
@@ -193,58 +219,127 @@ function widgetBody(w, { media, venue, now, fmt }, fit) {
const u = unit(4.2 * 1.15, textWidth(venue.name.length, 4.2)) 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> return <span style={text(u, 4.2)} data-testid="signage-w-name">{venue.name}</span>
} }
if (w.kind === 'date') { if (w.kind === 'date') return line(formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong'), 'signage-w-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') { 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 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> 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 === 'message') { if (w.kind === 'message') {
const msg = w.text || venue?.message const msg = w.text || venue?.message
if (!msg) return null return msg ? line(msg, 'signage-w-message', 600) : 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 === 'text') return w.text ? line(w.text, 'signage-w-text', 600) : null
if (w.kind === 'qr') { if (w.kind === 'qr') {
if (!w.link) return null const link = x.link || w.link
if (!link) return null
const caption = w.qr_caption ? 2.4 * 1.15 + 0.8 : 0 const caption = w.qr_caption ? 2.4 * 1.15 + 0.8 : 0
const u = unit(16 + caption, Math.max(16, w.qr_caption ? textWidth(w.qr_caption.length, 2.4) : 0)) const u = unit(16 + caption, Math.max(16, w.qr_caption ? textWidth(w.qr_caption.length, 2.4) : 0))
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: u(0.8) }} data-testid="signage-w-qr" data-link={w.link}> <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: u(0.8) }} data-testid="signage-w-qr" data-link={link}>
<div style={{ background: '#fff', padding: u(1), borderRadius: u(1), lineHeight: 0 }}> <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) }} /> <QRCodeSVG value={link} size={256} style={{ width: u(14), height: u(14) }} />
</div> </div>
{w.qr_caption && <span style={text(u, 2.4)}>{w.qr_caption}</span>} {w.qr_caption && <span style={text(u, 2.4)}>{w.qr_caption}</span>}
</div> </div>
) )
} }
if (w.kind === 'weather') { if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate)
const wx = venue?.weather if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} />, 'menu')
if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack')
return null
}
/** The weather: now or a day of the forecast (today, tomorrow, the day after), and the next days;
* its picture and degrees, only the picture or only the degrees (2026-11-21). */
function weatherBody(w, wx, unit, text, formatDate) {
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 from = w.weather_from || 0
const deg = wx.units === 'fahrenheit' ? '°F' : '°C' const style = w.weather_style || 'both'
const days = (w.weather_days || 1) > 1 ? (wx.days || []).slice(1, w.weather_days) : [] const pic = style !== 'text'
const u = unit(6, 6 + 1.5 + textWidth(4, 4.4) + days.length * (1.5 + 3.4 + textWidth(12, 2.4))) const deg = style !== 'icon'
const unitMark = wx.units === 'fahrenheit' ? '°F' : '°C'
const days = wx.days || []
const dayName = d => formatDate(`${d.date}T12:00:00Z`, 'weekday').slice(0, 3)
const main = from === 0
? { icon: weatherIcon(wx.code, wx.is_day), label: `${Math.round(wx.temperature)}${unitMark}` }
: days[from] && { icon: weatherIcon(days[from].code, true), label: `${dayName(days[from])} ${Math.round(days[from].max)}° / ${Math.round(days[from].min)}°` }
if (!main) return null
const rest = days.slice(from + 1, from + (w.weather_days || 1))
const restText = d => `${Math.round(d.max)}° / ${Math.round(d.min)}°`
const u = unit(6, (pic ? 6 + 1.5 : 0) + (deg ? textWidth(main.label.length, 4.4) : 0)
+ rest.length * (1.5 + (pic ? 3.4 : 0) + textWidth(4 + (deg ? 11 : 0), 2.4)))
const MainIcon = ICONS[main.icon] || Cloud
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: u(1.5) }} data-testid="signage-w-weather"> <div style={{ display: 'flex', alignItems: 'center', gap: u(1.5) }} data-testid="signage-w-weather" data-style={style} data-from={from}>
<Icon style={{ width: u(6), height: u(6), flexShrink: 0 }} aria-hidden="true" /> {pic && <MainIcon style={{ width: u(6), height: u(6), flexShrink: 0 }} aria-hidden="true" />}
<span style={text(u, 4.4)}>{Math.round(wx.temperature)}{deg}</span> {deg && <span style={text(u, 4.4)}>{main.label}</span>}
{days.map(d => { {rest.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: u(0.6), ...text(u, 2.4, 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: u(3.4), height: u(3.4) }} aria-hidden="true" /> {dayName(d)} {pic && <DayIcon style={{ width: u(3.4), height: u(3.4) }} aria-hidden="true" />}
{Math.round(d.max)}° / {Math.round(d.min)}° {deg && restText(d)}
</span> </span>
) )
})} })}
</div> </div>
) )
} }
return null
/**
* A menu widget (2026-11-21): a board's list in the widget's box (inside an element with
* `container-type: size`), its pages turning on the clock; the text sized so a page fills the box.
*/
function MenuWidget({ board: b, menu, now }) {
const groups = visibleGroups(menu?.groups)
const per = b.page_size || 8
const headings = b.category_titles !== false
const pages = menuPages(groups, per, headings)
const page = pageAt(pages.length, b.page_seconds, now.getTime())
const cols = b.columns || 1
const scale = (b.text_size || 100) / 100
const rowH = b.show_photos ? 2.6 : b.show_descriptions ? 2.1 : 1.5
const lines = Math.ceil(per / cols) + (headings ? 1 : 0)
const fontSize = `calc(${scale} * min(${(100 / (lines * rowH + (b.title ? 2 : 0) + 0.8)).toFixed(3)}cqh, ${(100 / (cols * 15)).toFixed(3)}cqw))`
const accent = b.accent_colour || '#f59e0b'
return (
<div style={{ width: '100%', height: '100%', overflow: 'hidden', fontSize, color: b.text_colour || '#fff', fontFamily: FONTS[b.font] || FONTS.sans, textAlign: 'left' }}
data-testid="signage-w-menu" data-page={page} data-pages={pages.length}>
{b.title && <div style={{ fontSize: '1.5em', fontWeight: 800, color: accent, lineHeight: 1.15, marginBottom: '0.3em' }}>{b.title}</div>}
<div style={{ columnCount: cols, columnGap: '1.2em', columnFill: 'auto' }}>
<MenuGroups c={b} groups={pages[page] || []} accent={accent} />
</div>
</div>
)
}
/**
* A stack (2026-11-21): parts side by side ("row") or one over the other ("column"), each its share
* of the stack, showing a widget (filling the part) or a whole library slide.
*/
function Stack({ w, path, ctx }) {
const cells = w.cells || []
const Embed = ctx.embed
return (
<div style={{ display: 'flex', flexDirection: w.direction === 'column' ? 'column' : 'row', width: '100%', height: '100%' }}
data-testid="signage-w-stack" data-direction={w.direction || 'row'}>
{cells.map((c, j) => {
const cp = `${path}.${j}`
const slide = c.slide_id ? ctx.extras[cp]?.slide : null
const body = c.widget ? widgetBody(c.widget, ctx, true, cp) : null
const align = c.widget?.align && c.widget.align !== 'auto' ? c.widget.align : 'center'
return (
<div key={j} style={{ flex: `${c.share || 1} 1 0%`, minWidth: 0, minHeight: 0, position: 'relative', overflow: 'hidden', containerType: 'size' }}
data-testid="signage-stack-cell" data-share={c.share}>
{body && (
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: SELF[align], textAlign: align }}>{body}</div>
)}
{slide && Embed && <Embed slide={slide} media={ctx.media} venue={ctx.venue} now={ctx.now} />}
</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 ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning }
+29 -1
View File
@@ -246,7 +246,13 @@ export function boardPages(slide, rotation, w, h) {
const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: c.text_size, photos: c.show_photos, const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: c.text_size, photos: c.show_photos,
descriptions: c.show_descriptions, title: !!c.title, bars }) descriptions: c.show_descriptions, title: !!c.title, bars })
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(visibleGroups(slide.menu?.groups), per, c.category_titles !== false)
}
/** A board's groups without the products hidden from it (the editor's list keeps them, marked
* `hidden`, 2026-11-21); groups left empty go too. */
export function visibleGroups(groups) {
return (groups || []).map(g => ({ ...g, items: (g.items || []).filter(i => !i.hidden) })).filter(g => g.items.length)
} }
// ── widgets placed by hand (owner 2026-11-21) ───────────────────────────────── // ── widgets placed by hand (owner 2026-11-21) ─────────────────────────────────
@@ -254,6 +260,28 @@ export function boardPages(slide, rotation, w, h) {
/** The slide kinds that carry widgets. */ /** The slide kinds that carry widgets. */
export const WIDGET_HOSTS = ['text', 'menu', 'blank'] export const WIDGET_HOSTS = ['text', 'menu', 'blank']
/** A stack's parts' shares as whole percents adding up to 100 (2026-11-21). */
export function evenShares(n) {
const base = Math.floor(100 / n)
return Array.from({ length: n }, (_, i) => (i < 100 - base * n ? base + 1 : base))
}
/**
* A stack's part `i` set to `value` % (5…): the difference is taken from (or given to) the part
* after it (the one before, for the last part), which keeps at least 5 %; the shares still add up
* to 100. → the new shares.
*/
export function setShare(shares, i, value) {
const out = [...shares]
if (out.length < 2) return [100]
const j = i < out.length - 1 ? i + 1 : i - 1
const room = out[i] + out[j] - 5
const v = Math.max(5, Math.min(room, Math.round(Number(value) || 0)))
out[j] = out[i] + out[j] - v
out[i] = v
return out
}
/** How a widget lines up inside its place: its own choice, else by its corner / its box's side. */ /** How a widget lines up inside its place: its own choice, else by its corner / its box's side. */
export function widgetAlign(w) { export function widgetAlign(w) {
if (w?.align && w.align !== 'auto') return w.align if (w?.align && w.align !== 'auto') return w.align
+13
View File
@@ -155,3 +155,16 @@ test('a screen whose default is a library slide plays it when no line matches',
playlists: { 1: { id: 1, slides: [] }, 'slide:3': one } } playlists: { 1: { id: 1, slides: [] }, 'slide:3': one } }
assert.equal(playlistNow(data, new Date('2026-11-21T12:00:00Z')), one) assert.equal(playlistNow(data, new Date('2026-11-21T12:00:00Z')), one)
}) })
test('stacks: even shares and a part resized against its neighbour; hidden products never on the TV (2026-11-21)', async () => {
const { boardPages, evenShares, setShare, visibleGroups } = await import('../src/logic.js')
assert.deepEqual(evenShares(3), [34, 33, 33])
assert.deepEqual(evenShares(2), [50, 50])
assert.deepEqual(setShare([50, 50], 0, 25), [25, 75])
assert.deepEqual(setShare([25, 25, 50], 2, 70), [25, 5, 70]) // the last part takes from the one before
assert.deepEqual(setShare([50, 50], 1, 99), [5, 95]) // its neighbour keeps 5 %
const groups = [{ category: { id: 1 }, items: [{ id: 1, hidden: true }] }, { category: { id: 2 }, items: [{ id: 2 }, { id: 3, hidden: true }] }]
assert.deepEqual(visibleGroups(groups), [{ category: { id: 2 }, items: [{ id: 2 }] }])
const pages = boardPages({ content: { columns: 1 }, menu: { groups } }, 0, 1920, 1080)
assert.deepEqual(pages.flat().flatMap(g => g.items.map(i => i.id)), [2])
})
+2
View File
@@ -347,6 +347,8 @@
box-sizing: border-box; min-height: var(--x-control-md); padding: var(--x-space-2) var(--x-space-3); 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); background: var(--x-surface); border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control);
} }
.x-switch-row--boxed { cursor: pointer; }
.x-switch-row--boxed.x-switch-row--disabled { cursor: not-allowed; }
.x-switch-row--boxed .x-switch-row__label { font-size: var(--x-text-label); } .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); } .x-confirm__body { font-size: var(--x-text-body); line-height: var(--x-leading-body); color: var(--x-ink-2); }
+9 -4
View File
@@ -7,7 +7,8 @@ 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). * boxed: framed and as tall as an input, the text left and the switch right (a switch in a row of fields);
* a click anywhere in the frame toggles it (2026-11-21).
*/ */
export function Switch({ checked, onChange, label, description, info, disabled = false, boxed = 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()
@@ -21,9 +22,10 @@ export function Switch({ checked, onChange, label, description, info, disabled =
role="switch" role="switch"
aria-checked={!!checked} aria-checked={!!checked}
aria-describedby={description ? descId : undefined} aria-describedby={description ? descId : undefined}
aria-label={boxed && typeof label === 'string' ? label : undefined}
disabled={disabled} disabled={disabled}
className={cx('x-switch', checked && 'x-switch--on')} className={cx('x-switch', checked && 'x-switch--on')}
onClick={() => onChange?.(!checked)} onClick={boxed ? undefined : () => onChange?.(!checked)}
{...rest} {...rest}
> >
<span className="x-switch__thumb" /> <span className="x-switch__thumb" />
@@ -32,11 +34,14 @@ 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', boxed && 'x-switch-row--boxed', disabled && 'x-switch-row--disabled', className)}> <div className={cx('x-switch-row', boxed && 'x-switch-row--boxed', disabled && 'x-switch-row--disabled', className)}
onClick={boxed && !disabled ? () => onChange?.(!checked) : undefined}>
<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">
<label className="x-switch-row__label" htmlFor={switchId}>{label}</label> {boxed
? <span className="x-switch-row__label">{label}</span>
: <label className="x-switch-row__label" htmlFor={switchId}>{label}</label>}
{info} {info}
</span> </span>
)} )}
+28 -1
View File
@@ -299,9 +299,36 @@ try {
mc.select === 'custom' && mc.category_ids?.includes(catA.id) && mc.category_ids?.includes(catB.id) && mc.product_ids?.includes(extra.id) mc.select === 'custom' && mc.category_ids?.includes(catA.id) && mc.category_ids?.includes(catB.id) && mc.product_ids?.includes(extra.id)
&& mc.exclude_ids?.includes(hiddenId) && mc.category_order?.[0] === catB.id && mc.badges?.[String(badgeId)] === 'offer' && mc.exclude_ids?.includes(hiddenId) && mc.category_order?.[0] === catB.id && mc.badges?.[String(badgeId)] === 'offer'
&& (mc.widgets || []).some(w => w.kind === 'clock') && (mc.widgets || []).some(w => w.kind === 'clock')
&& !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 && !i.hidden) && 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') })
// ── owner review 2 (2026-11-21): a hidden product stays in the list, greyed; widgets ordered, moved by the keys from their card; stacks ──
r.check('2026-11-21 (2): a product hidden from the board stays in the list of the editor, marked hidden',
await mgr.locator(`[data-testid="signage-menu-row"][data-id="${hiddenId}"]`).getAttribute('data-hidden') === 'true')
await mgr.getByTestId('signage-widget-add-text').click()
await mgr.locator('[data-testid="signage-widget"][data-kind="text"]').getByTestId('signage-widget-own-text').fill('Happy hour')
await mgr.locator('[data-testid="signage-widget"][data-kind="text"]').getByTestId('signage-widget-up').click()
const kinds = await mgr.getByTestId('signage-widget').evaluateAll(els => els.map(e => e.dataset.kind))
r.check('2026-11-21 (2): a text widget, moved up the list with its arrow', kinds.indexOf('text') < kinds.lastIndexOf('clock'), JSON.stringify(kinds))
r.check('2026-11-21 (2): …shown on the preview', await waitFor(async () => (await mgr.getByTestId('signage-preview').getByTestId('signage-w-text').count()) > 0, 5000, 200) === true)
const textCard = mgr.locator('[data-testid="signage-widget"][data-kind="text"]')
await textCard.locator('span', { hasText: 'Text' }).first().click()
await mgr.keyboard.press('ArrowRight')
r.check('2026-11-21 (2): picked on its card, the arrow keys move the widget (Custom)',
await waitFor(async () => (await textCard.getByTestId('signage-widget-position').textContent()).includes('Custom'), 4000, 200) === true)
await mgr.getByTestId('signage-widget-add-hstack').click()
const stackCard = mgr.locator('[data-testid="signage-widget"][data-kind="stack"]')
await stackCard.getByTestId('signage-stack-shows').first().click()
await mgr.getByRole('option', { name: 'Clock', exact: true }).click()
await stackCard.getByTestId('signage-stack-share').first().fill('25')
r.check('2026-11-21 (2): a horizontal stack: a clock in its first part, 25 / 75, on the preview',
await waitFor(async () => {
const cells = mgr.getByTestId('signage-preview').getByTestId('signage-stack-cell')
return (await cells.count()) === 2 && (await cells.first().getAttribute('data-share')) === '25'
&& (await cells.first().getByTestId('signage-w-clock').count()) === 1
}, 6000, 300) === true)
await stackCard.getByTestId('signage-widget-remove').click()
await textCard.getByTestId('signage-widget-remove').click()
// ── 2026-11-21: a widget moved and sized on the preview; the slide kept in the Slides library ── // ── 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 mgr.getByTestId('signage-preview-box').scrollIntoViewIfNeeded()
await sleep(300) await sleep(300)