feat(signage): venue badges, widgets' own look, widgets placed inside stacks, Save and leave, shared controls (owner review 5)

- Badges: the venue's list (setting signage.badges: names el/en, colours, an icon from a food and
  drink set) edited under Signage -> "Message & settings"; sent with the venue to screens and
  previews; several badges per product (MenuList.badges lists, a single one still read) in the
  shared multiple Dropdown; a board's badge colour / text colour override them (None = each own).
- Widgets: colour, background plate, font, bold / italic / underline, text size, QR colours;
  widgets in a stack's part get every setting, vertical alignment, and a custom box inside their
  place, picked (stack, then widget) and dragged on the preview (selection by path "2.1.0").
- Menu slides: vertical alignment of the list (board_valign); "Where the list sits" is now
  "Horizontal alignment".
- Message of the day: one component in the settings tab, on the Overview and from its widget.
- Leaving a slide with changes: "Save and leave" (ConfirmDialog altLabel).
- @xenia/ui: ColourField (with colour.js helpers), FieldRow (framed only while wrapped), Slider,
  IconPicker, Segmented multiple; native selects on the Overview and signage replaced by Dropdown,
  the device settings' colour input by ColourField.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 14:17:27 +02:00
co-authored by Claude Opus 5.5
parent aaa0914778
commit aa3fe85053
51 changed files with 1378 additions and 432 deletions
+6 -1
View File
@@ -49,6 +49,11 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| Search | `SearchInput` | icon, clear button; `onChange(text)` | | Search | `SearchInput` | icon, clear button; `onChange(text)` |
| Choose one / several | `Dropdown` (`multiple`) | **never a native `<select>` in a toolbar.** Multi: value is an array, `[]` = all (`allLabel`). Options can carry a `dot` (a zone's colour) and a `hint`. Search box from 9 options. Same heights as `Input`. Native `Select` stays only inside forms where the phone's own picker is better | | Choose one / several | `Dropdown` (`multiple`) | **never a native `<select>` in a toolbar.** Multi: value is an array, `[]` = all (`allLabel`). Options can carry a `dot` (a zone's colour) and a `hint`. Search box from 9 options. Same heights as `Input`. Native `Select` stays only inside forms where the phone's own picker is better |
| A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) | | A small panel under a button | `Popover` (`open`, `anchor` = the button's ref, `onClose`) | a colour picker, an "Add…" menu. Drawn over everything (portal), flips above, stays inside the window: **never an `absolute` panel inside a section** (it is clipped and makes the section scroll) |
| A colour (a venue's: data) | `ColourField` (`auto`, `opacity`, `presets`) | a field with its swatch and code; its panel (over the page) has 12 ready colours, the picker, the opacity (`#rrggbbaa`) and the code. `auto` = a first choice that leaves it to something else ("As the slide"). **Never** a bare `<input type="color">` |
| An icon from a set | `IconPicker` (`icons` = { key: component }) | a field showing the icon; a grid of the set over the page, "No icon" first |
| A slider with its value | `Slider` (`suffix`) | framed and as tall as the fields beside it |
| Fields that should wrap | `FieldRow` (`min`, `shade` on every other row) | each field keeps its least width; a row that wraps is framed (and tinted with `shade`), a row on one line looks like any row |
| Toggles that go together (bold / italic / underline) | `Segmented multiple` | value is an array |
| A toggle filter (a state) | `FilterChip` (`tone`, `count`) | | | A toggle filter (a state) | `FilterChip` (`tone`, `count`) | |
| Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) | | Two or three views (List / Map / QR) | `Segmented` | the view in the address (`?view=`) |
| Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) | | Sections of a page or a dialog | `Tabs` (`size="lg"` on pages) | scrolls sideways only, never up/down. `inset`: the strip is a card's header (card padding at the sides, the same room above and below a button in `end`, the labels level with it, no line under it). `fill`: the tabs share the width equally (a narrow column) |
@@ -58,7 +63,7 @@ Every page is on `<Page>` except Inventory → Stock (a placeholder). Two-column
| A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) | | A quiet text action that warns | `Button variant="ghost" tone="danger"` | grey text, red under the pointer ("Remove" a picture) |
| A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline | | A switch on its own in a row of buttons | `Switch` without a label | lines up with the buttons (centred), never with a text baseline |
| Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` | | Dialogs | `Dialog` `sm` 400 · `md` 520 · `lg` 720 · `xl` 920 · `wide` (~88 % of a 16:9 screen, capped on ultrawides) | the day summary is `xl`, the product editor `wide` |
| Ask before doing something (delete, leave unsaved work) | `useConfirm()` → `confirm({ title, body, confirmLabel, tone })` (or `ConfirmDialog`) | **never the browser's `window.confirm`**; render the returned dialog in the component | | 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. Leaving unsaved work: add `altLabel` ("Save and leave"): the promise answers `'alt'` |
| 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 | | 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` |
+69 -12
View File
@@ -75,7 +75,7 @@ WidgetKind = Literal["logo", "name", "date", "clock", "message", "qr", "weather"
Position = Literal["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right", "top-bar", "bottom-bar", "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"] BADGE_KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$" # a badge of the venue's list (services/signage_badges.py)
Align = Literal["left", "center", "right"] Align = Literal["left", "center", "right"]
@@ -124,7 +124,7 @@ class MenuList(_Strict):
sales_point: Optional[str] = "in_store" # whose prices; None = no prices sales_point: Optional[str] = "in_store" # whose prices; None = no prices
show_photos: bool = False show_photos: bool = False
show_descriptions: bool = False show_descriptions: bool = False
badges: Dict[str, Badge] = Field(default_factory=dict) # product id → badge badges: Dict[str, List[str]] = Field(default_factory=dict) # product id → its badges (keys of the venue's list; up to 4)
sold_out: Literal["strike", "hide"] = "strike" sold_out: Literal["strike", "hide"] = "strike"
language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed language: Optional[Literal["el", "en"]] = None # 6.4: the menu's language on this board; None = as typed
# pages (the player pages through what doesn't fit, 5.5b) # pages (the player pages through what doesn't fit, 5.5b)
@@ -133,8 +133,9 @@ class MenuList(_Strict):
page_seconds: int = Field(default=10, ge=3, le=120) page_seconds: int = Field(default=10, ge=3, le=120)
font: Font = "sans" font: Font = "sans"
text_colour: str = Field(default="#ffffff", pattern=HEX) text_colour: str = Field(default="#ffffff", pattern=HEX)
accent_colour: str = Field(default="#f59e0b", pattern=HEX) # badges, page dots (headings and prices unless their own) accent_colour: str = Field(default="#f59e0b", pattern=HEX) # page dots; headings and prices until their own
badge_text_colour: Optional[str] = Field(default=None, pattern=HEX) # None: white or black, to read on the badge badge_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (the venue's list)
badge_text_colour: Optional[str] = Field(default=None, pattern=HEX) # None: each badge its own (else white / black)
text_size: int = Field(default=100, ge=50, le=250) text_size: int = Field(default=100, ge=50, le=250)
# the look of each part (owner review 3, 2026-11-21) # the look of each part (owner review 3, 2026-11-21)
heading_style: TextStyle = Field(default_factory=TextStyle) heading_style: TextStyle = Field(default_factory=TextStyle)
@@ -162,12 +163,23 @@ class MenuList(_Strict):
raise ValueError(f"one of {', '.join(sales_points.ALL)}") raise ValueError(f"one of {', '.join(sales_points.ALL)}")
return v return v
@field_validator("badges") @field_validator("badges", mode="before")
@classmethod @classmethod
def _badge_keys(cls, v): def _badge_keys(cls, v):
if any(not k.isdigit() for k in v): import re as _re
raise ValueError("badges are keyed by product id") if not isinstance(v, dict):
return v return v
out = {}
for k, x in v.items():
if not str(k).isdigit():
raise ValueError("badges are keyed by product id")
keys = [x] if isinstance(x, str) else list(x or []) # one badge (before owner review 5) or several
keys = list(dict.fromkeys(str(b) for b in keys))
if len(keys) > 4 or any(not _re.match(BADGE_KEY, b) for b in keys):
raise ValueError("up to 4 badges of the venue's list")
if keys:
out[str(k)] = keys
return out
class Box(_Strict): class Box(_Strict):
@@ -237,6 +249,17 @@ class Widget(_Strict):
weather_from: int = Field(default=0, ge=0, le=2) # 0 today (now), 1 tomorrow, 2 the day after 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 weather_style: Literal["both", "icon", "text"] = "both" # picture and degrees, the picture, the degrees
board: Optional[MenuList] = None # menu: what it lists and how board: Optional[MenuList] = None # menu: what it lists and how
# its look (owner review 5, 2026-11-21): None = the slide's
vertical: Literal["auto", "top", "middle", "bottom"] = "auto" # inside its place (a stack's part, its box)
colour: Optional[str] = Field(default=None, pattern=HEX) # its text and pictures (weather, clock…)
background_colour: Optional[str] = Field(default=None, pattern=HEX) # a plate behind it
font: Optional[Font] = None
bold: Optional[bool] = None # None: as the widget usually is
italic: bool = False
underline: bool = False
text_size: int = Field(default=100, ge=50, le=200) # % of its usual text
qr_colour: Optional[str] = Field(default=None, pattern=HEX) # the code's dots (default black)
qr_background: Optional[str] = Field(default=None, pattern=HEX) # around them (default white)
direction: Literal["row", "column"] = "row" # stack: side by side / one over the other direction: Literal["row", "column"] = "row" # stack: side by side / one over the other
cells: List[Cell] = Field(default_factory=list, max_length=6) cells: List[Cell] = Field(default_factory=list, max_length=6)
@@ -316,6 +339,7 @@ class MenuContent(MenuList):
with its widgets.""" with its widgets."""
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
board_valign: Literal["top", "middle", "bottom"] = "top" # where a shorter list sits (owner review 5)
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)
@@ -1116,8 +1140,7 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]}, out = {"screen": {"id": dev.id, "name": dev.name, "orientation": cfg["orientation"], "rotation": cfg["rotation"]},
"playlist": playlist, "schedule": schedule, "playlists": playlists, "playlist": playlist, "schedule": schedule, "playlists": playlists,
# for the widgets (5.4c): weather None = hide it (no internet, no place, too old) # for the widgets (5.4c): weather None = hide it (no internet, no place, too old)
"venue": {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "venue": _venue(db)}
"weather": weather.current(db)}}
out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16] out["version"] = hashlib.sha256(json.dumps(out, sort_keys=True, default=str).encode()).hexdigest()[:16]
return out return out
@@ -1217,6 +1240,33 @@ def put_message(body: MessageBody, db: Session = Depends(get_db), user=Depends(r
return {"text": (body.text or "").strip() or None} return {"text": (body.text or "").strip() or None}
class BadgesBody(BaseModel):
badges: list = Field(default_factory=list)
@router.get("/badges")
def get_badges(db: Session = Depends(get_db), user=Depends(require(KEY))):
"""The badges boards can put on products (owner review 5), with the icons they may have."""
from services import signage_badges
return {"badges": signage_badges.load(db), "icons": list(signage_badges.ICONS)}
@router.put("/badges")
def put_badges(body: BadgesBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""The venue's badges, all at once: their names, colours (the boards' defaults) and icons."""
from pydantic import ValidationError
from services import signage_badges
try:
parsed = signage_badges.BadgeList(badges=body.badges)
except ValidationError as e:
first = e.errors()[0]
raise XeniaError("signage.content_invalid", field=".".join(str(x) for x in first.get("loc", ())), reason=first.get("msg", ""))
out = signage_badges.save(db, parsed.badges)
db.commit()
tell_all_screens(db)
return {"badges": out, "icons": list(signage_badges.ICONS)}
@router.get("/weather") @router.get("/weather")
def weather_status(db: Session = Depends(get_db), user=Depends(require(KEY))): def weather_status(db: Session = Depends(get_db), user=Depends(require(KEY))):
from services import weather from services import weather
@@ -1273,8 +1323,15 @@ class MenuPreviewBody(BaseModel):
@router.get("/venue") @router.get("/venue")
def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))): def preview_venue(db: Session = Depends(get_db), user=Depends(require(KEY))):
"""What the widgets show (the same as a screen gets), for the editor's previews.""" """What the widgets show (the same as a screen gets), for the editor's previews."""
from services import weather return _venue(db)
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None, "weather": weather.current(db)}
def _venue(db) -> dict:
"""What the widgets need of the venue: its name, the message of the day, the weather (None = hide
it: no internet, no place, too old) and its badges (owner review 5)."""
from services import signage_badges, weather
return {"name": _setting(db, "venue.name") or None, "message": _setting(db, MESSAGE) or None,
"weather": weather.current(db), "badges": signage_badges.load(db)}
class SlidePreviewBody(BaseModel): class SlidePreviewBody(BaseModel):
+104
View File
@@ -0,0 +1,104 @@
"""The badges a menu board can put on a product (owner review 5, 2026-11-21): the venue's own list,
kept in the setting `signage.badges` (JSON), edited under Signage → Message & settings. Each badge
has a key (what boards store), its name in Greek and English, its colours (background, text: None =
white or black, whichever reads) and an icon (a name from ICONS, drawn by @xenia/signage). Its
colours are the defaults: a board may give all its badges one colour of its own.
Until the venue changes it, the list is DEFAULTS (the seven badges boards had before)."""
from __future__ import annotations
import json
import re
from typing import Dict, List, Optional
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
SETTING = "signage.badges"
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"
KEY = r"^[a-z0-9][a-z0-9_-]{0,23}$"
# the icons a badge can have (lucide names; @xenia/signage BADGE_ICONS draws the same list)
ICONS = (
"sparkles", "chef-hat", "tag", "star", "flame", "sprout", "leaf", "vegan", "wheat", "wheat-off", "fish", "shrimp", "beef",
"drumstick", "egg", "milk", "nut", "carrot", "salad", "pizza", "hamburger", "sandwich", "soup", "croissant",
"ice-cream-cone", "cake-slice", "coffee", "cup-soda", "wine", "beer", "martini", "glass-water", "citrus", "cherry",
"apple", "heart", "award", "thumbs-up", "clock", "percent", "gift", "crown", "zap", "snowflake",
)
DEFAULTS = [
{"key": "new", "names": {"el": "Νέο", "en": "New"}, "colour": "#22c55e", "text_colour": None, "icon": "sparkles"},
{"key": "chef", "names": {"el": "Πρόταση σεφ", "en": "Chef's pick"}, "colour": "#f59e0b", "text_colour": None, "icon": "chef-hat"},
{"key": "offer", "names": {"el": "Προσφορά", "en": "Offer"}, "colour": "#ef4444", "text_colour": None, "icon": "tag"},
{"key": "popular", "names": {"el": "Δημοφιλές", "en": "Popular"}, "colour": "#f472b6", "text_colour": None, "icon": "star"},
{"key": "spicy", "names": {"el": "Καυτερό", "en": "Spicy"}, "colour": "#dc2626", "text_colour": None, "icon": "flame"},
{"key": "vegetarian", "names": {"el": "Χορτοφαγικό", "en": "Vegetarian"}, "colour": "#16a34a", "text_colour": None, "icon": "sprout"},
{"key": "vegan", "names": {"el": "Vegan", "en": "Vegan"}, "colour": "#15803d", "text_colour": None, "icon": "vegan"},
]
class BadgeDef(BaseModel):
model_config = ConfigDict(extra="forbid")
key: str = Field(pattern=KEY)
names: Dict[str, str] = Field(default_factory=dict)
colour: str = Field(default="#f59e0b", pattern=HEX)
text_colour: Optional[str] = Field(default=None, pattern=HEX)
icon: Optional[str] = None
@field_validator("names")
@classmethod
def _names(cls, v):
out = {k: " ".join(str(x).split())[:24] for k, x in v.items() if k in ("el", "en")}
out = {k: x for k, x in out.items() if x}
if not out:
raise ValueError("a badge has a name")
return out
@field_validator("icon")
@classmethod
def _icon(cls, v):
if v is not None and v not in ICONS:
raise ValueError("an icon of the list")
return v
class BadgeList(BaseModel):
model_config = ConfigDict(extra="forbid")
badges: List[BadgeDef] = Field(default_factory=list, max_length=30)
@model_validator(mode="after")
def _unique(self):
keys = [b.key for b in self.badges]
if len(set(keys)) != len(keys):
raise ValueError("each badge has its own key")
return self
def load(db) -> list[dict]:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
if row is None or not row.value:
return [dict(b) for b in DEFAULTS]
try:
return BadgeList(badges=json.loads(row.value)).model_dump()["badges"]
except Exception: # noqa: BLE001 — a broken setting falls back to the defaults
return [dict(b) for b in DEFAULTS]
def save(db, badges: list[BadgeDef]) -> list[dict]:
from models.settings import PosSettings
value = json.dumps([b.model_dump() for b in badges], ensure_ascii=False)
row = db.query(PosSettings).filter(PosSettings.key == SETTING).first()
if row is None:
db.add(PosSettings(key=SETTING, value=value))
else:
row.value = value
return [b.model_dump() for b in badges]
def new_key(name: str, taken: set) -> str:
"""A key for a new badge from its name (the editor makes its own; kept for scripts)."""
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:20] or "badge"
key, n = base, 2
while key in taken:
key, n = f"{base}-{n}", n + 1
return key
+2 -2
View File
@@ -80,7 +80,7 @@ def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> dict:
return (prod_rank(p.id), member_order.get((p.primary_category_id, p.id), p.sort_order or 0), (p.name or "").lower()) return (prod_rank(p.id), member_order.get((p.primary_category_id, p.id), p.sort_order or 0), (p.name or "").lower())
prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {} prices = dict(zip([p.id for p in products], unit_prices(db, products, point, now=now))) if point and products else {}
badges = {int(k): v for k, v in (content.get("badges") or {}).items() if str(k).isdigit()} badges = {int(k): ([v] if isinstance(v, str) else list(v or [])) for k, v in (content.get("badges") or {}).items() if str(k).isdigit()}
lang = content.get("language") # 6.4: the board's language; None = the base texts lang = content.get("language") # 6.4: the board's language; None = the base texts
@@ -102,7 +102,7 @@ def resolve(db, content: dict, now=None, keep_hidden: bool = False) -> 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), **({"hidden": True} if p.id in excluded else {})} "badges": badges.get(p.id) or [], **({"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 = {}
+4 -3
View File
@@ -97,7 +97,7 @@ def test_prices_sold_out_badges_photos(client, owner_h, tv, menu, db):
badges={str(menu["souvlaki"].id): "chef"}) badges={str(menu["souvlaki"].id): "chef"})
_, m = board(client, owner_h, tv, **content) _, m = board(client, owner_h, tv, **content)
souv, steak = m["groups"][0]["items"] souv, steak = m["groups"][0]["items"]
assert (souv["price"], souv["badge"], souv["description"], souv["image"]) == (3.5, "chef", "Pork, on a stick", photo["urls"]["card"]) assert (souv["price"], souv["badges"], souv["description"], souv["image"]) == (3.5, ["chef"], "Pork, on a stick", photo["urls"]["card"])
assert steak["available"] is False and steak["price"] == 12.0 and steak["image"] is None assert steak["available"] is False and steak["price"] == 12.0 and steak["image"] is None
_, m = board(client, owner_h, tv, **content, sold_out="hide") _, m = board(client, owner_h, tv, **content, sold_out="hide")
assert [i["name"] for i in m["groups"][0]["items"]] == ["Souvlaki"] assert [i["name"] for i in m["groups"][0]["items"]] == ["Souvlaki"]
@@ -136,7 +136,7 @@ def test_menu_settings_are_checked(client, owner_h, tv):
url = f"/api/signage/playlists/{tv['playlist']}/slides" url = f"/api/signage/playlists/{tv['playlist']}/slides"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"sales_point": "moon"}})) == "signage.content_invalid" assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"sales_point": "moon"}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"x": "new"}}})) == "signage.content_invalid" assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"x": "new"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "shiny"}}})) == "signage.content_invalid" assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"badges": {"3": "Shiny!"}}})) == "signage.content_invalid"
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid" assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": {"columns": 4}})) == "signage.content_invalid"
@@ -148,4 +148,5 @@ def test_the_editor_previews(client, owner_h, tv, menu):
assert names(draft["menu"]) == [["Grill", ["Steak"]]] and draft["content"]["columns"] == 2 assert names(draft["menu"]) == [["Grill", ["Steak"]]] and draft["content"]["columns"] == 2
assert err(client.post("/api/signage/preview/menu", headers=owner_h, json={"content": {"columns": 9}})) == "signage.content_invalid" assert err(client.post("/api/signage/preview/menu", headers=owner_h, json={"content": {"columns": 9}})) == "signage.content_invalid"
client.put("/api/signage/message", headers=owner_h, json={"text": "Hello"}) client.put("/api/signage/message", headers=owner_h, json={"text": "Hello"})
assert client.get("/api/signage/venue", headers=owner_h).json() == {"name": None, "message": "Hello", "weather": None} v = client.get("/api/signage/venue", headers=owner_h).json()
assert {k: v[k] for k in ("name", "message", "weather")} == {"name": None, "message": "Hello", "weather": None} and len(v["badges"]) == 7
@@ -141,3 +141,35 @@ def test_a_part_holds_several_widgets_and_colours_can_be_see_through(client, own
assert m["badge_text_colour"] == "#fde68aCC" and m["accent_colour"] == "#1e3a8a" assert m["badge_text_colour"] == "#fde68aCC" and m["accent_colour"] == "#1e3a8a"
for bad in ({"badge_text_colour": "#fff"}, {"text_colour": "#12345"}): for bad in ({"badge_text_colour": "#fff"}, {"text_colour": "#12345"}):
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
def test_the_venues_badges_and_a_widgets_own_look(client, owner_h, menu, screens):
"""Owner review 5 (2026-11-21): the venue's badges (names, colours, icons) edited in one place and
sent with the venue; a product with several badges; a widget's own look; a board's list placed
up or down."""
got = client.get("/api/signage/badges", headers=owner_h).json()
assert [b["key"] for b in got["badges"]][:3] == ["new", "chef", "offer"] and "flame" in got["icons"]
mine = got["badges"][:2] + [{"key": "gluten-free", "names": {"el": "Χωρίς γλουτένη", "en": "Gluten free"}, "colour": "#0ea5e9", "text_colour": "#ffffff", "icon": "wheat-off"}]
r = client.put("/api/signage/badges", headers=owner_h, json={"badges": mine})
assert r.status_code == 200, r.text and [b["key"] for b in r.json()["badges"]] == ["new", "chef", "gluten-free"]
for bad in ([{"key": "x", "names": {}}], [{"key": "x", "names": {"en": "X"}, "icon": "unicorn"}],
[{"key": "x", "names": {"en": "X"}}, {"key": "x", "names": {"en": "Y"}}]):
assert err(client.put("/api/signage/badges", headers=owner_h, json={"badges": bad})) == "signage.content_invalid", bad
assert client.get("/api/signage/venue", headers=owner_h).json()["badges"][2]["icon"] == "wheat-off"
p = playlist(client, owner_h)
sid = str(menu["steak"].id)
s = slide(client, owner_h, p["id"], "menu", content={"product_ids": [menu["steak"].id], "badges": {sid: ["chef", "gluten-free"]},
"board_valign": "middle", "badge_colour": "#000000", "widgets": [
{"kind": "qr", "qr_colour": "#1e3a8a", "qr_background": "#fde68a", "colour": "#ff0000", "bold": False, "italic": True, "font": "serif", "text_size": 150,
"background_colour": "#00000080"},
stack({"share": 100, "widgets": [{"kind": "clock", "vertical": "bottom", "align": "right"},
{"kind": "date", "position": "custom", "box": {"x": 10, "y": 10, "w": 50, "h": 40}}]})]})
c = s["content"]
assert c["badges"] == {sid: ["chef", "gluten-free"]} and c["board_valign"] == "middle" and c["badge_colour"] == "#000000"
q = c["widgets"][0]
assert (q["qr_colour"], q["qr_background"], q["bold"], q["italic"], q["text_size"], q["font"]) == ("#1e3a8a", "#fde68a", False, True, 150, "serif")
part = c["widgets"][1]["cells"][0]["widgets"]
assert part[0]["vertical"] == "bottom" and part[1]["box"] == {"x": 10, "y": 10, "w": 50, "h": 40}
url = f"/api/signage/playlists/{p['id']}/slides"
for bad in ({"badges": {sid: ["a", "b", "c", "d", "e"]}}, {"board_valign": "centre"}, {"widgets": [{"kind": "clock", "text_size": 400}]}):
assert err(client.post(url, headers=owner_h, json={"kind": "menu", "content": bad})) == "signage.content_invalid", bad
@@ -9,7 +9,7 @@ import toast from 'react-hot-toast'
import { CalendarDays, Check, Pencil, Phone, Plus, Armchair, UserCheck, Users, X } from 'lucide-react' import { CalendarDays, Check, Pencil, Phone, Plus, Armchair, UserCheck, Users, X } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Spinner, Textarea } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, Spinner, Textarea } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { BOOKING_OFFSETS, bookingBody, offsetFrom, tableName, tablesByZone, venueWallClock } from './overviewLogic' import { BOOKING_OFFSETS, bookingBody, offsetFrom, tableName, tablesByZone, venueWallClock } from './overviewLogic'
@@ -168,14 +168,9 @@ export function BookingDialog({ tables, initial, onClose, onSaved }) {
))} ))}
</div> </div>
<Field label={t('overview.bookings.table')}> <Field label={t('overview.bookings.table')}>
<Select value={form.table_id ?? ''} onChange={e => set('table_id', e.target.value ? Number(e.target.value) : null)}> <Dropdown value={form.table_id != null ? String(form.table_id) : ''} onChange={v => set('table_id', v ? Number(v) : null)}
<option value="">{t('overview.bookings.noTable')}</option> options={[{ value: '', label: t('overview.bookings.noTable') },
{zones.map(z => ( ...zones.flatMap(z => z.tables.map(tb => ({ value: String(tb.id), label: tableName(tb), hint: z.zone })))]} />
<optgroup key={z.zone} label={z.zone}>
{z.tables.map(tb => <option key={tb.id} value={tb.id}>{tableName(tb)}</option>)}
</optgroup>
))}
</Select>
</Field> </Field>
<div className="grid grid-cols-2 gap-3"> <div className="grid grid-cols-2 gap-3">
<Field label={t('overview.bookings.phone')}><Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} /></Field> <Field label={t('overview.bookings.phone')}><Input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} /></Field>
@@ -8,7 +8,7 @@ import toast from 'react-hot-toast'
import { ArrowRight, Printer, X } from 'lucide-react' import { ArrowRight, Printer, X } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, IconButton, Spinner, cx } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery' import { useLiveQuery } from '../../live/useLiveQuery'
import { lineTotal, orderTotal } from './overviewLogic' import { lineTotal, orderTotal } from './overviewLogic'
@@ -99,7 +99,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
<span className="flex-1" /> <span className="flex-1" />
{printers.length > 0 && ( {printers.length > 0 && (
<span className="flex items-center gap-2"> <span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('overview.order.printer')} <Dropdown size="sm" value={printerId} onChange={setPrinterId} aria-label={t('overview.order.printer')}
placeholder={t('overview.order.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} /> placeholder={t('overview.order.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} <Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending}
onClick={() => print.mutate(Number(printerId))}>{t('overview.order.print')}</Button> onClick={() => print.mutate(Number(printerId))}>{t('overview.order.print')}</Button>
@@ -9,7 +9,7 @@ import { useContext, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query' import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { BarChart3, Eye, EyeOff, Lock, Play, Power } from 'lucide-react' import { BarChart3, Eye, EyeOff, Lock, Play, Power, Tv } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useCan, useModule } from '@xenia/access' import { useCan, useModule } from '@xenia/access'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
@@ -27,6 +27,7 @@ import { usePrintProblems } from '../orders/usePrintProblems'
import ShiftDialog from './ShiftDialog' import ShiftDialog from './ShiftDialog'
import ShiftsCard from './ShiftsCard' import ShiftsCard from './ShiftsCard'
import TablesCard from './TablesCard' import TablesCard from './TablesCard'
import MessageOfTheDay from '../signage/MessageOfTheDay'
import { dayKpis, dayOrders, hourBuckets, orderPairs, tableCards } from './overviewLogic' import { dayKpis, dayOrders, hourBuckets, orderPairs, tableCards } from './overviewLogic'
import { Card, HourBars, Money, Pill } from './parts' import { Card, HourBars, Money, Pill } from './parts'
import { SOLID } from './tones' import { SOLID } from './tones'
@@ -48,6 +49,8 @@ export default function OverviewPage() {
const notesOn = useCan('notes.use') && notesModule // what /api/notes checks (6.13b) const notesOn = useCan('notes.use') && notesModule // what /api/notes checks (6.13b)
const bookingsOn = useModule('reservations') const bookingsOn = useModule('reservations')
const chatOn = useModule('chat') const chatOn = useModule('chat')
const signageModule = useModule('signage')
const messageOn = useCan('signage.manage') && signageModule // the TVs' message of the day (owner review 5)
const [hidden, setHidden] = useState(readPrivacy) const [hidden, setHidden] = useState(readPrivacy)
const [order, setOrder] = useState(null) // { id, table } const [order, setOrder] = useState(null) // { id, table }
@@ -175,6 +178,14 @@ export default function OverviewPage() {
</Card> </Card>
</div> </div>
<div className="grid gap-5 min-w-0"> <div className="grid gap-5 min-w-0">
{messageOn && (
<Card title={<span className="flex items-center gap-2"><Tv size={18} className="text-ink-3" aria-hidden="true" />{t('overview.tvMessage.title')}</span>} testId="overview-message">
<div className="p-card grid gap-2">
<p className="text-label text-ink-3">{t('overview.tvMessage.hint')}</p>
<MessageOfTheDay testId="overview-message-input" />
</div>
</Card>
)}
{notesOn && <NotesCard />} {notesOn && <NotesCard />}
{bookingsOn && <BookingsCard tables={tables} onNew={() => setNewBooking(true)} />} {bookingsOn && <BookingsCard tables={tables} onNew={() => setNewBooking(true)} />}
{chatOn && <MessagesCard staff={staff} tables={tables} />} {chatOn && <MessagesCard staff={staff} tables={tables} />}
@@ -6,7 +6,7 @@ import toast from 'react-hot-toast'
import { BarChart3, Coffee, MessageSquare, Plus } from 'lucide-react' import { BarChart3, Coffee, MessageSquare, Plus } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { parseNumber, useFormat, useTranslation } from '@xenia/i18n' import { parseNumber, useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, cx } from '@xenia/ui' import { Button, Dialog, Dropdown, EmptyState, Field, IconButton, Input, cx } from '@xenia/ui'
import { Avatar, Card, Money, Pill } from './parts' import { Avatar, Card, Money, Pill } from './parts'
import { useDuration } from './hooks' import { useDuration } from './hooks'
@@ -75,7 +75,7 @@ function StartShiftDialog({ waiters, onClose, onStart }) {
</>}> </>}>
<div className="grid gap-3"> <div className="grid gap-3">
<Field label={t('overview.shifts.waiter')} error={error && !waiterId ? error : undefined}> <Field label={t('overview.shifts.waiter')} error={error && !waiterId ? error : undefined}>
<Select value={waiterId} onChange={e => { setWaiterId(e.target.value); setError(null) }} placeholder={t('overview.shifts.pick')} <Dropdown value={waiterId} onChange={v => { setWaiterId(v); setError(null) }} placeholder={t('overview.shifts.pick')}
options={waiters.map(w => ({ value: String(w.id), label: w.full_name || w.username }))} data-testid="shift-start-waiter" /> options={waiters.map(w => ({ value: String(w.id), label: w.full_name || w.username }))} data-testid="shift-start-waiter" />
</Field> </Field>
<Field label={t('overview.shifts.startCash')} hint={t('overview.shifts.startCashHint')} error={error && waiterId ? error : undefined}> <Field label={t('overview.shifts.startCash')} hint={t('overview.shifts.startCashHint')} error={error && waiterId ? error : undefined}>
@@ -5,7 +5,7 @@
// Used by the pair and edit dialogs of DevicesPage. // Used by the pair and edit dialogs of DevicesPage.
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Field, Input, Select, Switch } from '@xenia/ui' import { ColourField, Field, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { configGroups, configValue, refOptions } from './devicesLogic' import { configGroups, configValue, refOptions } from './devicesLogic'
@@ -64,10 +64,7 @@ export default function DeviceConfigFields({ appKey, fields = [], value, onChang
} }
if (f.type === 'color') { if (f.type === 'color') {
return ( return (
<Field key={f.key} label={label} hint={hint}> <ColourField key={f.key} label={label} hint={hint} value={v || '#000000'} onChange={c => set(f, c)} opacity={false} testId={`config-${f.key}`} />
<input type="color" value={v || '#000000'} onChange={e => set(f, e.target.value)} data-config={f.key}
className="h-10 w-16 rounded-control border border-line bg-surface cursor-pointer" />
</Field>
) )
} }
return ( return (
@@ -0,0 +1,102 @@
// The venue's badges for menu boards (owner review 5, 2026-11-21), under Signage → Message & settings:
// each with its name in Greek and English, its colours (background, text: "Automatic" = white or
// black, whichever reads) and an icon from a set for food and drink venues. Their colours are the
// defaults: a board may give all its badges a colour of its own (Text look). Saved all at once.
import { useEffect, useMemo, useState } from 'react'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useLanguage, useTranslation } from '@xenia/i18n'
import { BADGE_ICONS, badgeColours, badgeName } from '@xenia/signage'
import { Button, ColourField, Field, FieldRow, IconButton, IconPicker, Input, Spinner, useConfirm } from '@xenia/ui'
import * as api from './signageApi'
import { MENU_COLOURS, moved } from './signageLogic'
import { setBadges as shareBadges } from './useBadges'
const newKey = taken => {
let n = 1
while (taken.has(`badge-${n}`)) n++
return `badge-${n}`
}
export default function BadgesSettings() {
const { t } = useTranslation('manager')
const { language } = useLanguage()
const [saved, setSaved] = useState(null)
const [list, setList] = useState(null)
const [busy, setBusy] = useState(false)
const [confirm, confirmDialog] = useConfirm()
useEffect(() => {
api.getBadges().then(r => { setSaved(r.badges); setList(r.badges) }).catch(err => toast.error(errorMessage(err, t)))
}, [t])
const dirty = useMemo(() => JSON.stringify(list) !== JSON.stringify(saved), [list, saved])
if (!list) return <section className="rounded-card border border-line bg-surface p-4 flex justify-center"><Spinner /></section>
const set = (i, patch) => setList(l => l.map((b, j) => (j === i ? { ...b, ...patch } : b)))
const setName = (i, lang, v) => setList(l => l.map((b, j) => (j === i ? { ...b, names: { ...b.names, [lang]: v } } : b)))
const add = () => setList(l => [...l, { key: newKey(new Set(l.map(b => b.key))), names: { el: '', en: '' }, colour: MENU_COLOURS.newBadge, text_colour: null, icon: null }])
const remove = async i => {
const b = list[i]
if (await confirm({ title: t('signage.badgesSettings.removeTitle', { name: badgeName(b, language) || b.key }), body: t('signage.badgesSettings.removeBody'),
confirmLabel: t('fees.delete'), tone: 'danger', testId: 'signage-badge-remove-confirm' })) setList(l => l.filter((_, j) => j !== i))
}
const save = async () => {
if (list.some(b => !b.names?.el?.trim() && !b.names?.en?.trim())) { toast.error(t('signage.badgesSettings.needName')); return }
setBusy(true)
try {
const r = await api.putBadges(list.map(b => ({ ...b, names: Object.fromEntries(Object.entries(b.names || {}).filter(([, v]) => v?.trim())) })))
setSaved(r.badges); setList(r.badges); shareBadges(r.badges)
toast.success(t('settings.saved'))
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
return (
<section className="rounded-card border border-line bg-surface p-4 grid gap-3" data-testid="signage-badges">
<div className="flex flex-wrap items-start gap-3">
<div className="grid gap-1 flex-1 min-w-[16rem]">
<h2 className="text-body font-semibold text-ink">{t('signage.badgesSettings.title')}</h2>
<p className="text-label text-ink-2">{t('signage.badgesSettings.hint')}</p>
</div>
<Button variant="secondary" disabled={!dirty || busy} onClick={() => setList(saved)}>{t('signage.undo')}</Button>
<Button loading={busy} disabled={!dirty} onClick={save} data-testid="signage-badges-save">{t('fees.save')}</Button>
</div>
<div className="grid gap-2">
{list.map((b, i) => {
const Icon = BADGE_ICONS[b.icon]
return (
<div key={b.key} className="grid gap-2 rounded-control border border-line bg-surface-2 p-3" data-testid="signage-badge-row" data-key={b.key}>
<div className="flex items-center gap-2">
{/* as the TV draws it */}
<span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-caption font-extrabold uppercase tracking-wide" style={badgeColours(b)}
data-testid="signage-badge-preview">
{Icon && <Icon size={13} strokeWidth={2.5} aria-hidden="true" />}{badgeName(b, language) || '…'}
</span>
<span className="flex-1" />
<IconButton size="sm" label={t('display.earlier')} disabled={i === 0} onClick={() => setList(l => moved(l, i, i - 1))}><ArrowUp size={14} /></IconButton>
<IconButton size="sm" label={t('display.later')} disabled={i === list.length - 1} onClick={() => setList(l => moved(l, i, i + 1))}><ArrowDown size={14} /></IconButton>
<IconButton size="sm" tone="danger" label={t('fees.delete')} onClick={() => remove(i)} data-testid="signage-badge-remove"><Trash2 size={14} /></IconButton>
</div>
<FieldRow className="-mx-3 -mb-3" min="11rem">
<Field label={t('signage.badgesSettings.nameEl')}>
<Input value={b.names?.el || ''} maxLength={24} onChange={e => setName(i, 'el', e.target.value)} data-testid="signage-badge-name-el" />
</Field>
<Field label={t('signage.badgesSettings.nameEn')}>
<Input value={b.names?.en || ''} maxLength={24} onChange={e => setName(i, 'en', e.target.value)} data-testid="signage-badge-name-en" />
</Field>
<ColourField label={t('signage.badgesSettings.colour')} value={b.colour} onChange={colour => set(i, { colour })} testId="signage-badge-bg" />
<ColourField label={t('signage.badgesSettings.text')} value={b.text_colour || badgeColours(b).color} onChange={text_colour => set(i, { text_colour })} testId="signage-badge-fg"
auto={{ label: t('signage.look.badgeTextAuto'), on: !b.text_colour, pick: () => set(i, { text_colour: null }) }} />
<IconPicker label={t('signage.badgesSettings.icon')} icons={BADGE_ICONS} value={b.icon} onChange={icon => set(i, { icon })} testId="signage-badge-icon" />
</FieldRow>
</div>
)
})}
</div>
{list.length < 30 && (
<div><Button variant="secondary" icon={<Plus size={14} />} onClick={add} data-testid="signage-badge-add">{t('signage.badgesSettings.add')}</Button></div>
)}
{confirmDialog}
</section>
)
}
@@ -13,15 +13,19 @@
// Owner review 3 (2026-11-21): the look part by part (MenuLook: headings, names, prices, dots, // Owner review 3 (2026-11-21): the look part by part (MenuLook: headings, names, prices, dots,
// spacing, photos); a pencil beside each category and product on the board gives it a name for // spacing, photos); a pencil beside each category and product on the board gives it a name for
// this board only (the catalogue keeps its own: the waiters' names stay as they are). // this board only (the catalogue keeps its own: the waiters' names stay as they are).
// Owner review 5 (2026-11-21): several badges per product, from the venue's list (Message & settings),
// in the shared multiple-choice dropdown; the list placed up / middle / down as well as left / right.
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import { AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, Eye, EyeOff, Pencil, RotateCcw, X } from 'lucide-react' import { AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Eye, EyeOff, Pencil, RotateCcw, 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, useLanguage, useTranslation } from '@xenia/i18n'
import { Dropdown, Field, IconButton, Input, Segmented, Select, Switch } from '@xenia/ui' import { badgeName } from '@xenia/signage'
import { Dropdown, Field, IconButton, Input, Segmented, Slider, Switch } from '@xenia/ui'
import client from '../../api/client' import client from '../../api/client'
import { BADGES, boardOrder, moveGroup, moveItem, toggled } from './signageLogic' import { boardOrder, moveGroup, moveItem, toggled } from './signageLogic'
import { useBadges } from './useBadges'
import MenuLook from './MenuLook' import MenuLook from './MenuLook'
import { BackgroundField, Range, Section } from './SignageFields' import { BackgroundField, Section } from './SignageFields'
import WidgetsEditor from './WidgetsEditor' import WidgetsEditor from './WidgetsEditor'
let catalogue = null // categories and products, read once for every menu editor on the page let catalogue = null // categories and products, read once for every menu editor on the page
@@ -41,6 +45,9 @@ function useCatalogue() {
export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [], widget = null, onWidget, extras, board = false, testid = 'signage-menu-editor' }) { 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 { language } = useLanguage()
const defs = useBadges()
const badgeOptions = defs.map(d => ({ value: d.key, label: badgeName(d, language === 'el' ? 'el' : 'en'), dot: d.colour }))
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, products } = useCatalogue() const { cats, products } = useCatalogue()
@@ -53,6 +60,13 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
const found = q.trim().length < 1 ? [] : products.filter(p => p.name.toLowerCase().includes(q.trim().toLowerCase()) && !listed.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 badgesOf = id => { const v = badges[String(id)]; return typeof v === 'string' ? [v] : v || [] }
const setBadgesOf = (id, list) => {
const next = { ...badges }
if (list.length) next[String(id)] = list.slice(0, 4)
else delete next[String(id)]
setC({ badges: next })
}
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 || []) const hidden = new Set(c.exclude_ids || [])
// this board's own names: empty = the catalogue's again // this board's own names: empty = the catalogue's again
@@ -146,14 +160,8 @@ export default function MenuEditor({ slide, onChange, media, onMedia, misfit = [
className={`text-label ${off ? 'text-ink-3 opacity-70' : it.available ? 'text-ink' : 'text-ink-3 line-through'}`} /> className={`text-label ${off ? 'text-ink-3 opacity-70' : it.available ? 'text-ink' : 'text-ink-3 line-through'}`} />
{off && <span className="text-caption text-ink-3">{t('signage.menu.hiddenTag')}</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>} {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} <Dropdown multiple size="sm" value={badgesOf(it.id)} onChange={list => setBadgesOf(it.id, list)} allLabel={t('signage.menu.noBadge')}
onChange={e => { aria-label={t('signage.menu.badge')} data-testid="signage-menu-badge" disabled={off} className="w-40 shrink-0" options={badgeOptions} />
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}`) }))]} />
<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(off ? 'signage.menu.showAgain' : 'signage.menu.hide')} data-testid="signage-item-hide" aria-pressed={off} <IconButton size="sm" variant="ghost" label={t(off ? 'signage.menu.showAgain' : 'signage.menu.hide')} data-testid="signage-item-hide" aria-pressed={off}
@@ -196,19 +204,24 @@ 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 items-start ${board ? 'xl:grid-cols-3' : 'xl:grid-cols-5'}`}> <div className={`grid gap-4 grid-cols-2 items-start ${board ? 'xl:grid-cols-3' : 'xl:grid-cols-6'}`}>
<Field label={t('signage.columns')}> <Field label={t('signage.columns')}>
<Segmented value={String(c.columns || (board ? 1 : 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 && <> {!board && <>
<Range label={t('signage.menu.width')} value={c.board_width || 100} min={40} max={100} step={5} suffix="%" <Slider 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}>
<Segmented value={c.board_align || 'left'} onChange={v => setC({ board_align: v })} data-testid="signage-menu-align" fill <Segmented value={c.board_align || 'left'} onChange={v => setC({ board_align: v })} data-testid="signage-menu-align" fill
options={[['left', AlignLeft], ['center', AlignCenter], ['right', AlignRight]].map(([v, Icon]) => ( 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.vplace')} hint={t('signage.menu.vplaceHint')}>
<Segmented value={c.board_valign || 'top'} onChange={v => setC({ board_valign: v })} data-testid="signage-menu-valign" fill
options={[['top', AlignVerticalJustifyStart], ['middle', AlignVerticalJustifyCenter], ['bottom', AlignVerticalJustifyEnd]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.verticals.${v}`), testId: `signage-menu-valign-${v}` }))} />
</Field>
</>} </>}
<Field label={t('signage.menu.perPage')} hint={t(board ? 'signage.menu.perPageWidgetHint' : 'signage.menu.perPageHint')}> <Field label={t('signage.menu.perPage')} hint={t(board ? 'signage.menu.perPageWidgetHint' : 'signage.menu.perPageHint')}>
<Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={board ? '8' : t('signage.menu.auto')} <Input inputMode="numeric" value={c.page_size ? String(c.page_size) : ''} placeholder={board ? '8' : t('signage.menu.auto')}
+67 -101
View File
@@ -3,18 +3,20 @@
// the dots between name and price with the badges' colours, the spacing (line and letter spacing: // the dots between name and price with the badges' colours, the spacing (line and letter spacing:
// Auto or a choice) with the photos' size and shape. The player draws it (menuLook). // Auto or a choice) with the photos' size and shape. The player draws it (menuLook).
// Owner review 4 (2026-11-21): every field says what it sets ("Headings size"), so a row needs no // Owner review 4 (2026-11-21): every field says what it sets ("Headings size"), so a row needs no
// title; fields keep their width and wrap to a second line, each row on its own band. Every field // title; every field changes only itself: a part that still follows another (headings and prices
// changes only itself: a part that still follows another (headings and prices take the names' size // take the names' size and the accent colour, the dots the text colour) is given that value before
// and the accent colour, the dots the text colour) is given that value before the other changes. // the other changes. Names align left or right; "Reset the look" puts every part back.
// Names align left or right; "Reset the look" puts every part back. // Owner review 5: rows are @xenia/ui FieldRows (framed and tinted only while they wrap); badges take
// each badge's own colours (Signage → Message & settings) unless the board gives them one; the page
// dots have their own colour field.
import { AlignCenter, AlignLeft, AlignRight, Bold, Italic, RotateCcw, Underline } from 'lucide-react' import { AlignCenter, AlignLeft, AlignRight, Bold, Italic, RotateCcw, Underline } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, Segmented, useConfirm } from '@xenia/ui' import { Button, ColourField, Dropdown, Field, FieldRow, joinAlpha, Segmented, Slider, splitAlpha, useConfirm } from '@xenia/ui'
import { readableOn } from '@xenia/signage' import { FONT_KEYS, LETTER_SPACINGS, LINE_HEIGHTS, MENU_COLOURS, MENU_LOOK_DEFAULTS } from './signageLogic'
import { FONT_KEYS, joinAlpha, LETTER_SPACINGS, LINE_HEIGHTS, MENU_COLOURS, MENU_LOOK_DEFAULTS, splitAlpha } from './signageLogic' import { Section } from './SignageFields'
import { ColourField, Range, Section } from './SignageFields'
const ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight } const ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight }
export default function MenuLook({ c, setC }) { export default function MenuLook({ c, setC }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [confirm, confirmDialog] = useConfirm() const [confirm, confirmDialog] = useConfirm()
@@ -41,35 +43,31 @@ export default function MenuLook({ c, setC }) {
} }
} }
const cell = (_w, node) => <div className="min-w-0">{node}</div>
/** Headings, names or prices: size, colour, font, style, alignment. */ /** Headings, names or prices: size, colour, font, style, alignment. */
const partRow = (part, key, { size, colour, font, onSize, onColour, onFont, inherit, align, aligns = ['left', 'center', 'right'] }) => { const partRow = (part, key, shade, { size, colour, font, onSize, onColour, onFont, inherit, align, aligns = ['left', 'center', 'right'] }) => {
const s = style(key) const s = style(key)
const styles = [s.bold !== false && 'bold', s.italic && 'italic', s.underline && 'underline'].filter(Boolean)
return ( return (
<Band testid={`signage-look-${key}`}> <FieldRow shade={shade} data-testid={`signage-look-${key}`}>
{cell('size', <Range label={L(part, 'size')} value={size} min={50} max={300} step={10} suffix="%" onChange={onSize} testid={`signage-look-${key}-size`} />)} <Slider label={L(part, 'size')} value={size} min={50} max={300} step={10} suffix="%" onChange={onSize} testId={`signage-look-${key}-size`} />
{cell('colour', <ColourField label={L(part, 'colour')} value={colour} onChange={onColour} testid={`signage-look-${key}-colour`} />)} <ColourField label={L(part, 'colour')} value={colour} onChange={onColour} testId={`signage-look-${key}-colour`} />
{cell('font', ( <Field label={L(part, 'font')}>
<Field label={L(part, 'font')}> <Dropdown value={font} onChange={onFont} options={fontOptions(inherit)} data-testid={`signage-look-${key}-font`} />
<Dropdown value={font} onChange={onFont} options={fontOptions(inherit)} data-testid={`signage-look-${key}-font`} /> </Field>
</Field> <Field label={L(part, 'style')}>
))} <Segmented multiple fill value={styles} data-testid={`signage-look-${key}-style`}
{cell('style', ( onChange={list => setStyle(key, { bold: list.includes('bold'), italic: list.includes('italic'), underline: list.includes('underline') })}
<Field label={L(part, 'style')}> options={[['bold', Bold], ['italic', Italic], ['underline', Underline]].map(([v, Icon]) => (
<TextToggles s={s} onChange={patch => setStyle(key, patch)} testid={`signage-look-${key}`} /> { value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.look.${v}`), testId: `signage-look-${key}-${v}` }))} />
</Field> </Field>
))} <Field label={L(part, 'align')}>
{cell('align', ( <Segmented value={aligns.includes(s.align) ? s.align : align} onChange={v => setStyle(key, { align: v })} fill data-testid={`signage-look-${key}-align`}
<Field label={L(part, 'align')}> options={aligns.map(v => {
<Segmented value={aligns.includes(s.align) ? s.align : align} onChange={v => setStyle(key, { align: v })} fill data-testid={`signage-look-${key}-align`} const Icon = ALIGN_ICONS[v]
options={aligns.map(v => { return { value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.aligns.${v}`), testId: `signage-look-${key}-align-${v}` }
const Icon = ALIGN_ICONS[v] })} />
return { value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.aligns.${v}`), testId: `signage-look-${key}-align-${v}` } </Field>
})} /> </FieldRow>
</Field>
))}
</Band>
) )
} }
@@ -81,90 +79,58 @@ export default function MenuLook({ c, setC }) {
return ( return (
<Section title={t('signage.textLook')} testid="signage-text-look" <Section title={t('signage.textLook')} testid="signage-text-look"
aside={<Button size="sm" variant="ghost" icon={<RotateCcw size={14} />} onClick={reset} data-testid="signage-look-reset">{t('signage.look.reset')}</Button>}> aside={<Button size="sm" variant="ghost" icon={<RotateCcw size={14} />} onClick={reset} data-testid="signage-look-reset">{t('signage.look.reset')}</Button>}>
<div className="grid gap-2"> <div className="grid gap-1 -mx-3">
{partRow('heading', 'heading_style', { {partRow('heading', 'heading_style', false, {
size: h.size || base, onSize: v => setStyle('heading_style', { size: v }), size: h.size || base, onSize: v => setStyle('heading_style', { size: v }),
colour: h.colour || accent, onColour: v => setStyle('heading_style', { colour: v }), colour: h.colour || accent, onColour: v => setStyle('heading_style', { colour: v }),
font: h.font || '', onFont: v => setStyle('heading_style', { font: v || null }), inherit: true, font: h.font || '', onFont: v => setStyle('heading_style', { font: v || null }), inherit: true,
align: c.board_align || 'left', align: c.board_align || 'left',
})} })}
{partRow('item', 'item_style', { {partRow('item', 'item_style', true, {
size: base, onSize: setNamesSize, size: base, onSize: setNamesSize,
colour: text, onColour: setNamesColour, colour: text, onColour: setNamesColour,
font: c.font || 'sans', onFont: v => setC({ font: v }), inherit: false, align: 'left', aligns: ['left', 'right'], font: c.font || 'sans', onFont: v => setC({ font: v }), inherit: false, align: 'left', aligns: ['left', 'right'],
})} })}
{partRow('price', 'price_style', { {partRow('price', 'price_style', false, {
size: p.size || base, onSize: v => setStyle('price_style', { size: v }), size: p.size || base, onSize: v => setStyle('price_style', { size: v }),
colour: p.colour || accent, onColour: v => setStyle('price_style', { colour: v }), colour: p.colour || accent, onColour: v => setStyle('price_style', { colour: v }),
font: p.font || '', onFont: v => setStyle('price_style', { font: v || null }), inherit: true, align: 'right', font: p.font || '', onFont: v => setStyle('price_style', { font: v || null }), inherit: true, align: 'right',
})} })}
<Band testid="signage-look-dots"> <FieldRow shade data-testid="signage-look-dots">
{cell('size', <Range label={L('dots', 'size')} value={d.size || 100} min={50} max={300} step={10} suffix="%" onChange={v => setStyle('dot_style', { size: v })} testid="signage-look-dots-size" />)} <Slider label={L('dots', 'size')} value={d.size || 100} min={50} max={300} step={10} suffix="%" onChange={v => setStyle('dot_style', { size: v })} testId="signage-look-dots-size" />
{cell('colour', <ColourField label={L('dots', 'colour')} value={d.colour || dotsAuto} onChange={v => setStyle('dot_style', { colour: v })} testid="signage-look-dots-colour" />)} <ColourField label={L('dots', 'colour')} value={d.colour || dotsAuto} onChange={v => setStyle('dot_style', { colour: v })} testId="signage-look-dots-colour" />
{cell('font', ( <Field label={L('dots', 'line')}>
<Field label={L('dots', 'line')}> <Dropdown value={d.style || 'dotted'} onChange={v => setStyle('dot_style', { style: v })} data-testid="signage-look-dots-style"
<Dropdown value={d.style || 'dotted'} onChange={v => setStyle('dot_style', { style: v })} data-testid="signage-look-dots-style" options={['dotted', 'dashed', 'solid', 'none'].map(x => ({ value: x, label: t(`signage.look.dotStyles.${x}`) }))} />
options={['dotted', 'dashed', 'solid', 'none'].map(x => ({ value: x, label: t(`signage.look.dotStyles.${x}`) }))} /> </Field>
</Field> <ColourField label={t('signage.look.pageDots')} value={accent} onChange={setAccent} testId="signage-accent" />
))} </FieldRow>
{cell('colour', <ColourField label={t('signage.look.badgeColour')} value={accent} onChange={setAccent} testid="signage-accent" />)} <FieldRow data-testid="signage-look-badges">
{cell('colour', <ColourField label={t('signage.look.badgeText')} value={c.badge_text_colour || readableOn(accent)} onChange={v => setC({ badge_text_colour: v })} <ColourField label={t('signage.look.badgeColour')} value={c.badge_colour || accent} onChange={v => setC({ badge_colour: v })} testId="signage-badge-colour"
testid="signage-badge-text" auto={{ label: t('signage.look.badgeTextAuto'), on: !c.badge_text_colour, pick: () => setC({ badge_text_colour: null }) }} />)} auto={{ label: t('signage.look.badgeOwn'), on: !c.badge_colour, pick: () => setC({ badge_colour: null }) }} />
</Band> <ColourField label={t('signage.look.badgeText')} value={c.badge_text_colour || text} onChange={v => setC({ badge_text_colour: v })} testId="signage-badge-text"
<Band testid="signage-look-spacing"> auto={{ label: t('signage.look.badgeOwn'), on: !c.badge_text_colour, pick: () => setC({ badge_text_colour: null }) }} />
{cell('font', ( </FieldRow>
<Field label={t('signage.look.lineHeight')}> <FieldRow shade data-testid="signage-look-spacing">
<Dropdown value={c.line_height != null ? String(c.line_height) : ''} onChange={v => setC({ line_height: v === '' ? null : Number(v) })} data-testid="signage-look-line-height" <Field label={t('signage.look.lineHeight')}>
options={choices(LINE_HEIGHTS, c.line_height, x => `${x}×`)} /> <Dropdown value={c.line_height != null ? String(c.line_height) : ''} onChange={v => setC({ line_height: v === '' ? null : Number(v) })} data-testid="signage-look-line-height"
</Field> options={choices(LINE_HEIGHTS, c.line_height, x => `${x}×`)} />
))} </Field>
{cell('font', ( <Field label={t('signage.look.letterSpacing')}>
<Field label={t('signage.look.letterSpacing')}> <Dropdown value={c.letter_spacing != null ? String(c.letter_spacing) : ''} onChange={v => setC({ letter_spacing: v === '' ? null : Number(v) })} data-testid="signage-look-letter-spacing"
<Dropdown value={c.letter_spacing != null ? String(c.letter_spacing) : ''} onChange={v => setC({ letter_spacing: v === '' ? null : Number(v) })} data-testid="signage-look-letter-spacing" options={choices(LETTER_SPACINGS, c.letter_spacing, x => `${x > 0 ? '+' : ''}${Math.round(x * 100)}%`)} />
options={choices(LETTER_SPACINGS, c.letter_spacing, x => `${x > 0 ? '+' : ''}${Math.round(x * 100)}%`)} /> </Field>
</Field>
))}
{c.show_photos && <> {c.show_photos && <>
{cell('size', <Range label={t('signage.look.photoSize')} value={c.photo_size || 100} min={50} max={250} step={10} suffix="%" onChange={v => setC({ photo_size: v })} testid="signage-look-photo-size" />)} <Slider label={t('signage.look.photoSize')} value={c.photo_size || 100} min={50} max={250} step={10} suffix="%" onChange={v => setC({ photo_size: v })} testId="signage-look-photo-size" />
{cell('font', ( <Field label={t('signage.look.photoShape')}>
<Field label={t('signage.look.photoShape')}> <Dropdown value={c.photo_shape || 'rounded'} onChange={v => setC({ photo_shape: v })} data-testid="signage-look-photo-shape"
<Dropdown value={c.photo_shape || 'rounded'} onChange={v => setC({ photo_shape: v })} data-testid="signage-look-photo-shape" options={['square', 'rounded', 'round'].map(x => ({ value: x, label: t(`signage.look.shapes.${x}`) }))} />
options={['square', 'rounded', 'round'].map(x => ({ value: x, label: t(`signage.look.shapes.${x}`) }))} /> </Field>
</Field>
))}
</>} </>}
</Band> </FieldRow>
<p className="text-caption text-ink-3 mt-1">{t('signage.look.hint')}</p> <p className="text-caption text-ink-3 px-3">{t('signage.look.hint')}</p>
</div> </div>
{confirmDialog} {confirmDialog}
</Section> </Section>
) )
} }
/** A row of the look: its fields keep their least width and wrap to a second line, in columns that
* line up from row to row; rows alternate shades. */
function Band({ testid, children }) {
return (
<div className="grid gap-3 items-end grid-cols-[repeat(auto-fill,minmax(10.5rem,1fr))] rounded-control border border-line p-3 bg-surface even:bg-surface-2" data-testid={testid}>
{children}
</div>
)
}
/** Bold, italic, underline: three toggles as tall as a field. */
function TextToggles({ s, onChange, testid }) {
const { t } = useTranslation('manager')
const items = [['bold', Bold, s.bold !== false], ['italic', Italic, !!s.italic], ['underline', Underline, !!s.underline]]
return (
<div className="h-control flex rounded-control border border-line bg-surface p-0.5 gap-0.5" role="group">
{items.map(([k, Icon, on]) => (
<button key={k} type="button" aria-pressed={on} aria-label={t(`signage.look.${k}`)} title={t(`signage.look.${k}`)}
onClick={() => onChange({ [k]: !on })} data-testid={`${testid}-${k}`}
className={`flex-1 min-w-[2rem] grid place-items-center rounded-[calc(var(--x-radius-control)-2px)] transition-colors duration-fast
${on ? 'bg-accent-soft text-accent-ink' : 'text-ink-2 hover:bg-surface-2'}`}>
<Icon size={16} aria-hidden="true" />
</button>
))}
</div>
)
}
@@ -0,0 +1,36 @@
// The message of the day (plan step 5.6c; owner review 5, 2026-11-21: one editor, used in Signage →
// Message & settings, on the Overview and from a message widget): every screen shows it at once.
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Input, Spinner } from '@xenia/ui'
import * as api from './signageApi'
export default function MessageOfTheDay({ onSaved, testId = 'signage-message' }) {
const { t } = useTranslation('manager')
const [text, setText] = useState(null)
const [saved, setSaved] = useState('')
const [busy, setBusy] = useState(false)
useEffect(() => {
api.getMessage().then(m => { setText(m.text || ''); setSaved(m.text || '') }).catch(err => toast.error(errorMessage(err, t)))
}, [t])
if (text === null) return <div className="flex justify-center p-3"><Spinner /></div>
const save = async () => {
setBusy(true)
try {
const r = await api.putMessage(text.trim())
setSaved(r.text || ''); setText(r.text || '')
toast.success(t('settings.saved'))
onSaved?.(r.text || '')
} catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false)
}
return (
<div className="flex gap-2 items-start">
<Input value={text} maxLength={200} onChange={e => setText(e.target.value)} className="flex-1" placeholder={t('signage.settings.messagePlaceholder')}
aria-label={t('signage.settings.message')} data-testid={testId} onKeyDown={e => { if (e.key === 'Enter' && text.trim() !== saved.trim()) save() }} />
<Button loading={busy} disabled={text.trim() === saved.trim()} onClick={save} data-testid={`${testId}-save`}>{t('fees.save')}</Button>
</div>
)
}
@@ -86,7 +86,14 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
catch (err) { toast.error(errorMessage(err, t)); return null } catch (err) { toast.error(errorMessage(err, t)); return null }
finally { setBusy(false) } finally { setBusy(false) }
} }
const leave = async () => !dirty || confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', testId: 'signage-discard' }) // leaving a slide with changes: save them and go, go without them, or stay (owner review 5)
const leave = async () => {
if (!dirty) return true
const how = await confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger',
altLabel: t('signage.saveAndLeave'), testId: 'signage-discard' })
if (how !== 'alt') return how
return (await run(() => api.updateSlide(draft.id, slideBody(draft)), t('settings.saved'))) != null
}
const pick = async s => { const pick = async s => {
if (s.id === selected || !(await leave())) return if (s.id === selected || !(await leave())) return
setSelected(s.id) setSelected(s.id)
@@ -3,13 +3,13 @@
// a background (colour or photo with darkening), a slider with its value. // a background (colour or photo with darkening), a slider with its value.
// 2026-11-21 (owner review 2): the slider framed like the fields beside it; a colour as a field // 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. // (its swatch and code) that opens the ready colours and the picker, so it fits a row of fields.
// Owner review 4: that colour field everywhere, its panel over the page, see-through colours. // Owner review 4: that colour field everywhere, its panel over the page, see-through colours
import { useCallback, useRef, useState } from 'react' // (owner review 5: it is @xenia/ui's ColourField now).
import { useState } from 'react'
import { AlertTriangle, Film, ImageIcon, X } from 'lucide-react' import { AlertTriangle, Film, ImageIcon, X } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, IconButton, Input, Popover } from '@xenia/ui' import { Button, ColourField, Dropdown, Field, IconButton, Slider } from '@xenia/ui'
import MediaPicker from '../media/MediaPicker' import MediaPicker from '../media/MediaPicker'
import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './signageLogic'
/** A part of the slide editor: its title over a thin line, then its fields (DESIGN.md §3). */ /** A part of the slide editor: its title over a thin line, then its fields (DESIGN.md §3). */
export function Section({ title, aside, children, testid, className = '' }) { export function Section({ title, aside, children, testid, className = '' }) {
@@ -25,19 +25,6 @@ export function Section({ title, aside, children, testid, className = '' }) {
) )
} }
/** 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 (
<Field label={label}>
<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))}
className="flex-1 min-w-0 accent-accent" aria-label={label} data-testid={testid} />
<span className="text-label text-ink-2 tabular-nums w-12 text-right">{value}{suffix}</span>
</span>
</Field>
)
}
/** Pick a picture or a video from the library; `entry` is the media map's item for `value`. */ /** Pick a picture or a video from the library; `entry` is the media map's item for `value`. */
export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, misfit, label, testid }) { export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, misfit, label, testid }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -70,74 +57,6 @@ export function MediaPick({ kind = 'image', value, entry, onChange, onRemove, mi
) )
} }
/**
* A colour the venue chooses for its TV (data, not a theme colour: #rrggbb, or #rrggbbaa when
* see-through): a field (its swatch and code) that opens a small panel over the page (owner review
* 4, 2026-11-21: every signage colour): twelve ready colours, then the picker, the opacity and the
* code typed by hand. Each field changes only its own colour. `auto` ({ label, on, pick }): a first
* choice that lets the TV choose (a badge's text: white or black, whichever reads).
*/
export function ColourField({ label, value, onChange, testid, presets = COLOUR_PRESETS, auto, className }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
const [typed, setTyped] = useState(null)
const btn = useRef(null)
const v = (value || '#000000').toLowerCase()
const { rgb, alpha } = splitAlpha(v)
const close = useCallback(() => { setOpen(false); setTyped(null) }, [])
return (
<>
<Field label={label} className={className}>
<button ref={btn} type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} aria-haspopup="dialog" data-testid={testid ? `${testid}-open` : undefined}
className="w-full min-w-0 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">
<Swatch colour={v} className="w-6 h-6" />
<span className={`truncate ${auto?.on ? 'text-ink-2' : 'font-mono text-ink-2'}`}>{auto?.on ? auto.label : v}</span>
</button>
</Field>
<Popover open={open} anchor={btn} onClose={close} aria-label={label} className="grid gap-3 p-3 w-[17.5rem]"
data-testid={testid ? `${testid}-panel` : 'signage-colour-panel'}>
{auto && (
<button type="button" onClick={() => { auto.pick(); close() }} aria-pressed={!!auto.on} data-testid={testid ? `${testid}-auto` : undefined}
className={`h-control px-3 rounded-control border text-label text-left transition-colors duration-fast ${auto.on ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line text-ink hover:bg-surface-2'}`}>
{auto.label}
</button>
)}
<div className="grid grid-cols-6 gap-2 justify-items-center">
{presets.map(c => (
<button key={c} type="button" onClick={() => { onChange(joinAlpha(c, alpha)); close() }} aria-label={c} aria-pressed={!auto?.on && rgb === c} title={c}
className={`w-8 h-8 rounded-full transition-transform duration-fast ${!auto?.on && rgb === c ? 'ring-2 ring-accent ring-offset-2 ring-offset-surface' : 'hover:scale-110'}`}
data-testid={testid ? `${testid}-preset` : undefined}>
<Swatch colour={c} className="w-8 h-8" />
</button>
))}
</div>
<div className="grid gap-2.5 border-t border-line pt-3">
<span className="text-overline font-semibold uppercase tracking-wide text-ink-3">{t('signage.colourPick.custom')}</span>
<div className="flex items-center gap-2">
<input type="color" value={rgb} onChange={e => { setTyped(null); onChange(joinAlpha(e.target.value, alpha)) }} data-testid={testid} aria-label={label}
className="w-10 h-control shrink-0 rounded-control border border-line bg-surface cursor-pointer p-0.5" />
<Input value={typed ?? v} maxLength={9} spellCheck={false} aria-label={t('signage.colourPick.code')} className="font-mono min-w-0 flex-1" data-testid={testid ? `${testid}-code` : undefined}
onChange={e => { setTyped(e.target.value); const c = typedColour(e.target.value); if (c) onChange(c) }} onBlur={() => setTyped(null)} />
</div>
<label className="grid gap-1 text-caption text-ink-2">
<span className="flex justify-between"><span>{t('signage.colourPick.opacity')}</span><span className="tabular-nums">{alpha}%</span></span>
<input type="range" min={0} max={100} step={5} value={alpha} onChange={e => { setTyped(null); onChange(joinAlpha(rgb, Number(e.target.value))) }}
className="accent-accent" data-testid={testid ? `${testid}-opacity` : undefined} />
</label>
</div>
</Popover>
</>
)
}
/** A colour's swatch, over a checkerboard so a see-through colour shows as one. */
function Swatch({ colour, className = '' }) {
return (
<span className={`block rounded-full border border-line-strong shrink-0 ${className}`} aria-hidden="true" data-venue-colour=""
style={{ background: `linear-gradient(${colour}, ${colour}), repeating-conic-gradient(#d1d5db 0 25%, #ffffff 0 50%) 0 0 / 8px 8px` }} />
)
}
/** 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')
@@ -151,12 +70,12 @@ export function BackgroundField({ value, onChange, media, onMedia, misfit, testi
options={[{ value: 'colour', label: t('signage.bgColour') }, { value: 'media', label: t('signage.bgPhoto') }]} /> options={[{ value: 'colour', label: t('signage.bgColour') }, { value: 'media', label: t('signage.bgPhoto') }]} />
</Field> </Field>
{bg.kind === 'colour' {bg.kind === 'colour'
? <ColourField label={t('signage.colour')} value={bg.colour} onChange={colour => set({ colour })} testid={`${testid}-colour`} className="max-w-xs" /> ? <ColourField label={t('signage.colour')} value={bg.colour} onChange={colour => set({ colour })} testId={`${testid}-colour`} className="max-w-xs" />
: ( : (
<div className="grid gap-4 sm:grid-cols-[auto_minmax(0,1fr)_12rem] items-end"> <div className="grid gap-4 sm:grid-cols-[auto_minmax(0,1fr)_12rem] items-end">
<MediaPick kind="image" value={bg.media_id} entry={media?.[String(bg.media_id)]} misfit={misfit} testid={`${testid}-photo`} <MediaPick kind="image" value={bg.media_id} entry={media?.[String(bg.media_id)]} misfit={misfit} testid={`${testid}-photo`}
onChange={item => { onMedia(item); set({ media_id: item.id }) }} onRemove={() => set({ media_id: null })} /> onChange={item => { onMedia(item); set({ media_id: item.id }) }} onRemove={() => set({ media_id: null })} />
<Range label={t('signage.dimLabel')} value={bg.dim} min={0} max={80} step={5} suffix="%" onChange={dim => set({ dim })} testid={`${testid}-dim`} /> <Slider label={t('signage.dimLabel')} value={bg.dim} min={0} max={80} step={5} suffix="%" onChange={dim => set({ dim })} testId={`${testid}-dim`} />
<Field label={t('signage.fit')}> <Field label={t('signage.fit')}>
<Dropdown value={bg.fit} onChange={fit => set({ fit })} <Dropdown value={bg.fit} onChange={fit => set({ fit })}
options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} /> options={[{ value: 'cover', label: t('signage.fits.cover') }, { value: 'contain', label: t('signage.fits.contain') }]} />
@@ -1,20 +1,21 @@
// Signage → Message and weather (plan step 5.6c): the message of the day (one place for every // Signage → Message & settings (plan step 5.6c; renamed in owner review 5, 2026-11-21): the message
// screen, at once) and the weather's town (picked from a search; the weather needs internet, and // of the day (one place for every screen, at once; also on the Overview), the weather's town (picked
// without it the widget is simply hidden on the TVs). // from a search; the weather needs internet, and without it the widget is simply hidden on the TVs)
// and the venue's badges for menu boards (BadgesSettings).
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useState } from 'react'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { CloudOff, RefreshCw, Search } from 'lucide-react' import { CloudOff, RefreshCw, Search } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n' import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
import { Button, Field, Input, Select, Spinner } from '@xenia/ui' import { Button, Dropdown, Field, Input, Spinner } from '@xenia/ui'
import BadgesSettings from './BadgesSettings'
import MessageOfTheDay from './MessageOfTheDay'
import * as api from './signageApi' import * as api from './signageApi'
export default function SignageSettingsTab() { export default function SignageSettingsTab() {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const { formatDateTime } = useFormat() const { formatDateTime } = useFormat()
const { language: lang } = useLanguage() const { language: lang } = useLanguage()
const [message, setMessage] = useState(null)
const [savedMessage, setSavedMessage] = useState('')
const [status, setStatus] = useState(null) const [status, setStatus] = useState(null)
const [q, setQ] = useState('') const [q, setQ] = useState('')
const [places, setPlaces] = useState(null) const [places, setPlaces] = useState(null)
@@ -23,29 +24,25 @@ export default function SignageSettingsTab() {
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
const [m, w] = await Promise.all([api.getMessage(), api.weatherStatus()]) const w = await api.weatherStatus()
setMessage(m.text || ''); setSavedMessage(m.text || ''); setStatus(w) setStatus(w)
if (w.place?.units) setUnits(w.place.units) if (w.place?.units) setUnits(w.place.units)
} catch (err) { toast.error(errorMessage(err, t)) } } catch (err) { toast.error(errorMessage(err, t)); setStatus(s => s || {}) }
}, [t]) }, [t])
useEffect(() => { load() }, [load]) useEffect(() => { load() }, [load])
const act = async (fn, done) => { const act = async (fn, done) => {
setBusy(true) setBusy(true)
try { const r = await fn(); if (done) toast.success(done); return r } catch (err) { toast.error(errorMessage(err, t)); return null } finally { setBusy(false) } try { const r = await fn(); if (done) toast.success(done); return r } catch (err) { toast.error(errorMessage(err, t)); return null } finally { setBusy(false) }
} }
if (message === null) return <div className="flex justify-center p-6"><Spinner /></div> if (status === null) return <div className="flex justify-center p-6"><Spinner /></div>
const w = status?.weather const w = status?.weather
return ( return (
<div className="grid gap-5 max-w-3xl" data-testid="signage-settings"> <div className="grid gap-5 max-w-5xl" data-testid="signage-settings">
<section className="rounded-card border border-line bg-surface p-4 grid gap-3"> <section className="rounded-card border border-line bg-surface p-4 grid gap-3">
<h2 className="text-body font-semibold text-ink">{t('signage.settings.message')}</h2> <h2 className="text-body font-semibold text-ink">{t('signage.settings.message')}</h2>
<p className="text-label text-ink-2">{t('signage.settings.messageHint')}</p> <p className="text-label text-ink-2">{t('signage.settings.messageHint')}</p>
<div className="flex gap-2 items-start"> <MessageOfTheDay />
<Input value={message} maxLength={200} onChange={e => setMessage(e.target.value)} className="flex-1" aria-label={t('signage.settings.message')} data-testid="signage-message" />
<Button disabled={busy || message.trim() === savedMessage.trim()} data-testid="signage-message-save"
onClick={() => act(() => api.putMessage(message.trim()), t('settings.saved')).then(r => { if (r) setSavedMessage(r.text || '') })}>{t('fees.save')}</Button>
</div>
</section> </section>
<section className="rounded-card border border-line bg-surface p-4 grid gap-3" data-testid="signage-weather"> <section className="rounded-card border border-line bg-surface p-4 grid gap-3" data-testid="signage-weather">
@@ -68,7 +65,7 @@ export default function SignageSettingsTab() {
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('signage.settings.townPlaceholder')} data-testid="signage-weather-search" /> <Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('signage.settings.townPlaceholder')} data-testid="signage-weather-search" />
</Field> </Field>
<Field label={t('signage.settings.unitsLabel')}> <Field label={t('signage.settings.unitsLabel')}>
<Select value={units} onChange={e => setUnits(e.target.value)} options={['celsius', 'fahrenheit'].map(u => ({ value: u, label: t(`signage.settings.units.${u}`) }))} /> <Dropdown value={units} onChange={setUnits} options={['celsius', 'fahrenheit'].map(u => ({ value: u, label: t(`signage.settings.units.${u}`) }))} />
</Field> </Field>
<Button variant="secondary" icon={<Search size={16} />} disabled={busy || q.trim().length < 2} data-testid="signage-weather-find" <Button variant="secondary" icon={<Search size={16} />} disabled={busy || q.trim().length < 2} data-testid="signage-weather-find"
onClick={() => act(() => api.weatherPlaces(q.trim(), lang === 'el' ? 'el' : 'en')).then(r => r && setPlaces(r))}>{t('signage.settings.find')}</Button> onClick={() => act(() => api.weatherPlaces(q.trim(), lang === 'el' ? 'el' : 'en')).then(r => r && setPlaces(r))}>{t('signage.settings.find')}</Button>
@@ -88,6 +85,8 @@ export default function SignageSettingsTab() {
))} ))}
</div> </div>
</section> </section>
<BadgesSettings />
</div> </div>
) )
} }
@@ -9,9 +9,9 @@
// font, size in a frame, colour as a field that opens its colours). // 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 { ColourField, Dropdown, Field, FilterChip, Input, Segmented, Slider, Switch, Textarea } from '@xenia/ui'
import { FONT_KEYS, TRANSITIONS } from './signageLogic' import { FONT_KEYS, TRANSITIONS } from './signageLogic'
import { BackgroundField, ColourField, MediaPick, Range, Section } from './SignageFields' import { BackgroundField, MediaPick, Section } from './SignageFields'
import MenuEditor from './MenuEditor' import MenuEditor from './MenuEditor'
import WidgetsEditor from './WidgetsEditor' import WidgetsEditor from './WidgetsEditor'
@@ -96,7 +96,7 @@ export default function SlideEditor({ slide, onChange, media, onMedia, misfit =
onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-picture" /> onChange={item => { onMedia(item); setC({ media_id: item.id }) }} testid="signage-picture" />
<div className="grid gap-4 md:grid-cols-[16rem_minmax(0,1fr)] items-start"> <div className="grid gap-4 md:grid-cols-[16rem_minmax(0,1fr)] items-start">
{fit} {fit}
<ColourField label={t('signage.around')} value={c.background_colour || '#000000'} onChange={v => setC({ background_colour: v })} testid="signage-around" className="max-w-xs" /> <ColourField label={t('signage.around')} value={c.background_colour || '#000000'} onChange={v => setC({ background_colour: v })} testId="signage-around" className="max-w-xs" />
</div> </div>
</Section> </Section>
)} )}
@@ -160,9 +160,9 @@ export function TextLook({ c, setC, align = true, children }) {
<Dropdown value={c.font || 'sans'} onChange={v => setC({ font: v })} data-testid="signage-font" <Dropdown value={c.font || 'sans'} onChange={v => setC({ font: v })} data-testid="signage-font"
options={FONT_KEYS.map(x => ({ value: x, label: t(`signage.fonts.${x}`) }))} /> options={FONT_KEYS.map(x => ({ value: x, label: t(`signage.fonts.${x}`) }))} />
</Field> </Field>
<Range label={t('signage.textSizeLabel')} value={c.text_size || 100} min={50} max={250} step={10} suffix="%" <Slider 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" />
<ColourField label={t('signage.textColour')} value={c.text_colour || '#ffffff'} onChange={v => setC({ text_colour: v })} testid="signage-text-colour" /> <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>
@@ -115,12 +115,19 @@ function SavedSlideEditor({ id, venue, onClose }) {
const set = patch => setDraft(d => ({ ...d, ...patch })) const set = patch => setDraft(d => ({ ...d, ...patch }))
const save = async () => { const save = async () => {
setBusy(true) setBusy(true)
try { const s = await api.updateSaved(id, savedBody(draft)); setSaved(s); setDraft(d => ({ ...structuredClone(s), menu: d.menu })); toast.success(t('settings.saved')) } let ok = false
try { const s = await api.updateSaved(id, savedBody(draft)); setSaved(s); setDraft(d => ({ ...structuredClone(s), menu: d.menu })); toast.success(t('settings.saved')); ok = true }
catch (err) { toast.error(errorMessage(err, t)) } catch (err) { toast.error(errorMessage(err, t)) }
setBusy(false) setBusy(false)
return ok
} }
// leaving with changes: save them and go, go without them, or stay (owner review 5)
const back = async () => { const back = async () => {
if (dirty && !(await confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger', testId: 'signage-discard' }))) return if (dirty) {
const how = await confirm({ title: t('signage.discardTitle'), body: t('signage.discard'), confirmLabel: t('signage.discardYes'), tone: 'danger',
altLabel: t('signage.saveAndLeave'), testId: 'signage-discard' })
if (!how || (how === 'alt' && (!draft.name?.trim() || !(await save())))) return
}
onClose() onClose()
} }
const tall = draft.orientation === 'portrait' const tall = draft.orientation === 'portrait'
@@ -7,9 +7,12 @@
// Owner review 2 (2026-11-21): the arrow keys move the picked widget wherever it was picked (here // 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; // or on its card below), unless you are typing or using a control that takes the arrows itself;
// Delete (or Backspace) removes it (owner review 3; "Undo changes" brings it back). // Delete (or Backspace) removes it (owner review 3; "Undo changes" brings it back).
// Owner review 5 (2026-11-21): widgets inside a stack's parts too. Pick the stack, then click a
// widget in it: it moves and sizes inside its place (it can't leave the stack; its box is % of its
// place). The picked widget is a path: "2", or "2.1.0" (stack 2, part 1, its first widget).
import { useEffect, useLayoutEffect, useRef, useState } from 'react' 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, stackOf, widgetAt } 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' }
@@ -22,32 +25,57 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl
const [rects, setRects] = useState({}) const [rects, setRects] = useState({})
const [guides, setGuides] = useState([]) const [guides, setGuides] = useState([])
const last = useRef('') const last = useRef('')
// where each widget is drawn now (the clock ticks, texts change): measured after every render // where each widget (and each stack place) is drawn now (the clock ticks, texts change): measured
// (on purpose without deps; it only sets state when something moved) // after every render (on purpose without deps; it only sets state when something moved). Widgets
// of a library slide drawn inside a part are not this slide's: left out.
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
useLayoutEffect(() => { useLayoutEffect(() => {
const box = boxRef.current const box = boxRef.current
if (!box) return if (!box) return
const frame = box.getBoundingClientRect() const frame = box.getBoundingClientRect()
const out = {} const out = {}
for (const el of box.querySelectorAll('[data-widget]')) { for (const el of box.querySelectorAll('[data-widget], [data-place]')) {
const r = el.getBoundingClientRect() if (el.closest('[data-embedded]')) continue
out[el.getAttribute('data-widget')] = boxFromRect(r, frame) const r = boxFromRect(el.getBoundingClientRect(), frame)
if (el.hasAttribute('data-widget')) out[el.getAttribute('data-widget')] = r
if (el.hasAttribute('data-place')) out[`place:${el.getAttribute('data-place')}`] = r
} }
const key = JSON.stringify(out) const key = JSON.stringify(out)
if (key !== last.current) { last.current = key; setRects(out) } if (key !== last.current) { last.current = key; setRects(out) }
}) })
const start = (e, i, handle = null) => { const sel = selected != null ? String(selected) : null
// a widget's box in its own frame: the slide's (%), or its place's for a widget in a stack
const own = path => {
const w = widgetAt(widgets, path)
if (w?.position === 'custom' && w.box) return w.box
const r = rects[path]
const place = stackOf(path) != null ? rects[`place:${path}`] : null
if (!r || stackOf(path) == null) return r || null
if (!place) return null
return { x: (r.x - place.x) / place.w * 100, y: (r.y - place.y) / place.h * 100, w: r.w / place.w * 100, h: r.h / place.h * 100 }
}
// …and where that is on the slide (for the outline)
const onSlide = path => {
const b = own(path)
const place = stackOf(path) != null ? rects[`place:${path}`] : null
if (!b || !place) return b
return { x: place.x + b.x * place.w / 100, y: place.y + b.y * place.h / 100, w: b.w * place.w / 100, h: b.h * place.h / 100 }
}
const start = (e, path, handle = null) => {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
onSelect(i) onSelect(path)
e.currentTarget.closest('[data-testid="signage-canvas"]')?.focus({ preventScroll: true }) e.currentTarget.closest('[data-testid="signage-canvas"]')?.focus({ preventScroll: true })
const box = boxRef.current const box = boxRef.current
const w = widgets[i] const base = own(path)
const base = w?.position === 'custom' && w.box ? w.box : rects[i]
if (!box || !base) return if (!box || !base) return
const { width, height } = box.getBoundingClientRect() const inside = stackOf(path) != null
const frame = box.getBoundingClientRect()
const place = inside ? rects[`place:${path}`] : { w: 100, h: 100 }
const width = frame.width * place.w / 100
const height = frame.height * place.h / 100
const x0 = e.clientX const x0 = e.clientX
const y0 = e.clientY const y0 = e.clientY
let moved = false let moved = false
@@ -57,9 +85,10 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl
const dx = (ev.clientX - x0) / width * 100 const dx = (ev.clientX - x0) / width * 100
const dy = (ev.clientY - y0) / height * 100 const dy = (ev.clientY - y0) / height * 100
const next = handle ? resizeBox(base, handle, dx, dy) : moveBox(base, dx, dy) const next = handle ? resizeBox(base, handle, dx, dy) : moveBox(base, dx, dy)
if (inside) { onPlace(path, next); return }
const snapped = snapBox(next, handle) const snapped = snapBox(next, handle)
setGuides(snapped.guides) setGuides(snapped.guides)
onPlace(i, snapped.box) onPlace(path, snapped.box)
} }
const up = () => { const up = () => {
window.removeEventListener('pointermove', move) window.removeEventListener('pointermove', move)
@@ -72,50 +101,61 @@ export default function WidgetCanvas({ boxRef, widgets, selected, onSelect, onPl
// the keys, on the whole page while a widget is picked // the keys, on the whole page while a widget is picked
useEffect(() => { useEffect(() => {
if (selected == null) return undefined if (sel == null) return undefined
const on = e => { const on = e => {
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return
if (e.target instanceof Element && e.target.closest(OWN_KEYS)) 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 }
if ((e.key === 'Delete' || e.key === 'Backspace') && onRemove) { e.preventDefault(); onRemove(selected); return } if ((e.key === 'Delete' || e.key === 'Backspace') && onRemove) { e.preventDefault(); onRemove(sel); 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]
if (!d) return if (!d) return
e.preventDefault() e.preventDefault()
const w = widgets[selected] const base = own(sel)
const base = w?.position === 'custom' && w.box ? w.box : rects[selected] if (base) onPlace(sel, moveBox(base, d[0], d[1]))
if (base) onPlace(selected, moveBox(base, d[0], d[1]))
} }
window.addEventListener('keydown', on) window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on) return () => window.removeEventListener('keydown', on)
}, [selected, widgets, rects, onPlace, onSelect, onRemove]) })
const sel = selected != null ? (widgets[selected]?.position === 'custom' && widgets[selected].box) || rects[selected] : null // what can be picked: the slide's widgets, and the widgets of the stack picked (or of the stack
// a picked widget sits in), drawn over it
const pickable = Object.keys(rects).filter(k => !k.startsWith('place:')).filter(k => {
const parent = stackOf(k)
return parent == null || (sel != null && (sel === parent || sel.startsWith(`${parent}.`)))
}).sort((a, b) => a.split('.').length - b.split('.').length)
const box = sel != null ? onSlide(sel) : null
const picked = widgetAt(widgets, sel)
return ( return (
<div className="absolute inset-0 outline-none" tabIndex={0} 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] && ( {pickable.map(k => {
<div key={i} className={`absolute cursor-move rounded-sm ${selected === i ? '' : 'hover:outline hover:outline-2 hover:outline-accent/60'}`} const w = widgetAt(widgets, k)
style={{ left: `${rects[i].x}%`, top: `${rects[i].y}%`, width: `${rects[i].w}%`, height: `${rects[i].h}%` }} if (!w) return null
onPointerDown={e => start(e, i)} data-testid="signage-canvas-widget" data-index={i} data-kind={w.kind} /> const r = rects[k]
))} return (
<div key={k} className={`absolute cursor-move rounded-sm ${sel === k ? '' : 'hover:outline hover:outline-2 hover:outline-accent/60'}`}
style={{ left: `${r.x}%`, top: `${r.y}%`, width: `${r.w}%`, height: `${r.h}%` }}
onPointerDown={e => start(e, k)} data-testid="signage-canvas-widget" data-index={k} data-kind={w.kind} />
)
})}
{guides.map(g => { {guides.map(g => {
const [axis, at] = g.split(':') const [axis, at] = g.split(':')
return <div key={g} className="absolute bg-accent pointer-events-none" data-testid="signage-canvas-guide" return <div key={g} className="absolute bg-accent pointer-events-none" data-testid="signage-canvas-guide"
style={axis === 'x' ? { left: `${at}%`, top: 0, bottom: 0, width: 1 } : { top: `${at}%`, left: 0, right: 0, height: 1 }} /> style={axis === 'x' ? { left: `${at}%`, top: 0, bottom: 0, width: 1 } : { top: `${at}%`, left: 0, right: 0, height: 1 }} />
})} })}
{sel && ( {box && picked && (
<div className="absolute pointer-events-none outline outline-2 outline-accent" data-testid="signage-canvas-selected" <div className="absolute pointer-events-none outline outline-2 outline-accent" data-testid="signage-canvas-selected"
style={{ left: `${sel.x}%`, top: `${sel.y}%`, width: `${sel.w}%`, height: `${sel.h}%` }}> style={{ left: `${box.x}%`, top: `${box.y}%`, width: `${box.w}%`, height: `${box.h}%` }}>
<span className={`absolute left-0 whitespace-nowrap rounded-sm bg-accent text-accent-fg text-caption font-semibold px-1.5 py-0.5 ${sel.y < 8 ? 'top-full mt-2' : 'bottom-full mb-2'}`}> <span className={`absolute left-0 whitespace-nowrap rounded-sm bg-accent text-accent-fg text-caption font-semibold px-1.5 py-0.5 ${box.y < 8 ? 'top-full mt-2' : 'bottom-full mb-2'}`}>
{t(`signage.widgets.kinds.${widgets[selected]?.kind}`)} {t(`signage.widgets.kinds.${picked.kind === 'stack' ? (picked.direction === 'column' ? 'vstack' : 'hstack') : picked.kind}`)}
</span> </span>
{HANDLES.map(h => ( {HANDLES.map(h => (
<span key={h} className="absolute pointer-events-auto bg-surface border-2 border-accent rounded-[3px]" data-testid={`signage-handle-${h}`} <span key={h} className="absolute pointer-events-auto bg-surface border-2 border-accent rounded-[3px]" data-testid={`signage-handle-${h}`}
style={{ width: SIZE, height: SIZE, cursor: CURSOR[h], style={{ width: SIZE, height: SIZE, cursor: CURSOR[h],
left: h.includes('w') ? -SIZE / 2 : h.includes('e') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)`, left: h.includes('w') ? -SIZE / 2 : h.includes('e') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)`,
top: h.includes('n') ? -SIZE / 2 : h.includes('s') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)` }} top: h.includes('n') ? -SIZE / 2 : h.includes('s') ? `calc(100% - ${SIZE / 2}px)` : `calc(50% - ${SIZE / 2}px)` }}
onPointerDown={e => start(e, selected, h)} /> onPointerDown={e => start(e, sel, h)} />
))} ))}
</div> </div>
)} )}
@@ -13,20 +13,26 @@
// Owner review 3 (2026-11-21): a stack's parts sized by dragging the lines between them on its bar; // Owner review 3 (2026-11-21): a stack's parts sized by dragging the lines between them on its bar;
// "Add a widget" beside what a part shows; Delete removes the picked widget (WidgetCanvas). // "Add a widget" beside what a part shows; Delete removes the picked widget (WidgetCanvas).
// Owner review 4 (2026-11-21): a part holds several widgets, added with "Add a widget". // Owner review 4 (2026-11-21): a part holds several widgets, added with "Add a widget".
// Owner review 5 (2026-11-21): each widget's own look ("Text and colours": colour, a plate behind
// it, font, bold / italic / underline, text size; a QR code's colours); a widget in a stack's part
// has every setting a slide's widget has, aligned both ways in its place or moved and sized there on
// the preview (Custom); the message of the day changed from its widget. The picked widget is a path
// ("2", "2.1.0": see WidgetCanvas).
// Up to 10 (the server's limit). // Up to 10 (the server's limit).
import { Fragment, useEffect, useRef, useState } from 'react' import { Fragment, useEffect, useRef, useState } from 'react'
import { import {
AlignCenter, AlignLeft, AlignRight, ArrowDown, ArrowUp, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical, AlignCenter, AlignLeft, AlignRight, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd, AlignVerticalJustifyStart, ArrowDown, ArrowUp, Bold, Italic, Palette, RotateCcw, Underline, BookImage, CalendarDays, ChevronDown, Clock, CloudSun, Columns3, GripVertical,
ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed, ImageIcon, LayoutList, MessageSquare, Plus, QrCode, Rows3, Store, Trash2, Type, UtensilsCrossed,
} from 'lucide-react' } from 'lucide-react'
import { cellWidgets, evenShares, setShare } from '@xenia/signage' import { cellWidgets, evenShares, setShare } from '@xenia/signage'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, IconButton, Input, Popover, Segmented, Switch } from '@xenia/ui' import { Button, ColourField, Dialog, Dropdown, Field, FieldRow, IconButton, Input, Popover, Segmented, Slider, Switch } from '@xenia/ui'
import MessageOfTheDay from './MessageOfTheDay'
import * as api from './signageApi' import * as api from './signageApi'
import MenuEditor from './MenuEditor' import MenuEditor from './MenuEditor'
import { MediaPick, Section } from './SignageFields' import { MediaPick, Section } from './SignageFields'
import { import {
CELL_KINDS, cellWidget, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS, CELL_KINDS, cellWidget, fillPlace, FONT_KEYS, WIDGET_COLOURS, moved, newWidget, pickedAfterMove, presetWidget, WEATHER_CHOICES, weatherChoice, WIDGET_KINDS, WIDGET_POSITIONS,
} from './signageLogic' } from './signageLogic'
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 ICON = { logo: ImageIcon, name: Store, date: CalendarDays, clock: Clock, message: MessageSquare, text: Type, qr: QrCode, weather: CloudSun, menu: UtensilsCrossed, hstack: Columns3, vstack: Rows3 }
@@ -50,12 +56,13 @@ export default function WidgetsEditor({ widgets = [], onChange, media, onMedia,
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, newWidget(kind)]) onChange([...widgets, newWidget(kind)])
onSelect?.(widgets.length) onSelect?.(String(widgets.length))
} }
const move = (from, to) => { const move = (from, to) => {
if (to < 0 || to >= widgets.length || from === to) return if (to < 0 || to >= widgets.length || from === to) return
onChange(moved(widgets, from, to)) onChange(moved(widgets, from, to))
onSelect?.(pickedAfterMove(selected, from, to)) const top = selected != null && !String(selected).includes('.') ? Number(selected) : null
onSelect?.(top == null ? null : String(pickedAfterMove(top, from, to)))
} }
const over = (e, i) => { const over = (e, i) => {
if (!drag) return if (!drag) return
@@ -77,11 +84,11 @@ export default function WidgetsEditor({ widgets = [], onChange, media, onMedia,
{widgets.map((w, i) => { {widgets.map((w, i) => {
const Icon = iconOf(w) const Icon = iconOf(w)
const custom = w.position === 'custom' const custom = w.position === 'custom'
const on = selected === i const on = selected != null && (String(selected) === String(i) || String(selected).startsWith(`${i}.`))
return ( return (
<div key={i} className="grid gap-3"> <div key={i} className="grid gap-3">
{line(i)} {line(i)}
<div onPointerDown={() => onSelect?.(i)} onDragOver={e => over(e, i)} onDrop={drop} <div onPointerDown={() => onSelect?.(String(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'} 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' : ''}`} ${drag?.from === i ? 'opacity-50' : ''}`}
data-testid="signage-widget" data-kind={w.kind} data-index={i} data-selected={on ? 'true' : undefined}> data-testid="signage-widget" data-kind={w.kind} data-index={i} data-selected={on ? 'true' : undefined}>
@@ -114,7 +121,9 @@ export default function WidgetsEditor({ widgets = [], onChange, media, onMedia,
{w.kind !== 'stack' && <AlignField w={w} set={patch => set(i, patch)} />} {w.kind !== 'stack' && <AlignField w={w} set={patch => set(i, patch)} />}
<InlineFields w={w} set={patch => set(i, patch)} /> <InlineFields w={w} set={patch => set(i, patch)} />
</div> </div>
<BelowFields w={w} set={patch => set(i, patch)} media={media} onMedia={onMedia} extras={extras} path={String(i)} depth={0} /> <LookFields w={w} set={patch => set(i, patch)} />
<BelowFields w={w} set={patch => set(i, patch)} media={media} onMedia={onMedia} extras={extras} path={String(i)} depth={0}
selected={selected} onSelect={onSelect} />
</div> </div>
</div> </div>
) )
@@ -152,6 +161,88 @@ function AlignField({ w, set, testid = 'signage-widget-align' }) {
) )
} }
/** How a widget in a stack's part lines up from top to bottom in its place. */
function VerticalField({ w, set }) {
const { t } = useTranslation('manager')
return (
<Field label={t('signage.widgets.vertical')}>
<Segmented value={w.vertical && w.vertical !== 'auto' ? w.vertical : 'middle'} onChange={vertical => set({ vertical })} fill data-testid="signage-cell-vertical"
options={[['top', AlignVerticalJustifyStart], ['middle', AlignVerticalJustifyCenter], ['bottom', AlignVerticalJustifyEnd]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.verticals.${v}`), testId: `signage-cell-vertical-${v}` }))} />
</Field>
)
}
// which widgets have text (their colour, font, style and size), a QR code's own colours, a plate
const TEXT_KINDS = ['name', 'date', 'clock', 'message', 'text', 'qr', 'weather']
/**
* A widget's own look (owner review 5), folded under "Text and colours": its colour (text and
* pictures; empty = the slide's), a plate behind it, its font, bold / italic / underline and text
* size; a QR code's dots and background. A logo has only the plate; a menu has its own look.
*/
function LookFields({ w, set }) {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
if (w.kind === 'menu' || w.kind === 'stack') return null
const text = TEXT_KINDS.includes(w.kind)
const changed = !!(w.colour || w.background_colour || w.font || w.bold != null || w.italic || w.underline || (w.text_size && w.text_size !== 100) || w.qr_colour || w.qr_background)
const styles = [w.bold !== false && 'bold', w.italic && 'italic', w.underline && 'underline'].filter(Boolean)
return (
<div className="grid gap-2" data-testid="signage-widget-look">
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} data-testid="signage-widget-look-toggle"
className="justify-self-start flex items-center gap-1.5 text-label font-medium text-ink-2 hover:text-ink">
<Palette size={15} aria-hidden="true" />{t(text ? 'signage.widgets.look' : 'signage.widgets.plateOnly')}
{changed && <span className="w-1.5 h-1.5 rounded-full bg-accent" aria-hidden="true" />}
<ChevronDown size={15} className={`transition-transform duration-fast ${open ? 'rotate-180' : ''}`} aria-hidden="true" />
</button>
{open && (
<FieldRow className="-mx-3" min="10rem">
{text && <ColourField label={t('signage.widgets.colour')} value={w.colour || WIDGET_COLOURS.text} onChange={colour => set({ colour })} testId="signage-widget-colour"
auto={{ label: t('signage.widgets.asSlide'), on: !w.colour, pick: () => set({ colour: null }) }} />}
<ColourField label={t('signage.widgets.plate')} value={w.background_colour || WIDGET_COLOURS.plate} onChange={background_colour => set({ background_colour })} testId="signage-widget-plate"
auto={{ label: t('signage.widgets.noPlate'), on: !w.background_colour, pick: () => set({ background_colour: null }) }} />
{text && <>
<Field label={t('signage.font')}>
<Dropdown value={w.font || ''} onChange={v => set({ font: v || null })} data-testid="signage-widget-font"
options={[{ value: '', label: t('signage.widgets.asSlide') }, ...FONT_KEYS.map(x => ({ value: x, label: t(`signage.fonts.${x}`) }))]} />
</Field>
<Field label={t('signage.look.f.widget.style')}>
<Segmented multiple fill value={styles} data-testid="signage-widget-style"
onChange={list => set({ bold: list.includes('bold') ? null : false, italic: list.includes('italic'), underline: list.includes('underline') })}
options={[['bold', Bold], ['italic', Italic], ['underline', Underline]].map(([v, Icon]) => (
{ value: v, icon: <Icon size={16} aria-hidden="true" />, ariaLabel: t(`signage.look.${v}`), testId: `signage-widget-${v}` }))} />
</Field>
<Slider label={t('signage.widgets.textSize')} value={w.text_size || 100} min={50} max={200} step={10} suffix="%" onChange={text_size => set({ text_size })} testId="signage-widget-text-size" />
</>}
{w.kind === 'qr' && <>
<ColourField label={t('signage.widgets.qrColour')} value={w.qr_colour || WIDGET_COLOURS.qr} onChange={qr_colour => set({ qr_colour })} testId="signage-widget-qr-colour" opacity={false} />
<ColourField label={t('signage.widgets.qrBackground')} value={w.qr_background || WIDGET_COLOURS.qrBackground} onChange={qr_background => set({ qr_background })} testId="signage-widget-qr-background" />
</>}
</FieldRow>
)}
</div>
)
}
/** The message of the day's hint, and the message itself changed right here (owner review 5). */
function MessageHint() {
const { t } = useTranslation('manager')
const [open, setOpen] = useState(false)
return (
<div className="flex flex-wrap items-center gap-2 -mt-2">
<p className="text-caption text-ink-3 flex-1 min-w-[12rem]">{t('signage.widgets.ownTextHint')}</p>
<Button size="sm" variant="secondary" onClick={() => setOpen(true)} data-testid="signage-widget-message-open">{t('signage.widgets.changeMessage')}</Button>
{open && (
<Dialog open size="md" title={t('signage.settings.message')} onClose={() => setOpen(false)}
footer={<Button variant="secondary" onClick={() => setOpen(false)}>{t('overview.close')}</Button>}>
<MessageOfTheDay onSaved={() => setOpen(false)} />
</Dialog>
)}
</div>
)
}
/** The options only some widgets have, on the same row as where / size / alignment. */ /** The options only some widgets have, on the same row as where / size / alignment. */
function InlineFields({ w, set }) { function InlineFields({ w, set }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
@@ -209,13 +300,13 @@ function InlineFields({ w, set }) {
} }
/** What needs more room, under the row: the picture, hints, the QR's own link, a menu's list, a stack's parts. */ /** 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 }) { function BelowFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
if (w.kind === 'logo') { if (w.kind === 'logo') {
return <MediaPick kind="image" value={w.media_id} entry={media[String(w.media_id)]} testid="signage-widget-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 }) }} /> 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 === 'message') return <MessageHint />
if (w.kind === 'weather') return <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.weatherNeedsInternet')}</p> if (w.kind === 'weather') return <p className="text-caption text-ink-3 -mt-2">{t('signage.widgets.weatherNeedsInternet')}</p>
if (w.kind === 'qr') { if (w.kind === 'qr') {
return ( return (
@@ -228,7 +319,7 @@ function BelowFields({ w, set, media, onMedia, extras, path, depth }) {
) )
} }
if (w.kind === 'menu') return <MenuBoardFields w={w} set={set} extras={extras} path={path} /> 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} /> if (w.kind === 'stack') return <StackFields w={w} set={set} media={media} onMedia={onMedia} extras={extras} path={path} depth={depth} selected={selected} onSelect={onSelect} />
return null return null
} }
@@ -260,7 +351,7 @@ function MenuBoardFields({ w, set, extras, path }) {
* other in a side-by-side stack, side by side in the other; each with its settings, moved up or * other in a side-by-side stack, side by side in the other; each with its settings, moved up or
* down, removed), another stack (one level deep), or a slide from the Slides library. * down, removed), another stack (one level deep), or a slide from the Slides library.
*/ */
function StackFields({ w, set, media, onMedia, extras, path, depth }) { function StackFields({ w, set, media, onMedia, extras, path, depth, selected, onSelect }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const slides = useLibrary() const slides = useLibrary()
const cells = w.cells || [] const cells = w.cells || []
@@ -305,7 +396,7 @@ function StackFields({ w, set, media, onMedia, extras, path, depth }) {
</div> </div>
</div> </div>
<ShareBar column={w.direction === 'column'} shares={shares} labels={cells.map(label)} onChange={setShares} /> <ShareBar column={w.direction === 'column'} shares={shares} labels={cells.map(label)} onChange={setShares} />
<p className="text-caption text-ink-3 -mt-1">{t(w.direction === 'column' ? 'signage.widgets.stack.barHintColumn' : 'signage.widgets.stack.barHint')}</p> <p className="text-caption text-ink-3 -mt-1">{t(w.direction === 'column' ? 'signage.widgets.stack.barHintColumn' : 'signage.widgets.stack.barHint')} {t('signage.widgets.stack.pickHint')}</p>
{cells.map((c, j) => { {cells.map((c, j) => {
const cp = `${path}.${j}` const cp = `${path}.${j}`
const ws = cellWidgets(c) const ws = cellWidgets(c)
@@ -336,8 +427,13 @@ function StackFields({ w, set, media, onMedia, extras, path, depth }) {
{ws.map((x, k) => { {ws.map((x, k) => {
const Icon = iconOf(x) const Icon = iconOf(x)
const setW = patch => setOne(k, patch) const setW = patch => setOne(k, patch)
const wp = `${cp}.${k}`
const on = selected != null && (String(selected) === wp || String(selected).startsWith(`${wp}.`))
const custom = x.position === 'custom' && x.box
return ( return (
<div key={k} className="grid gap-3 rounded-control border border-line bg-surface p-3" data-testid="signage-stack-part-widget" data-kind={x.kind}> <div key={k} onPointerDown={e => { e.stopPropagation(); onSelect?.(wp) }}
className={`grid gap-3 rounded-control border p-3 transition-colors duration-fast ${on ? 'border-accent ring-1 ring-accent bg-surface' : 'border-line bg-surface'}`}
data-testid="signage-stack-part-widget" data-kind={x.kind} data-path={wp} data-selected={on ? 'true' : undefined}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Icon size={15} className="text-ink-2 shrink-0" aria-hidden="true" /> <Icon size={15} className="text-ink-2 shrink-0" aria-hidden="true" />
<span className="text-label font-semibold text-ink flex-1 min-w-0 truncate">{kindLabel(t, x)}</span> <span className="text-label font-semibold text-ink flex-1 min-w-0 truncate">{kindLabel(t, x)}</span>
@@ -350,11 +446,18 @@ function StackFields({ w, set, media, onMedia, extras, path, depth }) {
</div> </div>
{x.kind !== 'stack' && ( {x.kind !== 'stack' && (
<div className={ROW}> <div className={ROW}>
<Field label={t('signage.widgets.inPart')}>
{custom
? <Button variant="secondary" icon={<RotateCcw size={14} />} onClick={() => setW(fillPlace(x))} data-testid="signage-cell-fill">{t('signage.widgets.backInPlace')}</Button>
: <span className="h-control flex items-center text-label text-ink-2" data-testid="signage-cell-place">{t('signage.widgets.fillsPlace')}</span>}
</Field>
<AlignField w={x} set={setW} testid="signage-cell-align" /> <AlignField w={x} set={setW} testid="signage-cell-align" />
<VerticalField w={x} set={setW} />
<InlineFields w={x} set={setW} /> <InlineFields w={x} set={setW} />
</div> </div>
)} )}
<BelowFields w={x} set={setW} media={media} onMedia={onMedia} extras={extras} path={`${cp}.${k}`} depth={depth + 1} /> <LookFields w={x} set={setW} />
<BelowFields w={x} set={setW} media={media} onMedia={onMedia} extras={extras} path={wp} depth={depth + 1} selected={selected} onSelect={onSelect} />
</div> </div>
) )
})} })}
@@ -42,3 +42,7 @@ export const weatherPlaces = (q, language) => client.get('/api/signage/weather/p
export const setWeatherPlace = body => client.put('/api/signage/weather/place', body).then(data) export const setWeatherPlace = body => client.put('/api/signage/weather/place', body).then(data)
export const forgetWeatherPlace = () => client.delete('/api/signage/weather/place').then(data) export const forgetWeatherPlace = () => client.delete('/api/signage/weather/place').then(data)
export const refreshWeather = () => client.post('/api/signage/weather/refresh').then(data) export const refreshWeather = () => client.post('/api/signage/weather/refresh').then(data)
// the venue's badges (owner review 5): their names, colours and icons
export const getBadges = () => client.get('/api/signage/badges').then(data)
export const putBadges = badges => client.put('/api/signage/badges', { badges }).then(data)
@@ -206,34 +206,6 @@ export function slideFromSaved(saved) {
return { kind: saved.kind, ...slideBody(saved), content: JSON.parse(JSON.stringify(saved.content || {})) } return { kind: saved.kind, ...slideBody(saved), content: JSON.parse(JSON.stringify(saved.content || {})) }
} }
/** Colours offered with one click in the colour picker (the venue's TV: data, not the theme):
* two rows of six (owner review 4, 2026-11-21). */
export const COLOUR_PRESETS = [
'#ffffff', '#d1d5db', '#6b7280', '#111827', '#000000', '#fde68a',
'#f59e0b', '#ef4444', '#f472b6', '#a78bfa', '#38bdf8', '#22c55e',
]
/** A colour as its #rrggbb and its opacity (0–100 %): #rrggbbaa is see-through (2026-11-21). */
export function splitAlpha(hex) {
const h = String(hex || '#000000').toLowerCase()
const rgb = /^#[0-9a-f]{6}/.test(h) ? h.slice(0, 7) : '#000000'
const a = /^#[0-9a-f]{8}$/.test(h) ? Math.round((parseInt(h.slice(7, 9), 16) / 255) * 100) : 100
return { rgb, alpha: a }
}
/** #rrggbb with an opacity: #rrggbb when it is solid, #rrggbbaa otherwise. */
export function joinAlpha(rgb, alpha) {
const a = Math.max(0, Math.min(100, Math.round(alpha)))
return a >= 100 ? rgb : `${rgb}${Math.round((a / 100) * 255).toString(16).padStart(2, '0')}`
}
/** A colour typed by hand: #rgb, #rrggbb or #rrggbbaa (the # optional) → #rrggbb(aa), or null. */
export function typedColour(text) {
let h = String(text || '').trim().toLowerCase().replace(/^#/, '')
if (/^[0-9a-f]{3}$/.test(h)) h = h.split('').map(x => x + x).join('')
return /^[0-9a-f]{6}([0-9a-f]{2})?$/.test(h) ? `#${h}` : null
}
// ── widgets moved and sized on the preview (2026-11-21) ────────────────────── // ── widgets moved and sized on the preview (2026-11-21) ──────────────────────
const round = v => Math.round(v * 10) / 10 const round = v => Math.round(v * 10) / 10
@@ -298,6 +270,52 @@ export function placeWidget(w, box) {
return { ...w, position: 'custom', size: 'custom', box } return { ...w, position: 'custom', size: 'custom', box }
} }
// ── widgets by path (owner review 5): "2" a slide's widget, "2.1.0" the first widget of its part 1 ──
const partWidgets = c => (c?.widgets?.length ? c.widgets : c?.widget ? [c.widget] : [])
/** The widget at a path, or null. */
export function widgetAt(widgets, path) {
if (path == null) return null
const seg = String(path).split('.').map(Number)
let w = widgets?.[seg[0]] || null
for (let i = 1; w && i < seg.length; i += 2) w = partWidgets(w.cells?.[seg[i]])[seg[i + 1]] || null
return w
}
/** The widgets with the one at `path` changed by fn (fn → null removes it). A part stored with one
* `widget` is written as `widgets`. */
export function updateWidgetAt(widgets, path, fn) {
const seg = String(path).split('.').map(Number)
const walk = (list, k) => {
const i = seg[k]
if (k === seg.length - 1) {
const next = fn(list[i])
return next == null ? list.filter((_, j) => j !== i) : list.map((x, j) => (j === i ? next : x))
}
const w = list[i]
const part = seg[k + 1]
const cells = (w.cells || []).map((c, j) => {
if (j !== part) return c
const { widget: _old, ...rest } = c
return { ...rest, widgets: walk(partWidgets(c), k + 2) }
})
return list.map((x, j) => (j === i ? { ...w, cells } : x))
}
return walk(widgets || [], 0)
}
/** A widget inside a stack's part ("2.1.0"), not one of the slide's own ("2"). */
export const inStack = path => path != null && String(path).includes('.')
/** The stack a widget sits in ("2.1.0" → "2"), or null. */
export const stackOf = path => (inStack(path) ? String(path).split('.').slice(0, -2).join('.') : null)
/** A widget in a stack's part back to filling its place (no box of its own). */
export function fillPlace(w) {
const { box: _box, ...rest } = w
return { ...rest, position: 'top-right', size: 'medium' }
}
/** A widget put back in a corner or a bar: no box, a real size again. */ /** A widget put back in a corner or a bar: no box, a real size again. */
export function presetWidget(w, position) { export function presetWidget(w, position) {
const { box: _box, ...rest } = w const { box: _box, ...rest } = w
@@ -333,11 +351,13 @@ export function toggleMonthDay(line, key) {
} }
/** A menu's colours until the venue picks its own (the TV's data, as the player draws them). */ /** A menu's colours until the venue picks its own (the TV's data, as the player draws them). */
export const MENU_COLOURS = { accent: '#f59e0b', text: '#ffffff' } export const MENU_COLOURS = { accent: '#f59e0b', text: '#ffffff', newBadge: '#38bdf8' }
/** A widget's colours before the venue picks its own (owner review 5). */
export const WIDGET_COLOURS = { text: '#ffffff', plate: '#00000080', qr: '#000000', qrBackground: '#ffffff' }
/** A menu's look as new ("Reset the look", owner review 4): every part back to the board's. */ /** A menu's look as new ("Reset the look", owner review 4): every part back to the board's. */
export const MENU_LOOK_DEFAULTS = { export const MENU_LOOK_DEFAULTS = {
font: 'sans', text_size: 100, text_colour: MENU_COLOURS.text, accent_colour: MENU_COLOURS.accent, badge_text_colour: null, font: 'sans', text_size: 100, text_colour: MENU_COLOURS.text, accent_colour: MENU_COLOURS.accent, badge_colour: null, badge_text_colour: null,
heading_style: {}, item_style: {}, price_style: {}, dot_style: {}, heading_style: {}, item_style: {}, price_style: {}, dot_style: {},
line_height: null, letter_spacing: null, photo_size: 100, photo_shape: 'rounded', line_height: null, letter_spacing: null, photo_size: 100, photo_shape: 'rounded',
} }
@@ -0,0 +1,23 @@
// The venue's badges (owner review 5, 2026-11-21), read once for the page and shared by every menu
// editor; saving them (Message & settings) updates every editor at once.
import { useEffect, useState } from 'react'
import { DEFAULT_BADGES } from '@xenia/signage'
import * as api from './signageApi'
let cache = null
const listeners = new Set()
export function setBadges(list) {
cache = list
listeners.forEach(f => f(list))
}
export function useBadges() {
const [list, setList] = useState(cache || DEFAULT_BADGES)
useEffect(() => {
listeners.add(setList)
if (!cache) api.getBadges().then(r => setBadges(r.badges)).catch(() => {})
return () => { listeners.delete(setList) }
}, [])
return list
}
@@ -3,7 +3,7 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { WIDGET_HOSTS } from '@xenia/signage' import { WIDGET_HOSTS } from '@xenia/signage'
import * as api from './signageApi' import * as api from './signageApi'
import { placeWidget } from './signageLogic' import { placeWidget, updateWidgetAt } from './signageLogic'
// what doesn't change what the server adds (where things sit, how they look): left out of the key // what doesn't change what the server adds (where things sit, how they look): left out of the key
const LOOK = new Set(['box', 'position', 'size', 'align', 'background', 'text_colour', 'accent_colour', 'font', 'text_size', const LOOK = new Set(['box', 'position', 'size', 'align', 'background', 'text_colour', 'accent_colour', 'font', 'text_size',
@@ -43,12 +43,10 @@ export function useWidgetEditor(setDraft, slideKey, label) {
const [state, setState] = useState({ key: slideKey, widget: null }) const [state, setState] = useState({ key: slideKey, widget: null })
const widget = state.key === slideKey ? state.widget : null const widget = state.key === slideKey ? state.widget : null
const setWidget = w => setState({ key: slideKey, widget: w }) const setWidget = w => setState({ key: slideKey, widget: w })
const onPlace = (i, box) => setDraft(d => { // `widget` is a path: "2", or "2.1.0" for a widget inside a stack's part (owner review 5)
const ws = d?.content?.widgets || [] const onPlace = (path, box) => setDraft(d => ({ ...d, content: { ...d.content, widgets: updateWidgetAt(d?.content?.widgets || [], path, w => placeWidget(w, box)) } }))
return { ...d, content: { ...d.content, widgets: ws.map((w, j) => (j === i ? placeWidget(w, box) : w)) } } const onRemove = path => {
}) setDraft(d => ({ ...d, content: { ...d.content, widgets: updateWidgetAt(d?.content?.widgets || [], path, () => null) } }))
const onRemove = i => {
setDraft(d => ({ ...d, content: { ...d.content, widgets: (d?.content?.widgets || []).filter((_, j) => j !== i) } }))
setWidget(null) setWidget(null)
} }
return { widget, setWidget, editor: { selected: widget, onSelect: setWidget, onPlace, onRemove, label } } return { widget, setWidget, editor: { selected: widget, onSelect: setWidget, onPlace, onRemove, label } }
-12
View File
@@ -102,15 +102,3 @@ test('the Slides library: what is saved, and a copy for a playlist', async () =>
assert.equal(saved.content.widgets[0].kind, 'name') // a copy, never the kept slide assert.equal(saved.content.widgets[0].kind, 'name') // a copy, never the kept slide
}) })
test('a colour with its opacity: #rrggbbaa, typed by hand (owner review 4)', async () => {
const { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } = await import('../src/pages/signage/signageLogic.js')
assert.equal(COLOUR_PRESETS.length, 12)
assert.deepEqual(splitAlpha('#FF0000'), { rgb: '#ff0000', alpha: 100 })
assert.deepEqual(splitAlpha('#ff000080'), { rgb: '#ff0000', alpha: 50 })
assert.equal(joinAlpha('#ff0000', 100), '#ff0000')
assert.equal(joinAlpha('#ff0000', 50), '#ff000080')
assert.equal(joinAlpha('#ff0000', 0), '#ff000000')
assert.equal(typedColour('abc'), '#aabbcc')
assert.equal(typedColour(' #11223344 '), '#11223344')
assert.equal(typedColour('#12345'), null)
})
+5 -1
View File
@@ -40,7 +40,11 @@
"clear": "Καθαρισμός", "clear": "Καθαρισμός",
"all": "Όλα", "all": "Όλα",
"noOptions": "Δεν βρέθηκε τίποτα", "noOptions": "Δεν βρέθηκε τίποτα",
"selected": "{{count}} επιλεγμένα" "selected": "{{count}} επιλεγμένα",
"colourOwn": "Δικό σας χρώμα",
"colourCode": "Κωδικός χρώματος",
"opacity": "Αδιαφάνεια",
"noIcon": "Χωρίς εικονίδιο"
}, },
"override": { "override": {
"title": "Έγκριση υπευθύνου", "title": "Έγκριση υπευθύνου",
+49 -13
View File
@@ -1434,7 +1434,7 @@
"which": "Προϊόντα", "which": "Προϊόντα",
"layout": "Διάταξη", "layout": "Διάταξη",
"width": "Πλάτος λίστας", "width": "Πλάτος λίστας",
"place": "Θέση λίστας", "place": "Οριζόντια στοίχιση",
"placeHint": "Σε όλο το πλάτος η λίστα γεμίζει την οθόνη: στενέψτε την για να τη μετακινήσετε.", "placeHint": "Σε όλο το πλάτος η λίστα γεμίζει την οθόνη: στενέψτε την για να τη μετακινήσετε.",
"hiddenTag": "κρυμμένο", "hiddenTag": "κρυμμένο",
"pageSecondsHint": "Όταν η λίστα δεν χωράει στην οθόνη, χωρίζεται σε σελίδες που εναλλάσσονται: κάθε σελίδα μένει τόσα δευτερόλεπτα.", "pageSecondsHint": "Όταν η λίστα δεν χωράει στην οθόνη, χωρίζεται σε σελίδες που εναλλάσσονται: κάθε σελίδα μένει τόσα δευτερόλεπτα.",
@@ -1443,7 +1443,9 @@
"rename": "Άλλο όνομα σε αυτόν τον πίνακα", "rename": "Άλλο όνομα σε αυτόν τον πίνακα",
"renameBack": "Πίσω στο όνομα του καταλόγου", "renameBack": "Πίσω στο όνομα του καταλόγου",
"catalogueName": "Το όνομα του καταλόγου (αυτό βλέπουν οι σερβιτόροι)", "catalogueName": "Το όνομα του καταλόγου (αυτό βλέπουν οι σερβιτόροι)",
"catalogueNameIs": "Κατάλογος: {{name}}" "catalogueNameIs": "Κατάλογος: {{name}}",
"vplace": "Κάθετη στοίχιση",
"vplaceHint": "Πού μπαίνει μια σύντομη λίστα: πάνω, στη μέση ή κάτω."
}, },
"badges": { "badges": {
"new": "Νέο", "new": "Νέο",
@@ -1488,7 +1490,7 @@
"bottom-bar": "Μπάρα κάτω" "bottom-bar": "Μπάρα κάτω"
}, },
"ownText": "Δικό του κείμενο (προαιρετικό)", "ownText": "Δικό του κείμενο (προαιρετικό)",
"ownTextHint": "Κενό: το μήνυμα ημέρας του καταστήματος (Προβολή → Οθόνες).", "ownTextHint": "Κενό: το μήνυμα της ημέρας του καταστήματος (το ίδιο σε κάθε οθόνη).",
"dateLong": "Τρίτη, 17 Νοεμβρίου 2026", "dateLong": "Τρίτη, 17 Νοεμβρίου 2026",
"dateShort": "17/11/2026", "dateShort": "17/11/2026",
"seconds": "Με δευτερόλεπτα", "seconds": "Με δευτερόλεπτα",
@@ -1539,14 +1541,29 @@
"removeSlide": "Αφαίρεση της διαφάνειας από αυτό το τμήμα", "removeSlide": "Αφαίρεση της διαφάνειας από αυτό το τμήμα",
"removeWidget": "Αφαίρεση αυτού του widget", "removeWidget": "Αφαίρεση αυτού του widget",
"before": "Μετακίνηση πριν", "before": "Μετακίνηση πριν",
"after": "Μετακίνηση μετά" "after": "Μετακίνηση μετά",
} "pickHint": "Στην προεπισκόπηση, διαλέξτε τη στοίβα και μετά πατήστε ένα widget της για να το μετακινήσετε ή να αλλάξετε το μέγεθός του μέσα στο τμήμα του."
},
"inPart": "Στη θέση του",
"fillsPlace": "Στοιχισμένο στη θέση του",
"backInPlace": "Πίσω σε στοίχιση",
"vertical": "Κάθετη στοίχιση",
"look": "Κείμενο και χρώματα",
"plateOnly": "Φόντο πίσω του",
"colour": "Χρώμα",
"asSlide": "Όπως η διαφάνεια",
"plate": "Φόντο πίσω του",
"noPlate": "Κανένα",
"textSize": "Μέγεθος κειμένου",
"qrColour": "Χρώμα κωδικού QR",
"qrBackground": "Φόντο κωδικού QR",
"changeMessage": "Αλλαγή μηνύματος"
}, },
"tabs": { "tabs": {
"playlists": "Λίστες", "playlists": "Λίστες",
"screens": "Οθόνες", "screens": "Οθόνες",
"schedules": "Προγράμματα", "schedules": "Προγράμματα",
"settings": "Μήνυμα και καιρός", "settings": "Μήνυμα & ρυθμίσεις",
"slides": "Διαφάνειες" "slides": "Διαφάνειες"
}, },
"screens": { "screens": {
@@ -1638,7 +1655,8 @@
"noForecast": "Καμία πρόγνωση: ο διακομιστής δεν φτάνει την υπηρεσία καιρού (χωρίς internet;). Το στοιχείο κρύβεται στο μεταξύ.", "noForecast": "Καμία πρόγνωση: ο διακομιστής δεν φτάνει την υπηρεσία καιρού (χωρίς internet;). Το στοιχείο κρύβεται στο μεταξύ.",
"waiting": "Καμία πρόγνωση ακόμα.", "waiting": "Καμία πρόγνωση ακόμα.",
"refresh": "Ενημέρωση τώρα", "refresh": "Ενημέρωση τώρα",
"forget": "Αφαίρεση πόλης" "forget": "Αφαίρεση πόλης",
"messagePlaceholder": "π.χ. Σήμερα: φρέσκο χταπόδι στα κάρβουνα"
}, },
"discardTitle": "Αλλαγές χωρίς αποθήκευση", "discardTitle": "Αλλαγές χωρίς αποθήκευση",
"discardYes": "Έξοδος χωρίς αποθήκευση", "discardYes": "Έξοδος χωρίς αποθήκευση",
@@ -1696,7 +1714,7 @@
"rounded": "Στρογγυλεμένο", "rounded": "Στρογγυλεμένο",
"round": "Στρογγυλό" "round": "Στρογγυλό"
}, },
"hint": "Κάθε πεδίο αλλάζει μόνο τον εαυτό του. Οι επικεφαλίδες και οι τιμές ξεκινούν με το μέγεθος και τη γραμματοσειρά των ονομάτων («Όπως τα ονόματα»). Το χρώμα των σημάτων χρωματίζει και τις τελείες σελίδας. Τα ονόματα με δεξιά στοίχιση τελειώνουν όλα στο ίδιο σημείο, με ίσες τελείες πριν από τις τιμές.", "hint": "Κάθε πεδίο αλλάζει μόνο τον εαυτό του. Οι επικεφαλίδες και οι τιμές ξεκινούν με το μέγεθος και τη γραμματοσειρά των ονομάτων («Όπως τα ονόματα»). Τα σήματα έχουν τα δικά τους χρώματα (Προβολή → Μήνυμα & ρυθμίσεις), εκτός αν διαλέξετε εδώ χρώματα για όλα. Τα ονόματα με δεξιά στοίχιση τελειώνουν όλα στο ίδιο σημείο, με ίσες τελείες πριν από τις τιμές.",
"f": { "f": {
"heading": { "heading": {
"size": "Μέγεθος επικεφαλίδων", "size": "Μέγεθος επικεφαλίδων",
@@ -1723,6 +1741,9 @@
"size": "Μέγεθος τελειών", "size": "Μέγεθος τελειών",
"colour": "Χρώμα τελειών", "colour": "Χρώμα τελειών",
"line": "Γραμμή τελειών" "line": "Γραμμή τελειών"
},
"widget": {
"style": "Στυλ"
} }
}, },
"badgeColour": "Χρώμα σημάτων", "badgeColour": "Χρώμα σημάτων",
@@ -1730,12 +1751,23 @@
"badgeTextAuto": "Αυτόματο", "badgeTextAuto": "Αυτόματο",
"reset": "Επαναφορά εμφάνισης", "reset": "Επαναφορά εμφάνισης",
"resetTitle": "Επαναφορά της εμφάνισης αυτού του μενού;", "resetTitle": "Επαναφορά της εμφάνισης αυτού του μενού;",
"resetBody": "Κάθε μέγεθος, χρώμα, γραμματοσειρά, στυλ, στοίχιση και διάστιχο γυρίζει στην αρχή. Τα προϊόντα, η σειρά και τα ονόματά τους μένουν. Η «Αναίρεση αλλαγών» τα φέρνει πίσω μέχρι να αποθηκεύσετε." "resetBody": "Κάθε μέγεθος, χρώμα, γραμματοσειρά, στυλ, στοίχιση και διάστιχο γυρίζει στην αρχή. Τα προϊόντα, η σειρά και τα ονόματά τους μένουν. Η «Αναίρεση αλλαγών» τα φέρνει πίσω μέχρι να αποθηκεύσετε.",
"pageDots": "Χρώμα τελειών σελίδας",
"badgeOwn": "Του κάθε σήματος"
}, },
"colourPick": { "saveAndLeave": "Αποθήκευση και έξοδος",
"custom": "Δικό σας χρώμα", "badgesSettings": {
"code": "Κωδικός χρώματος", "title": "Σήματα για πίνακες μενού",
"opacity": "Αδιαφάνεια" "hint": "Τα σήματα που μπορείτε να βάλετε σε προϊόντα στους πίνακες μενού και στα widgets μενού: τα ονόματα, τα χρώματα και τα εικονίδιά τους. Τα χρώματά τους είναι τα προεπιλεγμένα: ένας πίνακας μπορεί να δώσει σε όλα τα σήματά του δικό του χρώμα.",
"nameEl": "Όνομα στα ελληνικά",
"nameEn": "Όνομα στα αγγλικά",
"colour": "Φόντο",
"text": "Κείμενο",
"icon": "Εικονίδιο",
"add": "Προσθήκη σήματος",
"removeTitle": "Αφαίρεση του σήματος «{{name}}»;",
"removeBody": "Οι πίνακες που το χρησιμοποιούν σταματούν να το δείχνουν. Τίποτα δεν αλλάζει μέχρι να αποθηκεύσετε.",
"needName": "Κάθε σήμα χρειάζεται όνομα (στα ελληνικά ή στα αγγλικά)."
} }
}, },
"overview": { "overview": {
@@ -2104,6 +2136,10 @@
"putOnTab": "Σε καρτέλες", "putOnTab": "Σε καρτέλες",
"tabOutsideShifts": "Πληρωμές καρτελών σε κάποιον χωρίς βάρδια", "tabOutsideShifts": "Πληρωμές καρτελών σε κάποιον χωρίς βάρδια",
"tabOutsideShiftsTip": "Καταγράφονται ως εισπράξεις αυτού του ατόμου (π.χ. του ιδιοκτήτη)· δεν είναι στο συρτάρι καμίας βάρδιας, οπότε δεν μετρούν στο αναμενόμενο του συρταριού." "tabOutsideShiftsTip": "Καταγράφονται ως εισπράξεις αυτού του ατόμου (π.χ. του ιδιοκτήτη)· δεν είναι στο συρτάρι καμίας βάρδιας, οπότε δεν μετρούν στο αναμενόμενο του συρταριού."
},
"tvMessage": {
"title": "Μήνυμα της ημέρας",
"hint": "Σε όλες τις τηλεοράσεις μαζί, στα widgets που το δείχνουν."
} }
}, },
"products": { "products": {
+5 -1
View File
@@ -40,7 +40,11 @@
"clear": "Clear", "clear": "Clear",
"all": "All", "all": "All",
"noOptions": "Nothing found", "noOptions": "Nothing found",
"selected": "{{count}} selected" "selected": "{{count}} selected",
"colourOwn": "Your own colour",
"colourCode": "Colour code",
"opacity": "Opacity",
"noIcon": "No icon"
}, },
"override": { "override": {
"title": "Manager approval", "title": "Manager approval",
+49 -13
View File
@@ -1434,7 +1434,7 @@
"which": "Products", "which": "Products",
"layout": "Layout", "layout": "Layout",
"width": "Width of the list", "width": "Width of the list",
"place": "Where the list sits", "place": "Horizontal alignment",
"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", "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.", "pageSecondsHint": "When the list doesn't fit on the screen it is split into pages that take turns: each page stays this many seconds.",
@@ -1443,7 +1443,9 @@
"rename": "Name it differently on this board", "rename": "Name it differently on this board",
"renameBack": "Back to the catalogue's name", "renameBack": "Back to the catalogue's name",
"catalogueName": "The catalogue's name (the waiters see this one)", "catalogueName": "The catalogue's name (the waiters see this one)",
"catalogueNameIs": "Catalogue: {{name}}" "catalogueNameIs": "Catalogue: {{name}}",
"vplace": "Vertical alignment",
"vplaceHint": "Where a short list sits: at the top, in the middle or at the bottom."
}, },
"badges": { "badges": {
"new": "New", "new": "New",
@@ -1488,7 +1490,7 @@
"bottom-bar": "Bar at the bottom" "bottom-bar": "Bar at the bottom"
}, },
"ownText": "Its own text (optional)", "ownText": "Its own text (optional)",
"ownTextHint": "Empty: the venue's message of the day (Signage → Screens).", "ownTextHint": "Empty: the venue's message of the day (the same on every screen).",
"dateLong": "Tuesday, 17 November 2026", "dateLong": "Tuesday, 17 November 2026",
"dateShort": "17/11/2026", "dateShort": "17/11/2026",
"seconds": "With seconds", "seconds": "With seconds",
@@ -1539,14 +1541,29 @@
"removeSlide": "Take the slide out of this part", "removeSlide": "Take the slide out of this part",
"removeWidget": "Remove this widget", "removeWidget": "Remove this widget",
"before": "Move before", "before": "Move before",
"after": "Move after" "after": "Move after",
} "pickHint": "On the preview, pick the stack, then click a widget in it to move or size it inside its part."
},
"inPart": "In its place",
"fillsPlace": "Aligned in its place",
"backInPlace": "Back to aligned",
"vertical": "Vertical alignment",
"look": "Text and colours",
"plateOnly": "Background plate",
"colour": "Colour",
"asSlide": "As the slide",
"plate": "Background plate",
"noPlate": "None",
"textSize": "Text size",
"qrColour": "QR code colour",
"qrBackground": "QR code background",
"changeMessage": "Change the message"
}, },
"tabs": { "tabs": {
"playlists": "Playlists", "playlists": "Playlists",
"screens": "Screens", "screens": "Screens",
"schedules": "Schedules", "schedules": "Schedules",
"settings": "Message and weather", "settings": "Message & settings",
"slides": "Slides" "slides": "Slides"
}, },
"screens": { "screens": {
@@ -1638,7 +1655,8 @@
"noForecast": "No forecast: the server can't reach the weather service (no internet?). The widget is hidden meanwhile.", "noForecast": "No forecast: the server can't reach the weather service (no internet?). The widget is hidden meanwhile.",
"waiting": "No forecast yet.", "waiting": "No forecast yet.",
"refresh": "Fetch now", "refresh": "Fetch now",
"forget": "Remove the town" "forget": "Remove the town",
"messagePlaceholder": "e.g. Today: fresh grilled octopus"
}, },
"discardTitle": "Unsaved changes", "discardTitle": "Unsaved changes",
"discardYes": "Leave without saving", "discardYes": "Leave without saving",
@@ -1696,7 +1714,7 @@
"rounded": "Rounded", "rounded": "Rounded",
"round": "Round" "round": "Round"
}, },
"hint": "Each field changes only itself. Headings and prices start in the names' size and font (\"As the names\"). The badges' colour also colours the page dots. Names aligned right all end at the same point, with equal dots before the prices.", "hint": "Each field changes only itself. Headings and prices start in the names' size and font (\"As the names\"). Badges take their own colours (Signage → Message & settings) unless you pick colours here for all of them. Names aligned right all end at the same point, with equal dots before the prices.",
"f": { "f": {
"heading": { "heading": {
"size": "Headings size", "size": "Headings size",
@@ -1723,6 +1741,9 @@
"size": "Dots size", "size": "Dots size",
"colour": "Dots colour", "colour": "Dots colour",
"line": "Dots line" "line": "Dots line"
},
"widget": {
"style": "Style"
} }
}, },
"badgeColour": "Badges colour", "badgeColour": "Badges colour",
@@ -1730,12 +1751,23 @@
"badgeTextAuto": "Automatic", "badgeTextAuto": "Automatic",
"reset": "Reset the look", "reset": "Reset the look",
"resetTitle": "Reset the look of this menu?", "resetTitle": "Reset the look of this menu?",
"resetBody": "Every size, colour, font, style, alignment and spacing goes back to the start. The products, their order and names stay. \"Undo changes\" brings it back until you save." "resetBody": "Every size, colour, font, style, alignment and spacing goes back to the start. The products, their order and names stay. \"Undo changes\" brings it back until you save.",
"pageDots": "Page dots colour",
"badgeOwn": "Each badge's own"
}, },
"colourPick": { "saveAndLeave": "Save and leave",
"custom": "Your own colour", "badgesSettings": {
"code": "Colour code", "title": "Badges for menu boards",
"opacity": "Opacity" "hint": "The badges you can put on products on menu boards and menu widgets: their names, colours and icons. Their colours are the defaults: a board can still give all its badges a colour of its own.",
"nameEl": "Name in Greek",
"nameEn": "Name in English",
"colour": "Background",
"text": "Text",
"icon": "Icon",
"add": "Add a badge",
"removeTitle": "Remove the badge \"{{name}}\"?",
"removeBody": "Boards that use it stop showing it. Nothing changes until you save.",
"needName": "Every badge needs a name (in Greek or in English)."
} }
}, },
"overview": { "overview": {
@@ -2104,6 +2136,10 @@
"putOnTab": "Put on tabs", "putOnTab": "Put on tabs",
"tabOutsideShifts": "Paid on tabs to someone with no shift", "tabOutsideShifts": "Paid on tabs to someone with no shift",
"tabOutsideShiftsTip": "Recorded as received by that person (e.g. the owner); it isn't in any shift's drawer, so it isn't in the drawer's expected amount." "tabOutsideShiftsTip": "Recorded as received by that person (e.g. the owner); it isn't in any shift's drawer, so it isn't in the drawer's expected amount."
},
"tvMessage": {
"title": "Message of the day",
"hint": "On every TV at once, on the widgets that show it."
} }
}, },
"products": { "products": {
+4
View File
@@ -44,5 +44,9 @@ export function useUiLabels() {
noOptions: t('ui.noOptions'), noOptions: t('ui.noOptions'),
selected: count => t('ui.selected', { count }), selected: count => t('ui.selected', { count }),
pinProgress: (count, total) => t('ui.pinProgress', { count, total }), pinProgress: (count, total) => t('ui.pinProgress', { count, total }),
colourOwn: t('ui.colourOwn'),
colourCode: t('ui.colourCode'),
opacity: t('ui.opacity'),
noIcon: t('ui.noIcon'),
}), [t, language]) // eslint-disable-line react-hooks/exhaustive-deps }), [t, language]) // eslint-disable-line react-hooks/exhaustive-deps
} }
+1 -1
View File
@@ -39,7 +39,7 @@ function EmbeddedSlide({ slide, media, venue, now }) {
const pages = slide.kind === 'menu' && size ? boardPages(slide, 0, size.w || 16, size.h || 9) : null 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 const page = pages ? pageAt(pages.length, slide.content?.page_seconds, now.getTime()) : 0
return ( 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}> <div ref={ref} style={{ position: 'absolute', inset: 0, overflow: 'hidden', containerType: 'size' }} data-testid="signage-embedded" data-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} />} {size && <SlideView slide={{ ...slide, video_to_end: false }} media={media} venue={venue} now={now} pages={pages} page={page} />}
</div> </div>
) )
+59 -25
View File
@@ -4,8 +4,9 @@
// same on any TV. // same on any TV.
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 { BADGE_ICONS } from './badges'
import { useFormat, useTranslation } from '@xenia/i18n' import { useFormat, useTranslation } from '@xenia/i18n'
import { cellWidgets, fitUnit, FONTS, menuLook, menuPages, pageAt, priceChars, textWidth, visibleGroups, weatherIcon, widgetAlign } from './logic' import { badgeColours, badgeName, cellWidgets, fitUnit, FONTS, itemBadges, menuLook, menuPages, pageAt, priceChars, 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 }) {
@@ -63,12 +64,15 @@ export function MenuSlide({ slide, media, venue, now, page, pages, extras, embed
data-testid="signage-menu" data-page={page} data-pages={pages.length}> data-testid="signage-menu" data-page={page} data-pages={pages.length}>
{/* the list: the whole width, or narrower and placed left / centre / right (2026-11-21) */} {/* the list: the whole width, or narrower and placed left / centre / right (2026-11-21) */}
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', width: `${c.board_width || 100}%`, <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', width: `${c.board_width || 100}%`,
alignSelf: BOARD_ALIGN[c.board_align] || 'flex-start' }} data-testid="signage-menu-board" data-align={c.board_align || 'left'}> alignSelf: BOARD_ALIGN[c.board_align] || 'flex-start', justifyContent: VSELF[c.board_valign] || 'flex-start' }}
data-testid="signage-menu-board" data-align={c.board_align || 'left'} data-valign={c.board_valign || 'top'}>
{c.title && <h1 style={{ fontSize: `${7 * scale}cqmin`, fontWeight: 800, margin: '0 0 2cqmin', color: c.heading_style?.colour || accent, lineHeight: 1.1, {c.title && <h1 style={{ fontSize: `${7 * scale}cqmin`, fontWeight: 800, margin: '0 0 2cqmin', color: c.heading_style?.colour || 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, minHeight: 0, overflow: 'hidden', columnFill: 'auto', ...listSpacing(c) }} {/* top: the list takes the height (columns fill one after the other); middle / bottom: as tall as it is, placed (owner review 5) */}
<div style={{ columnCount: c.columns || 2, columnGap: '5cqmin', fontSize: `${3.2 * scale}cqmin`, flex: (c.board_valign || 'top') === 'top' ? 1 : '0 1 auto',
minHeight: 0, overflow: 'hidden', columnFill: 'auto', ...listSpacing(c) }}
data-testid="signage-menu-list"> data-testid="signage-menu-list">
<MenuGroups c={c} groups={groups} /> <MenuGroups c={c} groups={groups} badges={venue?.badges} />
</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">
@@ -96,8 +100,9 @@ const listSpacing = c => {
return { lineHeight: look.lineHeight, letterSpacing: look.letterSpacing } return { lineHeight: look.lineHeight, letterSpacing: look.letterSpacing }
} }
export function MenuGroups({ c, groups }) { export function MenuGroups({ c, groups, badges }) {
const { t } = useTranslation('terminal') const { t, i18n } = useTranslation('terminal')
const lang = c.language || (String(i18n.language || '').startsWith('el') ? 'el' : 'en')
const { formatMoney } = useFormat() const { formatMoney } = useFormat()
const look = menuLook(c) const look = menuLook(c)
const priceW = `${(priceChars(groups, formatMoney) * 0.62).toFixed(2)}em` const priceW = `${(priceChars(groups, formatMoney) * 0.62).toFixed(2)}em`
@@ -121,10 +126,16 @@ export function MenuGroups({ c, groups }) {
<div style={{ display: 'flex', alignItems: 'baseline', gap: '0.3em' }}> <div style={{ display: 'flex', alignItems: 'baseline', gap: '0.3em' }}>
<span style={{ ...look.item, textDecoration: it.available ? look.item.textDecoration : 'line-through', <span style={{ ...look.item, textDecoration: it.available ? look.item.textDecoration : 'line-through',
...(nameFills ? { flex: 1, minWidth: 0, textAlign: look.itemAlign } : {}) }} data-testid="signage-menu-name">{it.name}</span> ...(nameFills ? { flex: 1, minWidth: 0, textAlign: look.itemAlign } : {}) }} data-testid="signage-menu-name">{it.name}</span>
{it.badge && ( {itemBadges(it, badges).map(d => {
<span style={{ ...look.badge, fontSize: '0.55em', fontWeight: 800, padding: '0.1em 0.5em', borderRadius: '99em', const Icon = BADGE_ICONS[d.icon]
textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap', lineHeight: 1.4 }} data-testid="signage-badge">{t(`signage.badges.${it.badge}`)}</span> return (
)} <span key={d.key} style={{ ...badgeColours(d, c), fontSize: '0.55em', fontWeight: 800, padding: '0.1em 0.55em', borderRadius: '99em',
textTransform: 'uppercase', letterSpacing: '0.05em', whiteSpace: 'nowrap', lineHeight: 1.4, display: 'inline-flex', alignItems: 'center', gap: '0.3em',
alignSelf: 'center' }} data-testid="signage-badge" data-key={d.key}>
{Icon && <Icon style={{ width: '1.15em', height: '1.15em', flexShrink: 0 }} strokeWidth={2.5} aria-hidden="true" />}{badgeName(d, lang)}
</span>
)
})}
{!it.available && <span style={{ fontSize: '0.6em', whiteSpace: 'nowrap' }} data-testid="signage-sold-out">{t('signage.soldOut')}</span>} {!it.available && <span style={{ fontSize: '0.6em', whiteSpace: 'nowrap' }} data-testid="signage-sold-out">{t('signage.soldOut')}</span>}
{it.price != null && <> {it.price != null && <>
<span style={{ ...look.dots, ...(nameFills ? { flex: '0 0 2em' } : { flex: 1, minWidth: '0.6em' }) }} data-testid="signage-menu-dots" /> <span style={{ ...look.dots, ...(nameFills ? { flex: '0 0 2em' } : { flex: 1, minWidth: '0.6em' }) }} data-testid="signage-menu-dots" />
@@ -154,6 +165,12 @@ 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' }
const VSELF = { top: 'flex-start', middle: 'center', bottom: 'flex-end', auto: 'center' }
/** A widget's own colour and the plate behind it (owner review 5); `pad`: a plate that hugs it. */
const plate = (w, pad) => ({
...(w.colour ? { color: w.colour } : {}),
...(w.background_colour ? { background: w.background_colour, borderRadius: '1.2cqmin', ...(pad ? { padding: '0.8cqmin 1.6cqmin' } : {}) } : {}),
})
// a menu or a stack in a corner or a bar has no box of its own: it gets one of this size (cqmin) // 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] } const BOXED = { menu: [48, 56], stack: [60, 36] }
@@ -179,7 +196,7 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '3cqmin', padding: '2cqmin 4cqmin', style={{ ...pos, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '3cqmin', padding: '2cqmin 4cqmin',
background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: '9cqmin' }}> background: 'rgba(0,0,0,0.35)', color: colour || '#fff', minHeight: '9cqmin' }}>
{bar(where).map(([w, i, body]) => ( {bar(where).map(([w, i, body]) => (
<div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w) }}>{body}</div> <div key={i} data-widget={i} style={{ display: 'flex', flexDirection: 'column', alignItems: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w, true) }}>{body}</div>
))} ))}
</div> </div>
))} ))}
@@ -188,7 +205,7 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
return ( return (
<div key={i} data-widget={i} className="absolute" data-testid="signage-w-box" <div key={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: VSELF[w.vertical] || 'center', justifyContent: SELF[widgetAlign(w)], textAlign: widgetAlign(w), ...plate(w) }}>
{body} {body}
</div> </div>
</div> </div>
@@ -196,7 +213,7 @@ export function Widgets({ widgets, media, venue, now, colour, extras, embed }) {
} }
const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {} const own = w.align && w.align !== 'auto' ? { alignItems: SELF[w.align], textAlign: w.align } : {}
return ( return (
<div key={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" style={{ ...CORNER[w.position], ...own, display: 'flex', flexDirection: 'column', color: colour || '#fff', ...plate(w, true) }}>
{body} {body}
</div> </div>
) )
@@ -216,10 +233,17 @@ function widgetBody(w, ctx, fit, path) {
const { media, venue, now, fmt, extras } = ctx const { media, venue, now, fmt, extras } = ctx
const { formatDate, formatTime } = fmt const { formatDate, formatTime } = fmt
const x = extras[path] || {} const x = extras[path] || {}
const s = SIZE[w.size] || 1 const ts = (w.text_size || 100) / 100 // its own text size (owner review 5)
const unit = (height, width) => (fit ? fitUnit(height, width) : n => `${+(n * s).toFixed(3)}cqmin`) const s = (SIZE[w.size] || 1) * ts
const text = (u, size, weight = 700) => ({ fontSize: u(size), fontWeight: weight, lineHeight: 1.15, // in a box of its own the box sets the size: its text size can only make it smaller there
textShadow: '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)', whiteSpace: fit ? 'nowrap' : undefined }) const unit = (height, width) => {
if (!fit) return n => `${+(n * s).toFixed(3)}cqmin`
const f = fitUnit(height, width)
return n => f(n * Math.min(1, ts))
}
const text = (u, size, weight = 700) => ({ fontSize: u(size), fontWeight: w.bold === false ? 400 : w.bold ? Math.max(weight, 800) : weight, lineHeight: 1.15,
textShadow: w.background_colour ? undefined : '0 0.2cqmin 0.8cqmin rgba(0,0,0,0.35)', whiteSpace: fit ? 'nowrap' : undefined,
...(w.font ? { fontFamily: FONTS[w.font] } : {}), ...(w.italic ? { fontStyle: 'italic' } : {}), ...(w.underline ? { textDecoration: 'underline' } : {}) })
const line = (str, testid, weight) => { const line = (str, testid, weight) => {
const u = unit(3.4 * 1.15, textWidth(str.length, 3.4)) 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> return <span style={text(u, 3.4, weight)} data-testid={testid}>{str}</span>
@@ -257,15 +281,15 @@ function widgetBody(w, ctx, fit, path) {
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={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: w.qr_background || '#fff', padding: u(1), borderRadius: u(1), lineHeight: 0 }}>
<QRCodeSVG value={link} size={256} style={{ width: u(14), height: u(14) }} /> <QRCodeSVG value={link} size={256} fgColor={w.qr_colour || '#000000'} bgColor={w.qr_background || '#ffffff'} 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') return weatherBody(w, venue?.weather, unit, text, formatDate) if (w.kind === 'weather') return weatherBody(w, venue?.weather, unit, text, formatDate)
if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} />, 'menu') if (w.kind === 'menu') return boxed(<MenuWidget board={w.board || {}} menu={x.menu} now={now} badges={venue?.badges} />, 'menu')
if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack') if (w.kind === 'stack') return boxed(<Stack w={w} path={path} ctx={ctx} />, 'stack')
return null return null
} }
@@ -311,7 +335,7 @@ function weatherBody(w, wx, unit, text, formatDate) {
* A menu widget (2026-11-21): a board's list in the widget's box (inside an element with * 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. * `container-type: size`), its pages turning on the clock; the text sized so a page fills the box.
*/ */
function MenuWidget({ board: b, menu, now }) { function MenuWidget({ board: b, menu, now, badges }) {
const groups = visibleGroups(menu?.groups) const groups = visibleGroups(menu?.groups)
const per = b.page_size || 8 const per = b.page_size || 8
const headings = b.category_titles !== false const headings = b.category_titles !== false
@@ -328,7 +352,7 @@ function MenuWidget({ board: b, menu, now }) {
data-testid="signage-w-menu" data-page={page} data-pages={pages.length}> data-testid="signage-w-menu" data-page={page} data-pages={pages.length}>
{b.title && <div style={{ fontSize: '1.5em', fontWeight: 800, color: b.heading_style?.colour || accent, lineHeight: 1.15, marginBottom: '0.3em' }}>{b.title}</div>} {b.title && <div style={{ fontSize: '1.5em', fontWeight: 800, color: b.heading_style?.colour || accent, lineHeight: 1.15, marginBottom: '0.3em' }}>{b.title}</div>}
<div style={{ columnCount: cols, columnGap: '1.2em', columnFill: 'auto', ...listSpacing(b) }} data-testid="signage-menu-list"> <div style={{ columnCount: cols, columnGap: '1.2em', columnFill: 'auto', ...listSpacing(b) }} data-testid="signage-menu-list">
<MenuGroups c={b} groups={pages[page] || []} /> <MenuGroups c={b} groups={pages[page] || []} badges={badges} />
</div> </div>
</div> </div>
) )
@@ -354,11 +378,21 @@ function Stack({ w, path, ctx }) {
<div key={j} style={{ flex: `${c.share || 1} 1 0%`, minWidth: 0, minHeight: 0, position: 'relative', overflow: 'hidden', containerType: 'size', <div key={j} style={{ flex: `${c.share || 1} 1 0%`, minWidth: 0, minHeight: 0, position: 'relative', overflow: 'hidden', containerType: 'size',
display: 'flex', flexDirection: across }} data-testid="signage-stack-cell" data-share={c.share}> display: 'flex', flexDirection: across }} data-testid="signage-stack-cell" data-share={c.share}>
{ws.map((cw, k) => { {ws.map((cw, k) => {
const wp = `${cp}.${k}`
const own = cw.position === 'custom' && cw.box
const align = cw.align && cw.align !== 'auto' ? cw.align : 'center' const align = cw.align && cw.align !== 'auto' ? cw.align : 'center'
const body = widgetBody(cw, ctx, true, wp)
return ( return (
<div key={k} style={{ flex: '1 1 0%', minWidth: 0, minHeight: 0, overflow: 'hidden', containerType: 'size', <div key={k} style={{ flex: '1 1 0%', minWidth: 0, minHeight: 0, overflow: 'hidden', containerType: 'size', position: 'relative',
display: 'flex', alignItems: 'center', justifyContent: SELF[align], textAlign: align }} data-testid="signage-stack-place"> ...(own ? {} : { display: 'flex', alignItems: VSELF[cw.vertical] || 'center', justifyContent: SELF[align], textAlign: align }) }}
{widgetBody(cw, ctx, true, `${cp}.${k}`)} data-testid="signage-stack-place" data-place={wp}>
{body && (own ? (
<div data-widget={wp} style={{ position: 'absolute', left: `${cw.box.x}%`, top: `${cw.box.y}%`, width: `${cw.box.w}%`, height: `${cw.box.h}%`,
containerType: 'size', display: 'flex', alignItems: VSELF[cw.vertical] || 'center', justifyContent: SELF[align], textAlign: align, ...plate(cw) }}
data-testid="signage-w-box">{body}</div>
) : (
<div data-widget={wp} style={{ display: 'flex', maxWidth: '100%', maxHeight: '100%', ...(cw.kind === 'menu' || cw.kind === 'stack' ? { width: '100%', height: '100%' } : {}), ...plate(cw, true) }}>{body}</div>
))}
</div> </div>
) )
})} })}
+16
View File
@@ -0,0 +1,16 @@
// The icons a menu badge can have (owner review 5, 2026-11-21): the same names as the server's
// list (local_backend/services/signage_badges.py ICONS), drawn on the TV and offered in the editor.
import {
Apple, Award, Beef, Beer, CakeSlice, Carrot, ChefHat, Cherry, Citrus, Clock, Coffee, Croissant, Crown, CupSoda, Drumstick, Egg,
Fish, Flame, Gift, GlassWater, Hamburger, Heart, IceCreamCone, Leaf, Martini, Milk, Nut, Percent, Pizza, Salad, Sandwich, Shrimp,
Snowflake, Soup, Sparkles, Sprout, Star, Tag, ThumbsUp, Vegan, Wheat, WheatOff, Wine, Zap,
} from 'lucide-react'
export const BADGE_ICONS = {
sparkles: Sparkles, 'chef-hat': ChefHat, tag: Tag, star: Star, flame: Flame, sprout: Sprout, leaf: Leaf, vegan: Vegan, wheat: Wheat,
'wheat-off': WheatOff, fish: Fish, shrimp: Shrimp, beef: Beef, drumstick: Drumstick, egg: Egg, milk: Milk, nut: Nut, carrot: Carrot,
salad: Salad, pizza: Pizza, hamburger: Hamburger, sandwich: Sandwich, soup: Soup, croissant: Croissant, 'ice-cream-cone': IceCreamCone,
'cake-slice': CakeSlice, coffee: Coffee, 'cup-soda': CupSoda, wine: Wine, beer: Beer, martini: Martini, 'glass-water': GlassWater,
citrus: Citrus, cherry: Cherry, apple: Apple, heart: Heart, award: Award, 'thumbs-up': ThumbsUp, clock: Clock, percent: Percent,
gift: Gift, crown: Crown, zap: Zap, snowflake: Snowflake,
}
+1
View File
@@ -2,5 +2,6 @@
// player (terminal/src/apps/signage) and in the manager's live previews. Sizes are container // player (terminal/src/apps/signage) and in the manager's live previews. Sizes are container
// units (cqmin): put a slide inside an element with `container-type: size` (frameStyle() does). // units (cqmin): put a slide inside an element with `container-type: size` (frameStyle() does).
export * from './logic.js' export * from './logic.js'
export { BADGE_ICONS } from './badges.js'
export { Background, BlankSlide, MenuSlide, TextSlide, Widgets } from './Slides.jsx' export { Background, BlankSlide, MenuSlide, TextSlide, Widgets } from './Slides.jsx'
export { SlideView } from './SlideView.jsx' export { SlideView } from './SlideView.jsx'
+35 -4
View File
@@ -321,8 +321,8 @@ const DOTS = { dotted: 'dotted', dashed: 'dashed', solid: 'solid' }
* board's text size): headings, names and prices each their own size, colour, font, bold / italic / * board's text size): headings, names and prices each their own size, colour, font, bold / italic /
* underline and alignment (empty: the board's text size and font, the text colour for names and the * underline and alignment (empty: the board's text size and font, the text colour for names and the
* accent colour for headings and prices); the dots between name and price; line and letter spacing * accent colour for headings and prices); the dots between name and price; line and letter spacing
* (auto: 1.25 and normal; set on the list, never inherited from the page); photos' size and shape; * (auto: 1.25 and normal; set on the list, never inherited from the page); photos' size and shape.
* the badges' colours (2026-11-21: their text the venue's, or white / black to read on them). * Badges: badgeColours (owner review 5).
*/ */
export function menuLook(c = {}) { export function menuLook(c = {}) {
const base = c.text_size || 100 const base = c.text_size || 100
@@ -346,8 +346,6 @@ export function menuLook(c = {}) {
dots: d.style === 'none' dots: d.style === 'none'
? { borderBottom: 'none' } ? { borderBottom: 'none' }
: { borderBottom: `${+(0.08 * (d.size || 100) / 100).toFixed(3)}em ${DOTS[d.style] || 'dotted'} ${d.colour || 'currentColor'}`, opacity: d.colour ? 1 : 0.35 }, : { borderBottom: `${+(0.08 * (d.size || 100) / 100).toFixed(3)}em ${DOTS[d.style] || 'dotted'} ${d.colour || 'currentColor'}`, opacity: d.colour ? 1 : 0.35 },
// badges: the accent (also the page dots), their text the venue's or one that reads on it
badge: { background: accent, color: c.badge_text_colour || readableOn(accent) },
title: c.heading_style?.colour || accent, title: c.heading_style?.colour || accent,
lineHeight: c.line_height || 1.25, lineHeight: c.line_height || 1.25,
letterSpacing: c.letter_spacing != null ? `${c.letter_spacing}em` : 'normal', letterSpacing: c.letter_spacing != null ? `${c.letter_spacing}em` : 'normal',
@@ -358,6 +356,39 @@ export function menuLook(c = {}) {
} }
} }
/**
* The badges a venue has until it edits its own (owner review 5; the server's DEFAULTS in
* services/signage_badges.py): a screen that hasn't heard of the venue's list draws these.
*/
export const DEFAULT_BADGES = [
{ key: 'new', names: { el: 'Νέο', en: 'New' }, colour: '#22c55e', text_colour: null, icon: 'sparkles' },
{ key: 'chef', names: { el: 'Πρόταση σεφ', en: "Chef's pick" }, colour: '#f59e0b', text_colour: null, icon: 'chef-hat' },
{ key: 'offer', names: { el: 'Προσφορά', en: 'Offer' }, colour: '#ef4444', text_colour: null, icon: 'tag' },
{ key: 'popular', names: { el: 'Δημοφιλές', en: 'Popular' }, colour: '#f472b6', text_colour: null, icon: 'star' },
{ key: 'spicy', names: { el: 'Καυτερό', en: 'Spicy' }, colour: '#dc2626', text_colour: null, icon: 'flame' },
{ key: 'vegetarian', names: { el: 'Χορτοφαγικό', en: 'Vegetarian' }, colour: '#16a34a', text_colour: null, icon: 'sprout' },
{ key: 'vegan', names: { el: 'Vegan', en: 'Vegan' }, colour: '#15803d', text_colour: null, icon: 'vegan' },
]
/** A product's badges as their definitions (unknown keys left out; one badge stored as `badge` too). */
export function itemBadges(it, defs) {
const list = defs?.length ? defs : DEFAULT_BADGES
const keys = it?.badges?.length ? it.badges : it?.badge ? [it.badge] : []
return keys.map(k => list.find(d => d.key === k)).filter(Boolean)
}
/** A badge's colours on a board: the board's own for all its badges, else the badge's; text that reads. */
export function badgeColours(def, c = {}) {
const background = c.badge_colour || def?.colour || '#f59e0b'
return { background, color: c.badge_text_colour || def?.text_colour || readableOn(background) }
}
/** A badge's name in a language (the board's, else the screen's), else in the other one. */
export function badgeName(def, lang) {
const n = def?.names || {}
return n[lang] || n.el || n.en || def?.key || ''
}
/** A stack part's widgets (a part stored before owner review 4 has one `widget`). */ /** A stack part's widgets (a part stored before owner review 4 has one `widget`). */
export function cellWidgets(c) { export function cellWidgets(c) {
return c?.widgets?.length ? c.widgets : c?.widget ? [c.widget] : [] return c?.widgets?.length ? c.widgets : c?.widget ? [c.widget] : []
+12 -2
View File
@@ -202,7 +202,17 @@ test('owner review 4: a part\'s widgets (one stored as `widget` too), badges tha
assert.equal(readableOn('#1e3a8acc'), '#ffffff') assert.equal(readableOn('#1e3a8acc'), '#ffffff')
assert.equal(readableOn('#f59e0b'), '#111111') assert.equal(readableOn('#f59e0b'), '#111111')
assert.equal(readableOn('#fff'), '#111111') assert.equal(readableOn('#fff'), '#111111')
assert.deepEqual(menuLook({ accent_colour: '#1e3a8a' }).badge, { background: '#1e3a8a', color: '#ffffff' })
assert.deepEqual(menuLook({ accent_colour: '#1e3a8a', badge_text_colour: '#fde68a' }).badge, { background: '#1e3a8a', color: '#fde68a' })
assert.equal(menuLook({ accent_colour: '#123456', heading_style: { colour: '#ff0000' } }).title, '#ff0000') assert.equal(menuLook({ accent_colour: '#123456', heading_style: { colour: '#ff0000' } }).title, '#ff0000')
}) })
test('owner review 5: the venue badges, several per product; a board with its own badge colours', async () => {
const { badgeColours, badgeName, DEFAULT_BADGES, itemBadges } = await import('../src/logic.js')
const mine = [{ key: 'gf', names: { en: 'Gluten free' }, colour: '#0ea5e9', text_colour: null, icon: 'wheat-off' }, DEFAULT_BADGES[1]]
assert.deepEqual(itemBadges({ badges: ['chef', 'gf', 'gone'] }, mine).map(d => d.key), ['chef', 'gf'])
assert.deepEqual(itemBadges({ badge: 'new' }, null).map(d => d.key), ['new']) // stored before: one badge; no list yet: the defaults
assert.deepEqual(badgeColours(mine[0]), { background: '#0ea5e9', color: '#111111' })
assert.deepEqual(badgeColours(mine[0], { badge_colour: '#1e3a8a' }), { background: '#1e3a8a', color: '#ffffff' })
assert.deepEqual(badgeColours(mine[0], { badge_text_colour: '#fde68a' }), { background: '#0ea5e9', color: '#fde68a' })
assert.equal(badgeName(mine[0], 'el'), 'Gluten free')
assert.equal(badgeName(DEFAULT_BADGES[1], 'el'), 'Πρόταση σεφ')
})
+71
View File
@@ -465,6 +465,77 @@
box-shadow: var(--x-shadow-popover); outline: none; box-shadow: var(--x-shadow-popover); outline: none;
animation: x-fade-in var(--x-duration-fast) var(--x-ease); animation: x-fade-in var(--x-duration-fast) var(--x-ease);
} }
/* ── FieldRow (2026-11-21): fields that wrap, framed while wrapped ─────────────── */
.x-field-row {
display: grid; gap: var(--x-space-3); align-items: end;
grid-template-columns: repeat(auto-fill, minmax(min(var(--x-field-min, 10.5rem), 100%), 1fr));
padding: var(--x-space-3); border: var(--x-border-width) solid transparent; border-radius: var(--x-radius-control);
transition: background-color var(--x-duration-fast) var(--x-ease), border-color var(--x-duration-fast) var(--x-ease);
}
.x-field-row--wrapped { border-color: var(--x-line); background: var(--x-surface); }
.x-field-row--wrapped.x-field-row--shade { background: var(--x-surface-2); }
/* ── Slider (2026-11-21): framed like a field, its value beside it ──────────────── */
.x-slider {
min-height: var(--x-control-md); display: flex; align-items: center; gap: var(--x-space-3); padding: 0 var(--x-space-3);
border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control); background: var(--x-surface);
}
.x-slider__input { flex: 1; min-width: 0; accent-color: var(--x-accent); }
.x-slider__value { width: 3rem; text-align: right; font-size: var(--x-text-label); color: var(--x-ink-2); font-variant-numeric: tabular-nums; }
/* ── ColourField (2026-11-21): a colour as a field; its panel over the page ──────── */
.x-swatch {
display: block; flex-shrink: 0; width: 24px; height: 24px; border-radius: 999px; border: var(--x-border-width) solid var(--x-line-strong);
background: linear-gradient(var(--x-swatch), var(--x-swatch)), repeating-conic-gradient(#d1d5db 0 25%, #ffffff 0 50%) 0 0 / 8px 8px;
}
.x-colour {
width: 100%; min-width: 0; min-height: var(--x-control-md); display: flex; align-items: center; gap: var(--x-space-2); padding: 0 var(--x-space-3);
border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control); background: var(--x-surface);
color: var(--x-ink); font: inherit; font-size: var(--x-text-label); cursor: pointer; text-align: left;
transition: border-color var(--x-duration-fast) var(--x-ease);
}
.x-colour:hover { border-color: var(--x-line-strong); }
.x-colour:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
.x-colour__value { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--x-ink-2); }
.x-colour__value--code { font-family: var(--x-font-mono, ui-monospace, monospace); }
.x-colour__panel { display: grid; gap: var(--x-space-3); padding: var(--x-space-3); width: 17.5rem; }
.x-colour__auto {
min-height: var(--x-control-md); padding: 0 var(--x-space-3); text-align: left; font: inherit; font-size: var(--x-text-label); cursor: pointer;
border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control); background: var(--x-surface); color: var(--x-ink);
}
.x-colour__auto:hover { background: var(--x-surface-2); }
.x-colour__auto--on { border-color: var(--x-accent); background: var(--x-accent-soft); color: var(--x-accent-ink); }
.x-colour__presets { display: grid; grid-template-columns: repeat(6, 1fr); gap: var(--x-space-2); justify-items: center; }
.x-colour__preset { padding: 0; border: 0; background: none; border-radius: 999px; cursor: pointer; transition: transform var(--x-duration-fast) var(--x-ease); }
.x-colour__preset .x-swatch { width: 32px; height: 32px; }
.x-colour__preset:hover { transform: scale(1.1); }
.x-colour__preset:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
.x-colour__preset--on { box-shadow: 0 0 0 2px var(--x-surface), 0 0 0 4px var(--x-accent); }
.x-colour__own { display: grid; gap: var(--x-space-2); border-top: var(--x-border-width) solid var(--x-line); padding-top: var(--x-space-3); }
.x-colour__heading { font-size: var(--x-text-overline, 11px); font-weight: var(--x-weight-semibold); text-transform: uppercase; letter-spacing: 0.04em; color: var(--x-ink-3); }
.x-colour__row { display: flex; align-items: center; gap: var(--x-space-2); }
.x-colour__picker {
width: 40px; height: var(--x-control-md); flex-shrink: 0; padding: 2px; cursor: pointer;
border: var(--x-border-width) solid var(--x-line); border-radius: var(--x-radius-control); background: var(--x-surface);
}
.x-colour__code { flex: 1; min-width: 0; font-family: var(--x-font-mono, ui-monospace, monospace); }
.x-colour__opacity { display: grid; gap: 4px; font-size: var(--x-text-caption); color: var(--x-ink-2); }
.x-colour__opacity-row { display: flex; justify-content: space-between; font-variant-numeric: tabular-nums; }
.x-colour__opacity input { accent-color: var(--x-accent); }
/* ── IconPicker (2026-11-21) ──────────────────────────────────────────────────── */
.x-icon-pick__current { width: 24px; height: 24px; display: grid; place-items: center; color: var(--x-ink); flex-shrink: 0; }
.x-icon-pick { display: grid; gap: var(--x-space-2); padding: var(--x-space-3); width: 20rem; }
.x-icon-pick__grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: var(--x-space-1); }
.x-icon-pick__item, .x-icon-pick__none {
display: grid; place-items: center; min-height: 36px; border: var(--x-border-width) solid transparent; border-radius: var(--x-radius-control);
background: none; color: var(--x-ink-2); cursor: pointer; font: inherit; font-size: var(--x-text-label);
}
.x-icon-pick__none { border-color: var(--x-line); }
.x-icon-pick__item:hover, .x-icon-pick__none:hover { background: var(--x-surface-2); color: var(--x-ink); }
.x-icon-pick__item:focus-visible, .x-icon-pick__none:focus-visible { outline: none; box-shadow: var(--x-focus-ring); }
.x-icon-pick__item--on { border-color: var(--x-accent); background: var(--x-accent-soft); color: var(--x-accent-ink); }
/* ── Popover (2026-11-21): a small panel under a button, kept inside the window ── */ /* ── Popover (2026-11-21): a small panel under a button, kept inside the window ── */
.x-popover { .x-popover {
position: fixed; z-index: var(--x-z-popover); box-sizing: border-box; position: fixed; z-index: var(--x-z-popover); box-sizing: border-box;
@@ -0,0 +1,75 @@
import { useCallback, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { Field, Input } from './Field.jsx'
import { Popover } from './Popover.jsx'
import { useLabels } from './labels.js'
import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './colour.js'
/**
* The one colour field of the product (2026-11-21): its swatch and code, as tall as the fields
* beside it; a click opens a small panel over the page (Popover) with the ready colours, then the
* picker, the opacity and the code typed by hand. Stores #rrggbb, or #rrggbbaa when see-through.
* <ColourField label="Text colour" value={c} onChange={setC} />
* auto: { label, on, pick } — a first choice that leaves the colour to something else ("Automatic",
* "Each badge's own"); `on` shows it chosen (the field then reads its label).
* opacity: false hides the opacity (a colour that can't be see-through).
*/
export function ColourField({ label, hint, value, onChange, presets = COLOUR_PRESETS, auto, opacity = true, className, testId }) {
const labels = useLabels()
const [open, setOpen] = useState(false)
const [typed, setTyped] = useState(null)
const btn = useRef(null)
const v = (value || '#000000').toLowerCase()
const { rgb, alpha } = splitAlpha(v)
const close = useCallback(() => { setOpen(false); setTyped(null) }, [])
const tid = s => (testId ? `${testId}-${s}` : undefined)
return (
<>
<Field label={label} hint={hint} className={className}>
<button ref={btn} type="button" className="x-colour" onClick={() => setOpen(o => !o)} aria-expanded={open} aria-haspopup="dialog" data-testid={tid('open')}>
<Swatch colour={v} />
<span className={cx('x-colour__value', !auto?.on && 'x-colour__value--code')}>{auto?.on ? auto.label : v}</span>
</button>
</Field>
<Popover open={open} anchor={btn} onClose={close} aria-label={label} className="x-colour__panel" data-testid={tid('panel')}>
{auto && (
<button type="button" className={cx('x-colour__auto', auto.on && 'x-colour__auto--on')} aria-pressed={!!auto.on}
onClick={() => { auto.pick(); close() }} data-testid={tid('auto')}>{auto.label}</button>
)}
<div className="x-colour__presets">
{presets.map(c => {
const chosen = !auto?.on && rgb === c.toLowerCase()
return (
<button key={c} type="button" className={cx('x-colour__preset', chosen && 'x-colour__preset--on')} aria-label={c} aria-pressed={chosen} title={c}
onClick={() => { onChange(opacity ? joinAlpha(c.toLowerCase(), alpha) : c.toLowerCase()); close() }} data-testid={tid('preset')}>
<Swatch colour={c} />
</button>
)
})}
</div>
<div className="x-colour__own">
<span className="x-colour__heading">{labels.colourOwn}</span>
<div className="x-colour__row">
<input type="color" className="x-colour__picker" value={rgb} aria-label={label} data-testid={testId}
onChange={e => { setTyped(null); onChange(opacity ? joinAlpha(e.target.value, alpha) : e.target.value) }} />
<Input value={typed ?? v} maxLength={9} spellCheck={false} aria-label={labels.colourCode} className="x-colour__code" data-testid={tid('code')}
onChange={e => { setTyped(e.target.value); const c = typedColour(e.target.value); if (c && (opacity || c.length === 7)) onChange(c) }}
onBlur={() => setTyped(null)} />
</div>
{opacity && (
<label className="x-colour__opacity">
<span className="x-colour__opacity-row"><span>{labels.opacity}</span><span>{alpha}%</span></span>
<input type="range" min={0} max={100} step={5} value={alpha} data-testid={tid('opacity')}
onChange={e => { setTyped(null); onChange(joinAlpha(rgb, Number(e.target.value))) }} />
</label>
)}
</div>
</Popover>
</>
)
}
/** A colour's swatch over a checkerboard, so a see-through colour shows as one. */
export function Swatch({ colour, className }) {
return <span className={cx('x-swatch', className)} aria-hidden="true" style={{ '--x-swatch': colour }} />
}
+9 -3
View File
@@ -8,15 +8,19 @@ import { useLabels } from './labels.js'
* (2026-11-21). tone 'danger' for deleting / throwing work away. * (2026-11-21). tone 'danger' for deleting / throwing work away.
* <ConfirmDialog open title="Delete this slide?" confirmLabel="Delete" tone="danger" * <ConfirmDialog open title="Delete this slide?" confirmLabel="Delete" tone="danger"
* onConfirm={remove} onCancel={close}>It goes from the playlist.</ConfirmDialog> * onConfirm={remove} onCancel={close}>It goes from the playlist.</ConfirmDialog>
* altLabel / onAlt: a third choice, the main one (2026-11-21: unsaved changes → "Save and leave"
* beside "Leave without saving"); the confirm button is then the secondary danger one.
*/ */
export function ConfirmDialog({ open, title, children, confirmLabel, cancelLabel, tone = 'primary', onConfirm, onCancel, busy = false, testId }) { export function ConfirmDialog({ open, title, children, confirmLabel, cancelLabel, tone = 'primary', onConfirm, onCancel, altLabel, onAlt, busy = false, testId }) {
const labels = useLabels() const labels = useLabels()
const alt = altLabel && onAlt
return ( return (
<Dialog open={open} size="sm" title={title} onClose={onCancel} <Dialog open={open} size={alt ? 'md' : 'sm'} title={title} onClose={onCancel}
footer={<> footer={<>
<Button variant="secondary" onClick={onCancel} data-testid={testId ? `${testId}-cancel` : 'confirm-cancel'}>{cancelLabel ?? labels.cancel}</Button> <Button variant="secondary" onClick={onCancel} data-testid={testId ? `${testId}-cancel` : 'confirm-cancel'}>{cancelLabel ?? labels.cancel}</Button>
<Button variant={tone === 'danger' ? 'danger' : 'primary'} loading={busy} onClick={onConfirm} <Button variant={alt ? 'secondary' : tone === 'danger' ? 'danger' : 'primary'} tone={alt && tone === 'danger' ? 'danger' : undefined} loading={busy && !alt} onClick={onConfirm}
data-testid={testId ? `${testId}-ok` : 'confirm-ok'}>{confirmLabel ?? labels.submit}</Button> data-testid={testId ? `${testId}-ok` : 'confirm-ok'}>{confirmLabel ?? labels.submit}</Button>
{alt && <Button variant="primary" loading={busy} onClick={onAlt} data-testid={testId ? `${testId}-alt` : 'confirm-alt'}>{altLabel}</Button>}
</>}> </>}>
{children && <div className="x-confirm__body">{children}</div>} {children && <div className="x-confirm__body">{children}</div>}
</Dialog> </Dialog>
@@ -27,6 +31,7 @@ export function ConfirmDialog({ open, title, children, confirmLabel, cancelLabel
* The same as a hook that answers with a promise: * The same as a hook that answers with a promise:
* const [confirm, confirmDialog] = useConfirm() * const [confirm, confirmDialog] = useConfirm()
* if (!(await confirm({ title, body, confirmLabel, tone: 'danger' }))) return * if (!(await confirm({ title, body, confirmLabel, tone: 'danger' }))) return
* With altLabel the promise answers 'alt' for the third choice (truthy: check it first).
* …render {confirmDialog} somewhere in the component. * …render {confirmDialog} somewhere in the component.
*/ */
export function useConfirm() { export function useConfirm() {
@@ -35,6 +40,7 @@ export function useConfirm() {
const answer = value => { ask?.resolve(value); setAsk(null) } const answer = value => { ask?.resolve(value); setAsk(null) }
const dialog = ask ? ( const dialog = ask ? (
<ConfirmDialog open title={ask.title} confirmLabel={ask.confirmLabel} cancelLabel={ask.cancelLabel} tone={ask.tone} testId={ask.testId} <ConfirmDialog open title={ask.title} confirmLabel={ask.confirmLabel} cancelLabel={ask.cancelLabel} tone={ask.tone} testId={ask.testId}
altLabel={ask.altLabel} onAlt={ask.altLabel ? () => answer('alt') : undefined}
onConfirm={() => answer(true)} onCancel={() => answer(false)}>{ask.body}</ConfirmDialog> onConfirm={() => answer(true)} onCancel={() => answer(false)}>{ask.body}</ConfirmDialog>
) : null ) : null
return [confirm, dialog] return [confirm, dialog]
+10 -3
View File
@@ -45,13 +45,20 @@ export function FilterChip({ pressed = false, tone = 'neutral', count, size = 'm
* A few mutually exclusive views (List / Map). options: [{ value, label, icon?, ariaLabel? }] * A few mutually exclusive views (List / Map). options: [{ value, label, icon?, ariaLabel? }]
* (ariaLabel: the name of an option shown as an icon only). fill: as wide as its column, the options sharing it. * (ariaLabel: the name of an option shown as an icon only). fill: as wide as its column, the options sharing it.
* <Segmented value={view} onChange={setView} options={[…]} aria-label="View" /> * <Segmented value={view} onChange={setView} options={[…]} aria-label="View" />
* multiple (2026-11-21): toggles that go together (bold / italic / underline); value is an array.
*/ */
export function Segmented({ options = [], value, onChange, size = 'md', fill = false, className, ...rest }) { export function Segmented({ options = [], value, onChange, size = 'md', fill = false, multiple = false, className, ...rest }) {
const on = v => (multiple ? (value || []).includes(v) : v === value)
const pick = v => {
if (!multiple) return onChange?.(v)
const list = value || []
return onChange?.(list.includes(v) ? list.filter(x => x !== v) : [...list, v])
}
return ( return (
<div role="group" className={cx('x-segmented', `x-segmented--${size}`, fill && 'x-segmented--fill', className)} {...rest}> <div role="group" className={cx('x-segmented', `x-segmented--${size}`, fill && 'x-segmented--fill', className)} {...rest}>
{options.map(o => ( {options.map(o => (
<button key={o.value} type="button" aria-pressed={o.value === value} className={cx('x-segmented__item', o.value === value && 'x-segmented__item--on')} <button key={o.value} type="button" aria-pressed={on(o.value)} className={cx('x-segmented__item', on(o.value) && 'x-segmented__item--on')}
onClick={() => onChange?.(o.value)} data-testid={o.testId} aria-label={o.ariaLabel} title={o.ariaLabel}> onClick={() => pick(o.value)} data-testid={o.testId} aria-label={o.ariaLabel} title={o.ariaLabel}>
{o.icon}{o.label} {o.icon}{o.label}
</button> </button>
))} ))}
+34
View File
@@ -0,0 +1,34 @@
import { Children, useLayoutEffect, useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
/**
* A row of fields that wraps (2026-11-21): each field keeps its least width (`min`) and the ones
* that don't fit go to a second line, in columns that line up from row to row. While a row is
* wrapped it is framed and (with `shade`, every other row) tinted, so its two lines read as one
* set; a row that fits on one line looks like any other row.
* <FieldRow><Field …/><Field …/></FieldRow>
* <FieldRow shade>…</FieldRow> (alternate rows)
*/
export function FieldRow({ min = '10.5rem', shade = false, className, style, children, ...rest }) {
const ref = useRef(null)
const [wrapped, setWrapped] = useState(false)
const count = Children.count(children)
useLayoutEffect(() => {
const el = ref.current
if (!el) return undefined
const check = () => {
const kids = [...el.children].filter(k => k.offsetParent !== null || k.getClientRects().length)
setWrapped(kids.length > 1 && kids.some(k => k.offsetTop > kids[0].offsetTop + 2))
}
check()
const ro = new ResizeObserver(check)
ro.observe(el)
return () => ro.disconnect()
}, [count])
return (
<div ref={ref} className={cx('x-field-row', wrapped && 'x-field-row--wrapped', wrapped && shade && 'x-field-row--shade', className)}
style={{ ...style, '--x-field-min': min }} data-wrapped={wrapped ? 'true' : undefined} {...rest}>
{children}
</div>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { useRef, useState } from 'react'
import { cx } from '../internal/cx.js'
import { Field } from './Field.jsx'
import { Popover } from './Popover.jsx'
import { useLabels } from './labels.js'
/**
* Pick an icon from a set (2026-11-21): a field showing the icon chosen; a click opens a grid of
* the set over the page (Popover), with "No icon" first.
* <IconPicker label="Icon" icons={{ flame: Flame, leaf: Leaf }} value={key} onChange={setKey} />
* icons: { key: a component taking `size` }. value null = no icon.
*/
export function IconPicker({ label, icons = {}, value, onChange, className, testId }) {
const labels = useLabels()
const [open, setOpen] = useState(false)
const btn = useRef(null)
const Current = value ? icons[value] : null
const pick = k => { onChange?.(k); setOpen(false) }
const tid = s => (testId ? `${testId}-${s}` : undefined)
return (
<>
<Field label={label} className={className}>
<button ref={btn} type="button" className="x-colour" onClick={() => setOpen(o => !o)} aria-expanded={open} aria-haspopup="dialog" data-testid={tid('open')}>
<span className="x-icon-pick__current" aria-hidden="true">{Current ? <Current size={18} /> : null}</span>
<span className="x-colour__value">{value || labels.noIcon}</span>
</button>
</Field>
<Popover open={open} anchor={btn} onClose={() => setOpen(false)} aria-label={label} className="x-icon-pick" data-testid={tid('panel')}>
<button type="button" className={cx('x-icon-pick__none', !value && 'x-icon-pick__item--on')} onClick={() => pick(null)} data-testid={tid('none')}>{labels.noIcon}</button>
<div className="x-icon-pick__grid">
{Object.entries(icons).map(([k, Icon]) => (
<button key={k} type="button" className={cx('x-icon-pick__item', value === k && 'x-icon-pick__item--on')} aria-label={k} aria-pressed={value === k} title={k}
onClick={() => pick(k)} data-testid={tid(k)}>
<Icon size={20} aria-hidden="true" />
</button>
))}
</div>
</Popover>
</>
)
}
+18
View File
@@ -0,0 +1,18 @@
import { Field } from './Field.jsx'
/**
* A slider with its label and its value, framed and as tall as the fields beside it (2026-11-21).
* <Slider label="Text size" value={size} min={50} max={250} step={10} suffix="%" onChange={setSize} />
* onChange receives the number.
*/
export function Slider({ label, value, min = 0, max = 100, step = 1, onChange, suffix = '', className, testId }) {
return (
<Field label={label} className={className}>
<span className="x-slider">
<input type="range" min={min} max={max} step={step} value={value} onChange={e => onChange?.(Number(e.target.value))}
className="x-slider__input" aria-label={label} data-testid={testId} />
<span className="x-slider__value">{value}{suffix}</span>
</span>
</Field>
)
}
+28
View File
@@ -0,0 +1,28 @@
// A colour's helpers for ColourField (2026-11-21): pure, unit-tested (tests/colour.test.mjs).
/** Twelve ready colours, two rows of six (a venue's colours: data, not the theme's). */
export const COLOUR_PRESETS = [
'#ffffff', '#d1d5db', '#6b7280', '#111827', '#000000', '#fde68a',
'#f59e0b', '#ef4444', '#f472b6', '#a78bfa', '#38bdf8', '#22c55e',
]
/** A colour as its #rrggbb and its opacity (0–100 %): #rrggbbaa is see-through. */
export function splitAlpha(hex) {
const h = String(hex || '#000000').toLowerCase()
const rgb = /^#[0-9a-f]{6}/.test(h) ? h.slice(0, 7) : '#000000'
const alpha = /^#[0-9a-f]{8}$/.test(h) ? Math.round((parseInt(h.slice(7, 9), 16) / 255) * 100) : 100
return { rgb, alpha }
}
/** #rrggbb with an opacity: #rrggbb when it is solid, #rrggbbaa otherwise. */
export function joinAlpha(rgb, alpha) {
const a = Math.max(0, Math.min(100, Math.round(alpha)))
return a >= 100 ? rgb : `${rgb}${Math.round((a / 100) * 255).toString(16).padStart(2, '0')}`
}
/** A colour typed by hand: #rgb, #rrggbb or #rrggbbaa (the # optional) → #rrggbb(aa), or null. */
export function typedColour(text) {
let h = String(text || '').trim().toLowerCase().replace(/^#/, '')
if (/^[0-9a-f]{3}$/.test(h)) h = h.split('').map(x => x + x).join('')
return /^[0-9a-f]{6}([0-9a-f]{2})?$/.test(h) ? `#${h}` : null
}
+4
View File
@@ -21,6 +21,10 @@ export const DEFAULT_LABELS = {
all: 'All', all: 'All',
noOptions: 'Nothing found', noOptions: 'Nothing found',
selected: n => `${n} selected`, selected: n => `${n} selected`,
colourOwn: 'Your own colour',
colourCode: 'Colour code',
opacity: 'Opacity',
noIcon: 'No icon',
pinProgress: (n, total) => `${n} of ${total} digits entered`, pinProgress: (n, total) => `${n} of ${total} digits entered`,
} }
+5
View File
@@ -23,6 +23,11 @@ export { Spinner } from './components/Spinner.jsx'
export { Field, Input, Textarea, Select } from './components/Field.jsx' export { Field, Input, Textarea, Select } from './components/Field.jsx'
export { Dropdown } from './components/Dropdown.jsx' export { Dropdown } from './components/Dropdown.jsx'
export { Popover } from './components/Popover.jsx' export { Popover } from './components/Popover.jsx'
export { ColourField, Swatch } from './components/ColourField.jsx'
export { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from './components/colour.js'
export { FieldRow } from './components/FieldRow.jsx'
export { Slider } from './components/Slider.jsx'
export { IconPicker } from './components/IconPicker.jsx'
export { Page, PageHeader, Pane, Toolbar, ToolbarSpacer } from './components/Page.jsx' export { Page, PageHeader, Pane, Toolbar, ToolbarSpacer } from './components/Page.jsx'
export { SearchInput, FilterChip, Segmented, Tabs } from './components/Controls.jsx' export { SearchInput, FilterChip, Segmented, Tabs } from './components/Controls.jsx'
export { Switch } from './components/Switch.jsx' export { Switch } from './components/Switch.jsx'
+15
View File
@@ -0,0 +1,15 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { COLOUR_PRESETS, joinAlpha, splitAlpha, typedColour } from '../src/components/colour.js'
test('a colour with its opacity: #rrggbbaa, typed by hand', () => {
assert.equal(COLOUR_PRESETS.length, 12)
assert.deepEqual(splitAlpha('#FF0000'), { rgb: '#ff0000', alpha: 100 })
assert.deepEqual(splitAlpha('#ff000080'), { rgb: '#ff0000', alpha: 50 })
assert.equal(joinAlpha('#ff0000', 100), '#ff0000')
assert.equal(joinAlpha('#ff0000', 50), '#ff000080')
assert.equal(joinAlpha('#ff0000', 0), '#ff000000')
assert.equal(typedColour('abc'), '#aabbcc')
assert.equal(typedColour(' #11223344 '), '#11223344')
assert.equal(typedColour('#12345'), null)
})
+3 -2
View File
@@ -202,7 +202,7 @@ try {
r.check('devices: the kitchen screen settings come in sections, prep zone "All zones" by default (3.2a)', r.check('devices: the kitchen screen settings come in sections, prep zone "All zones" by default (3.2a)',
await dlg.locator('[data-config-group]').count() >= 4 await dlg.locator('[data-config-group]').count() >= 4
&& (await dlg.getByLabel('Prep zone').locator('option:checked').textContent()) === 'All zones' && (await dlg.getByLabel('Prep zone').locator('option:checked').textContent()) === 'All zones'
&& await dlg.locator('input[type="color"]').count() === 4) && await dlg.locator('button[data-testid^="config-colour"][data-testid$="-open"]').count() === 4) // the shared colour field (owner review 5)
await dlg.getByLabel('Text size').fill('110') await dlg.getByLabel('Text size').fill('110')
await dlg.getByRole('button', { name: 'Pair a device' }).click() await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {}) await page.waitForFunction(() => document.querySelectorAll('[data-testid^="device-"][data-status]').length === 1, null, { timeout: 8000 }).catch(() => {})
@@ -933,7 +933,8 @@ try {
r.check(`${ov} "Open the day" opens it`, await dayState() === 'true' && !!(await api('GET', '/api/business-day/current', { token: boss }))) r.check(`${ov} "Open the day" opens it`, await dayState() === 'true' && !!(await api('GET', '/api/business-day/current', { token: boss })))
const ovWaiter = (await api('GET', '/api/waiters/', { token: boss })).find(w => w.username === 'demo_maria') const ovWaiter = (await api('GET', '/api/waiters/', { token: boss })).find(w => w.username === 'demo_maria')
await page.getByTestId('shift-start').click() await page.getByTestId('shift-start').click()
await page.getByTestId('shift-start-waiter').selectOption(String(ovWaiter.id)) await page.getByTestId('shift-start-waiter').click()
await page.getByRole('option', { name: ovWaiter.full_name || ovWaiter.username }).click()
await page.getByRole('dialog').getByLabel('Starting cash').fill('20,5') await page.getByRole('dialog').getByLabel('Starting cash').fill('20,5')
await page.getByTestId('shift-start-confirm').click() await page.getByTestId('shift-start-confirm').click()
const ovRow = page.getByTestId('shift-row').filter({ hasText: ovWaiter.full_name }) const ovRow = page.getByTestId('shift-row').filter({ hasText: ovWaiter.full_name })
+42 -4
View File
@@ -282,14 +282,18 @@ try {
const firstRow = mgr.getByTestId('signage-menu-row').first() const firstRow = mgr.getByTestId('signage-menu-row').first()
await sleep(700) await sleep(700)
const badgeId = Number(await firstRow.getAttribute('data-id')) const badgeId = Number(await firstRow.getAttribute('data-id'))
await firstRow.getByTestId('signage-menu-badge').selectOption('offer') // owner review 5: several badges, from the venue's list, in the shared dropdown
await firstRow.getByTestId('signage-menu-badge').click()
await mgr.getByRole('option', { name: 'Offer' }).click()
await mgr.getByRole('option', { name: 'Spicy' }).click()
await mgr.keyboard.press('Escape')
const hideRow = mgr.getByTestId('signage-menu-row').nth(1) const hideRow = mgr.getByTestId('signage-menu-row').nth(1)
const hiddenId = Number(await hideRow.getAttribute('data-id')) const hiddenId = Number(await hideRow.getAttribute('data-id'))
await hideRow.getByTestId('signage-item-hide').click() await hideRow.getByTestId('signage-item-hide').click()
await mgr.getByTestId('signage-widget-add-clock').click() await mgr.getByTestId('signage-widget-add-clock').click()
await sleep(900) await sleep(900)
r.check('5.6b: the preview shows the board with its badge', r.check('5.6b: the preview shows the board with its badges (two, with their icons)',
await waitFor(async () => (await mgr.getByTestId('signage-preview').getByTestId('signage-badge').count()) > 0, 8000, 300) === true) await waitFor(async () => (await mgr.getByTestId('signage-preview').locator('[data-testid="signage-badge"] svg').count()) >= 2, 8000, 300) === true)
await mgr.getByTestId('signage-slide-save').click() await mgr.getByTestId('signage-slide-save').click()
await sleep(1000) await sleep(1000)
const op = (await api('GET', '/api/signage/playlists', { token: boss })).find(x => x.name === 'Opening') const op = (await api('GET', '/api/signage/playlists', { token: boss })).find(x => x.name === 'Opening')
@@ -297,7 +301,7 @@ try {
const mc = menuSlide?.content || {} const mc = menuSlide?.content || {}
r.check('5.6b: saved: the categories, the single product, the hidden one, the board\'s own order, the badge, the clock', r.check('5.6b: saved: the categories, the single product, the hidden one, the board\'s own order, the badge, the clock',
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)]?.join() === 'offer,spicy'
&& (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 && !i.hidden) && 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 }))
@@ -349,6 +353,20 @@ try {
await stackCard.getByTestId('signage-stack-cell-editor').nth(1).locator('[data-testid="signage-stack-part-widget"][data-kind="date"]').getByTestId('signage-stack-part-remove').click() await stackCard.getByTestId('signage-stack-cell-editor').nth(1).locator('[data-testid="signage-stack-part-widget"][data-kind="date"]').getByTestId('signage-stack-part-remove').click()
r.check('2026-11-21 (4): …and one of them removed', r.check('2026-11-21 (4): …and one of them removed',
await waitFor(async () => (await part2().getByTestId('signage-stack-place').count()) === 1 && (await part2().getByTestId('signage-w-date').count()) === 0, 6000, 300) === true) await waitFor(async () => (await part2().getByTestId('signage-stack-place').count()) === 1 && (await part2().getByTestId('signage-w-date').count()) === 0, 6000, 300) === true)
// owner review 5: a widget in a part aligned to the bottom, in italics, in a colour of its own
const textInPart = stackCard.getByTestId('signage-stack-cell-editor').nth(1).locator('[data-testid="signage-stack-part-widget"][data-kind="text"]')
await textInPart.getByTestId('signage-cell-vertical-bottom').click()
await textInPart.getByTestId('signage-widget-look-toggle').click()
await textInPart.getByTestId('signage-widget-italic').click()
await textInPart.getByTestId('signage-widget-colour-open').click()
await mgr.getByTestId('signage-widget-colour-preset').nth(7).click()
r.check('2026-11-21 (5): a widget in a part: at the bottom of its place, in italics, its own colour',
await waitFor(async () => {
const place = part2().getByTestId('signage-stack-place').first()
const css = await place.evaluate(el => ({ align: getComputedStyle(el).alignItems, italic: getComputedStyle(el.querySelector('[data-testid="signage-w-text"]')).fontStyle,
colour: getComputedStyle(el.querySelector('[data-widget]')).color }))
return css.align === 'flex-end' && css.italic === 'italic' && css.colour === 'rgb(239, 68, 68)'
}, 6000, 300) === true)
// Delete removes the picked widget (picked on its card) // Delete removes the picked widget (picked on its card)
await stackCard.locator('span', { hasText: 'Horizontal stack' }).first().click() await stackCard.locator('span', { hasText: 'Horizontal stack' }).first().click()
await mgr.keyboard.press('Delete') await mgr.keyboard.press('Delete')
@@ -409,6 +427,15 @@ try {
const mc3 = (await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.find(x => x.kind === 'menu').content const mc3 = (await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.find(x => x.kind === 'menu').content
r.check('2026-11-21 (3): saved with a name for this board and the names aligned right', r.check('2026-11-21 (3): saved with a name for this board and the names aligned right',
Object.values(mc3.names || {}).includes('Signature dish') && mc3.item_style?.align === 'right', JSON.stringify({ names: mc3.names, item: mc3.item_style })) Object.values(mc3.names || {}).includes('Signature dish') && mc3.item_style?.align === 'right', JSON.stringify({ names: mc3.names, item: mc3.item_style }))
// owner review 5: leaving a slide with changes: "Save and leave"
await mgr.getByTestId('signage-menu-title').fill('Saved on the way out')
await mgr.locator('[data-testid="signage-slide-card"]:not([data-kind="menu"])').first().click()
await mgr.getByTestId('signage-discard-alt').click()
await sleep(1000)
r.check('2026-11-21 (5): "Save and leave" saves the slide before going to the next one',
(await api('GET', `/api/signage/playlists/${op.id}`, { token: boss })).slides.find(x => x.kind === 'menu').content.title === 'Saved on the way out')
await mgr.locator('[data-testid="signage-slide-card"][data-kind="menu"]').first().click()
await sleep(800)
await mgr.getByTestId('signage-keep-slide').click() await mgr.getByTestId('signage-keep-slide').click()
await mgr.getByTestId('signage-keep-name').fill('Board to keep') await mgr.getByTestId('signage-keep-name').fill('Board to keep')
await mgr.getByTestId('signage-keep-confirm').click() await mgr.getByTestId('signage-keep-confirm').click()
@@ -436,6 +463,17 @@ try {
await mgr.getByTestId('signage-message-save').click() await mgr.getByTestId('signage-message-save').click()
await sleep(700) await sleep(700)
r.check('5.6c: the message of the day is saved from the manager', (await api('GET', '/api/signage/message', { token: boss })).text === 'Kalimera from the manager') r.check('5.6c: the message of the day is saved from the manager', (await api('GET', '/api/signage/message', { token: boss })).text === 'Kalimera from the manager')
// owner review 5: the venue's badges: one added with its name, colours and icon
await mgr.getByTestId('signage-badge-add').click()
const newRow = mgr.getByTestId('signage-badge-row').last()
await newRow.getByTestId('signage-badge-name-en').fill('Gluten free')
await newRow.getByTestId('signage-badge-icon-open').click()
await mgr.getByTestId('signage-badge-icon-wheat-off').click()
await mgr.getByTestId('signage-badges-save').click()
await sleep(700)
const mine = (await api('GET', '/api/signage/badges', { token: boss })).badges.at(-1)
r.check('2026-11-21 (5): a badge of the venue saved with its name and icon', mine?.names?.en === 'Gluten free' && mine?.icon === 'wheat-off', JSON.stringify(mine))
r.check('2026-11-21 (5): the tab is "Message & settings"', (await mgr.getByTestId('signage-tab-settings').textContent()).includes('settings'))
r.check('5.6c: the weather section says what it needs (no town yet)', await shown(mgr, 'signage-weather', 5000) r.check('5.6c: the weather section says what it needs (no town yet)', await shown(mgr, 'signage-weather', 5000)
&& (await mgr.getByTestId('signage-weather').textContent()).includes('internet')) && (await mgr.getByTestId('signage-weather').textContent()).includes('internet'))
await mgr.getByTestId('signage-tab-screens').click() await mgr.getByTestId('signage-tab-screens').click()