Files
xenia-pos-local/packages/signage/src/logic.js
T
bonaminandClaude Opus 5.5 2a38602d45 feat(manager): the venue's identity (Settings -> Identity): name, slogan, named colours, logos, guest Wi-Fi, contact details
Set once (GET/PUT /api/identity, venue.name + venue.identity); every colour field
offers the venue's colours first (VenueColoursProvider in @xenia/ui); signage screens
get the identity and the venue's time zone with their venue and are told on a change;
logos are protected in the media library; wifiQr() for the join-the-network code.
Plan 6R.14, F-111.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 13:10:58 +02:00

522 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The signage player's logic (plan steps 5.5a, 5.5b; @xenia/signage since 5.6a). Pure: unit-tested in
// Node (packages/signage/tests/logic.test.mjs).
// The schedule rules are the server's (local_backend/services/signage_schedule.py) so a screen
// switches playlists by itself while the server is down; the same cases are tested on both sides.
import { cq } from './cq.js'
/** The venue's local clock at `date`: { weekday (0 = Monday), minutes, date: "YYYY-MM-DD" }. */
export function localNow(timeZone, date = new Date()) {
// the venue's zone (the schedule's), not the TV's: a TV set to another zone still switches on time
const opts = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short', hourCycle: 'h23' }
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', { timeZone: timeZone || undefined, ...opts })
.formatToParts(date).map(p => [p.type, p.value]))
const weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].indexOf(parts.weekday)
return { weekday, minutes: Number(parts.hour) * 60 + Number(parts.minute), date: `${parts.year}-${parts.month}-${parts.day}` }
}
/** The day before a local moment (for windows that pass midnight). */
function yesterday(local) {
const d = new Date(`${local.date}T12:00:00Z`)
d.setUTCDate(d.getUTCDate() - 1)
return { weekday: (local.weekday + 6) % 7, minutes: local.minutes, date: d.toISOString().slice(0, 10) }
}
const mins = hhmm => {
if (!hhmm) return null
const [h, m] = hhmm.split(':').map(Number)
return h * 60 + m
}
// ── smart days (owner 2026-11-21): the same as local_backend/core/calendar_days.py ──────────
export const MONTH_DAYS = ['first', 'last', 'first_week', 'last_week', 'holiday', 'not_holiday']
const FIXED_HOLIDAYS = ['01-01', '01-06', '03-25', '05-01', '08-15', '10-28', '12-25', '12-26']
const FROM_EASTER = [-48, -2, 0, 1, 50] // Clean Monday, Good Friday, Easter Sunday, Easter Monday, Whit Monday
const iso = d => d.toISOString().slice(0, 10)
/** The Orthodox Easter Sunday of a year, "YYYY-MM-DD" (Meeus' Julian algorithm + 13 days, 1900-2099). */
export function orthodoxEaster(year) {
const a = year % 4
const b = year % 7
const c = year % 19
const d = (19 * c + 15) % 30
const e = (2 * a + 4 * b - d + 34) % 7
const month = Math.floor((d + e + 114) / 31)
const day = ((d + e + 114) % 31) + 1
return iso(new Date(Date.UTC(year, month - 1, day + 13)))
}
/** A Greek public holiday (nationwide), for a "YYYY-MM-DD" date. */
export function isHoliday(date) {
if (FIXED_HOLIDAYS.includes(date.slice(5))) return true
const easter = new Date(`${orthodoxEaster(Number(date.slice(0, 4)))}T00:00:00Z`)
return FROM_EASTER.some(n => iso(new Date(easter.getTime() + n * 86400000)) === date)
}
/** Does a "YYYY-MM-DD" day pass a line's smart days (empty = every day)? Any one is enough; "not_holiday" keeps holidays out. */
export function monthDaysOk(tokens, date) {
const list = (tokens || []).filter(t => MONTH_DAYS.includes(t))
if (!list.length) return true
const hol = isHoliday(date)
if (list.includes('not_holiday') && hol) return false
const wanted = list.filter(t => t !== 'not_holiday')
if (!wanted.length) return true
const [y, m, d] = date.split('-').map(Number)
const last = new Date(Date.UTC(y, m, 0)).getUTCDate()
return wanted.some(t => (t === 'first' && d === 1) || (t === 'last' && d === last) || (t === 'first_week' && d <= 7)
|| (t === 'last_week' && d > last - 7) || (t === 'holiday' && hol))
}
function dayOk(w, local) {
const days = w.days || []
return (!days.length || days.includes(local.weekday)) &&
(!w.date_from || local.date >= w.date_from) && (!w.date_to || local.date <= w.date_to) && monthDaysOk(w.month_days, local.date)
}
/** Does a window (days, smart days, time_from / time_to that may pass midnight, date_from / date_to,
* a scene that must be on) cover `local`? */
export function matches(w, local, scenes) {
if (w.scene_id != null && !(scenes || []).includes(w.scene_id)) return false
let start = mins(w.time_from)
let end = mins(w.time_to)
if (start == null && end == null) return dayOk(w, local)
start = start ?? 0
end = end ?? 24 * 60
if (start < end) return local.minutes >= start && local.minutes < end && dayOk(w, local)
if (local.minutes >= start) return dayOk(w, local)
if (local.minutes < end) return dayOk(w, yesterday(local))
return false
}
const specific = e => ((e.date_from || e.date_to) ? 4 : 0) + ((e.days?.length || e.month_days?.length) ? 2 : 0) + ((e.time_from || e.time_to) ? 1 : 0)
/** The playlist a schedule plays at `local`: highest priority, then the most specific, then the later entry. */
export function pick(entries, fallback, local, scenes) {
let best = null
let bestKey = null
;(entries || []).forEach((e, i) => {
if (e.playlist_id == null || !matches(e, local, scenes)) return
const key = [e.priority || 0, specific(e), i]
if (!bestKey || key[0] > bestKey[0] || (key[0] === bestKey[0] && (key[1] > bestKey[1] || (key[1] === bestKey[1] && key[2] > bestKey[2])))) {
best = e.playlist_id
bestKey = key
}
})
return best ?? fallback ?? null
}
/** The playlist to play now from the screen's answer (GET /api/signage/screen): a schedule line
* (with the scenes that were on when it last heard from the server), else the screen's default. */
export function playlistNow(data, now = new Date()) {
if (!data) return null
if (!data.schedule) return data.playlist || null
const id = pick(data.schedule.entries, data.schedule.fallback_playlist_id, localNow(data.schedule.timezone, now), data.schedule.scenes)
return id != null ? data.playlists?.[String(id)] ?? null : null
}
/** A slide may show now: its own window (days / hours / dates), in venue time. */
export function slideShows(slide, local) {
return matches({ days: slide.days, time_from: slide.time_from, time_to: slide.time_to, date_from: slide.date_from, date_to: slide.date_to }, local)
}
/** The index of the next slide that may show after `current` (wrapping), or -1 when none may. */
export function nextSlide(slides, current, local) {
const n = slides?.length || 0
for (let step = 1; step <= n; step++) {
const i = (((current ?? -1) + step) % n + n) % n
if (slideShows(slides[i], local)) return i
}
return -1
}
/** How long a slide stays, in ms; null = until its video ends (with a safety limit in the player). */
export function slideMs(slide) {
if (slide.kind === 'video' && slide.video_to_end) return null
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. `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 W = size ? `${size.width}px` : '100vw'
const H = size ? `${size.height}px` : '100vh'
if (r === 90 || r === 270) {
return { width: H, height: W, transform: `translate(-50%, -50%) rotate(${r}deg)`, top: '50%', left: '50%', 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. */
export function mediaUrls(data) {
if (!data) return []
const lists = data.schedule ? Object.values(data.playlists || {}) : (data.playlist ? [data.playlist] : [])
const out = new Set()
for (const p of lists) {
for (const m of Object.values(p.media || {})) {
if (m.url) out.add(m.url)
if (m.poster) out.add(m.poster) // a video's still frame (5.4e), shown while it loads
}
}
return [...out]
}
/** The fonts a slide can choose (all on the device: nothing to download, works offline). */
export const FONTS = {
sans: 'system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
serif: 'Georgia, "Times New Roman", serif',
rounded: 'ui-rounded, "SF Pro Rounded", "Arial Rounded MT Bold", system-ui, sans-serif',
condensed: '"Arial Narrow", "Roboto Condensed", "Helvetica Neue", sans-serif',
display: 'Impact, "Arial Black", system-ui, sans-serif',
}
// ── menu boards (5.5b) ───────────────────────────────────────────────────────
/** The frame's height in cqmin (its shorter side is 100) for a screen w × h: 100 when wide, ~178 when tall (16:9). */
export function frameHeightVmin(rotation, w = 16, h = 9) {
const turned = Number(rotation) === 90 || Number(rotation) === 270
const frameTall = turned ? w > h : h > w // the screen's sides, swapped when the picture is turned
return frameTall ? (100 * Math.max(w, h)) / Math.min(w, h) : 100
}
/**
* How many rows fit in one column of a menu board: rows are items (taller with a photo or a
* description) and group headings. Sizes in cqmin, as the board draws them.
*/
export function rowsPerColumn({ heightVmin = 100, textSize = 100, photos = false, descriptions = false, title = false, bars = 0 }) {
const s = (textSize || 100) / 100
const row = (photos ? 8 : descriptions ? 7 : 4.8) * s
const used = 10 + (title ? 11 * s : 0) + bars * 9 // padding, the title, top / bottom bars of widgets
return Math.max(3, Math.floor((heightVmin - used) / row))
}
/**
* The board's pages: groups split into pages of at most `perPage` rows (a heading counts as a
* row; a group cut in two repeats its heading on the next page). → [[{category, items}], …]
*/
export function menuPages(groups, perPage, headings = true) {
const per = Math.max(1, perPage | 0)
const pages = []
let page = []
let used = 0
const flush = () => { if (page.length) pages.push(page); page = []; used = 0 }
for (const g of groups || []) {
let items = [...(g.items || [])]
if (!items.length) continue
while (items.length) {
const head = headings && g.category ? 1 : 0
if (used + head + 1 > per) flush()
const room = per - used - head
const take = items.slice(0, Math.max(1, room))
page.push({ category: g.category, items: take })
used += head + take.length
items = items.slice(take.length)
if (items.length) flush()
}
}
flush()
return pages
}
/** A menu slide's time: every page for its seconds, at least the slide's own time. */
export function menuMs(slide, pageCount) {
// owner review 6 (2026-11-21): a board with pages plays whole rounds of them, never cut in the
// middle: its seconds on screen rounded up to the next full round (10 s, 2 pages of 3 s → 12 s)
if (!(pageCount > 1)) return slideMs(slide)
const round = pageCount * Math.max(1, slide.content?.page_seconds || 10) * 1000
return Math.max(1, Math.ceil(slideMs(slide) / round)) * round
}
/** The page on screen `elapsedMs` into the slide (the pages go round while the slide lasts). */
export function pageAt(pageCount, pageSeconds, elapsedMs) {
if (pageCount <= 1 || !(elapsedMs > 0)) return 0 // the clock's last tick may be just before the slide began
return Math.floor(elapsedMs / (Math.max(1, pageSeconds || 10) * 1000)) % pageCount // round and round while the slide lasts
}
/** A weather code (WMO, as Open-Meteo sends it) → an icon name for the widget. */
export function weatherIcon(code, isDay = true) {
if (code == null) return 'cloud'
if (code === 0) return isDay ? 'sun' : 'moon'
if (code <= 2) return isDay ? 'cloud-sun' : 'cloud-moon'
if (code === 3) return 'cloud'
if (code === 45 || code === 48) return 'fog'
if ((code >= 51 && code <= 67) || (code >= 80 && code <= 82)) return 'rain'
if ((code >= 71 && code <= 77) || code === 85 || code === 86) return 'snow'
if (code >= 95) return 'storm'
return 'cloud'
}
/** A menu slide's pages for this screen (w × h pixels, turned by `rotation`). */
export function boardPages(slide, rotation, w, h) {
const c = slide.content || {}
const widgets = c.widgets || []
const bars = ['top-bar', 'bottom-bar'].filter(p => widgets.some(x => x.position === p)).length
const look = menuLook(c)
const rows = rowsPerColumn({ heightVmin: frameHeightVmin(rotation, w, h), textSize: (c.text_size || 100) * look.rowScale, photos: c.show_photos,
descriptions: c.show_descriptions, title: !!c.title, bars })
const per = c.page_size || rows * (c.columns || 2)
return menuPages(visibleGroups(slide.menu?.groups), per, c.category_titles !== false)
}
/** A board's groups without the products hidden from it (the editor's list keeps them, marked
* `hidden`, 2026-11-21); groups left empty go too. */
export function visibleGroups(groups) {
return (groups || []).map(g => ({ ...g, items: (g.items || []).filter(i => !i.hidden) })).filter(g => g.items.length)
}
// ── widgets placed by hand (owner 2026-11-21) ─────────────────────────────────
/** Widgets whose box, placed by hand, is exactly their content (owner review 6): its height (× the
* widget's text size) sets the size, its width follows. A menu or a stack fills its box. */
export const TIGHT = ['logo', 'name', 'date', 'clock', 'message', 'text', 'qr', 'weather']
/** The slide kinds that carry widgets. */
export const WIDGET_HOSTS = ['text', 'menu', 'blank']
/** A stack's parts' shares as whole percents adding up to 100 (2026-11-21). */
export function evenShares(n) {
const base = Math.floor(100 / n)
return Array.from({ length: n }, (_, i) => (i < 100 - base * n ? base + 1 : base))
}
/**
* A stack's part `i` set to `value` % (5…): the difference is taken from (or given to) the part
* after it (the one before, for the last part), which keeps at least 5 %; the shares still add up
* to 100. → the new shares.
*/
export function setShare(shares, i, value) {
const out = [...shares]
if (out.length < 2) return [100]
const j = i < out.length - 1 ? i + 1 : i - 1
const room = out[i] + out[j] - 5
const v = Math.max(5, Math.min(room, Math.round(Number(value) || 0)))
out[j] = out[i] + out[j] - v
out[i] = v
return out
}
/** How a widget lines up inside its place: its own choice, else by its corner / its box's side. */
export function widgetAlign(w) {
if (w?.align && w.align !== 'auto') return w.align
if (w?.position === 'custom' && w.box) {
const mid = w.box.x + w.box.w / 2
return mid < 100 / 3 ? 'left' : mid > 200 / 3 ? 'right' : 'center'
}
const p = w?.position || ''
return p.endsWith('left') ? 'left' : p.endsWith('right') ? 'right' : p.endsWith('center') ? 'center' : 'left'
}
/**
* A size unit for a widget that fills its own box: `n` units of its usual size (cqmin at "medium")
* scaled so the whole widget, `height` × `width` usual units, fits the box (inside an element with
* `container-type: size`). → n → CSS length.
*/
export function fitUnit(height, width) {
const byH = 100 / Math.max(0.1, height)
const byW = 100 / Math.max(0.1, width)
return n => `calc(${+n.toFixed(3)} * min(${cq(+byH.toFixed(4), 'h')}, ${cq(+byW.toFixed(4), 'w')}))`
}
/** A line of `chars` characters at `size` usual units: about how wide it is (bold sans). */
export function textWidth(chars, size) {
return Math.max(1, chars) * size * 0.6
}
// ── a menu's look, part by part (owner review 3, 2026-11-21) ──────────────────
const WEIGHT = { heading: 700, item: 600, price: 700 }
const RADIUS = { square: '0', rounded: '0.3em', round: '50%' }
const DOTS = { dotted: 'dotted', dashed: 'dashed', solid: 'solid' }
/**
* How a menu's parts look, as CSS for MenuGroups (sizes in em of the list's text, which is the
* board's text size): headings, names and prices each their own size, colour, font, bold / italic /
* underline and alignment (empty: the board's text size and font, the text colour for names and the
* accent colour for headings and prices); the dots between name and price; line and letter spacing
* (auto: 1.25 and normal; set on the list, never inherited from the page); photos' size and shape.
* Badges: badgeColours (owner review 5).
*/
export function menuLook(c = {}) {
const base = c.text_size || 100
const accent = c.accent_colour || '#f59e0b'
const text = c.text_colour || '#fff'
const part = (s = {}, kind, colour, scale) => ({
fontSize: `${+(((s.size || base) / base) * scale).toFixed(3)}em`,
color: s.colour || colour,
fontFamily: s.font ? FONTS[s.font] : undefined,
fontWeight: s.bold === false ? 400 : WEIGHT[kind],
fontStyle: s.italic ? 'italic' : undefined,
textDecoration: s.underline ? 'underline' : undefined,
})
const d = c.dot_style || {}
return {
heading: { ...part(c.heading_style, 'heading', accent, 1.15), textAlign: c.heading_style?.align || undefined },
item: part(c.item_style, 'item', text, 1),
itemAlign: c.item_style?.align || 'left',
price: part(c.price_style, 'price', accent, 1),
priceAlign: c.price_style?.align || 'right',
dots: d.style === 'none'
? { borderBottom: 'none' }
: { borderBottom: `${+(0.08 * (d.size || 100) / 100).toFixed(3)}em ${DOTS[d.style] || 'dotted'} ${d.colour || 'currentColor'}`, opacity: d.colour ? 1 : 0.35 },
title: c.heading_style?.colour || accent,
lineHeight: c.line_height || 1.25,
letterSpacing: c.letter_spacing != null ? `${c.letter_spacing}em` : 'normal',
photo: { size: `${+(2.2 * (c.photo_size || 100) / 100).toFixed(3)}em`, radius: RADIUS[c.photo_shape] || RADIUS.rounded },
// how much taller a row is than the usual (for the pages' sums)
rowScale: Math.max(1, (c.price_style?.size || base) / base, (c.item_style?.size || base) / base, (c.heading_style?.size || base) / base)
* ((c.line_height || 1.25) / 1.25),
}
}
/**
* The badges a venue has until it edits its own (owner review 5; the server's DEFAULTS in
* services/signage_badges.py): a screen that hasn't heard of the venue's list draws these.
*/
export const DEFAULT_BADGES = [
{ key: 'new', names: { el: 'Νέο', en: 'New' }, colour: '#22c55e', text_colour: null, icon: 'sparkles' },
{ key: 'chef', names: { el: 'Πρόταση σεφ', en: "Chef's pick" }, colour: '#f59e0b', text_colour: null, icon: 'chef-hat' },
{ key: 'offer', names: { el: 'Προσφορά', en: 'Offer' }, colour: '#ef4444', text_colour: null, icon: 'tag' },
{ key: 'popular', names: { el: 'Δημοφιλές', en: 'Popular' }, colour: '#f472b6', text_colour: null, icon: 'star' },
{ key: 'spicy', names: { el: 'Καυτερό', en: 'Spicy' }, colour: '#dc2626', text_colour: null, icon: 'flame' },
{ key: 'vegetarian', names: { el: 'Χορτοφαγικό', en: 'Vegetarian' }, colour: '#16a34a', text_colour: null, icon: 'sprout' },
{ key: 'vegan', names: { el: 'Vegan', en: 'Vegan' }, colour: '#15803d', text_colour: null, icon: 'vegan' },
]
/** A product's badges as their definitions (unknown keys left out; one badge stored as `badge` too). */
export function itemBadges(it, defs) {
const list = defs?.length ? defs : DEFAULT_BADGES
const keys = it?.badges?.length ? it.badges : it?.badge ? [it.badge] : []
return keys.map(k => list.find(d => d.key === k)).filter(Boolean)
}
/** A badge's colours on a board: the board's own for all its badges, else the badge's; text that reads. */
export function badgeColours(def, c = {}) {
const background = c.badge_colour || def?.colour || '#f59e0b'
return { background, color: c.badge_text_colour || def?.text_colour || readableOn(background) }
}
/** A badge's name in a language (the board's, else the screen's), else in the other one. */
export function badgeName(def, lang) {
const n = def?.names || {}
return n[lang] || n.el || n.en || def?.key || ''
}
/** A stack part's widgets (a part stored before owner review 4 has one `widget`). */
export function cellWidgets(c) {
return c?.widgets?.length ? c.widgets : c?.widget ? [c.widget] : []
}
/**
* A text colour that reads on `hex` (#rgb, #rrggbb or #rrggbbaa; the alpha is ignored): white on a
* dark colour, near-black on a light one (a badge's text when the venue chose none, 2026-11-21).
*/
export function readableOn(hex) {
let h = String(hex || '').replace('#', '')
if (h.length === 3 || h.length === 4) h = h.slice(0, 3).split('').map(x => x + x).join('')
if (!/^[0-9a-f]{6}/i.test(h)) return '#111111'
const [r, g, b] = [0, 2, 4].map(i => {
const v = parseInt(h.slice(i, i + 2), 16) / 255
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
})
const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b
// the text with the better contrast (WCAG): white beats near-black below ~0.18
return lum < 0.18 ? '#ffffff' : '#111111'
}
/** A page's widest price, in characters: the price column's width, so names and dots line up. */
export function priceChars(groups, format) {
let n = 0
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
}
// ── 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}`
}
// ── the venue's identity (6R.14) ──────────────────────────────────────────────
/** The text of a QR code that joins a Wi-Fi network ("WIFI:T:WPA;S:…;P:…;;"), or '' without a network name. */
export function wifiQr(wifi) {
if (!wifi?.ssid) return ''
const esc = v => String(v).replace(/([\;,:"])/g, '\$1')
const sec = wifi.security === 'nopass' ? 'nopass' : wifi.security === 'WEP' ? 'WEP' : 'WPA'
const pw = sec !== 'nopass' && wifi.password ? `P:${esc(wifi.password)};` : ''
return `WIFI:T:${sec};S:${esc(wifi.ssid)};${pw}${wifi.hidden ? 'H:true;' : ''};`
}