diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3bce670..dbe659f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -58,7 +58,7 @@ Every page is on `` 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 | | Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` | | Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component | -| A switch in a row of fields | `Switch boxed` | framed and as tall as an input: text left, switch right | +| 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` | | 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 | diff --git a/local_backend/routers/signage.py b/local_backend/routers/signage.py index 12efd3f..16f9061 100644 --- a/local_backend/routers/signage.py +++ b/local_backend/routers/signage.py @@ -71,10 +71,59 @@ class Background(_Strict): 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"] +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): """Where a widget moved by hand sits (2026-11-21): % of the slide's width / height.""" x: float = Field(ge=0, le=100) @@ -92,9 +141,28 @@ class Box(_Strict): 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): """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 position: Position = "top-right" size: Literal["small", "medium", "large", "custom"] = "medium" @@ -107,7 +175,12 @@ class Widget(_Strict): qr_target: Literal["ordering", "menu", "custom"] = "ordering" qr_url: Optional[str] = Field(default=None, max_length=300) 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") def _place(self): @@ -121,6 +194,20 @@ class Widget(_Strict): self.size = "medium" 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") @classmethod def _url(cls, v): @@ -131,6 +218,9 @@ class Widget(_Strict): return v +Cell.model_rebuild() + + class ImageContent(_Strict): media_id: Optional[int] = None # a picture fit: Literal["cover", "contain"] = "cover" @@ -162,57 +252,15 @@ class BlankContent(_Strict): widgets: List[Widget] = Field(default_factory=list, max_length=10) -Badge = Literal["new", "chef", "offer", "popular", "spicy", "vegetarian", "vegan"] - - -class MenuContent(_Strict): +class MenuContent(MenuList): """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.""" - 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 - # how it's laid out (the player pages through what doesn't fit, 5.5b) - columns: int = Field(default=2, ge=1, le=3) + own order, with a sales point's live prices, and how it looks (MenuList), on its background + with its widgets.""" board_width: int = Field(default=100, ge=40, le=100) # % of the screen the list takes (2026-11-21) board_align: Literal["left", "center", "right"] = "left" # where a narrower list sits, and its title - page_size: Optional[int] = Field(default=None, ge=3, le=60) # items per page; None = as many as fit - page_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) 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} Kind = Literal["menu", "image", "video", "text", "blank"] @@ -367,6 +415,60 @@ def media_ids(value) -> list[int]: 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: """The content as stored: typed for its kind, every media id an existing file of the right kind.""" from pydantic import ValidationError @@ -389,9 +491,16 @@ def _content(db, kind: str, raw: dict | None) -> dict: raise XeniaError("signage.not_a_video") if kind != "video" and m.kind != "image": 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): 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 @@ -472,10 +581,13 @@ def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict: if slides: from services.signage_menu import resolve out["slides"] = [_slide_out(s) for s in p.slides] + more = [] for s in out["slides"]: if s["kind"] == "menu": - s["menu"] = resolve(db, s["content"]) # 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["menu"] = resolve(db, s["content"], keep_hidden=True) # the editor's preview (5.6a) + 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 @@ -539,8 +651,8 @@ def tell_all_screens(db) -> None: def menu_changed(db) -> None: """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.""" - playlists = {pid for (pid,) in db.query(SignageSlide.playlist_id).filter(SignageSlide.kind == "menu")} - boards = {slide_key(sid) for (sid,) in db.query(SignageSavedSlide.id).filter(SignageSavedSlide.kind == "menu")} + playlists = {x.playlist_id for x in db.query(SignageSlide) if _needs_menu(x.kind, x.content)} + boards = {slide_key(x.id) for x in db.query(SignageSavedSlide) if _needs_menu(x.kind, x.content)} 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]) @@ -705,12 +817,29 @@ def _saved_out(s: SignageSavedSlide, db=None) -> dict: if db is not None: if s.kind == "menu": 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)) out["screens"] = [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in showing] 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: name = (body.name or "").strip() if not name: @@ -722,8 +851,9 @@ def _saved_name(body) -> str: def list_saved(db: Session = Depends(get_db), user=Depends(require(KEY))): """Every kept slide, with its menu resolved (the gallery's previews) and the media they show.""" rows = db.query(SignageSavedSlide).order_by(SignageSavedSlide.name, SignageSavedSlide.id).all() - return {"slides": [_saved_out(s, db) for s in rows], - "media": _media_map(db, [i for s in rows for i in media_ids(s.content or {})])} + slides = [_saved_out(s, db) for s in rows] + 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) @@ -739,14 +869,14 @@ def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depen db.add(s) db.commit() db.refresh(s) - return _saved_out(s, db) + return _saved_one(db, s) @router.get("/library/{slide_id}") def get_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): s = _saved(db, slide_id) out = _saved_out(s, db) - out["media"] = _media_map(db, media_ids(s.content or {})) + out["media"] = _media_map(db, media_ids(s.content or {}) + out.pop("extra_media")) return out @@ -764,14 +894,14 @@ def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_ s.orientation = body.orientation db.commit() db.refresh(s) - _tell(_screens_showing_slide(db, s.id)) - return _saved_out(s, db) + _tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)) + return _saved_one(db, s) @router.delete("/library/{slide_id}", status_code=204) def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): s = _saved(db, slide_id) - showing = _screens_showing_slide(db, s.id) + showing = _screens_showing_slide(db, s.id) + _embedding_screens(db, s.id) for d in _screens(db): if (d.config or {}).get("slide") == s.id: 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.commit() db.refresh(copy) - return _saved_out(copy, db) + return _saved_one(db, copy) # ── 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.""" from services.signage_menu import resolve slides = [_slide_out(s) for s in p.slides if s.enabled] + more = [] for s in slides: s["transition"] = s["transition"] or p.transition if s["kind"] == "menu": 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 []: if w["kind"] == "qr": w["link"] = _qr_link(w) 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: @@ -869,12 +1002,13 @@ def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict: one["transition"] = one["transition"] or "fade" if one["kind"] == "menu": one["menu"] = resolve(db, one["content"]) + one["extras"], more = extras(db, one["content"]) for w in one["content"].get("widgets") or []: if w["kind"] == "qr": w["link"] = _qr_link(w) slides = [one] if s.enabled else [] return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides, - "media": _media_map(db, media_ids(one["content"]))} + "media": _media_map(db, media_ids(one["content"]) + more)} 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)} +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") 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).""" from services.signage_menu import resolve content = _content(db, "menu", body.content) - return {"content": content, "menu": resolve(db, content)} + return {"content": content, "menu": resolve(db, content, keep_hidden=True)} diff --git a/local_backend/services/signage_menu.py b/local_backend/services/signage_menu.py index 3ce7f70..917eb75 100644 --- a/local_backend/services/signage_menu.py +++ b/local_backend/services/signage_menu.py @@ -34,8 +34,11 @@ def _rank(order: list[int]): return lambda v: (0, pos[v]) if v in pos else (1, 0) -def resolve(db, content: dict, now=None) -> dict: - """{"groups": [{"category": {id, name} | None, "items": [...]}], "count": n} for a menu slide.""" +def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict: + """{"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 services import media as media_store from services.pos_cart import unit_prices @@ -55,7 +58,8 @@ def resolve(db, content: dict, now=None) -> dict: ids = in_cats | set(content.get("product_ids") or []) products = q.filter(Product.id.in_(ids)).all() if ids else [] excluded = set(content.get("exclude_ids") or []) - products = [p for p in products if p.id not in excluded] + if not keep_hidden: + products = [p for p in products if p.id not in excluded] point = content.get("sales_point") if 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, "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, - "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): groups: dict = {} @@ -101,4 +105,4 @@ def resolve(db, content: dict, now=None) -> dict: else: 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 [] - return {"groups": out, "count": len(products)} + return {"groups": out, "count": len([p for p in products if p.id not in excluded])} diff --git a/local_backend/tests/test_signage_stacks.py b/local_backend/tests/test_signage_stacks.py new file mode 100644 index 0000000..46678a4 --- /dev/null +++ b/local_backend/tests/test_signage_stacks.py @@ -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" diff --git a/manager_dashboard/src/pages/signage/MenuEditor.jsx b/manager_dashboard/src/pages/signage/MenuEditor.jsx index a712f97..329d7fe 100644 --- a/manager_dashboard/src/pages/signage/MenuEditor.jsx +++ b/manager_dashboard/src/pages/signage/MenuEditor.jsx @@ -2,12 +2,16 @@ // 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 // 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 // switches on one); the layout: columns, how wide the list is and where it sits (left / centre / // 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 { 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 { useFormat, useTranslation } from '@xenia/i18n' 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 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 { formatMoney } = useFormat() const c = slide.content || {} const setC = patch => onChange({ ...slide, content: { ...c, ...patch } }) - const [cats, setCats] = useState([]) - const [products, setProducts] = useState([]) + const { cats, products } = useCatalogue() 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 top = cats.filter(x => !x.parent_id) const subsOf = id => cats.filter(x => x.parent_id === id) const groups = slide.menu?.groups || [] - const shown = 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 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()) && !listed.has(p.id)).slice(0, 8) const reorder = next => setC(boardOrder(next)) const badges = c.badges || {} const digits = v => Number(String(v).replace(/\D/g, '')) + const hidden = new Set(c.exclude_ids || []) return ( -
+
{/* what it lists */}
@@ -75,7 +89,8 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [ {(c.product_ids || []).map(id => ( {byId[id]?.name ?? `#${id}`} - setC({ product_ids: (c.product_ids || []).filter(x => x !== id) })}> + setC({ product_ids: (c.product_ids || []).filter(x => x !== id), exclude_ids: (c.exclude_ids || []).filter(x => x !== id) })}> ))}
@@ -95,22 +110,9 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [ )}
} - {(c.exclude_ids || []).length > 0 && ( -
- {t('signage.menu.hidden')} -
- {(c.exclude_ids || []).map(id => ( - - ))} -
-
- )} - {/* the board's own order, badges, hiding */} + {/* the board's own order, badges, hiding (hidden ones stay here, greyed) */}

{t('signage.menu.orderHint')}

@@ -124,24 +126,31 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
)}
    - {g.items.map((it, ii) => ( -
  • - {it.name} - {it.price != null && {formatMoney(it.price)}} - { + const next = { ...badges } + if (e.target.value) next[String(it.id)] = e.target.value + else delete next[String(it.id)] + setC({ badges: next }) + }} + options={[{ value: '', label: t('signage.menu.noBadge') }, ...BADGES.map(b => ({ value: b, label: t(`signage.badges.${b}`) }))]} /> + reorder(moveItem(groups, gi, ii, -1))} data-testid="signage-item-up"> + reorder(moveItem(groups, gi, ii, 1))}> + setC({ exclude_ids: toggled(c.exclude_ids, it.id) })}> + {off ? : } + +
  • + ) + })}
))} @@ -175,34 +184,39 @@ 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) */}
-
+
- setC({ columns: Number(v) })} data-testid="signage-columns" fill + 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}` }))} /> - setC({ board_width: v })} testid="signage-menu-width" /> - = 100 ? t('signage.menu.placeHint') : undefined}> - setC({ board_align: v })} data-testid="signage-menu-align" fill - options={[['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight]].map(([v, Icon]) => ( - { value: v, icon:
- setC({ accent_colour: v })} testid="signage-accent" /> + setC({ accent_colour: v })} testid="signage-accent" /> - setC({ background })} media={media} onMedia={onMedia} - misfit={misfit.includes(c.background?.media_id)} /> - setC({ widgets })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} /> + {!board && <> + setC({ background })} media={media} onMedia={onMedia} + misfit={misfit.includes(c.background?.media_id)} /> + setC({ widgets })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} + extras={extras} /> + } ) } diff --git a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx index a158536..6b683e1 100644 --- a/manager_dashboard/src/pages/signage/PlaylistEditor.jsx +++ b/manager_dashboard/src/pages/signage/PlaylistEditor.jsx @@ -18,7 +18,7 @@ import { mediaEntry, mediaLookup, misfits, moved, slideBody, totalSeconds, TRANS import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' import SlideEditor, { SlideBasics } from './SlideEditor' 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). */ 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])) } }) api.previewVenue().then(setVenue).catch(() => {}) }, [load]) - useMenuPreview(draft, setDraft) + useSlidePreview(draft, setDraft, more => setMedia(m => ({ ...m, ...more }))) const saved = pl?.slides.find(s => s.id === selected) const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved]) diff --git a/manager_dashboard/src/pages/signage/SignageFields.jsx b/manager_dashboard/src/pages/signage/SignageFields.jsx index 125b0f4..02733ce 100644 --- a/manager_dashboard/src/pages/signage/SignageFields.jsx +++ b/manager_dashboard/src/pages/signage/SignageFields.jsx @@ -1,7 +1,9 @@ // 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), // 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 { useTranslation } from '@xenia/i18n' 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 }) { return ( - + onChange(Number(e.target.value))} className="flex-1 min-w-0 accent-accent" aria-label={label} data-testid={testid} /> {value}{suffix} @@ -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 - * ready colours with one click, and the picker for any other (2026-11-21). */ -export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS }) { + * ready colours with one click, and the picker for any other (2026-11-21). `compact`: a field + * (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() + if (compact) return return (
{label} @@ -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 ( + +
+ + {open && ( +
+
+ {presets.map(c => ( +
+ +
+ )} +
+
+ ) +} + /** 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' }) { const { t } = useTranslation('manager') diff --git a/manager_dashboard/src/pages/signage/SlideEditor.jsx b/manager_dashboard/src/pages/signage/SlideEditor.jsx index ec193cd..e49c922 100644 --- a/manager_dashboard/src/pages/signage/SlideEditor.jsx +++ b/manager_dashboard/src/pages/signage/SlideEditor.jsx @@ -5,6 +5,8 @@ // Reworked 2026-11-21 (owner review): name | show this slide, transition effect | seconds; the // text's look on one row (alignment, height, font, size) and its colour with ready colours under // it; sections with a title and a line; blank slides (a background and widgets). +// 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 { useTranslation } from '@xenia/i18n' 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 setC = patch => set({ content: { ...c, ...patch } }) const bad = id => misfit.includes(id) - const widgets = setC({ widgets: ws })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} /> + const widgets = setC({ widgets: ws })} media={media} onMedia={onMedia} selected={widget} onSelect={onWidget} extras={slide.extras} /> const fit = ( setC({ fit: v })} @@ -127,21 +129,21 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit = {widgets} } - {slide.kind === 'menu' && } + {slide.kind === 'menu' && }
) } /** - * The look of a text: alignment, height, font and size on one row, its colour (ready colours and - * the picker) under them. A menu board (`align` off) has no alignment / height; it passes its - * accent colour as `children`, beside the text's colour. + * The look of a text, all on one row (owner review 2, 2026-11-21): horizontal and vertical + * alignment, font, size and colour (a field that opens the ready colours and the picker). A menu + * 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 }) { const { t } = useTranslation('manager') return (
-
+
{align && <> setC({ align: v })} data-testid="signage-align" fill @@ -160,9 +162,7 @@ export function TextLook({ c, setC, align = true, children }) { setC({ text_size: v })} testid="signage-text-size" /> -
-
- setC({ text_colour: v })} testid="signage-text-colour" /> + setC({ text_colour: v })} testid="signage-text-colour" /> {children}
diff --git a/manager_dashboard/src/pages/signage/SlidesTab.jsx b/manager_dashboard/src/pages/signage/SlidesTab.jsx index 96b6e3e..ee0d2bd 100644 --- a/manager_dashboard/src/pages/signage/SlidesTab.jsx +++ b/manager_dashboard/src/pages/signage/SlidesTab.jsx @@ -15,7 +15,7 @@ import { mediaEntry, mediaLookup, misfits, savedBody } from './signageLogic' import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' import SlideEditor, { SlideBasics } from './SlideEditor' import SlidePreview from './SlidePreview' -import { useMenuPreview, useWidgetEditor } from './useSlideDraft' +import { useSlidePreview, useWidgetEditor } from './useSlideDraft' export default function SlidesTab({ open, onOpen }) { 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 || {}) }) .catch(err => { toast.error(errorMessage(err, t)); onClose() }) }, [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 draftBad = useMemo(() => (draft ? misfits([draft], media, draft.orientation)[draft.id] || [] : []), [draft, media]) if (!draft) return
diff --git a/manager_dashboard/src/pages/signage/WidgetCanvas.jsx b/manager_dashboard/src/pages/signage/WidgetCanvas.jsx index 4f7d1a4..c71515a 100644 --- a/manager_dashboard/src/pages/signage/WidgetCanvas.jsx +++ b/manager_dashboard/src/pages/signage/WidgetCanvas.jsx @@ -4,13 +4,17 @@ // slide's edges and middle lines (shown while it does). A widget moved or sized this way gets // position and size "custom" and its own box (% of the slide), which the TV draws the same. // It lies over SlidePreview's box and finds each widget by its `data-widget` (@xenia/signage). -import { useLayoutEffect, useRef, useState } from 'react' +// 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 { boxFromRect, moveBox, resizeBox, snapBox } from './signageLogic' const HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] const CURSOR = { n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize' } const SIZE = 14 // a handle, px +// 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 }) { const { t } = useTranslation('manager') @@ -65,21 +69,28 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl window.addEventListener('pointerup', up) } - const key = e => { - if (selected == null) return - if (e.key === 'Escape') { onSelect(null); return } - const step = e.shiftKey ? 2 : 0.5 - const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key] - if (!d) return - e.preventDefault() - const w = widgets[selected] - const base = w?.position === 'custom' && w.box ? w.box : rects[selected] - if (base) onPlace(selected, moveBox(base, d[0], d[1])) - } + // the keys, on the whole page while a widget is picked + 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 } + const step = e.shiftKey ? 2 : 0.5 + const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key] + if (!d) return + e.preventDefault() + const w = widgets[selected] + const base = w?.position === 'custom' && w.box ? w.box : rects[selected] + if (base) onPlace(selected, moveBox(base, d[0], d[1])) + } + 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 return ( -
onSelect(null)} +
onSelect(null)} role="application" aria-label={label} data-testid="signage-canvas"> {widgets.map((w, i) => rects[i] && (
(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 [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 add = kind => { - onChange([...widgets, { kind, position: kind === 'message' ? 'bottom-bar' : 'top-right', size: 'medium', align: 'auto' }]) + onChange([...widgets, newWidget(kind)]) 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 && ( + ))} - {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]) => { + if (w.position === 'custom') { + return ( +
+
+ {body} +
+
+ ) + } const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {} return ( -
+
{body}
) })} - {shown.filter(([w]) => w.position === 'custom' && w.box).map(([w, i, body]) => ( -
-
- {body} -
-
- ))} ) } @@ -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 - * 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 x = extras[path] || {} const s = SIZE[w.size] || 1 const unit = (height, width) => (fit ? fitUnit(height, width) : n => `${+(n * s).toFixed(3)}cqmin`) const text = (u, size, weight = 700) => ({ fontSize: u(size), fontWeight: weight, lineHeight: 1.15, textShadow: '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)', whiteSpace: fit ? 'nowrap' : undefined }) + const line = (str, testid, weight) => { + const u = unit(3.4 * 1.15, textWidth(str.length, 3.4)) + return {str} + } + // 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 : ( +
{body}
+ )) if (w.kind === 'logo') { const m = media(w.media_id) 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)) return {venue.name} } - if (w.kind === 'date') { - const str = formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong') - const u = unit(3.4 * 1.15, textWidth(str.length, 3.4)) - return {str} - } + if (w.kind === 'date') return line(formatDate(now, w.date_style === 'short' ? 'date' : 'dateLong'), 'signage-w-date') if (w.kind === 'clock') { const u = unit(4.6 * 1.15, textWidth(w.clock_seconds ? 8 : 5, 4.6)) // its usual width: the size stays as the minutes turn return {formatTime(now, w.clock_seconds ? 'timeSeconds' : 'time')} } if (w.kind === 'message') { const msg = w.text || venue?.message - if (!msg) return null - const u = unit(3.4 * 1.15, textWidth(msg.length, 3.4)) - return {msg} + return msg ? line(msg, 'signage-w-message', 600) : null } + if (w.kind === 'text') return w.text ? line(w.text, 'signage-w-text', 600) : null 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 u = unit(16 + caption, Math.max(16, w.qr_caption ? textWidth(w.qr_caption.length, 2.4) : 0)) return ( -
+
- +
{w.qr_caption && {w.qr_caption}}
) } - if (w.kind === 'weather') { - const wx = venue?.weather - if (!wx || wx.temperature == null) return null // no internet / no place: hidden (5.4c) - const Icon = ICONS[weatherIcon(wx.code, wx.is_day)] || Cloud - const deg = wx.units === 'fahrenheit' ? '°F' : '°C' - const days = (w.weather_days || 1) > 1 ? (wx.days || []).slice(1, w.weather_days) : [] - const u = unit(6, 6 + 1.5 + textWidth(4, 4.4) + days.length * (1.5 + 3.4 + textWidth(12, 2.4))) - return ( -
-
- ) - } + if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate) + if (w.kind === 'menu') return boxed(, 'menu') + if (w.kind === 'stack') return boxed(, '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) + const from = w.weather_from || 0 + const style = w.weather_style || 'both' + const pic = style !== 'text' + 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 ( +
+ {pic &&
+ ) +} + +/** + * 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 ( +
+ {b.title &&
{b.title}
} +
+ +
+
+ ) +} + +/** + * 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 ( +
+ {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 ( +
+ {body && ( +
{body}
+ )} + {slide && Embed && } +
+ ) + })} +
+ ) +} + const ICONS = { sun: Sun, moon: Moon, 'cloud-sun': CloudSun, 'cloud-moon': CloudMoon, cloud: Cloud, fog: CloudFog, rain: CloudRain, snow: CloudSnow, storm: CloudLightning } diff --git a/packages/signage/src/logic.js b/packages/signage/src/logic.js index f23c968..43c5c0c 100644 --- a/packages/signage/src/logic.js +++ b/packages/signage/src/logic.js @@ -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, descriptions: c.show_descriptions, title: !!c.title, bars }) const per = c.page_size || rows * (c.columns || 2) - return menuPages(slide.menu?.groups || [], per, c.category_titles !== false) + 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) ───────────────────────────────── @@ -254,6 +260,28 @@ export function boardPages(slide, rotation, w, h) { /** The slide kinds that carry widgets. */ 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. */ export function widgetAlign(w) { if (w?.align && w.align !== 'auto') return w.align diff --git a/packages/signage/tests/logic.test.mjs b/packages/signage/tests/logic.test.mjs index d9d9d37..b62dc47 100644 --- a/packages/signage/tests/logic.test.mjs +++ b/packages/signage/tests/logic.test.mjs @@ -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 } } 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]) +}) diff --git a/packages/ui/src/components.css b/packages/ui/src/components.css index f06c1fb..19e4b11 100644 --- a/packages/ui/src/components.css +++ b/packages/ui/src/components.css @@ -347,6 +347,8 @@ box-sizing: border-box; min-height: var(--x-control-md); padding: var(--x-space-2) var(--x-space-3); background: var(--x-surface); border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control); } +.x-switch-row--boxed { 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-confirm__body { font-size: var(--x-text-body); line-height: var(--x-leading-body); color: var(--x-ink-2); } diff --git a/packages/ui/src/components/Switch.jsx b/packages/ui/src/components/Switch.jsx index 1f6eb84..ac0b570 100644 --- a/packages/ui/src/components/Switch.jsx +++ b/packages/ui/src/components/Switch.jsx @@ -7,7 +7,8 @@ import { cx } from '../internal/cx.js' * onChange receives the new boolean. Without `label`, pass aria-label. * The whole row (label + description) is clickable. * info: an element right after the label (an ), 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 }) { const auto = useId() @@ -21,9 +22,10 @@ export function Switch({ checked, onChange, label, description, info, disabled = role="switch" aria-checked={!!checked} aria-describedby={description ? descId : undefined} + aria-label={boxed && typeof label === 'string' ? label : undefined} disabled={disabled} className={cx('x-switch', checked && 'x-switch--on')} - onClick={() => onChange?.(!checked)} + onClick={boxed ? undefined : () => onChange?.(!checked)} {...rest} > @@ -32,11 +34,14 @@ export function Switch({ checked, onChange, label, description, info, disabled = if (!label && !description) return {control} return ( -
+
onChange?.(!checked) : undefined}>
{label && ( - + {boxed + ? {label} + : } {info} )} diff --git a/tests/e2e/signage.mjs b/tests/e2e/signage.mjs index ad8633d..09d1d4e 100644 --- a/tests/e2e/signage.mjs +++ b/tests/e2e/signage.mjs @@ -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.exclude_ids?.includes(hiddenId) && mc.category_order?.[0] === catB.id && mc.badges?.[String(badgeId)] === 'offer' && (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 })) 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 ── await mgr.getByTestId('signage-preview-box').scrollIntoViewIfNeeded() await sleep(300)