feat(signage): slides keep their shape on any screen, custom shapes (21:9, 16:10…), Calibrate the picture edge by edge with presets

A slide is drawn at its playlist's shape, as large as fits the screen's picture,
the bands in its own background (or stretched, the screen's choice). Playlists and
library slides may have a shape of their own (aspect, Alembic 0045). Signage ->
Screens -> Calibrate the picture: the TV outlines its area with arrows and its size,
each edge moves pixel by pixel or a preset centres a shape; the TV follows live
(signage.calibrate) and reports its window (POST /screen/viewport). Plan 6R.13, F-110.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 13:04:24 +02:00
co-authored by Claude Opus 5.5
parent d5c19e17ce
commit 1c8d45e00c
32 changed files with 917 additions and 103 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory | | `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) | | `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). **`data/media` belongs in every site backup together with `pos.db`** (the database only holds ids and hashes; DEPLOYMENT_GUIDE → Backups). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) |
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out | | `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`, and its picture (6R.13): `fit` (keep a slide's shape with bands / stretch) and `area_*` (px cut off each edge, set by Screens → Calibrate the picture; `signage.calibrate` to that screen while calibrating; the TV reports its window with `POST /api/signage/screen/viewport`); playlists and library slides have a shape (`orientation` + `aspect` "21:9", `shapeOf()` in `@xenia/signage`); `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out |
| `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) | | `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" **Ordering at the table (6.6, D-30):** `services/tablet_orders.py` + `models/tablet_order.py` (`tablet_orders`, 0034). Device config `ordering` (off), `bill`, and per-tablet overrides `order_confirm` / `order_no_order` / `order_max_items` / `order_max_of_one` / `order_min_seconds` (-1 / `venue` = the venue's); the venue's rules are the JSON setting `menu_tablet.ordering` (`GET/PUT /api/menu-tablet/ordering`, Settings → Menu tablets). `/menu` adds `table.can_order`, `table.can_see_bill` and `ordering` (rules + `choices`: the POS product shape at in-store prices, so the tablet reuses `pos/ProductDialog`). `POST /quote` / `/order` take POS lines by id (`pos_cart.resolve_line`, never prices or discounts); every order is a `TabletOrder` row (it also times the limit); kitchen mode places it with `orders_api.add_priced_items(source="tablet")`, waiter mode leaves it `waiting` until `POST /requests/{id}/accept|decline` (`ordering.orders.open`; the phone's `TabletRequests` on the table page). Events: `tablet_order_updated` {id, table_id, status} to all (the phones refresh their list), `menu_tablet.order` to the tablet. Staff message type `tablet_order`. `GET/POST /bill`: the table's open order and asking for the bill (a `table_call` message, once a minute) |
| `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) | | `local_backend/routers/pricing.py`, `services/pricing.py`, `manager_dashboard/src/pages/pricing/` | Pricing (6.7): price groups, modifiers (price rules), deals, discount limits. Every set-up endpoint needs `pricing.manage` and broadcasts `pricing.changed` (the page's `useLiveQuery`); the phones keep reading rules / deals with any signed-in user. Conditions are checked on save (`_condition_ok` → `pricing.bad_condition`): an incomplete one used to raise in `services/pricing.py::_eval_condition` at quote time. Venue limits live in settings `discounts.*` (empty = no limit; `pricing.bad_limit`). The page's rules as data: `pricingLogic.js` (`tests/pricing.test.mjs`) |
| `local_backend/routers/floor_plans.py`, `services/floor_live.py`, `packages/floorplan`, manager `src/pages/floor/` | The table map (6.8, D-31): `floor_plans` / `floor_items` (0035) and the tables' `plan_id`, `floor_x/y` (centre), `width`, `height`, `rotation`, `shape`. Set-up `/api/floor-plans` (`catalog.tables.manage`; `PUT /{id}/layout` saves tables + items whole) sends `floor_plans.changed`; `GET /api/floor-plans/live` (any signed-in person, the waiter app's zone rule) gives each table's state, guests (`customer_count`), waiters and time. `@xenia/floorplan`: `FloorView` (inline styles on tokens, so the waiter app can use it), `Floor` / `Item` / `TableShape`, `geometry.js` (grid snap = positions and sizes in whole cells; `@xenia/floorplan/geometry` for node tests). Dockerfiles copy its package.json | | `local_backend/routers/floor_plans.py`, `services/floor_live.py`, `packages/floorplan`, manager `src/pages/floor/` | The table map (6.8, D-31): `floor_plans` / `floor_items` (0035) and the tables' `plan_id`, `floor_x/y` (centre), `width`, `height`, `rotation`, `shape`. Set-up `/api/floor-plans` (`catalog.tables.manage`; `PUT /{id}/layout` saves tables + items whole) sends `floor_plans.changed`; `GET /api/floor-plans/live` (any signed-in person, the waiter app's zone rule) gives each table's state, guests (`customer_count`), waiters and time. `@xenia/floorplan`: `FloorView` (inline styles on tokens, so the waiter app can use it), `Floor` / `Item` / `TableShape`, `geometry.js` (grid snap = positions and sizes in whole cells; `@xenia/floorplan/geometry` for node tests). Dockerfiles copy its package.json |
@@ -0,0 +1,28 @@
"""Signage slide shapes (6R.13, owner 2026-11-22): a playlist or a library slide may be built for a
custom shape ("21:9", "16:10", …) besides landscape / portrait. NULL = its orientation's 16:9 / 9:16.
Revision ID: 0045_signage_shapes
Revises: 0044_signage_saved_slides
Create Date: 2026-11-22 10:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0045_signage_shapes'
down_revision = '0044_signage_saved_slides'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('signage_playlists') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
with op.batch_alter_table('signage_saved_slides') as b:
b.add_column(sa.Column('aspect', sa.String(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('signage_saved_slides') as b:
b.drop_column('aspect')
with op.batch_alter_table('signage_playlists') as b:
b.drop_column('aspect')
+2
View File
@@ -23,6 +23,7 @@ class SignagePlaylist(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False) name = Column(String, nullable=False)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
transition = Column(String, nullable=False, default="fade") # the slides' default transition = Column(String, nullable=False, default="fade") # the slides' default
created_at = Column(UTCDateTime, default=utcnow, nullable=False) created_at = Column(UTCDateTime, default=utcnow, nullable=False)
updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False) updated_at = Column(UTCDateTime, default=utcnow, onupdate=utcnow, nullable=False)
@@ -91,6 +92,7 @@ class SignageSavedSlide(Base):
name = Column(String, nullable=False) name = Column(String, nullable=False)
description = Column(String, nullable=True) description = Column(String, nullable=True)
orientation = Column(String, nullable=False, default="landscape") # landscape | portrait orientation = Column(String, nullable=False, default="landscape") # landscape | portrait
aspect = Column(String, nullable=True) # a custom shape "21:9" (6R.13); None: 16:9 / 9:16
kind = Column(String, nullable=False) # menu | image | video | text | blank kind = Column(String, nullable=False) # menu | image | video | text | blank
duration_s = Column(Integer, nullable=False, default=10) duration_s = Column(Integer, nullable=False, default=10)
transition = Column(String, nullable=True) transition = Column(String, nullable=True)
@@ -31,5 +31,12 @@ MODULE = Module(
ConfigField('slide', 'ref', default=None, choices_from='signage_slides'), ConfigField('slide', 'ref', default=None, choices_from='signage_slides'),
ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')), ConfigField('orientation', 'enum', default='landscape', choices=('landscape', 'portrait')),
ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)), ConfigField('rotation', 'int', default=0, choices=(0, 90, 180, 270)),
# its picture (6R.13): a slide of another shape keeps its shape (bands) or fills the picture;
# px cut off each edge of the TV's window (set by Signage > Screens > Calibrate)
ConfigField('fit', 'enum', default='keep', choices=('keep', 'stretch'), group='picture'),
ConfigField('area_left', 'int', default=0, min=0, max=4000, group='picture'),
ConfigField('area_top', 'int', default=0, min=0, max=4000, group='picture'),
ConfigField('area_right', 'int', default=0, min=0, max=4000, group='picture'),
ConfigField('area_bottom', 'int', default=0, min=0, max=4000, group='picture'),
)), )),
) )
+145 -16
View File
@@ -18,11 +18,14 @@ Manager side (signage.manage):
PUT /api/signage/library/{id} change it (a screen showing it is told) PUT /api/signage/library/{id} change it (a screen showing it is told)
DELETE /api/signage/library/{id} screens that had it as their default show nothing DELETE /api/signage/library/{id} screens that had it as their default show nothing
POST /api/signage/library/{id}/duplicate a copy POST /api/signage/library/{id}/duplicate a copy
GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation GET /api/signage/screens the paired screens: playlist or slide, orientation, rotation,
PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation} picture area (insets), fit, the window size it reported
PUT /api/signage/screens/{id} {playlist_id | slide_id, orientation, rotation, area_*, fit}
POST /api/signage/screens/{id}/calibrate {on} the TV outlines its picture area (6R.13)
The screen (a paired device running `signage`, no sign-in): The screen (a paired device running `signage`, no sign-in):
GET /api/signage/screen its playlist resolved for playing GET /api/signage/screen its playlist resolved for playing
POST /api/signage/screen/viewport {width, height, ratio} its window (for calibrating)
Any change sends `signage.changed` only to the screens playing that playlist (a screen's own Any change sends `signage.changed` only to the screens playing that playlist (a screen's own
settings: `device.updated` plus `signage.changed` to it). A slide's content is typed per kind settings: `device.updated` plus `signage.changed` to it). A slide's content is typed per kind
@@ -51,10 +54,16 @@ KEY = "signage.manage"
MESSAGE = "signage.message" MESSAGE = "signage.message"
MAX_WIDGETS = "signage.max_widgets" # widgets a slide may hold (owner review 6: Performance; 10 recommended) MAX_WIDGETS = "signage.max_widgets" # widgets a slide may hold (owner review 6: Performance; 10 recommended)
MAX_WIDGETS_CAP = 50 # never more, whatever the setting MAX_WIDGETS_CAP = 50 # never more, whatever the setting
AREA_MAX = 4000 # px a screen's picture area may cut off one edge (6R.13)
AREA_KEYS = ("area_left", "area_top", "area_right", "area_bottom")
CALIBRATE_S = 15 * 60 # a calibration nobody ends stops by itself
_viewports: dict = {} # device id → {width, height, ratio} (what the TV reported; memory only)
_calibrating: dict = {} # device id → when calibration started (monotonic)
HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" # #rrggbb, or #rrggbbaa (see-through, 2026-11-21) HEX = r"^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$" # #rrggbb, or #rrggbbaa (see-through, 2026-11-21)
TIME = r"^([01]\d|2[0-3]):[0-5]\d$" TIME = r"^([01]\d|2[0-3]):[0-5]\d$"
DATE = r"^\d{4}-\d{2}-\d{2}$" DATE = r"^\d{4}-\d{2}-\d{2}$"
Orientation = Literal["landscape", "portrait"] Orientation = Literal["landscape", "portrait"]
ASPECT = r"^\d{1,2}:\d{1,2}$" # a custom shape "21:9" (6R.13), from 1:4 to 4:1
Transition = Literal["none", "fade", "slide", "zoom"] Transition = Literal["none", "fade", "slide", "zoom"]
Font = Literal["sans", "serif", "rounded", "condensed", "display"] Font = Literal["sans", "serif", "rounded", "condensed", "display"]
@@ -353,13 +362,55 @@ Kind = Literal["menu", "image", "video", "text", "blank"]
# ── requests ─────────────────────────────────────────────────────────────────── # ── requests ───────────────────────────────────────────────────────────────────
class PlaylistBody(BaseModel): def _aspect(v):
"""A custom shape "W:H" (6R.13): None / "" = none; between 1:4 and 4:1."""
import re as _re
v = (v or "").strip() or None
if v is None:
return None
if not _re.match(ASPECT, v):
raise ValueError("a shape is written W:H, e.g. 21:9")
w, h = (int(x) for x in v.split(":"))
if not w or not h or w / h > 4 or h / w > 4:
raise ValueError("a shape between 1:4 and 4:1")
return v
class _Shaped(BaseModel):
aspect: Optional[str] = None # a custom shape "21:9"; None / "" = landscape / portrait
@field_validator("aspect")
@classmethod
def _shape(cls, v):
return _aspect(v)
def set_shape(obj, body) -> None:
"""A playlist's / library slide's shape from a body: `aspect` sets orientation too (wide or tall;
"16:9" / "9:16" are plain landscape / portrait); `orientation` alone drops a custom shape."""
sent = body.model_fields_set
if "aspect" in sent:
a = body.aspect
if a is None:
obj.aspect = None
if body.orientation is not None:
obj.orientation = body.orientation
return
w, h = (int(x) for x in a.split(":"))
obj.orientation = "landscape" if w >= h else "portrait"
obj.aspect = None if a in ("16:9", "9:16") else a
elif body.orientation is not None:
obj.orientation = body.orientation
obj.aspect = None
class PlaylistBody(_Shaped):
name: str = Field(min_length=1, max_length=80) name: str = Field(min_length=1, max_length=80)
orientation: Orientation = "landscape" orientation: Orientation = "landscape"
transition: Transition = "fade" transition: Transition = "fade"
class PlaylistUpdate(BaseModel): class PlaylistUpdate(_Shaped):
name: Optional[str] = Field(default=None, min_length=1, max_length=80) name: Optional[str] = Field(default=None, min_length=1, max_length=80)
orientation: Optional[Orientation] = None orientation: Optional[Orientation] = None
transition: Optional[Transition] = None transition: Optional[Transition] = None
@@ -438,6 +489,12 @@ class SavedSlideBody(SlideFields):
kind: Optional[Kind] = None kind: Optional[Kind] = None
description: Optional[str] = Field(default=None, max_length=300) description: Optional[str] = Field(default=None, max_length=300)
orientation: Optional[Orientation] = None orientation: Optional[Orientation] = None
aspect: Optional[str] = None # a custom shape (6R.13)
@field_validator("aspect")
@classmethod
def _shape(cls, v):
return _aspect(v)
class ScreenBody(BaseModel): class ScreenBody(BaseModel):
@@ -445,6 +502,22 @@ class ScreenBody(BaseModel):
slide_id: Optional[int] = None # … or a library slide (one or the other) slide_id: Optional[int] = None # … or a library slide (one or the other)
orientation: Optional[Orientation] = None orientation: Optional[Orientation] = None
rotation: Optional[Literal[0, 90, 180, 270]] = None rotation: Optional[Literal[0, 90, 180, 270]] = None
# its picture area (6R.13): px cut off each edge of the TV's window; how a slide of another shape fits
area_left: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
area_top: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
area_right: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
area_bottom: Optional[int] = Field(default=None, ge=0, le=AREA_MAX)
fit: Optional[Literal["keep", "stretch"]] = None
class CalibrateBody(BaseModel):
on: bool
class ViewportBody(BaseModel):
width: int = Field(ge=1, le=20000)
height: int = Field(ge=1, le=20000)
ratio: float = Field(default=1, gt=0, le=10) # device pixels per CSS px
# ── helpers ──────────────────────────────────────────────────────────────────── # ── helpers ────────────────────────────────────────────────────────────────────
@@ -670,7 +743,7 @@ def _slide_out(s: SignageSlide) -> dict:
def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict: def _playlist_out(db, p: SignagePlaylist, slides: bool = False) -> dict:
playing = set(_screens_playing(db, p.id)) playing = set(_screens_playing(db, p.id))
out = {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, out = {"id": p.id, "name": p.name, "orientation": p.orientation, "aspect": p.aspect, "transition": p.transition,
"slide_count": len(p.slides), "screens": [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in playing]} "slide_count": len(p.slides), "screens": [{"id": d.id, "name": d.name} for d in _screens(db) if d.id in playing]}
if slides: if slides:
from services.signage_menu import resolve from services.signage_menu import resolve
@@ -761,6 +834,7 @@ def list_playlists(db: Session = Depends(get_db), user=Depends(require(KEY))):
@router.post("/playlists", status_code=201) @router.post("/playlists", status_code=201)
def create_playlist(body: PlaylistBody, db: Session = Depends(get_db), user=Depends(require(KEY))): def create_playlist(body: PlaylistBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
p = SignagePlaylist(name=body.name.strip(), orientation=body.orientation, transition=body.transition) p = SignagePlaylist(name=body.name.strip(), orientation=body.orientation, transition=body.transition)
set_shape(p, body)
db.add(p) db.add(p)
db.commit() db.commit()
db.refresh(p) db.refresh(p)
@@ -777,8 +851,7 @@ def update_playlist(playlist_id: int, body: PlaylistUpdate, db: Session = Depend
p = _playlist(db, playlist_id) p = _playlist(db, playlist_id)
if body.name is not None: if body.name is not None:
p.name = body.name.strip() p.name = body.name.strip()
if body.orientation is not None: set_shape(p, body)
p.orientation = body.orientation
if body.transition is not None: if body.transition is not None:
p.transition = body.transition p.transition = body.transition
db.commit() db.commit()
@@ -804,7 +877,7 @@ def delete_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depend
@router.post("/playlists/{playlist_id}/duplicate", status_code=201) @router.post("/playlists/{playlist_id}/duplicate", status_code=201)
def duplicate_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): def duplicate_playlist(playlist_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
p = _playlist(db, playlist_id) p = _playlist(db, playlist_id)
copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, transition=p.transition) copy = SignagePlaylist(name=f"{p.name} (2)"[:80], orientation=p.orientation, aspect=p.aspect, transition=p.transition)
db.add(copy) db.add(copy)
db.flush() db.flush()
for s in p.slides: for s in p.slides:
@@ -904,7 +977,7 @@ def _saved(db, sid: int) -> SignageSavedSlide:
def _saved_out(s: SignageSavedSlide, db=None) -> dict: def _saved_out(s: SignageSavedSlide, db=None) -> dict:
out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "kind": s.kind, out = {"id": s.id, "name": s.name, "description": s.description, "orientation": s.orientation, "aspect": s.aspect, "kind": s.kind,
"duration_s": s.duration_s, "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled), "duration_s": s.duration_s, "transition": s.transition, "video_to_end": bool(s.video_to_end), "enabled": bool(s.enabled),
"days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to, "days": s.days or [], "time_from": s.time_from, "time_to": s.time_to, "date_from": s.date_from, "date_to": s.date_to,
"content": s.content or {}} "content": s.content or {}}
@@ -957,6 +1030,7 @@ def create_saved(body: SavedSlideBody, db: Session = Depends(get_db), user=Depen
name = _saved_name(body) name = _saved_name(body)
s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True, s = SignageSavedSlide(name=name, kind=body.kind, orientation=body.orientation or "landscape", duration_s=10, enabled=True,
video_to_end=body.kind == "video", content=_content(db, body.kind, None)) video_to_end=body.kind == "video", content=_content(db, body.kind, None))
set_shape(s, body)
_apply(db, s, body) _apply(db, s, body)
s.name = name s.name = name
s.description = (body.description or "").strip() or None s.description = (body.description or "").strip() or None
@@ -984,8 +1058,7 @@ def update_saved(slide_id: int, body: SavedSlideBody, db: Session = Depends(get_
s.name = name s.name = name
if "description" in body.model_fields_set: if "description" in body.model_fields_set:
s.description = (body.description or "").strip() or None s.description = (body.description or "").strip() or None
if body.orientation is not None: set_shape(s, body)
s.orientation = body.orientation
db.commit() db.commit()
db.refresh(s) db.refresh(s)
_tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id)) _tell(_screens_showing_slide(db, s.id) + _embedding_screens(db, s.id))
@@ -1008,7 +1081,7 @@ def delete_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(requ
@router.post("/library/{slide_id}/duplicate", status_code=201) @router.post("/library/{slide_id}/duplicate", status_code=201)
def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))): def duplicate_saved(slide_id: int, db: Session = Depends(get_db), user=Depends(require(KEY))):
s = _saved(db, slide_id) s = _saved(db, slide_id)
copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, kind=s.kind, copy = SignageSavedSlide(name=f"{s.name} (2)"[:80], description=s.description, orientation=s.orientation, aspect=s.aspect, kind=s.kind,
duration_s=s.duration_s, transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled, duration_s=s.duration_s, transition=s.transition, video_to_end=s.video_to_end, enabled=s.enabled,
days=s.days, time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to, days=s.days, time_from=s.time_from, time_to=s.time_to, date_from=s.date_from, date_to=s.date_to,
content=json.loads(json.dumps(s.content or {}))) content=json.loads(json.dumps(s.content or {})))
@@ -1039,7 +1112,30 @@ def _screen_out(db, d) -> dict:
return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None, return {"id": d.id, "name": d.name, "playlist_id": p.id if p else None, "playlist_name": p.name if p else None,
"slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None, "slide_id": sl.id if sl else None, "slide_name": sl.name if sl else None,
"orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now, "orientation": cfg["orientation"], "rotation": cfg["rotation"], "now": now,
"orientation_mismatch": any(o != cfg["orientation"] for o in shapes)} "orientation_mismatch": any(o != cfg["orientation"] for o in shapes),
**_picture(d, cfg), "viewport": _viewports.get(d.id)}
def _area(cfg: dict) -> dict:
return {k[5:]: int(cfg.get(k) or 0) for k in AREA_KEYS}
def calibrating(device_id: int) -> bool:
import time
at = _calibrating.get(device_id)
if at is not None and time.monotonic() - at > CALIBRATE_S:
_calibrating.pop(device_id, None)
return False
return at is not None
def _picture(d, cfg: dict) -> dict:
"""A screen's picture (6R.13): the insets of its area, how a slide of another shape fits, calibrating now."""
return {"area": _area(cfg), "fit": cfg.get("fit") or "keep", "calibrating": calibrating(d.id)}
def _tell_calibration(d, cfg: dict) -> None:
broadcast_sync("signage.calibrate", {"on": calibrating(d.id), "area": _area(cfg)}, device_ids=[d.id])
@router.get("/screens") @router.get("/screens")
@@ -1064,11 +1160,36 @@ def update_screen(device_id: int, body: ScreenBody, db: Session = Depends(get_db
cfg["playlist"] = None cfg["playlist"] = None
d.config = validate(for_app("signage"), cfg, db) d.config = validate(for_app("signage"), cfg, db)
db.commit() db.commit()
if calibrating(d.id):
_tell_calibration(d, _screen_config(d)) # the TV moves its outline at once
broadcast_sync("device.updated", {}, device_ids=[d.id]) broadcast_sync("device.updated", {}, device_ids=[d.id])
_tell([d.id]) _tell([d.id])
return _screen_out(db, d) return _screen_out(db, d)
def _a_screen(db, device_id: int):
from models.device import Device
d = db.get(Device, device_id)
if d is None or d.app_key != "signage" or d.revoked_at is not None:
raise XeniaError("signage.not_a_screen", device_id=device_id)
return d
@router.post("/screens/{device_id}/calibrate")
def calibrate_screen(device_id: int, body: CalibrateBody, db: Session = Depends(get_db), user=Depends(require(KEY))):
"""Calibrating a screen's picture (6R.13): on, the TV outlines its picture area with arrows
pointing out and its size, and follows every change of the insets at once; off (the manager's
dialog closes, or after 15 min) it plays again."""
import time
d = _a_screen(db, device_id)
if body.on:
_calibrating[d.id] = time.monotonic()
else:
_calibrating.pop(d.id, None)
_tell_calibration(d, _screen_config(d))
return _screen_out(db, d)
# ── the screen itself ────────────────────────────────────────────────────────── # ── the screen itself ──────────────────────────────────────────────────────────
def _resolved(db, p: SignagePlaylist) -> dict: def _resolved(db, p: SignagePlaylist) -> dict:
@@ -1085,7 +1206,7 @@ def _resolved(db, p: SignagePlaylist) -> dict:
for w in s["content"].get("widgets") or []: for w in s["content"].get("widgets") or []:
if w["kind"] == "qr": if w["kind"] == "qr":
w["link"] = _qr_link(w) w["link"] = _qr_link(w)
return {"id": p.id, "name": p.name, "orientation": p.orientation, "transition": p.transition, "slides": slides, return {"id": p.id, "name": p.name, "orientation": p.orientation, "aspect": p.aspect, "transition": p.transition, "slides": slides,
"media": _media_map(db, [i for s in slides for i in media_ids(s["content"])] + more)} "media": _media_map(db, [i for s in slides for i in media_ids(s["content"])] + more)}
@@ -1101,7 +1222,7 @@ def _resolved_slide(db, s: SignageSavedSlide, orientation: str) -> dict:
if w["kind"] == "qr": if w["kind"] == "qr":
w["link"] = _qr_link(w) w["link"] = _qr_link(w)
slides = [one] if s.enabled else [] slides = [one] if s.enabled else []
return {"id": slide_key(s.id), "name": s.name, "orientation": orientation, "transition": "fade", "slides": slides, return {"id": slide_key(s.id), "name": s.name, "orientation": s.orientation, "aspect": s.aspect, "transition": "fade", "slides": slides,
"media": _media_map(db, media_ids(one["content"]) + more)} "media": _media_map(db, media_ids(one["content"]) + more)}
@@ -1143,7 +1264,7 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key} schedule = {"entries": entries, "fallback_playlist_id": default, "scenes": scenes, "timezone": venue_tz().key}
else: else:
playlist = fallback playlist = fallback
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"], **_picture(dev, cfg)},
"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": _venue(db)} "venue": _venue(db)}
@@ -1151,6 +1272,14 @@ def screen(db: Session = Depends(get_db), dev=Depends(require_device("signage"))
return out return out
@router.post("/screen/viewport")
def screen_viewport(body: ViewportBody, dev=Depends(require_device("signage"))):
"""The TV's window size (6R.13), sent when it starts and when it changes: the calibration
dialog's presets fit a shape into it. Kept in memory only (the TV sends it again after a restart)."""
_viewports[dev.id] = {"width": body.width, "height": body.height, "ratio": round(body.ratio, 3)}
return {"ok": True}
# ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ───── # ── schedules (5.4d; lines with their screens and scenes, owner 2026-11-21) ─────
def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict: def _line_out(i: SignageScheduleItem, now_ids: dict) -> dict:
+2 -1
View File
@@ -56,7 +56,8 @@ def test_a_screen_plays_its_playlist_in_order(client, owner_h, screens, sent):
assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default assert [s["transition"] for s in pl["slides"]] == ["fade", "fade", "zoom"] # the playlist's default
assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"] assert pl["media"][str(pic["id"])]["url"] == pic["urls"]["full"] and pl["media"][str(vid["id"])]["url"] == vid["urls"]["original"]
assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40 assert pl["media"][str(bg["id"])]["kind"] == "image" and pl["slides"][2]["content"]["background"]["dim"] == 40
assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0} assert got["screen"] == {"id": screens[1]["id"], "name": "TV 1", "orientation": "landscape", "rotation": 0,
"area": {"left": 0, "top": 0, "right": 0, "bottom": 0}, "fit": "keep", "calibrating": False}
assert len(got["version"]) == 16 assert len(got["version"]) == 16
@@ -0,0 +1,69 @@
"""Slide shapes and a screen's picture (6R.13, owner 2026-11-22): custom shapes for playlists and
library slides, a screen's picture area (insets) and fit, calibrating told to that screen only,
the window size a screen reports."""
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
def test_custom_shapes_for_playlists_and_library_slides(client, owner_h):
p = playlist(client, owner_h, aspect="21:9")
assert (p["orientation"], p["aspect"]) == ("landscape", "21:9")
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "10:16"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", "10:16")
# the plain shapes are landscape / portrait; picking one drops a custom shape
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "16:9"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("landscape", None)
client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": "32:9"})
r = client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"orientation": "portrait"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
for bad in ("21x9", "9:1", "0:5"):
assert client.put(f"/api/signage/playlists/{p['id']}", headers=owner_h, json={"aspect": bad}).status_code == 422
dup = client.post(f"/api/signage/playlists/{p['id']}/duplicate", headers=owner_h).json()
assert dup["orientation"] == "portrait"
s = client.post("/api/signage/library", headers=owner_h, json={"name": "Wide", "kind": "text", "aspect": "16:10"}).json()
assert (s["orientation"], s["aspect"]) == ("landscape", "16:10")
r = client.put(f"/api/signage/library/{s['id']}", headers=owner_h, json={"aspect": None, "orientation": "portrait"})
assert (r.json()["orientation"], r.json()["aspect"]) == ("portrait", None)
def test_a_screens_picture_area_and_calibration(client, owner_h, screens, sent):
tv, other = screens[1], screens[2]
p = playlist(client, owner_h, aspect="21:9")
slide(client, owner_h, p["id"], "text", content={"title": "Wide"})
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"playlist_id": p["id"]})
got = client.get("/api/signage/screen", headers=tv["h"]).json()
assert got["playlist"]["aspect"] == "21:9" and got["screen"]["fit"] == "keep" and got["screen"]["calibrating"] is False
# the TV reports its window; the manager sees it
assert client.post("/api/signage/screen/viewport", headers=tv["h"], json={"width": 2560, "height": 1080, "ratio": 1}).status_code == 200
one = next(s for s in client.get("/api/signage/screens", headers=owner_h).json() if s["id"] == tv["id"])
assert one["viewport"] == {"width": 2560, "height": 1080, "ratio": 1.0} and one["area"] == {"left": 0, "top": 0, "right": 0, "bottom": 0}
# calibrating: only that TV hears it, with its area; every change of the insets follows at once
sent.clear()
r = client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
assert r.json()["calibrating"] is True and sent == [("signage.calibrate", [tv["id"]])]
sent.clear()
r = client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 320, "area_right": 320, "fit": "stretch"})
assert r.json()["area"] == {"left": 320, "top": 0, "right": 320, "bottom": 0} and r.json()["fit"] == "stretch"
assert sent[0] == ("signage.calibrate", [tv["id"]]) and ("signage.changed", [tv["id"]]) in sent
scr = client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]
assert scr["area"]["left"] == 320 and scr["calibrating"] is True
sent.clear()
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": False})
assert sent == [("signage.calibrate", [tv["id"]])]
sent.clear()
client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_top": 5})
assert ("signage.calibrate", [tv["id"]]) not in sent
# limits; not a screen
assert client.put(f"/api/signage/screens/{tv['id']}", headers=owner_h, json={"area_left": 5000}).status_code == 422
assert err(client.post("/api/signage/screens/99999/calibrate", headers=owner_h, json={"on": True})) == "signage.not_a_screen"
# a screen can't calibrate itself or report for another
assert client.post(f"/api/signage/screens/{other['id']}/calibrate", headers=tv["h"], json={"on": True}).status_code in (401, 403)
def test_calibration_ends_by_itself(client, owner_h, screens, monkeypatch):
import routers.signage as sg
tv = screens[1]
client.post(f"/api/signage/screens/{tv['id']}/calibrate", headers=owner_h, json={"on": True})
assert sg.calibrating(tv["id"]) is True
sg._calibrating[tv["id"]] -= sg.CALIBRATE_S + 1
assert client.get("/api/signage/screen", headers=tv["h"]).json()["screen"]["calibrating"] is False
@@ -5,6 +5,7 @@
import { Film, ImageIcon, LayoutDashboard, LayoutList, Square, Type } from 'lucide-react' import { Film, ImageIcon, LayoutDashboard, LayoutList, Square, Type } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Spinner } from '@xenia/ui' import { Button, Dialog, Spinner } from '@xenia/ui'
import { shapeRatio } from '@xenia/signage'
import { BLANK_WITH_WIDGETS, mediaLookup, slideFromSaved, slideFromTemplate, TEMPLATES } from './signageLogic' import { BLANK_WITH_WIDGETS, mediaLookup, slideFromSaved, slideFromTemplate, TEMPLATES } from './signageLogic'
import SlidePreview from './SlidePreview' import SlidePreview from './SlidePreview'
@@ -28,7 +29,7 @@ function Heading({ children, hint }) {
export default function AddSlideDialog({ onClose, onPick, orientation = 'landscape', venue, library = null, libraryMedia = {}, title }) { export default function AddSlideDialog({ onClose, onPick, orientation = 'landscape', venue, library = null, libraryMedia = {}, title }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const tall = orientation === 'portrait' const tall = shapeRatio(orientation) < 1
return ( return (
<Dialog open size="xl" title={title || t('signage.addSlide')} onClose={onClose} <Dialog open size="xl" title={title || t('signage.addSlide')} onClose={onClose}
footer={<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>}> footer={<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>}>
@@ -0,0 +1,113 @@
// Calibrating a screen's picture (6R.13, owner 2026-11-22). While this is open the TV outlines its
// picture area with four arrows pointing out and shows its size; each edge moves in or out here
// pixel by pixel (or in steps of 10 / 50 px), or a preset sets the largest box of a common shape in
// the middle of the TV's window (it reports its size). Every change reaches the TV at once; closing
// ends the calibration (the TV also stops by itself after 15 min).
import { useCallback, useEffect, useRef, useState } from 'react'
import toast from 'react-hot-toast'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, NumberInput, Segmented } from '@xenia/ui'
import { pictureArea, presetInsets, shapeName } from '@xenia/signage'
import * as api from './signageApi'
import { ShapeMark } from './ShapeField'
const EDGES = ['top', 'right', 'bottom', 'left']
const PRESETS = ['full', '16:9', '16:10', '21:9', '32:9', '4:3', '9:16']
const SAVE_MS = 200
export default function CalibrateDialog({ screen, onClose, onSaved }) {
const { t } = useTranslation('manager')
const [area, setArea] = useState(screen.area || { left: 0, top: 0, right: 0, bottom: 0 })
const [viewport, setViewport] = useState(screen.viewport || null)
const [step, setStep] = useState(1)
const timer = useRef(null)
const latest = useRef(area)
// on while open; off when closed
useEffect(() => {
api.calibrateScreen(screen.id, true).catch(err => toast.error(errorMessage(err, t)))
return () => { api.calibrateScreen(screen.id, false).catch(() => {}) }
}, [screen.id]) // eslint-disable-line react-hooks/exhaustive-deps
// the TV's window size (it reports it when it starts and when it changes)
useEffect(() => {
const id = setInterval(() => {
api.listScreens().then(list => setViewport(list.find(s => s.id === screen.id)?.viewport || null)).catch(() => {})
}, 2000)
return () => clearInterval(id)
}, [screen.id])
const send = useCallback(() => {
const a = latest.current
api.updateScreen(screen.id, { area_left: a.left, area_top: a.top, area_right: a.right, area_bottom: a.bottom })
.then(onSaved).catch(err => toast.error(errorMessage(err, t)))
}, [screen.id, onSaved, t])
const change = next => {
latest.current = next
setArea(next)
clearTimeout(timer.current)
timer.current = setTimeout(send, SAVE_MS)
}
useEffect(() => () => clearTimeout(timer.current), [])
const win = viewport ? { w: viewport.width, h: viewport.height } : null
const pic = win ? pictureArea(win, area) : null
const setEdge = (edge, v) => change({ ...area, [edge]: Math.max(0, Math.min(4000, v ?? 0)) })
// the diagram: the TV's window and the picture inside it, to scale
const W = 320
const H = win ? Math.round(W * win.h / win.w) : 180
const k = win ? W / win.w : 0
const edge = e => (
<Field label={t(`signage.calibrate.edges.${e}`)} className="w-36">
<NumberInput size="sm" value={area[e]} min={0} max={4000} step={step} suffix="px" onChange={v => setEdge(e, v)} data-testid={`signage-calibrate-${e}`} />
</Field>
)
return (
<Dialog open size="lg" onClose={onClose} title={t('signage.calibrate.title', { name: screen.name })} description={t('signage.calibrate.intro')}
footer={<>
<Button variant="secondary" onClick={() => change({ left: 0, top: 0, right: 0, bottom: 0 })} data-testid="signage-calibrate-reset">{t('signage.calibrate.reset')}</Button>
<Button onClick={onClose} data-testid="signage-calibrate-done">{t('signage.calibrate.done')}</Button>
</>}>
<div className="grid gap-5" data-testid="signage-calibrate-dialog">
<p className="text-label text-ink-2" data-testid="signage-calibrate-window">
{win ? t('signage.calibrate.window', { w: win.w, h: win.h, shape: shapeName(win.w, win.h) }) : t('signage.calibrate.waiting')}
</p>
<div className="grid gap-2">
<span className="text-label font-medium text-ink">{t('signage.calibrate.presets')}</span>
<div className="flex flex-wrap gap-1.5">
{PRESETS.map(p => (
<Button key={p} size="sm" variant="secondary" disabled={!win} onClick={() => change(presetInsets(win, p))} data-preset={p}
icon={p === 'full' ? undefined : <ShapeMark shape={p} size={16} />}>
{p === 'full' ? t('signage.calibrate.full') : p}
</Button>
))}
</div>
</div>
<div className="flex flex-wrap items-center gap-3">
<span className="text-label font-medium text-ink">{t('signage.calibrate.step')}</span>
<Segmented value={step} onChange={setStep} options={[1, 10, 50].map(n => ({ value: n, label: `${n} px` }))} data-testid="signage-calibrate-step" />
</div>
<div className="grid justify-items-center gap-2">
{edge('top')}
<div className="flex items-center gap-3 flex-wrap justify-center">
{edge('left')}
<div className="relative rounded-control border border-line-strong bg-surface-2" style={{ width: W, height: H }} aria-hidden="true">
{pic && (
<div className="absolute border-2 border-accent bg-accent-soft grid place-items-center text-caption text-accent-ink tabular-nums"
style={{ left: pic.left * k, top: pic.top * k, width: pic.width * k, height: pic.height * k }}>
{Math.round(pic.width)} × {Math.round(pic.height)}
</div>
)}
</div>
{edge('right')}
</div>
{edge('bottom')}
</div>
<p className="text-label text-ink-2 text-center" data-testid="signage-calibrate-picture">
{pic ? t('signage.calibrate.picture', { w: Math.round(pic.width), h: Math.round(pic.height), shape: shapeName(pic.width, pic.height) }) : ''}
</p>
{EDGES.some(e => area[e] > 0) && <p className="text-caption text-ink-3">{t('signage.calibrate.outside')}</p>}
</div>
</Dialog>
)
}
@@ -12,6 +12,7 @@ import toast from 'react-hot-toast'
import { AlertTriangle, ArrowLeft, ArrowRight, BookmarkPlus, Copy, ImageIcon, Plus, Trash2 } from 'lucide-react' import { AlertTriangle, ArrowLeft, ArrowRight, BookmarkPlus, Copy, ImageIcon, Plus, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { shapeOf, shapeRatio } from '@xenia/signage'
import { Button, Dialog, Dropdown, Field, IconButton, Input, Spinner, Textarea, useConfirm } from '@xenia/ui' import { Button, Dialog, Dropdown, Field, IconButton, Input, Spinner, Textarea, useConfirm } from '@xenia/ui'
import * as api from './signageApi' import * as api from './signageApi'
import { mediaEntry, mediaLookup, misfits, moved, secondsMissing, slideBody, totalSeconds, TRANSITIONS, windowParts } from './signageLogic' import { mediaEntry, mediaLookup, misfits, moved, secondsMissing, slideBody, totalSeconds, TRANSITIONS, windowParts } from './signageLogic'
@@ -19,6 +20,7 @@ import { playSeconds } from './timing'
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' import AddSlideDialog, { KIND_ICON } from './AddSlideDialog'
import SlideEditor, { SlideBasics } from './SlideEditor' import SlideEditor, { SlideBasics } from './SlideEditor'
import SlidePreview from './SlidePreview' import SlidePreview from './SlidePreview'
import ShapeField from './ShapeField'
import { useSlidePreview, useWidgetEditor } from './useSlideDraft' import { useSlidePreview, useWidgetEditor } from './useSlideDraft'
/** The preview as big as its box allows (the box is as tall as the basics beside it). */ /** The preview as big as its box allows (the box is as tall as the basics beside it). */
@@ -32,7 +34,7 @@ export function FitPreview({ orientation, children }) {
ro.observe(el) ro.observe(el)
return () => ro.disconnect() return () => ro.disconnect()
}, []) }, [])
const ratio = orientation === 'portrait' ? 9 / 16 : 16 / 9 const ratio = shapeRatio(orientation)
const width = Math.max(0, Math.min(size.w, size.h * ratio)) const width = Math.max(0, Math.min(size.w, size.h * ratio))
return ( return (
<div ref={box} className="h-full min-h-[16rem] min-w-0 grid place-items-center" data-testid="signage-preview-box"> <div ref={box} className="h-full min-h-[16rem] min-w-0 grid place-items-center" data-testid="signage-preview-box">
@@ -77,8 +79,8 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
const saved = pl?.slides.find(s => s.id === selected) const saved = pl?.slides.find(s => s.id === selected)
const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved]) const dirty = useMemo(() => !!(draft && saved && JSON.stringify(slideBody(draft)) !== JSON.stringify(slideBody(saved))), [draft, saved])
const bad = useMemo(() => misfits(pl?.slides, media, pl?.orientation), [pl, media]) const bad = useMemo(() => misfits(pl?.slides, media, shapeOf(pl)), [pl, media])
const draftBad = useMemo(() => (draft ? misfits([draft], media, pl?.orientation)[draft.id] || [] : []), [draft, media, pl]) const draftBad = useMemo(() => (draft ? misfits([draft], media, shapeOf(pl))[draft.id] || [] : []), [draft, media, pl])
if (!pl) return <div className="flex justify-center p-8"><Spinner /></div> if (!pl) return <div className="flex justify-center p-8"><Spinner /></div>
const run = async (fn, done, select) => { const run = async (fn, done, select) => {
@@ -135,7 +137,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
const made = await run(() => api.addSlide(pl.id, body), t('signage.added')) const made = await run(() => api.addSlide(pl.id, body), t('signage.added'))
if (made) await load(made.id) if (made) await load(made.id)
} }
const total = totalSeconds(pl.slides, media, s => playSeconds(s, pl.orientation)) const shape = shapeOf(pl)
const tall = shapeRatio(shape) < 1
const total = totalSeconds(pl.slides, media, s => playSeconds(s, shape))
const marker = i => drag && drag.at === i && drag.at !== drag.from && drag.at !== drag.from + 1 const marker = i => drag && drag.at === i && drag.at !== drag.from && drag.at !== drag.from + 1
return ( return (
@@ -146,10 +150,7 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
onBlur={() => name.trim() && name.trim() !== pl.name && savePlaylist({ name: name.trim() })} onBlur={() => name.trim() && name.trim() !== pl.name && savePlaylist({ name: name.trim() })}
onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} /> onKeyDown={e => { if (e.key === 'Enter') e.currentTarget.blur() }} />
</Field> </Field>
<Field label={t('signage.orientation')} className="w-52"> <ShapeField value={pl} onChange={savePlaylist} />
<Dropdown value={pl.orientation} onChange={v => savePlaylist({ orientation: v })} data-testid="signage-orientation"
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} />
</Field>
<Field label={t('signage.defaultTransition')} className="w-44"> <Field label={t('signage.defaultTransition')} className="w-44">
<Dropdown value={pl.transition} onChange={v => savePlaylist({ transition: v })} <Dropdown value={pl.transition} onChange={v => savePlaylist({ transition: v })}
options={TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} /> options={TRANSITIONS.map(x => ({ value: x, label: t(`signage.transitions.${x}`) }))} />
@@ -179,8 +180,8 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
{marker(i) && <DropLine side="left" />} {marker(i) && <DropLine side="left" />}
{marker(i + 1) && i === pl.slides.length - 1 && <DropLine side="right" />} {marker(i + 1) && i === pl.slides.length - 1 && <DropLine side="right" />}
<div className="pointer-events-none h-28 grid place-items-center rounded-control bg-surface-2"> <div className="pointer-events-none h-28 grid place-items-center rounded-control bg-surface-2">
<div style={{ width: pl.orientation === 'portrait' ? 63 : '100%' }}> <div style={{ width: tall ? Math.round(112 * shapeRatio(shape)) : '100%' }}>
<SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} testid="signage-card-preview" /> <SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={shape} testid="signage-card-preview" />
</div> </div>
</div> </div>
<div className="grid gap-0.5 min-w-0"> <div className="grid gap-0.5 min-w-0">
@@ -191,7 +192,7 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
{bad[s.id] && <AlertTriangle size={14} className="text-warning-ink shrink-0" aria-label={t('signage.misfit')} data-testid="signage-card-misfit" />} {bad[s.id] && <AlertTriangle size={14} className="text-warning-ink shrink-0" aria-label={t('signage.misfit')} data-testid="signage-card-misfit" />}
</span> </span>
<span className="text-caption text-ink-3 truncate"> <span className="text-caption text-ink-3 truncate">
{s.kind === 'video' && s.video_to_end ? t('signage.toTheEnd') : t('signage.seconds', { count: playSeconds(s, pl.orientation) })} {s.kind === 'video' && s.video_to_end ? t('signage.toTheEnd') : t('signage.seconds', { count: playSeconds(s, shape) })}
{!s.enabled && <> · {t('signage.off')}</>} {!s.enabled && <> · {t('signage.off')}</>}
{parts.map(p => <span key={p.key}> · {p.key === 'days' ? p.params.days.map(d => t(`signage.weekdays.${d}`)).join(' ') : t(`signage.window.${p.key}`, p.params)}</span>)} {parts.map(p => <span key={p.key}> · {p.key === 'days' ? p.params.days.map(d => t(`signage.weekdays.${d}`)).join(' ') : t(`signage.window.${p.key}`, p.params)}</span>)}
</span> </span>
@@ -219,9 +220,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
{/* the picked slide: its basics beside its preview (one height), then what it shows */} {/* the picked slide: its basics beside its preview (one height), then what it shows */}
{draft ? <> {draft ? <>
<section className="grid gap-6 lg:grid-cols-2 items-stretch rounded-card border border-line bg-surface shadow-raised p-card min-w-0" data-testid="signage-slide-top"> <section className="grid gap-6 lg:grid-cols-2 items-stretch rounded-card border border-line bg-surface shadow-raised p-card min-w-0" data-testid="signage-slide-top">
<SlideBasics slide={draft} onChange={setDraft} orientation={pl.orientation} /> <SlideBasics slide={draft} onChange={setDraft} orientation={shape} />
<FitPreview orientation={pl.orientation}> <FitPreview orientation={shape}>
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={pl.orientation} playing editor={editor} /> <SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={shape} playing editor={editor} />
</FitPreview> </FitPreview>
</section> </section>
<section className="rounded-card border border-line bg-surface shadow-raised p-card min-w-0"> <section className="rounded-card border border-line bg-surface shadow-raised p-card min-w-0">
@@ -239,9 +240,9 @@ export default function PlaylistEditor({ playlistId, onChanged, onDeleted }) {
</> : <p className="text-body text-ink-3 p-6 text-center">{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}</p>} </> : <p className="text-body text-ink-3 p-6 text-center">{t(pl.slides.length ? 'signage.pickSlide' : 'signage.noSlides')}</p>}
{adding !== null && ( {adding !== null && (
<AddSlideDialog onClose={() => setAdding(null)} onPick={addSlide} orientation={pl.orientation} venue={venue} library={adding} libraryMedia={libMedia} /> <AddSlideDialog onClose={() => setAdding(null)} onPick={addSlide} orientation={shape} venue={venue} library={adding} libraryMedia={libMedia} />
)} )}
{keeping && draft && <KeepDialog draft={draft} orientation={pl.orientation} onClose={() => setKeeping(false)} />} {keeping && draft && <KeepDialog draft={draft} shape={{ orientation: pl.orientation, aspect: pl.aspect || null }} onClose={() => setKeeping(false)} />}
{confirmDialog} {confirmDialog}
{confirmDelete && ( {confirmDelete && (
@@ -265,7 +266,7 @@ function DropLine({ side }) {
} }
/** Keep the slide (as it is now, saved or not) in the Slides library, with a name and a description. */ /** Keep the slide (as it is now, saved or not) in the Slides library, with a name and a description. */
function KeepDialog({ draft, orientation, onClose }) { function KeepDialog({ draft, shape, onClose }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [name, setName] = useState(draft.name || '') const [name, setName] = useState(draft.name || '')
const [description, setDescription] = useState('') const [description, setDescription] = useState('')
@@ -273,7 +274,7 @@ function KeepDialog({ draft, orientation, onClose }) {
const keep = async () => { const keep = async () => {
setBusy(true) setBusy(true)
try { try {
await api.createSaved({ ...slideBody(draft), kind: draft.kind, name: name.trim(), description: description.trim() || null, orientation }) await api.createSaved({ ...slideBody(draft), kind: draft.kind, name: name.trim(), description: description.trim() || null, ...shape })
toast.success(t('signage.library.kept')) toast.success(t('signage.library.kept'))
onClose() onClose()
} catch (err) { toast.error(errorMessage(err, t)) } } catch (err) { toast.error(errorMessage(err, t)) }
@@ -2,14 +2,17 @@
// playlist, or one slide from the Slides library shown alone), its shape and how its picture is // playlist, or one slide from the Slides library shown alone), its shape and how its picture is
// turned, and what plays on it now. A schedule line for a screen // turned, and what plays on it now. A schedule line for a screen
// (Schedules) wins over its default while it matches. A warning when a playlist it may play was // (Schedules) wins over its default while it matches. A warning when a playlist it may play was
// made for the other shape. New TVs are paired in Devices. // made for the other shape. New TVs are paired in Devices. 6R.13: how slides of another shape fit
// (keep their shape with bands, or stretch) and Calibrate the picture (CalibrateDialog).
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 { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { AlertTriangle, CalendarClock, Monitor, Smartphone } from 'lucide-react' import { AlertTriangle, CalendarClock, Monitor, Scan, Smartphone } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Dropdown, EmptyState, Field, Spinner } from '@xenia/ui' import { Button, Dropdown, EmptyState, Field, Spinner } from '@xenia/ui'
import { pictureArea, shapeName } from '@xenia/signage'
import CalibrateDialog from './CalibrateDialog'
import { DeviceSupport } from '../platform/DeviceSupport' import { DeviceSupport } from '../platform/DeviceSupport'
import * as api from './signageApi' import * as api from './signageApi'
@@ -18,6 +21,7 @@ export default function ScreensTab() {
const [screens, setScreens] = useState(null) const [screens, setScreens] = useState(null)
const [playlists, setPlaylists] = useState([]) const [playlists, setPlaylists] = useState([])
const [slides, setSlides] = useState([]) const [slides, setSlides] = useState([])
const [calibrating, setCalibrating] = useState(null) // the screen whose picture is being calibrated
const load = useCallback(async () => { const load = useCallback(async () => {
try { try {
const [s, p, l] = await Promise.all([api.listScreens(), api.listPlaylists(), api.listSaved().catch(() => ({ slides: [] }))]) const [s, p, l] = await Promise.all([api.listScreens(), api.listPlaylists(), api.listSaved().catch(() => ({ slides: [] }))])
@@ -25,6 +29,7 @@ export default function ScreensTab() {
} catch (err) { toast.error(errorMessage(err, t)) } } catch (err) { toast.error(errorMessage(err, t)) }
}, [t]) }, [t])
useEffect(() => { load() }, [load]) useEffect(() => { load() }, [load])
const replace = useCallback(s => setScreens(list => list.map(x => (x.id === s.id ? s : x))), [])
const save = async (id, body) => { const save = async (id, body) => {
try { const s = await api.updateScreen(id, body); setScreens(list => list.map(x => (x.id === id ? s : x))); toast.success(t('settings.saved')) } try { const s = await api.updateScreen(id, body); setScreens(list => list.map(x => (x.id === id ? s : x))); toast.success(t('settings.saved')) }
catch (err) { toast.error(errorMessage(err, t)) } catch (err) { toast.error(errorMessage(err, t)) }
@@ -61,7 +66,7 @@ export default function ScreensTab() {
{s.now?.scheduled && <CalendarClock size={14} className="text-accent-ink" aria-hidden="true" />} {s.now?.scheduled && <CalendarClock size={14} className="text-accent-ink" aria-hidden="true" />}
{s.now ? t(s.now.scheduled ? 'signage.screens.nowScheduled' : s.now.slide ? 'signage.screens.nowSlide' : 'signage.screens.nowDefault', { name: s.now.name }) : t('signage.screens.nowNothing')} {s.now ? t(s.now.scheduled ? 'signage.screens.nowScheduled' : s.now.slide ? 'signage.screens.nowSlide' : 'signage.screens.nowDefault', { name: s.now.name }) : t('signage.screens.nowNothing')}
</p> </p>
<div className="grid gap-3 sm:grid-cols-3 max-w-4xl"> <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4 max-w-5xl">
<Field label={t('signage.screens.default')} hint={t('signage.screens.defaultHint')}> <Field label={t('signage.screens.default')} hint={t('signage.screens.defaultHint')}>
<Dropdown value={s.playlist_id ? `p:${s.playlist_id}` : s.slide_id ? `s:${s.slide_id}` : ''} data-testid="signage-screen-playlist" <Dropdown value={s.playlist_id ? `p:${s.playlist_id}` : s.slide_id ? `s:${s.slide_id}` : ''} data-testid="signage-screen-playlist"
onChange={v => save(s.id, v.startsWith('s:') ? { slide_id: Number(v.slice(2)) } : { playlist_id: v ? Number(v.slice(2)) : null, slide_id: null })} onChange={v => save(s.id, v.startsWith('s:') ? { slide_id: Number(v.slice(2)) } : { playlist_id: v ? Number(v.slice(2)) : null, slide_id: null })}
@@ -77,11 +82,32 @@ export default function ScreensTab() {
<Dropdown value={s.rotation} onChange={v => save(s.id, { rotation: Number(v) })} data-testid="signage-screen-rotation" <Dropdown value={s.rotation} onChange={v => save(s.id, { rotation: Number(v) })} data-testid="signage-screen-rotation"
options={[0, 90, 180, 270].map(r => ({ value: r, label: t(`signage.screens.rotations.${r}`) }))} /> options={[0, 90, 180, 270].map(r => ({ value: r, label: t(`signage.screens.rotations.${r}`) }))} />
</Field> </Field>
<Field label={t('signage.screens.fit')} hint={t('signage.screens.fitHint')}>
<Dropdown value={s.fit || 'keep'} onChange={v => save(s.id, { fit: v })} data-testid="signage-screen-fit"
options={['keep', 'stretch'].map(f => ({ value: f, label: t(`signage.screens.fits.${f}`) }))} />
</Field>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button variant="secondary" icon={<Scan size={16} />} onClick={() => setCalibrating(s)} data-testid="signage-screen-calibrate">{t('signage.calibrate.open')}</Button>
<span className="text-label text-ink-2" data-testid="signage-screen-picture">{pictureText(s, t)}</span>
</div> </div>
</li> </li>
) )
})} })}
</ul> </ul>
{calibrating && <CalibrateDialog screen={calibrating} onSaved={replace} onClose={() => { setCalibrating(null); load() }} />}
</div> </div>
) )
} }
/** "The whole window (2560 × 1080 px, 21:9)" / "1920 × 1080 px of its 2560 × 1080 window" / nothing known yet. */
function pictureText(s, t) {
const a = s.area || {}
const cut = a.left || a.top || a.right || a.bottom
if (!s.viewport) return cut ? t('signage.screens.pictureCut') : t('signage.screens.pictureWhole')
const win = { w: s.viewport.width, h: s.viewport.height }
const pic = pictureArea(win, a)
return cut
? t('signage.screens.pictureOf', { w: Math.round(pic.width), h: Math.round(pic.height), shape: shapeName(pic.width, pic.height), ww: win.w, wh: win.h })
: t('signage.screens.pictureWindow', { w: win.w, h: win.h, shape: shapeName(win.w, win.h) })
}
@@ -0,0 +1,59 @@
// A playlist's or library slide's shape (6R.13, owner 2026-11-22): landscape, portrait, or a shape of
// its own (21:9, 16:10…) picked from the common ones or typed as W : H, behind the icon beside the
// list. The previews and the TVs draw the slides at that shape.
import { useRef, useState } from 'react'
import { Proportions } from 'lucide-react'
import { useTranslation } from '@xenia/i18n'
import { Button, Dropdown, Field, IconButton, NumberInput, Popover } from '@xenia/ui'
import { parseAspect, shapeOf, shapeRatio, SHAPES } from '@xenia/signage'
/** A small rectangle of a shape, for the presets. */
export function ShapeMark({ shape, size = 22 }) {
const r = shapeRatio(shape)
const w = r >= 1 ? size : Math.round(size * r)
const h = r >= 1 ? Math.round(size / r) : size
return <span className="inline-block rounded-[3px] border-2 border-current shrink-0" style={{ width: w, height: h }} aria-hidden="true" />
}
export default function ShapeField({ value, onChange, label, className = 'w-60', testId = 'signage-orientation' }) {
const { t } = useTranslation('manager')
const shape = shapeOf(value)
const custom = shape !== 'landscape' && shape !== 'portrait'
const btn = useRef(null)
const [open, setOpen] = useState(false)
const [own, setOwn] = useState(() => parseAspect(value?.aspect) || [21, 9])
const ok = parseAspect(`${own[0]}:${own[1]}`)
const pick = aspect => { setOpen(false); onChange({ aspect }) }
const options = [
...['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) })),
...(custom ? [{ value: shape, label: t('signage.shape.custom', { shape }) }] : []),
]
return (
<Field label={label || t('signage.orientation')} className={className}>
<div className="flex gap-1.5 items-center">
<Dropdown className="flex-1 min-w-0" value={shape} data-testid={testId} data-shape={shape}
onChange={v => (v === 'landscape' || v === 'portrait') && onChange({ orientation: v, aspect: null })} options={options} />
<IconButton ref={btn} label={t('signage.shape.own')} onClick={() => setOpen(o => !o)} aria-expanded={open}
tone={custom ? 'info' : undefined} data-testid={`${testId}-custom`}><Proportions size={16} /></IconButton>
<Popover open={open} anchor={btn} onClose={() => setOpen(false)} className="w-72 p-3 grid gap-3" data-testid="signage-shape-panel">
<p className="text-caption text-ink-2">{t('signage.shape.hint')}</p>
<div className="grid grid-cols-5 gap-1.5">
{SHAPES.map(s => (
<button key={s} type="button" onClick={() => pick(s)} data-shape={s}
className={`flex flex-col items-center justify-center gap-1 h-14 rounded-control border text-caption ${s === shape || (s === '16:9' && shape === 'landscape') || (s === '9:16' && shape === 'portrait') ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line text-ink-2 hover:bg-surface-2'}`}>
<ShapeMark shape={s} />{s}
</button>
))}
</div>
<div className="flex items-end gap-1.5">
<Field label={t('signage.shape.width')} className="flex-1"><NumberInput size="sm" value={own[0]} min={1} max={99} onChange={v => setOwn([v, own[1]])} data-testid="signage-shape-w" /></Field>
<span className="pb-2 text-ink-3">:</span>
<Field label={t('signage.shape.height')} className="flex-1"><NumberInput size="sm" value={own[1]} min={1} max={99} onChange={v => setOwn([own[0], v])} data-testid="signage-shape-h" /></Field>
</div>
{!ok && <p className="text-caption text-danger-ink">{t('signage.shape.invalid')}</p>}
<Button size="sm" disabled={!ok} onClick={() => pick(`${own[0]}:${own[1]}`)} data-testid="signage-shape-apply">{t('signage.shape.use', { shape: ok ? `${own[0]}:${own[1]}` : '' })}</Button>
</Popover>
</div>
</Field>
)
}
@@ -12,8 +12,10 @@ import toast from 'react-hot-toast'
import { Monitor, Plus, Smartphone } from 'lucide-react' import { Monitor, Plus, Smartphone } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Dropdown, EmptyState, Field, Input, Page, PageHeader, Spinner, Tabs } from '@xenia/ui' import { Button, Dialog, EmptyState, Field, Input, Page, PageHeader, Spinner, Tabs } from '@xenia/ui'
import { shapeRatio } from '@xenia/signage'
import * as api from './signageApi' import * as api from './signageApi'
import ShapeField from './ShapeField'
import PlaylistEditor from './PlaylistEditor' import PlaylistEditor from './PlaylistEditor'
import SchedulesTab from './SchedulesTab' import SchedulesTab from './SchedulesTab'
import ScreensTab from './ScreensTab' import ScreensTab from './ScreensTab'
@@ -86,21 +88,20 @@ export default function SignagePage() {
function NewPlaylist({ onClose, onCreate }) { function NewPlaylist({ onClose, onCreate }) {
const { t } = useTranslation('manager') const { t } = useTranslation('manager')
const [name, setName] = useState('') const [name, setName] = useState('')
const [orientation, setOrientation] = useState('landscape') const [shape, setShape] = useState({ orientation: 'landscape', aspect: null })
return ( return (
<Dialog open size="sm" title={t('signage.newPlaylist')} onClose={onClose} <Dialog open size="sm" title={t('signage.newPlaylist')} onClose={onClose}
footer={<> footer={<>
<Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button> <Button variant="secondary" onClick={onClose}>{t('fees.cancel')}</Button>
<Button disabled={!name.trim()} onClick={() => onCreate({ name: name.trim(), orientation })} data-testid="signage-create-playlist">{t('display.looks.create')}</Button> <Button disabled={!name.trim()} onClick={() => onCreate({ name: name.trim(), orientation: shape.orientation || 'landscape', aspect: shape.aspect || null })} data-testid="signage-create-playlist">{t('display.looks.create')}</Button>
</>}> </>}>
<div className="grid gap-3"> <div className="grid gap-3">
<Field label={t('signage.playlistName')}> <Field label={t('signage.playlistName')}>
<Input value={name} autoFocus maxLength={80} onChange={e => setName(e.target.value)} placeholder={t('signage.playlistPlaceholder')} data-testid="signage-new-name" /> <Input value={name} autoFocus maxLength={80} onChange={e => setName(e.target.value)} placeholder={t('signage.playlistPlaceholder')} data-testid="signage-new-name" />
</Field> </Field>
<Field label={t('signage.orientation')} hint={t('signage.orientationHint')}> <ShapeField value={shape} className="" testId="signage-new-orientation"
<Dropdown value={orientation} onChange={setOrientation} data-testid="signage-new-orientation" onChange={v => setShape({ orientation: v.orientation || (shapeRatio(v.aspect) < 1 ? 'portrait' : 'landscape'), aspect: v.aspect ?? null })} />
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`) }))} /> <p className="text-caption text-ink-3 -mt-1">{t('signage.orientationHint')}</p>
</Field>
</div> </div>
</Dialog> </Dialog>
) )
@@ -1,15 +1,13 @@
// A slide drawn exactly as the TV draws it (@xenia/signage), in a box of the playlist's shape // A slide drawn exactly as the TV draws it (@xenia/signage), in a box of the playlist's shape
// (plan step 5.6a). The slide is laid out on a full-size 1920 × 1080 (or 1080 × 1920) frame and // (plan step 5.6a). The slide is laid out on a full-size frame (1920 × 1080, 1080 × 1920, or a
// scaled down to the box, so text, rows and menu pages match a real TV, not a small window. // custom shape with its long side 1920: 6R.13) and scaled down to the box, so text, rows and menu
// pages match a real TV, not a small window. `orientation` is the shape: landscape, portrait, "21:9".
// `editor` = { selected, onSelect, onPlace, label } (2026-11-21): the widgets can be picked, moved // `editor` = { selected, onSelect, onPlace, label } (2026-11-21): the widgets can be picked, moved
// and sized on it (WidgetCanvas). // and sized on it (WidgetCanvas).
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { boardPages, SlideView, WIDGET_HOSTS } from '@xenia/signage' import { boardPages, canvasOf, SlideView, WIDGET_HOSTS } from '@xenia/signage'
import WidgetCanvas from './WidgetCanvas' import WidgetCanvas from './WidgetCanvas'
const LONG = 1920
const SHORT = 1080
export default function SlidePreview({ slide, media, venue, orientation = 'landscape', page = 0, playing = false, className = '', testid = 'signage-preview', editor = null }) { export default function SlidePreview({ slide, media, venue, orientation = 'landscape', page = 0, playing = false, className = '', testid = 'signage-preview', editor = null }) {
const [now, setNow] = useState(() => new Date()) const [now, setNow] = useState(() => new Date())
const box = useRef(null) const box = useRef(null)
@@ -18,9 +16,7 @@ export default function SlidePreview({ slide, media, venue, orientation = 'lands
const id = setInterval(() => setNow(new Date()), 1000) const id = setInterval(() => setNow(new Date()), 1000)
return () => clearInterval(id) return () => clearInterval(id)
}, []) }, [])
const tall = orientation === 'portrait' const { w, h } = canvasOf(orientation)
const w = tall ? SHORT : LONG
const h = tall ? LONG : SHORT
useEffect(() => { useEffect(() => {
const el = box.current const el = box.current
if (!el) return undefined if (!el) return undefined
@@ -33,7 +29,7 @@ export default function SlidePreview({ slide, media, venue, orientation = 'lands
const pages = slide?.kind === 'menu' ? boardPages(slide, 0, w, h) : null const pages = slide?.kind === 'menu' ? boardPages(slide, 0, w, h) : null
return ( return (
<div ref={box} className={`relative rounded-control ${className}`} data-testid={testid} data-orientation={orientation} <div ref={box} className={`relative rounded-control ${className}`} data-testid={testid} data-orientation={orientation}
style={{ aspectRatio: tall ? '9 / 16' : '16 / 9' }}> style={{ aspectRatio: `${w} / ${h}` }}>
{/* the slide is clipped to its frame; the editor's handles may stick out of it */} {/* the slide is clipped to its frame; the editor's handles may stick out of it */}
<div className="absolute inset-0 overflow-hidden rounded-control bg-black"> <div className="absolute inset-0 overflow-hidden rounded-control bg-black">
{slide && scale > 0 && ( {slide && scale > 0 && (
@@ -9,12 +9,14 @@ import toast from 'react-hot-toast'
import { ArrowLeft, Copy, Layers, Monitor, Pencil, Plus, Smartphone, Trash2 } from 'lucide-react' import { ArrowLeft, Copy, Layers, Monitor, Pencil, Plus, Smartphone, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import { Button, EmptyState, Field, IconButton, Input, Pane, Segmented, Spinner, Textarea, useConfirm } from '@xenia/ui' import { shapeOf, shapeRatio } from '@xenia/signage'
import { Button, EmptyState, Field, IconButton, Input, Pane, Spinner, Textarea, useConfirm } from '@xenia/ui'
import * as api from './signageApi' import * as api from './signageApi'
import { mediaEntry, mediaLookup, misfits, savedBody, secondsMissing } from './signageLogic' import { mediaEntry, mediaLookup, misfits, savedBody, secondsMissing } from './signageLogic'
import AddSlideDialog, { KIND_ICON } from './AddSlideDialog' import AddSlideDialog, { KIND_ICON } from './AddSlideDialog'
import SlideEditor, { SlideBasics } from './SlideEditor' import SlideEditor, { SlideBasics } from './SlideEditor'
import SlidePreview from './SlidePreview' import SlidePreview from './SlidePreview'
import ShapeField from './ShapeField'
import { useSlidePreview, useWidgetEditor } from './useSlideDraft' import { useSlidePreview, useWidgetEditor } from './useSlideDraft'
export default function SlidesTab({ open, onOpen }) { export default function SlidesTab({ open, onOpen }) {
@@ -61,19 +63,20 @@ export default function SlidesTab({ open, onOpen }) {
<ul className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]" data-testid="signage-saved-list"> <ul className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]" data-testid="signage-saved-list">
{list.map(s => { {list.map(s => {
const Icon = KIND_ICON[s.kind] const Icon = KIND_ICON[s.kind]
const Shape = s.orientation === 'portrait' ? Smartphone : Monitor const shape = shapeOf(s)
const Shape = shapeRatio(shape) < 1 ? Smartphone : Monitor
return ( return (
<li key={s.id} className="rounded-card border border-line bg-surface shadow-raised overflow-hidden grid content-start" data-testid="signage-saved" data-name={s.name}> <li key={s.id} className="rounded-card border border-line bg-surface shadow-raised overflow-hidden grid content-start" data-testid="signage-saved" data-name={s.name}>
<button type="button" onClick={() => onOpen(s.id)} className="block bg-surface-2 p-3" aria-label={t('signage.library.edit', { name: s.name })}> <button type="button" onClick={() => onOpen(s.id)} className="block bg-surface-2 p-3" aria-label={t('signage.library.edit', { name: s.name })}>
<div className="pointer-events-none mx-auto" style={{ width: s.orientation === 'portrait' ? '40%' : '100%' }}> <div className="pointer-events-none mx-auto" style={{ width: shapeRatio(shape) < 1 ? `${Math.round(71 * shapeRatio(shape))}%` : '100%' }}>
<SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={s.orientation} testid="signage-saved-preview" /> <SlidePreview slide={s} media={mediaLookup(media)} venue={venue} orientation={shape} testid="signage-saved-preview" />
</div> </div>
</button> </button>
<div className="p-card grid gap-1 min-w-0"> <div className="p-card grid gap-1 min-w-0">
<span className="flex items-center gap-1.5 min-w-0"> <span className="flex items-center gap-1.5 min-w-0">
<Icon size={15} className="text-ink-2 shrink-0" aria-hidden="true" /> <Icon size={15} className="text-ink-2 shrink-0" aria-hidden="true" />
<span className="text-body font-semibold text-ink truncate">{s.name}</span> <span className="text-body font-semibold text-ink truncate">{s.name}</span>
<Shape size={14} className="text-ink-3 shrink-0 ml-auto" aria-label={t(`signage.orientations.${s.orientation}`)} /> <Shape size={14} className="text-ink-3 shrink-0 ml-auto" aria-label={shape === s.orientation ? t(`signage.orientations.${s.orientation}`) : shape} />
</span> </span>
<span className="text-caption text-ink-3 line-clamp-2 min-h-[2.2em]">{s.description || t(`signage.kinds.${s.kind}`)}</span> <span className="text-caption text-ink-3 line-clamp-2 min-h-[2.2em]">{s.description || t(`signage.kinds.${s.kind}`)}</span>
{s.screens?.length > 0 && <span className="text-caption text-success-ink truncate">{t('signage.library.onScreens', { names: s.screens.map(x => x.name).join(', ') })}</span>} {s.screens?.length > 0 && <span className="text-caption text-success-ink truncate">{t('signage.library.onScreens', { names: s.screens.map(x => x.name).join(', ') })}</span>}
@@ -109,7 +112,7 @@ function SavedSlideEditor({ id, venue, onClose }) {
}, [id]) // eslint-disable-line react-hooks/exhaustive-deps }, [id]) // eslint-disable-line react-hooks/exhaustive-deps
useSlidePreview(draft, setDraft, more => setMedia(m => ({ ...m, ...more }))) useSlidePreview(draft, setDraft, more => setMedia(m => ({ ...m, ...more })))
const dirty = useMemo(() => !!(draft && saved && JSON.stringify(savedBody(draft)) !== JSON.stringify(savedBody(saved))), [draft, saved]) const dirty = useMemo(() => !!(draft && saved && JSON.stringify(savedBody(draft)) !== JSON.stringify(savedBody(saved))), [draft, saved])
const draftBad = useMemo(() => (draft ? misfits([draft], media, draft.orientation)[draft.id] || [] : []), [draft, media]) const draftBad = useMemo(() => (draft ? misfits([draft], media, shapeOf(draft))[draft.id] || [] : []), [draft, media])
if (!draft) return <div className="flex justify-center p-6"><Spinner /></div> if (!draft) return <div className="flex justify-center p-6"><Spinner /></div>
const set = patch => setDraft(d => ({ ...d, ...patch })) const set = patch => setDraft(d => ({ ...d, ...patch }))
@@ -130,7 +133,8 @@ function SavedSlideEditor({ id, venue, onClose }) {
} }
onClose() onClose()
} }
const tall = draft.orientation === 'portrait' const shape = shapeOf(draft)
const tall = shapeRatio(shape) < 1
return ( return (
<div className="x-page__fill grid gap-5 lg:grid-cols-2" data-testid="signage-saved-editor" data-id={id}> <div className="x-page__fill grid gap-5 lg:grid-cols-2" data-testid="signage-saved-editor" data-id={id}>
@@ -145,16 +149,14 @@ function SavedSlideEditor({ id, venue, onClose }) {
}> }>
<div className="p-card grid gap-6 content-start"> <div className="p-card grid gap-6 content-start">
<div className="mx-auto w-full" style={{ maxWidth: tall ? '22rem' : undefined }}> <div className="mx-auto w-full" style={{ maxWidth: tall ? '22rem' : undefined }}>
<SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={draft.orientation} playing editor={editor} testid="signage-saved-live" /> <SlidePreview slide={draft} media={mediaLookup(media)} venue={venue} orientation={shape} playing editor={editor} testid="signage-saved-live" />
</div> </div>
<div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_auto] items-end"> <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_auto] items-end">
<Field label={t('signage.library.name')}> <Field label={t('signage.library.name')}>
<Input value={draft.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-saved-name" /> <Input value={draft.name || ''} maxLength={80} onChange={e => set({ name: e.target.value })} data-testid="signage-saved-name" />
</Field> </Field>
<Field label={t('signage.orientation')}> <ShapeField value={draft} testId="signage-saved-orientation"
<Segmented value={draft.orientation} onChange={v => set({ orientation: v })} data-testid="signage-saved-orientation" onChange={v => set({ orientation: v.orientation || (shapeRatio(v.aspect) < 1 ? 'portrait' : 'landscape'), aspect: v.aspect ?? null })} />
options={['landscape', 'portrait'].map(o => ({ value: o, label: t(`signage.orientations.${o}`), icon: o === 'portrait' ? <Smartphone size={15} aria-hidden="true" /> : <Monitor size={15} aria-hidden="true" /> }))} />
</Field>
</div> </div>
<Field label={t('signage.library.description')} hint={t('signage.library.descriptionHint')}> <Field label={t('signage.library.description')} hint={t('signage.library.descriptionHint')}>
<Textarea rows={3} value={draft.description || ''} maxLength={300} onChange={e => set({ description: e.target.value })} data-testid="signage-saved-description" /> <Textarea rows={3} value={draft.description || ''} maxLength={300} onChange={e => set({ description: e.target.value })} data-testid="signage-saved-description" />
@@ -167,7 +169,7 @@ function SavedSlideEditor({ id, venue, onClose }) {
</Pane> </Pane>
<Pane header={<h3 className="px-card py-card-y text-body font-semibold text-ink">{t('signage.library.settings')}</h3>}> <Pane header={<h3 className="px-card py-card-y text-body font-semibold text-ink">{t('signage.library.settings')}</h3>}>
<div className="p-card grid gap-7 content-start"> <div className="p-card grid gap-7 content-start">
<SlideBasics slide={draft} onChange={setDraft} showName={false} orientation={draft.orientation} /> <SlideBasics slide={draft} onChange={setDraft} showName={false} orientation={shape} />
<SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))} <SlideEditor slide={draft} onChange={setDraft} media={media} onMedia={item => setMedia(m => ({ ...m, [String(item.id)]: mediaEntry(item) }))}
misfit={draftBad} widget={widget} onWidget={setWidget} /> misfit={draftBad} widget={widget} onWidget={setWidget} />
</div> </div>
@@ -30,6 +30,8 @@ export const duplicateSaved = id => client.post(`/api/signage/library/${id}/dupl
export const listScreens = () => client.get('/api/signage/screens').then(data) export const listScreens = () => client.get('/api/signage/screens').then(data)
export const updateScreen = (id, body) => client.put(`/api/signage/screens/${id}`, body).then(data) export const updateScreen = (id, body) => client.put(`/api/signage/screens/${id}`, body).then(data)
// calibrating a screen's picture (6R.13): the TV outlines its area while on
export const calibrateScreen = (id, on) => client.post(`/api/signage/screens/${id}/calibrate`, { on }).then(data)
// the schedule lines (2026-11-21): all of them, saved together // the schedule lines (2026-11-21): all of them, saved together
export const listSchedules = () => client.get('/api/signage/schedules').then(data) export const listSchedules = () => client.get('/api/signage/schedules').then(data)
@@ -1,4 +1,5 @@
// The signage editor's pure helpers (plan step 5.6a): unit-tested in tests/signage.test.mjs. // The signage editor's pure helpers (plan step 5.6a): unit-tested in tests/signage.test.mjs.
import { shapeRatio } from '@xenia/signage/logic'
export const KINDS = ['image', 'video', 'text', 'menu', 'blank'] // blank: a background and widgets (2026-11-21) export const KINDS = ['image', 'video', 'text', 'menu', 'blank'] // blank: a background and widgets (2026-11-21)
export const TRANSITIONS = ['fade', 'slide', 'zoom', 'none'] export const TRANSITIONS = ['fade', 'slide', 'zoom', 'none']
@@ -44,11 +45,11 @@ export function slideFromTemplate(tpl, t = k => k) {
return { kind, ...fields, content: filled } return { kind, ...fields, content: filled }
} }
/** Does a picture / video fit a playlist's orientation? null when its size isn't known. */ /** Does a picture / video fit a playlist's shape ("landscape", "portrait", "21:9")? null when its size isn't known. */
export function fitsOrientation(media, orientation) { export function fitsOrientation(media, shape) {
if (!media?.width || !media?.height) return null if (!media?.width || !media?.height) return null
const wide = media.width >= media.height const wide = media.width >= media.height
return orientation === 'portrait' ? !wide || media.width === media.height : wide return shapeRatio(shape) < 1 ? !wide || media.width === media.height : wide
} }
/** The media ids a slide shows big (its picture / video and its background): what must fit the shape. */ /** The media ids a slide shows big (its picture / video and its background): what must fit the shape. */
@@ -210,7 +211,7 @@ export function toggled(list, id) {
/** What a library slide sends back (PUT /api/signage/library/{id}): a slide's fields, its name, description and shape. */ /** What a library slide sends back (PUT /api/signage/library/{id}): a slide's fields, its name, description and shape. */
export function savedBody(s) { export function savedBody(s) {
return { ...slideBody(s), name: (s.name || '').trim(), description: (s.description || '').trim() || null, orientation: s.orientation || 'landscape' } return { ...slideBody(s), name: (s.name || '').trim(), description: (s.description || '').trim() || null, orientation: s.orientation || 'landscape', aspect: s.aspect || null }
} }
/** A library slide added to a playlist: a copy of its fields (the playlist's slide is then its own). */ /** A library slide added to a playlist: a copy of its fields (the playlist's slide is then its own). */
@@ -1,11 +1,11 @@
// How long a slide really plays (owner review 6, 2026-11-21): a menu board with pages plays whole // How long a slide really plays (owner review 6, 2026-11-21): a menu board with pages plays whole
// rounds of them, so its seconds on screen are rounded up (the TV does the same: menuMs). // rounds of them, so its seconds on screen are rounded up (the TV does the same: menuMs).
import { boardPages, menuMs } from '@xenia/signage' import { boardPages, canvasOf, menuMs } from '@xenia/signage'
/** A menu board's pages on a TV of this shape (1 when it fits, or without its products yet). */ /** A menu board's pages on a TV of this shape ("landscape", "portrait" or "21:9"; 1 when it fits, or without its products yet). */
export function pagesOn(slide, orientation = 'landscape') { export function pagesOn(slide, shape = 'landscape') {
if (slide?.kind !== 'menu' || !slide.menu) return 1 if (slide?.kind !== 'menu' || !slide.menu) return 1
const [w, h] = orientation === 'portrait' ? [1080, 1920] : [1920, 1080] const { w, h } = canvasOf(shape)
return Math.max(1, boardPages(slide, 0, w, h).length) return Math.max(1, boardPages(slide, 0, w, h).length)
} }
+3
View File
@@ -20,6 +20,9 @@ test('does a picture fit the playlist\'s shape', () => {
assert.equal(fitsOrientation({ width: 1080, height: 1920 }, 'portrait'), true) assert.equal(fitsOrientation({ width: 1080, height: 1920 }, 'portrait'), true)
assert.equal(fitsOrientation({ width: 800, height: 800 }, 'portrait'), true) assert.equal(fitsOrientation({ width: 800, height: 800 }, 'portrait'), true)
assert.equal(fitsOrientation({}, 'portrait'), null) assert.equal(fitsOrientation({}, 'portrait'), null)
// custom shapes (6R.13): wide or tall by their ratio
assert.equal(fitsOrientation({ width: 2560, height: 1080 }, '21:9'), true)
assert.equal(fitsOrientation({ width: 1920, height: 1080 }, '10:16'), false)
const media = { 1: { width: 1080, height: 1920 }, 2: { width: 1920, height: 1080 } } const media = { 1: { width: 1080, height: 1920 }, 2: { width: 1920, height: 1080 } }
const slides = [{ id: 10, content: { media_id: 1 } }, { id: 11, content: { media_id: 2 } }, const slides = [{ id: 10, content: { media_id: 1 } }, { id: 11, content: { media_id: 2 } },
{ id: 12, content: { background: { kind: 'media', media_id: 1 } } }, { id: 13, content: { background: { kind: 'colour', media_id: 1 } } }] { id: 12, content: { background: { kind: 'media', media_id: 1 } } }, { id: 13, content: { background: { kind: 'colour', media_id: 1 } } }]
+40 -1
View File
@@ -1605,7 +1605,17 @@
"defaultHint": "Όταν δεν ταιριάζει καμία γραμμή προγράμματος: μια λίστα ή μία διαφάνεια μόνη της.", "defaultHint": "Όταν δεν ταιριάζει καμία γραμμή προγράμματος: μια λίστα ή μία διαφάνεια μόνη της.",
"aPlaylist": "Λίστα", "aPlaylist": "Λίστα",
"aSlide": "Διαφάνεια", "aSlide": "Διαφάνεια",
"nowSlide": "Τώρα: {{name}} (η διαφάνεια προεπιλογής της)" "nowSlide": "Τώρα: {{name}} (η διαφάνεια προεπιλογής της)",
"fit": "Διαφάνειες άλλου σχήματος",
"fitHint": "Διαφάνεια φτιαγμένη για άλλο σχήμα από την εικόνα αυτής της οθόνης.",
"fits": {
"keep": "Κρατούν το σχήμα τους (λωρίδες)",
"stretch": "Τέντωμα σε όλη την εικόνα"
},
"pictureWhole": "Η εικόνα γεμίζει όλο το παράθυρο της τηλεόρασης.",
"pictureCut": "Η εικόνα είναι βαθμονομημένη (άκρες μετακινημένες προς τα μέσα).",
"pictureWindow": "Η εικόνα γεμίζει όλο το παράθυρο της τηλεόρασης: {{w}} × {{h}} px, {{shape}}.",
"pictureOf": "Η εικόνα: {{w}} × {{h}} px ({{shape}}) από το παράθυρο {{ww}} × {{wh}} της τηλεόρασης."
}, },
"schedules": { "schedules": {
"new": "Νέο πρόγραμμα", "new": "Νέο πρόγραμμα",
@@ -1789,6 +1799,35 @@
"empty": "Συμπληρώστε έναν αριθμό (1 ή περισσότερα).", "empty": "Συμπληρώστε έναν αριθμό (1 ή περισσότερα).",
"backTo": "Πίσω στα {{n}}", "backTo": "Πίσω στα {{n}}",
"warning": "Πάνω από {{n}} widgets μπορεί να κάνουν τις τηλεοράσεις να κολλάνε (διαφάνειες που αλλάζουν αργά, βίντεο που κόβονται). Ελέγξτε τις οθόνες σας αφού τα προσθέσετε." "warning": "Πάνω από {{n}} widgets μπορεί να κάνουν τις τηλεοράσεις να κολλάνε (διαφάνειες που αλλάζουν αργά, βίντεο που κόβονται). Ελέγξτε τις οθόνες σας αφού τα προσθέσετε."
},
"shape": {
"custom": "Δικό του σχήμα {{shape}}",
"own": "Δικό του σχήμα (21:9, 16:10…)",
"hint": "Για οθόνες που δεν είναι 16:9. Οι διαφάνειες φτιάχνονται και προβάλλονται σε αυτό το σχήμα.",
"width": "Πλάτος",
"height": "Ύψος",
"invalid": "Από 1:4 έως 4:1, ακέραιοι έως 99.",
"use": "Χρήση {{shape}}"
},
"calibrate": {
"open": "Βαθμονόμηση εικόνας",
"title": "Βαθμονόμηση εικόνας: {{name}}",
"intro": "Η τηλεόραση δείχνει τώρα τις άκρες της εικόνας με τέσσερα βέλη προς τα έξω. Μετακινήστε κάθε άκρη μέχρι το βέλος της να ακουμπά την άκρη της οθόνης ή διαλέξτε σχήμα. Οι αλλαγές φαίνονται αμέσως στην τηλεόραση.",
"window": "Το παράθυρο της τηλεόρασης: {{w}} × {{h}} px ({{shape}}).",
"waiting": "Αναμονή για το μέγεθος της τηλεόρασης… Είναι ανοιχτή και δείχνει ψηφιακή σήμανση;",
"presets": "Σχήματα",
"full": "Όλη η οθόνη",
"step": "Κάθε κλικ μετακινεί",
"edges": {
"top": "Πάνω άκρη μέσα",
"right": "Δεξιά άκρη μέσα",
"bottom": "Κάτω άκρη μέσα",
"left": "Αριστερή άκρη μέσα"
},
"picture": "Η εικόνα: {{w}} × {{h}} px ({{shape}})",
"outside": "Έξω από την εικόνα η τηλεόραση μένει μαύρη.",
"reset": "Ξανά όλη η οθόνη",
"done": "Τέλος"
} }
}, },
"overview": { "overview": {
+24
View File
@@ -572,7 +572,31 @@
"180": "Ανάποδα", "180": "Ανάποδα",
"270": "90° αριστερά" "270": "90° αριστερά"
} }
},
"fit": {
"label": "Διαφάνειες άλλου σχήματος",
"hint": "Να κρατούν το σχήμα τους (λωρίδες με το φόντο της διαφάνειας) ή να τεντώνονται σε όλη την εικόνα.",
"choices": {
"keep": "Κρατούν το σχήμα τους",
"stretch": "Τέντωμα σε όλη την εικόνα"
} }
},
"area_left": {
"label": "Περιοχή εικόνας: αριστερή άκρη (px)",
"hint": "Ρυθμίζεται από Ψηφιακή σήμανση → Οθόνες → Βαθμονόμηση εικόνας."
},
"area_top": {
"label": "Περιοχή εικόνας: πάνω άκρη (px)"
},
"area_right": {
"label": "Περιοχή εικόνας: δεξιά άκρη (px)"
},
"area_bottom": {
"label": "Περιοχή εικόνας: κάτω άκρη (px)"
}
},
"config_groups": {
"picture": "Η εικόνα"
} }
}, },
"staff_planning": { "staff_planning": {
+4
View File
@@ -487,6 +487,10 @@
"spicy": "Καυτερό", "spicy": "Καυτερό",
"vegetarian": "Χορτοφαγικό", "vegetarian": "Χορτοφαγικό",
"vegan": "Vegan" "vegan": "Vegan"
},
"calibrate": {
"title": "Βαθμονόμηση εικόνας: {{name}}",
"hint": "Στον διαχειριστή (Ψηφιακή σήμανση → Οθόνες) μετακινήστε κάθε άκρη μέχρι τα βέλη να ακουμπούν τις άκρες της οθόνης."
} }
}, },
"menuTablet": { "menuTablet": {
+40 -1
View File
@@ -1605,7 +1605,17 @@
"defaultHint": "When no schedule line matches: a playlist, or one slide shown alone.", "defaultHint": "When no schedule line matches: a playlist, or one slide shown alone.",
"aPlaylist": "Playlist", "aPlaylist": "Playlist",
"aSlide": "Slide", "aSlide": "Slide",
"nowSlide": "Now: {{name}} (its default slide)" "nowSlide": "Now: {{name}} (its default slide)",
"fit": "Slides of another shape",
"fitHint": "A slide built for another shape than this screen's picture.",
"fits": {
"keep": "Keep their shape (bands)",
"stretch": "Stretch to fill"
},
"pictureWhole": "The picture fills the TV's whole window.",
"pictureCut": "The picture is calibrated (edges moved in).",
"pictureWindow": "The picture fills the TV's whole window: {{w}} × {{h}} px, {{shape}}.",
"pictureOf": "The picture: {{w}} × {{h}} px ({{shape}}) of the TV's {{ww}} × {{wh}} window."
}, },
"schedules": { "schedules": {
"new": "New schedule", "new": "New schedule",
@@ -1789,6 +1799,35 @@
"empty": "Fill in a number (1 or more).", "empty": "Fill in a number (1 or more).",
"backTo": "Back to {{n}}", "backTo": "Back to {{n}}",
"warning": "More than {{n}} widgets can make the TVs stutter (slides turning late, videos jerking). Check your screens after you add them." "warning": "More than {{n}} widgets can make the TVs stutter (slides turning late, videos jerking). Check your screens after you add them."
},
"shape": {
"custom": "Own shape {{shape}}",
"own": "A shape of its own (21:9, 16:10…)",
"hint": "For screens that aren't 16:9. The slides are built and shown at this shape.",
"width": "Width",
"height": "Height",
"invalid": "Between 1:4 and 4:1, whole numbers up to 99.",
"use": "Use {{shape}}"
},
"calibrate": {
"open": "Calibrate the picture",
"title": "Calibrate the picture: {{name}}",
"intro": "The TV now shows its picture's edges with four arrows pointing out. Move each edge until its arrow just touches the edge of the screen, or pick a shape. Changes show on the TV at once.",
"window": "The TV's window: {{w}} × {{h}} px ({{shape}}).",
"waiting": "Waiting for the TV to tell its size… Is it on and showing signage?",
"presets": "Shapes",
"full": "Whole screen",
"step": "Each click moves",
"edges": {
"top": "Top edge in",
"right": "Right edge in",
"bottom": "Bottom edge in",
"left": "Left edge in"
},
"picture": "The picture: {{w}} × {{h}} px ({{shape}})",
"outside": "Outside the picture the TV stays black.",
"reset": "Whole screen again",
"done": "Done"
} }
}, },
"overview": { "overview": {
+24
View File
@@ -572,7 +572,31 @@
"180": "Upside down", "180": "Upside down",
"270": "90° left" "270": "90° left"
} }
},
"fit": {
"label": "Slides of another shape",
"hint": "Keep their shape (bands in the slide's own background), or stretch them over the whole picture.",
"choices": {
"keep": "Keep their shape",
"stretch": "Stretch to fill"
} }
},
"area_left": {
"label": "Picture area: left edge (px)",
"hint": "Set with Signage → Screens → Calibrate the picture."
},
"area_top": {
"label": "Picture area: top edge (px)"
},
"area_right": {
"label": "Picture area: right edge (px)"
},
"area_bottom": {
"label": "Picture area: bottom edge (px)"
}
},
"config_groups": {
"picture": "The picture"
} }
}, },
"staff_planning": { "staff_planning": {
+4
View File
@@ -487,6 +487,10 @@
"spicy": "Spicy", "spicy": "Spicy",
"vegetarian": "Vegetarian", "vegetarian": "Vegetarian",
"vegan": "Vegan" "vegan": "Vegan"
},
"calibrate": {
"title": "Calibrating the picture of {{name}}",
"hint": "In the manager (Signage → Screens), move each edge until the arrows touch the edges of the screen."
} }
}, },
"menuTablet": { "menuTablet": {
+2 -1
View File
@@ -6,7 +6,8 @@
"description": "Signage slides as the TVs draw them, and the player's pure logic (schedule pick, slide windows, menu pages): one implementation for the terminal's player and the manager's previews (plan steps 5.5a-5.6a).", "description": "Signage slides as the TVs draw them, and the player's pure logic (schedule pick, slide windows, menu pages): one implementation for the terminal's player and the manager's previews (plan steps 5.5a-5.6a).",
"main": "src/index.js", "main": "src/index.js",
"exports": { "exports": {
".": "./src/index.js" ".": "./src/index.js",
"./logic": "./src/logic.js"
}, },
"dependencies": { "dependencies": {
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
+19
View File
@@ -46,6 +46,25 @@ function EmbeddedSlide({ slide, media, venue, now }) {
) )
} }
/**
* What fills the bands around a slide that keeps its shape on a screen of another shape (6R.13):
* the slide's own background colour; a photo background fills them blurred and darker, so the
* slide's edge doesn't show a seam.
*/
export function Backdrop({ slide, media }) {
const c = slide?.content || {}
if (slide?.kind === 'image' || slide?.kind === 'video') {
return <div className="absolute inset-0" style={{ background: c.background_colour || '#000' }} data-testid="signage-backdrop" />
}
const bg = c.background || {}
const m = bg.kind === 'media' ? media(bg.media_id) : null
return (
<div className="absolute inset-0 overflow-hidden" style={{ background: bg.colour || '#111827' }} data-testid="signage-backdrop">
{m && <img src={m.src} alt="" className="absolute inset-0 w-full h-full" style={{ objectFit: 'cover', filter: 'blur(24px) brightness(0.6)', transform: 'scale(1.1)' }} />}
</div>
)
}
function ImageSlide({ content, media }) { function ImageSlide({ content, media }) {
const m = content.media_id ? media(content.media_id) : null const m = content.media_id ? media(content.media_id) : null
return ( return (
+1 -1
View File
@@ -5,4 +5,4 @@ export * from './logic.js'
export { cq, CQ_BOX, CQ_NATIVE } from './cq.js' export { cq, CQ_BOX, CQ_NATIVE } from './cq.js'
export { BADGE_ICONS } from './badges.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 { Backdrop, SlideView } from './SlideView.jsx'
+87 -4
View File
@@ -134,13 +134,24 @@ export function slideMs(slide) {
return Math.max(1, slide.duration_s || 10) * 1000 return Math.max(1, slide.duration_s || 10) * 1000
} }
/** The frame's size and turn for a screen: CSS for the box that holds the slides. */ /**
export function frameStyle(rotation) { * The frame's size and turn for a screen: CSS for the box that holds the slides. `size` (6R.13):
* the picture area in px it fills (its parent), else the whole window.
*/
export function frameStyle(rotation, size) {
const r = Number(rotation) || 0 const r = Number(rotation) || 0
const W = size ? `${size.width}px` : '100vw'
const H = size ? `${size.height}px` : '100vh'
if (r === 90 || r === 270) { if (r === 90 || r === 270) {
return { width: '100vh', height: '100vw', transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', position: 'absolute', containerType: 'size' } return { width: H, height: W, transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', position: 'absolute', containerType: 'size' }
} }
return { width: '100vw', height: '100vh', transform: r === 180 ? 'rotate(180deg)' : undefined, top: 0, left: 0, position: 'absolute', containerType: 'size' } return { width: W, height: H, transform: r === 180 ? 'rotate(180deg)' : undefined, top: 0, left: 0, position: 'absolute', containerType: 'size' }
}
/** The frame's own width × height (after its turn) for a picture area. */
export function frameSize(rotation, size) {
const r = Number(rotation) || 0
return r === 90 || r === 270 ? { w: size.height, h: size.width } : { w: size.width, h: size.height }
} }
/** Every media address a playlist (or a schedule's playlists) needs, to keep on the device. */ /** Every media address a playlist (or a schedule's playlists) needs, to keep on the device. */
@@ -425,3 +436,75 @@ export function priceChars(groups, format) {
for (const g of groups || []) for (const it of g.items || []) if (it.price != null) n = Math.max(n, String(format(it.price)).length) for (const g of groups || []) for (const it of g.items || []) if (it.price != null) n = Math.max(n, String(format(it.price)).length)
return n return n
} }
// ── slide shapes and the screen's picture area (6R.13, owner 2026-11-22) ─────────
/** Shapes offered for a playlist / a library slide beyond landscape and portrait (and the calibration presets). */
export const SHAPES = ['16:9', '16:10', '21:9', '32:9', '4:3', '5:4', '1:1', '9:16', '10:16', '3:4']
/** "21:9" → [21, 9]; anything else → null. Shapes from 1:4 to 4:1. */
export function parseAspect(a) {
const m = /^(\d{1,2}):(\d{1,2})$/.exec(String(a || ''))
if (!m) return null
const w = Number(m[1])
const h = Number(m[2])
if (!w || !h || w / h > 4 || h / w > 4) return null
return [w, h]
}
/** What a playlist / library slide is built for: its custom shape ("21:9"), else landscape / portrait. */
export const shapeOf = x => (x && parseAspect(x.aspect) ? x.aspect : x?.orientation === 'portrait' ? 'portrait' : 'landscape')
/** Width ÷ height of a shape ("landscape", "portrait" or "W:H"). */
export function shapeRatio(shape) {
if (shape === 'portrait') return 9 / 16
const a = parseAspect(shape)
return a ? a[0] / a[1] : 16 / 9
}
/** The size a slide of this shape is laid out at (its long side 1920 px, as the editor's previews). */
export function canvasOf(shape) {
const r = shapeRatio(shape)
return r >= 1 ? { w: 1920, h: Math.round(1920 / r) } : { w: Math.round(1920 * r), h: 1920 }
}
/** The largest box of `ratio` (w ÷ h) inside W × H, centred: { left, top, width, height } in px. */
export function fitBox(W, H, ratio) {
if (!(W > 0) || !(H > 0) || !(ratio > 0)) return { left: 0, top: 0, width: Math.max(0, W || 0), height: Math.max(0, H || 0) }
let width = W
let height = W / ratio
if (height > H) { height = H; width = H * ratio }
return { left: (W - width) / 2, top: (H - height) / 2, width, height }
}
/** A screen's picture area in its window: the window minus the calibrated insets (never smaller than 50 px). */
export function pictureArea(win, area = {}) {
const l = Math.max(0, area.left || 0)
const t = Math.max(0, area.top || 0)
const width = Math.max(50, win.w - l - Math.max(0, area.right || 0))
const height = Math.max(50, win.h - t - Math.max(0, area.bottom || 0))
return { left: l, top: t, width, height }
}
/**
* Calibration presets (6R.13): the insets that leave the largest box of a shape in the middle of
* the window ("full": the whole window). → { left, top, right, bottom } in whole px.
*/
export function presetInsets(win, shape) {
if (shape === 'full' || !win?.w || !win?.h) return { left: 0, top: 0, right: 0, bottom: 0 }
const b = fitBox(win.w, win.h, shapeRatio(shape))
const left = Math.floor(b.left)
const top = Math.floor(b.top)
return { left, top, right: Math.max(0, win.w - left - Math.round(b.width)), bottom: Math.max(0, win.h - top - Math.round(b.height)) }
}
/** "1920 × 1080" → its nearest named shape ("16:9") when within 2 % (a "21:9" monitor is really 64:27), else "W:H" reduced (e.g. "43:18"). */
export function shapeName(w, h) {
if (!(w > 0) || !(h > 0)) return ''
const r = w / h
const near = SHAPES.find(s => Math.abs(shapeRatio(s) - r) / r < 0.02)
if (near) return near
const g = (a, b) => (b ? g(b, a % b) : a)
const d = g(Math.round(w), Math.round(h)) || 1
return `${Math.round(w) / d}:${Math.round(h) / d}`
}
+27
View File
@@ -243,3 +243,30 @@ test('container units: an older browser gets calc() of the variables the compat
assert.deepEqual(CQ_BOX, { 'data-cq': '' }) assert.deepEqual(CQ_BOX, { 'data-cq': '' })
} finally { delete globalThis.CSS } } finally { delete globalThis.CSS }
}) })
test('slide shapes: custom ratios, the canvas, the box a slide keeps on any screen (6R.13)', async () => {
const { canvasOf, fitBox, parseAspect, pictureArea, presetInsets, shapeName, shapeOf, shapeRatio } = await import('../src/logic.js')
assert.deepEqual(parseAspect('21:9'), [21, 9])
assert.equal(parseAspect('9:1'), null)
assert.equal(parseAspect('16x9'), null)
assert.equal(shapeOf({ orientation: 'portrait' }), 'portrait')
assert.equal(shapeOf({ orientation: 'landscape', aspect: '21:9' }), '21:9')
assert.equal(shapeOf({ orientation: 'landscape', aspect: 'nope' }), 'landscape')
assert.equal(shapeRatio('landscape'), 16 / 9)
assert.deepEqual(canvasOf('landscape'), { w: 1920, h: 1080 })
assert.deepEqual(canvasOf('portrait'), { w: 1080, h: 1920 })
assert.deepEqual(canvasOf('21:9'), { w: 1920, h: 823 })
// a 16:9 slide on a 21:9 monitor: full height, bands left and right
const b = fitBox(2560, 1080, 16 / 9)
assert.deepEqual([Math.round(b.left), b.top, Math.round(b.width), b.height], [320, 0, 1920, 1080])
// on 16:10: full width, bands above and below
const c = fitBox(1920, 1200, 16 / 9)
assert.deepEqual([c.left, c.top, c.width, c.height], [0, 60, 1920, 1080])
// calibration: the window minus the insets; the presets centre a shape
assert.deepEqual(pictureArea({ w: 1920, h: 1080 }, { left: 10, top: 0, right: 30, bottom: 20 }), { left: 10, top: 0, width: 1880, height: 1060 })
assert.deepEqual(presetInsets({ w: 2560, h: 1080 }, '16:9'), { left: 320, top: 0, right: 320, bottom: 0 })
assert.deepEqual(presetInsets({ w: 1920, h: 1080 }, 'full'), { left: 0, top: 0, right: 0, bottom: 0 })
assert.equal(shapeName(2560, 1080), '21:9')
assert.equal(shapeName(1920, 1200), '16:10')
assert.equal(shapeName(1000, 300), '10:3')
})
+68 -9
View File
@@ -6,11 +6,16 @@
// keeps playing (and switching by its schedule) while the server is down, and catches up on // keeps playing (and switching by its schedule) while the server is down, and catches up on
// `signage.changed`, a reconnect, or every few minutes (prices that change by time alone). // `signage.changed`, a reconnect, or every few minutes (prices that change by time alone).
// Menu boards page by themselves when they don't fit (5.5b); widgets sit in corners and bars. // Menu boards page by themselves when they don't fit (5.5b); widgets sit in corners and bars.
// 6R.13: the picture fills the screen's calibrated area (its window minus the insets set in
// Signage → Screens); a slide keeps its playlist's shape inside it (bands in its own background)
// unless the screen stretches it. While the manager calibrates, the area is outlined with arrows
// pointing out and its size; the TV reports its window size for the presets.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp } from 'lucide-react'
import { useTranslation } from '@xenia/i18n' import { useTranslation } from '@xenia/i18n'
import client from '../../api/client' import client from '../../api/client'
import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context' import { useDevice, useLiveEvent, useLiveEvents } from '../../device/context'
import { boardPages, CQ_BOX, frameStyle, localNow, mediaUrls, menuMs, nextSlide, pageAt, playlistNow, SlideView, slideMs } from '@xenia/signage' import { Backdrop, boardPages, CQ_BOX, fitBox, frameSize, frameStyle, localNow, mediaUrls, menuMs, nextSlide, pageAt, pictureArea, playlistNow, shapeName, shapeOf, shapeRatio, SlideView, slideMs } from '@xenia/signage'
const quiet = { xenia: { noOverride: true } } const quiet = { xenia: { noOverride: true } }
const CACHE_KEY = 'xenia:signage:screen' const CACHE_KEY = 'xenia:signage:screen'
@@ -18,6 +23,7 @@ const REFRESH_MS = 5 * 60_000
const VIDEO_MAX_MS = 15 * 60_000 // a video "to its end" that never ends moves on after this const VIDEO_MAX_MS = 15 * 60_000 // a video "to its end" that never ends moves on after this
const KEEP_VIDEO_BYTES = 120 * 1024 * 1024 // bigger videos stream from the server (not kept offline) const KEEP_VIDEO_BYTES = 120 * 1024 * 1024 // bigger videos stream from the server (not kept offline)
const TRANSITION_MS = 800 const TRANSITION_MS = 800
const CALIBRATE_MS = 15 * 60_000 // an outline nobody turns off goes away by itself
function readCache() { function readCache() {
try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null } try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null }
@@ -87,22 +93,66 @@ export default function SignageApp() {
return () => clearInterval(id) return () => clearInterval(id)
}, []) }, [])
// the window, for the picture area and the manager's calibration presets (6R.13)
const win = useWindowSize()
const report = useCallback(() => {
client.post('/api/signage/screen/viewport', { width: Math.round(window.innerWidth), height: Math.round(window.innerHeight), ratio: window.devicePixelRatio || 1 }, quiet).catch(() => {})
}, [])
useEffect(() => { report() }, [report, win.w, win.h])
useLiveEvent('ready', report)
const [calib, setCalib] = useState(null) // the last signage.calibrate: { on, area }
useLiveEvent('signage.calibrate', d => setCalib({ on: !!d?.on, area: d?.area || null }))
useEffect(() => {
if (!calib?.on) return undefined
const id = setTimeout(() => setCalib({ on: false, area: null }), CALIBRATE_MS)
return () => clearTimeout(id)
}, [calib])
const kept = useKeptMedia(useMemo(() => mediaUrls(data), [data])) const kept = useKeptMedia(useMemo(() => mediaUrls(data), [data]))
const playlist = playlistNow(data, now) const playlist = playlistNow(data, now)
const tz = data?.schedule?.timezone const tz = data?.schedule?.timezone
const screen = data?.screen const screen = data?.screen
const calibrating = calib ? calib.on : !!screen?.calibrating
const pic = pictureArea(win, (calib?.on && calib.area) || screen?.area)
const frame = frameSize(screen?.rotation, pic)
return ( return (
<main className="fixed inset-0 overflow-hidden select-none cursor-none" style={{ background: '#000' }} <main className="fixed inset-0 overflow-hidden select-none cursor-none" style={{ background: '#000' }}
data-testid="app-signage" data-playlist={playlist?.id ?? ''} data-orientation={screen?.orientation ?? ''} data-offline={offline ? 'true' : 'false'}> data-testid="app-signage" data-playlist={playlist?.id ?? ''} data-orientation={screen?.orientation ?? ''} data-offline={offline ? 'true' : 'false'}>
<div style={frameStyle(screen?.rotation)} {...CQ_BOX} data-testid="signage-frame" data-rotation={screen?.rotation ?? 0}> <div className="absolute overflow-hidden" style={{ left: pic.left, top: pic.top, width: pic.width, height: pic.height }}
data-testid="signage-area" data-area={`${pic.left},${pic.top},${pic.width},${pic.height}`}>
<div style={frameStyle(screen?.rotation, pic)} {...CQ_BOX} data-testid="signage-frame" data-rotation={screen?.rotation ?? 0}>
{playlist?.slides?.length {playlist?.slides?.length
? <Player key={playlist.id} playlist={playlist} kept={kept} tz={tz} venue={data?.venue} now={now} rotation={screen?.rotation} /> ? <Player key={playlist.id} playlist={playlist} kept={kept} tz={tz} venue={data?.venue} now={now} frame={frame} fit={screen?.fit} />
: <Empty text={data ? t('signage.nothing') : t('signage.starting')} />} : <Empty text={data ? t('signage.nothing') : t('signage.starting')} />}
</div> </div>
{calibrating && <Calibration pic={pic} name={screen?.name} />}
</div>
</main> </main>
) )
} }
/** The picture area while the manager calibrates it (6R.13): its outline, arrows pointing at the screen's edges, its size. */
function Calibration({ pic, name }) {
const { t } = useTranslation('terminal')
const arrow = 'absolute text-accent'
const size = { width: '8vmin', height: '8vmin' }
return (
<div className="absolute inset-0 border-4 border-accent" data-testid="signage-calibrate" data-size={`${Math.round(pic.width)}x${Math.round(pic.height)}`}>
<ArrowUp className={arrow} style={{ ...size, top: '1vmin', left: 'calc(50% - 4vmin)' }} aria-hidden="true" />
<ArrowDown className={arrow} style={{ ...size, bottom: '1vmin', left: 'calc(50% - 4vmin)' }} aria-hidden="true" />
<ArrowLeft className={arrow} style={{ ...size, left: '1vmin', top: 'calc(50% - 4vmin)' }} aria-hidden="true" />
<ArrowRight className={arrow} style={{ ...size, right: '1vmin', top: 'calc(50% - 4vmin)' }} aria-hidden="true" />
<div className="absolute rounded-card bg-surface text-ink text-center" style={{ left: '50%', top: '50%', transform: 'translate(-50%, -50%)', padding: '2.5vmin 4vmin', maxWidth: '70%' }}>
<div style={{ fontSize: '3.2vmin', fontWeight: 700 }}>{t('signage.calibrate.title', { name: name || '' })}</div>
<div style={{ fontSize: '5vmin', fontWeight: 800, fontVariantNumeric: 'tabular-nums' }} data-testid="signage-calibrate-size">
{Math.round(pic.width)} × {Math.round(pic.height)} px · {shapeName(pic.width, pic.height)}
</div>
<div className="text-ink-2" style={{ fontSize: '2.4vmin' }}>{t('signage.calibrate.hint')}</div>
</div>
</div>
)
}
function Empty({ text }) { function Empty({ text }) {
return ( return (
<div className="absolute inset-0 flex items-end justify-end p-4" data-testid="signage-empty"> <div className="absolute inset-0 flex items-end justify-end p-4" data-testid="signage-empty">
@@ -122,11 +172,16 @@ function useWindowSize() {
return size return size
} }
function Player({ playlist, kept, tz, venue, now, rotation }) { function Player({ playlist, kept, tz, venue, now, frame, fit }) {
const local = localNow(tz, now) const local = localNow(tz, now)
const slides = playlist.slides const slides = playlist.slides
const size = useWindowSize() // the slide's own box: its playlist's shape as large as fits the frame, centred (or the whole frame)
const pagesOf = useCallback(sl => (sl?.kind === 'menu' ? boardPages(sl, rotation, size.w, size.h) : null), [rotation, size]) const shape = shapeOf(playlist)
const stretch = fit === 'stretch'
const box = useMemo(() => (stretch ? { left: 0, top: 0, width: frame.w, height: frame.h } : fitBox(frame.w, frame.h, shapeRatio(shape))),
[stretch, frame.w, frame.h, shape])
const banded = box.width < frame.w - 1 || box.height < frame.h - 1
const pagesOf = useCallback(sl => (sl?.kind === 'menu' ? boardPages(sl, 0, box.width, box.height) : null), [box])
const [cur, setCur] = useState(() => ({ index: nextSlide(slides, -1, local), at: Date.now(), n: 0 })) const [cur, setCur] = useState(() => ({ index: nextSlide(slides, -1, local), at: Date.now(), n: 0 }))
const [prev, setPrev] = useState(null) const [prev, setPrev] = useState(null)
const media = id => { const media = id => {
@@ -171,21 +226,25 @@ function Player({ playlist, kept, tz, venue, now, rotation }) {
return ( return (
<> <>
{prev && slides[prev.index] && ( {prev && slides[prev.index] && (
<Layer key={`out-${prev.n}`} slide={slides[prev.index]} media={media} venue={venue} now={now} className={`sg-out sg-out-${transition}`} <Layer key={`out-${prev.n}`} slide={slides[prev.index]} media={media} venue={venue} now={now} className={`sg-out sg-out-${transition}`} box={box} banded={banded} shape={shape}
pages={pagesOf(slides[prev.index])} page={pageAt(pagesOf(slides[prev.index])?.length || 0, slides[prev.index].content?.page_seconds, cur.at - prev.at - 1)} /> pages={pagesOf(slides[prev.index])} page={pageAt(pagesOf(slides[prev.index])?.length || 0, slides[prev.index].content?.page_seconds, cur.at - prev.at - 1)} />
)} )}
<Layer key={`in-${cur.n}`} slide={slide} media={media} venue={venue} now={now} onEnded={advance} <Layer key={`in-${cur.n}`} slide={slide} media={media} venue={venue} now={now} onEnded={advance} box={box} banded={banded} shape={shape}
className={cur.n === 0 ? '' : `sg-in sg-in-${transition}`} current className={cur.n === 0 ? '' : `sg-in sg-in-${transition}`} current
pages={pagesOf(slide)} page={pageAt(pagesOf(slide)?.length || 0, slide.content?.page_seconds, now.getTime() - cur.at)} /> pages={pagesOf(slide)} page={pageAt(pagesOf(slide)?.length || 0, slide.content?.page_seconds, now.getTime() - cur.at)} />
</> </>
) )
} }
function Layer({ slide, media, venue, now, onEnded, className, current = false, pages, page }) { function Layer({ slide, media, venue, now, onEnded, className, current = false, pages, page, box, banded, shape }) {
return ( return (
<section className={`absolute inset-0 overflow-hidden ${className}`} style={{ animationDuration: `${TRANSITION_MS}ms` }} <section className={`absolute inset-0 overflow-hidden ${className}`} style={{ animationDuration: `${TRANSITION_MS}ms` }}
data-testid={current ? 'signage-slide' : 'signage-slide-out'} data-kind={slide.kind} data-slide={slide.id}> data-testid={current ? 'signage-slide' : 'signage-slide-out'} data-kind={slide.kind} data-slide={slide.id}>
{banded && <Backdrop slide={slide} media={media} />}
<div style={{ position: 'absolute', left: box.left, top: box.top, width: box.width, height: box.height, overflow: 'hidden', containerType: 'size' }}
{...CQ_BOX} data-testid={current ? 'signage-shape' : undefined} data-shape={shape} data-box={`${Math.round(box.width)}x${Math.round(box.height)}`}>
<SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={page} onEnded={current ? onEnded : undefined} /> <SlideView slide={slide} media={media} venue={venue} now={now} pages={pages} page={page} onEnded={current ? onEnded : undefined} />
</div>
</section> </section>
) )
} }
+54 -4
View File
@@ -190,7 +190,8 @@ try {
await shown(tall, 'pairing-code', 20_000) await shown(tall, 'pairing-code', 20_000)
const code2 = await tall.getByTestId('pairing-code').getAttribute('data-code') const code2 = await tall.getByTestId('pairing-code').getAttribute('data-code')
const dev2 = await api('POST', '/api/devices', { token: boss, body: { code: code2, app_key: 'signage', name: 'Tall TV' } }) const dev2 = await api('POST', '/api/devices', { token: boss, body: { code: code2, app_key: 'signage', name: 'Tall TV' } })
await api('PUT', `/api/signage/screens/${dev2.id}`, { token: boss, body: { playlist_id: board.id, orientation: 'portrait' } }) // (a landscape board keeps its shape on a portrait TV unless the screen stretches it: 6R.13)
await api('PUT', `/api/signage/screens/${dev2.id}`, { token: boss, body: { playlist_id: board.id, orientation: 'portrait', fit: 'stretch' } })
await waitFor(async () => (await tall.getByTestId('signage-slide').getAttribute('data-kind').catch(() => null)) === 'menu', 20_000, 300) await waitFor(async () => (await tall.getByTestId('signage-slide').getAttribute('data-kind').catch(() => null)) === 'menu', 20_000, 300)
const pagesTall = Number(await tall.getByTestId('signage-menu').getAttribute('data-pages')) const pagesTall = Number(await tall.getByTestId('signage-menu').getAttribute('data-pages'))
r.check('5.5b: on a portrait TV the same board needs fewer pages', pagesTall < pagesWide, `${pagesTall} < ${pagesWide}`) r.check('5.5b: on a portrait TV the same board needs fewer pages', pagesTall < pagesWide, `${pagesTall} < ${pagesWide}`)
@@ -365,8 +366,9 @@ try {
const place = part2().getByTestId('signage-stack-place').first() 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, 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 })) colour: getComputedStyle(el.querySelector('[data-widget]')).color }))
return css.align === 'flex-end' && css.italic === 'italic' && css.colour === 'rgb(239, 68, 68)' return ['flex-end', 'flow-end'].includes(css.align) && css.italic === 'italic' && css.colour === 'rgb(239, 68, 68)' ? true : null
}, 6000, 300) === true) }, 6000, 300) === true, JSON.stringify(await part2().getByTestId('signage-stack-place').first().evaluate(el => ({ align: getComputedStyle(el).alignItems,
italic: getComputedStyle(el.querySelector('[data-testid="signage-w-text"]')).fontStyle, colour: getComputedStyle(el.querySelector('[data-widget]')).color })).catch(e => String(e))))
// 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')
@@ -528,6 +530,53 @@ try {
await choose(card, 'signage-screen-playlist', 'Board to keep') await choose(card, 'signage-screen-playlist', 'Board to keep')
r.check('2026-11-21: Screens: a library slide as the default plays alone on the TV', r.check('2026-11-21: Screens: a library slide as the default plays alone on the TV',
!!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === `slide:${kept.id}`, 15_000, 300))) !!(await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === `slide:${kept.id}`, 15_000, 300)))
// ── 6R.13: slides keep their shape on a 21:9 TV; stretch; a playlist of its own shape; calibrating ──
await choose(card, 'signage-screen-playlist', 'Window')
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)
await tv.setViewportSize({ width: 1260, height: 540 })
const boxNow = () => tv.getByTestId('signage-shape').getAttribute('data-box', { timeout: 3000 }).catch(() => null)
r.check('6R.13: a 16:9 slide on a 21:9 TV keeps its shape, centred, the bands in its own background',
await waitFor(async () => (await boxNow()) === '960x540', 10_000, 200) === true && await tv.getByTestId('signage-backdrop').count() > 0, String(await boxNow()))
await tv.screenshot({ path: path.join(OUT, 'signage-21x9-bands.png') })
await choose(card, 'signage-screen-fit', 'Stretch to fill')
r.check('6R.13: …or stretched over the whole picture (the screen\'s choice)', await waitFor(async () => (await boxNow()) === '1260x540', 10_000, 200) === true)
await choose(card, 'signage-screen-fit', 'Keep their shape (bands)')
await waitFor(async () => (await boxNow()) === '960x540', 10_000, 200)
// the playlist built for 21:9 (its own shape, picked in the editor) fills it
await mgr.getByTestId('signage-tab-playlists').click()
await mgr.locator('[data-testid="signage-playlist-item"][data-name="Window"]').click()
await mgr.getByTestId('signage-orientation-custom').click()
await mgr.getByTestId('signage-shape-panel').locator('[data-shape="21:9"]').click()
const wide = await waitFor(async () => ((await api('GET', `/api/signage/playlists/${pl.id}`, { token: boss })).aspect === '21:9' ? true : null), 8000, 300)
r.check('6R.13: a playlist given its own shape (21:9) in the editor', wide === true
&& (await mgr.getByTestId('signage-orientation').getAttribute('data-shape')) === '21:9')
r.check('6R.13: …the TV draws it over the whole 21:9 picture, no bands',
await waitFor(async () => (await boxNow()) === '1260x540', 10_000, 200) === true && await tv.getByTestId('signage-backdrop').count() === 0, String(await boxNow()))
await api('PUT', `/api/signage/playlists/${pl.id}`, { token: boss, body: { orientation: 'landscape' } })
// calibrating: the TV outlines its picture; a preset and a pixel move reach it at once
await mgr.getByTestId('signage-tab-screens').click()
await card.getByTestId('signage-screen-calibrate').click()
const outlined = await shown(tv, 'signage-calibrate', 10_000)
const outline = outlined ? await tv.getByTestId('signage-calibrate').getAttribute('data-size') : null
r.check('6R.13: Calibrate the picture: the TV outlines it with arrows and its size', outline === '1260x540', `${outlined} ${outline}`)
r.check('6R.13: …the dialog knows the TV\'s window (it reported 1260 × 540)',
await waitFor(async () => (await mgr.getByTestId('signage-calibrate-window').textContent()).includes('1260 × 540'), 8000, 300) === true)
await mgr.getByTestId('signage-calibrate-dialog').locator('[data-preset="16:9"]').click()
const areaNow = () => tv.getByTestId('signage-area').getAttribute('data-area')
r.check('6R.13: the 16:9 preset leaves the largest 16:9 box in the middle of the TV', await waitFor(async () => (await areaNow()) === '150,0,960,540', 8000, 200) === true, String(await areaNow()))
const plus = mgr.getByTestId('signage-calibrate-top').locator('xpath=..').locator('button').last()
await plus.click(); await plus.click()
r.check('6R.13: …the top edge moved in 2 px with + (the TV follows)', await waitFor(async () => (await areaNow()) === '150,2,960,538', 8000, 200) === true, String(await areaNow()))
await mgr.screenshot({ path: path.join(OUT, 'signage-calibrate.png') })
await tv.screenshot({ path: path.join(OUT, 'signage-calibrate-tv.png') })
await mgr.getByTestId('signage-calibrate-done').click()
r.check('6R.13: Done: the outline goes away, the calibrated picture stays',
await tv.getByTestId('signage-calibrate').waitFor({ state: 'detached', timeout: 10_000 }).then(() => true).catch(() => false) && (await areaNow()) === '150,2,960,538')
const saved = (await api('GET', '/api/signage/screens', { token: boss })).find(x => x.id === dev.id)
r.check('6R.13: the insets are the screen\'s settings', JSON.stringify(saved.area) === JSON.stringify({ left: 150, top: 2, right: 150, bottom: 0 }), JSON.stringify(saved.area))
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { area_left: 0, area_top: 0, area_right: 0, area_bottom: 0 } })
await tv.setViewportSize({ width: 1280, height: 720 })
await mgr.context().close() await mgr.context().close()
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } }) await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300) await waitFor(async () => (await tv.getByTestId('app-signage').getAttribute('data-playlist')) === String(pl.id), 15_000, 300)
@@ -535,7 +584,8 @@ try {
// ── the server stops: the TV keeps playing ──────────────────────────────── // ── the server stops: the TV keeps playing ────────────────────────────────
await backend.stop() await backend.stop()
const offlineOrder = await watch(tv, 14_000) const offlineOrder = await watch(tv, 14_000)
r.check('server stopped: the TV keeps playing its slides', new Set(offlineOrder).size >= 3, offlineOrder.join(' ')) r.check('server stopped: the TV keeps playing its slides', new Set(offlineOrder).size >= 3,
`${offlineOrder.join(' ')} pages=${await tv.getByTestId('signage-menu').getAttribute('data-pages', { timeout: 1000 }).catch(() => '?')}`)
r.check('…with a small mark, never the banner over the slides', await shown(tv, 'offline-mark', 15_000) && await tv.getByTestId('offline-banner').count() === 0) r.check('…with a small mark, never the banner over the slides', await shown(tv, 'offline-mark', 15_000) && await tv.getByTestId('offline-banner').count() === 0)
const offImg = await waitFor(async () => (await kindNow(tv)) === 'image' ? tv.getByTestId('signage-image').evaluate(i => i.complete && i.naturalWidth) : null, 20_000, 200) const offImg = await waitFor(async () => (await kindNow(tv)) === 'image' ? tv.getByTestId('signage-image').evaluate(i => i.complete && i.naturalWidth) : null, 20_000, 200)
r.check('…and the picture still shows', offImg > 0, String(offImg)) r.check('…and the picture still shows', offImg > 0, String(offImg))