feat(terminal): the menu tablet app (platform-v2 step 5.7a)
terminal/src/apps/menu-tablet: the venue's menu for staff (a quick price
check) and guests. Category chips that jump to their section, or one A–Z
list; compact rows, expanded rows (photo, description) or full cards; tap a
product to see it big (photo, price, description, tags); search that ignores
accents and also finds names typed in Latin letters ("souvl"); sold out
marked; the guest's language for the tablet's texts; back to the start (search
cleared, first language, top) after the set time without a touch; light or
dark; the last menu kept for offline; live on menu_tablet.changed /
device.updated. @xenia/i18n exports ./latin for plain-JS use.
tests: logic (3), e2e menu_tablet.mjs (10 checks, in run-all).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,209 @@
|
||||
// The menu tablet (plan step 5.7a, owner 2026-11-17): the venue's menu on a tablet, for staff ("how
|
||||
// much is the steak?": search, see the price) and for guests (a menu at the entrance, or handed to
|
||||
// them). Just the products and their categories. How it looks is the tablet's device config:
|
||||
// compact / expanded / full view, photos, descriptions, grouped or one A–Z list, whose prices,
|
||||
// sold-out style, search, one category or all, languages, back to the start after a while, light /
|
||||
// dark. Keeps the last menu for offline; a menu change arrives live (`menu_tablet.changed`).
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Search, X } from 'lucide-react'
|
||||
import { useFormat, useLanguage, useTranslation } from '@xenia/i18n'
|
||||
import { applyTheme, Dialog, getStoredTheme, Input } from '@xenia/ui'
|
||||
import client from '../../api/client'
|
||||
import { useLiveEvent, useLiveEvents } from '../../device/context'
|
||||
import { idle, languagesOf, search, sections } from './logic'
|
||||
|
||||
const quiet = { xenia: { noOverride: true } }
|
||||
const CACHE_KEY = 'xenia:menu-tablet:menu'
|
||||
const REFRESH_MS = 5 * 60_000
|
||||
|
||||
function readCache() {
|
||||
try { return JSON.parse(localStorage.getItem(CACHE_KEY) || 'null') } catch { return null }
|
||||
}
|
||||
|
||||
export default function MenuTabletApp() {
|
||||
const { t } = useTranslation('terminal')
|
||||
const { language, changeLanguage } = useLanguage()
|
||||
const [data, setData] = useState(readCache)
|
||||
const [q, setQ] = useState('')
|
||||
const [open, setOpen] = useState(null)
|
||||
const lastTouch = useRef(0) // set on the first touch and when the tablet starts (below)
|
||||
const scroller = useRef(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const { data: d } = await client.get('/api/menu-tablet/menu', quiet)
|
||||
setData(d)
|
||||
try { localStorage.setItem(CACHE_KEY, JSON.stringify(d)) } catch { /* the memory copy still shows */ }
|
||||
} catch { /* offline: keep what we have */ }
|
||||
}, [])
|
||||
useEffect(() => { load() }, [load])
|
||||
useLiveEvent('ready', load)
|
||||
useLiveEvents(['menu_tablet.changed', 'device.updated'], load)
|
||||
useEffect(() => {
|
||||
const id = setInterval(load, REFRESH_MS)
|
||||
return () => clearInterval(id)
|
||||
}, [load])
|
||||
|
||||
const cfg = data?.config || {}
|
||||
const langs = languagesOf(cfg)
|
||||
// the tablet's language: one of those offered (the first after a reset)
|
||||
useEffect(() => {
|
||||
if (data && !langs.includes(language)) changeLanguage(langs[0])
|
||||
}, [data, langs.join(','), language]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
applyTheme(cfg.theme || 'light')
|
||||
return () => { applyTheme(getStoredTheme()) }
|
||||
}, [cfg.theme])
|
||||
|
||||
// back to the start after a while without a touch
|
||||
const reset = useCallback(() => {
|
||||
setQ('')
|
||||
setOpen(null)
|
||||
scroller.current?.scrollTo?.({ top: 0 })
|
||||
if (langs.length > 1 && language !== langs[0]) changeLanguage(langs[0])
|
||||
}, [langs, language, changeLanguage])
|
||||
useEffect(() => {
|
||||
const touch = () => { lastTouch.current = Date.now() }
|
||||
touch()
|
||||
window.addEventListener('pointerdown', touch)
|
||||
window.addEventListener('keydown', touch)
|
||||
const id = setInterval(() => {
|
||||
if (idle(lastTouch.current, cfg.idle_seconds)) { reset(); lastTouch.current = Date.now() }
|
||||
}, 5000)
|
||||
return () => { window.removeEventListener('pointerdown', touch); window.removeEventListener('keydown', touch); clearInterval(id) }
|
||||
}, [cfg.idle_seconds, reset])
|
||||
|
||||
const groups = useMemo(() => sections(data, cfg.group !== false, language), [data, cfg.group, language])
|
||||
const found = useMemo(() => search(data, q, language), [data, q, language])
|
||||
const goTo = id => scroller.current?.querySelector(`[data-section="${id}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
|
||||
if (!data) return <main className="fixed inset-0 bg-canvas" data-testid="app-menu_tablet" />
|
||||
return (
|
||||
<main className="fixed inset-0 bg-canvas text-ink flex flex-col select-none" data-testid="app-menu_tablet" data-view={cfg.view}>
|
||||
<header className="flex items-center gap-3 px-4 py-3 border-b border-line bg-surface">
|
||||
<h1 className="text-title font-semibold truncate flex-1" data-testid="menu-venue">{data.venue?.name || t('menuTablet.title')}</h1>
|
||||
{cfg.search !== false && (
|
||||
<div className="relative w-full max-w-xs">
|
||||
<Search size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
|
||||
<Input value={q} onChange={e => setQ(e.target.value)} placeholder={t('menuTablet.search')} aria-label={t('menuTablet.search')}
|
||||
className="pl-9 w-full" data-testid="menu-search" />
|
||||
{q && <button type="button" onClick={() => setQ('')} aria-label={t('menuTablet.clear')} className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-ink-3"><X size={16} /></button>}
|
||||
</div>
|
||||
)}
|
||||
{langs.length > 1 && (
|
||||
<div className="flex rounded-control border border-line overflow-hidden" role="group" aria-label={t('menuTablet.language')}>
|
||||
{langs.map(l => (
|
||||
<button key={l} type="button" onClick={() => changeLanguage(l)} aria-pressed={language === l} data-testid={`menu-lang-${l}`}
|
||||
className={`px-3 py-2 text-label font-semibold ${language === l ? 'bg-accent text-accent-fg' : 'bg-surface text-ink-2'}`}>{l.toUpperCase()}</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{!q && cfg.group !== false && groups.length > 1 && (
|
||||
<nav className="flex gap-2 px-4 py-2 overflow-x-auto border-b border-line bg-surface-2" aria-label={t('menuTablet.categories')} data-testid="menu-categories">
|
||||
{groups.filter(g => g.depth === 0).map(g => (
|
||||
<button key={g.id} type="button" onClick={() => goTo(g.id)} data-testid="menu-category-chip"
|
||||
className="px-3 py-1.5 rounded-control bg-surface border border-line text-label font-medium whitespace-nowrap">{g.name}</button>
|
||||
))}
|
||||
</nav>
|
||||
)}
|
||||
|
||||
<div ref={scroller} className="flex-1 overflow-y-auto px-4 py-4">
|
||||
{q ? (
|
||||
found.length ? <Items products={found} cfg={cfg} onOpen={setOpen} testid="menu-results" />
|
||||
: <p className="text-body text-ink-3 text-center py-10" data-testid="menu-no-results">{t('menuTablet.noResults', { q })}</p>
|
||||
) : groups.length === 0 ? <p className="text-body text-ink-3 text-center py-10">{t('menuTablet.empty')}</p> : (
|
||||
groups.map(g => (
|
||||
<section key={g.id} data-section={g.id} className="mb-6 scroll-mt-4" data-testid="menu-section">
|
||||
{g.name && <h2 className={`${g.depth ? 'text-body-lg' : 'text-heading'} font-semibold text-ink mb-3`}>{g.name}</h2>}
|
||||
<Items products={g.products} cfg={cfg} onOpen={setOpen} />
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{open && <Details product={open} cfg={cfg} onClose={() => setOpen(null)} />}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function Price({ value, className = '' }) {
|
||||
const { formatMoney } = useFormat()
|
||||
return value == null ? null : <span className={`tabular-nums font-semibold text-accent-ink whitespace-nowrap ${className}`} data-testid="menu-price">{formatMoney(value)}</span>
|
||||
}
|
||||
|
||||
function SoldOut({ product }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
return product.available ? null : <span className="text-caption font-semibold text-danger-ink uppercase" data-testid="menu-sold-out">{t('menuTablet.soldOut')}</span>
|
||||
}
|
||||
|
||||
/** The products in the tablet's view: compact rows, expanded rows, or full cards. */
|
||||
function Items({ products, cfg, onOpen, testid = 'menu-items' }) {
|
||||
const view = cfg.view || 'expanded'
|
||||
const photos = cfg.photos !== false
|
||||
const desc = cfg.descriptions !== false
|
||||
if (view === 'full') {
|
||||
return (
|
||||
<ul className="grid gap-4" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(15rem, 1fr))' }} data-testid={testid}>
|
||||
{products.map(p => (
|
||||
<li key={p.id}>
|
||||
<button type="button" onClick={() => onOpen(p)} data-testid="menu-item" data-id={p.id} data-available={p.available ? 'true' : 'false'}
|
||||
className={`w-full text-left rounded-card border border-line bg-surface overflow-hidden grid ${p.available ? '' : 'opacity-60'}`}>
|
||||
{photos && (p.image ? <img src={p.image.card} alt="" loading="lazy" className="w-full aspect-[4/3] object-cover bg-surface-3" />
|
||||
: <div className="w-full aspect-[4/3] bg-surface-2 flex items-center justify-center text-display font-semibold text-ink-3" aria-hidden="true">{p.name.trim()[0]}</div>)}
|
||||
<div className="p-3 grid gap-1">
|
||||
<div className="flex items-start gap-2">
|
||||
<span className={`text-body-lg font-semibold flex-1 ${p.available ? '' : 'line-through'}`}>{p.name}</span>
|
||||
<Price value={p.price} className="text-body-lg" />
|
||||
</div>
|
||||
<SoldOut product={p} />
|
||||
{desc && p.description && <p className="text-label text-ink-2 line-clamp-3">{p.description}</p>}
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<ul className={`grid ${view === 'compact' ? 'gap-0' : 'gap-2'}`} data-testid={testid}>
|
||||
{products.map(p => (
|
||||
<li key={p.id}>
|
||||
<button type="button" onClick={() => onOpen(p)} data-testid="menu-item" data-id={p.id} data-available={p.available ? 'true' : 'false'}
|
||||
className={`w-full text-left flex items-center gap-3 ${view === 'compact' ? 'py-2 border-b border-line' : 'p-2 rounded-card bg-surface border border-line'} ${p.available ? '' : 'opacity-60'}`}>
|
||||
{view === 'expanded' && photos && p.image && <img src={p.image.thumb} alt="" loading="lazy" className="w-16 h-16 rounded-control object-cover bg-surface-3 shrink-0" />}
|
||||
<div className="flex-1 min-w-0 grid gap-0.5">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className={`${view === 'compact' ? 'text-body' : 'text-body-lg'} font-medium ${p.available ? '' : 'line-through'}`}>{p.name}</span>
|
||||
<SoldOut product={p} />
|
||||
</div>
|
||||
{view === 'expanded' && desc && p.description && <p className="text-label text-ink-2 line-clamp-2">{p.description}</p>}
|
||||
</div>
|
||||
<Price value={p.price} className={view === 'compact' ? 'text-body' : 'text-body-lg'} />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** One product, big: its photo, price, description and tags. */
|
||||
function Details({ product: p, cfg, onClose }) {
|
||||
const { t } = useTranslation('terminal')
|
||||
return (
|
||||
<Dialog open size="md" title={p.name} onClose={onClose} closeLabel={t('menuTablet.close')}>
|
||||
<div className="grid gap-3" data-testid="menu-details" data-id={p.id}>
|
||||
{cfg.photos !== false && p.image && <img src={p.image.full} alt="" className="w-full rounded-card object-cover max-h-[50vh]" />}
|
||||
<div className="flex items-center gap-3">
|
||||
<Price value={p.price} className="text-heading" />
|
||||
<SoldOut product={p} />
|
||||
</div>
|
||||
{p.description && <p className="text-body text-ink-2 whitespace-pre-line">{p.description}</p>}
|
||||
{p.tags?.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">{p.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-control bg-surface-2 text-label text-ink-2">{tag}</span>)}</div>
|
||||
)}
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// The menu tablet's logic (plan step 5.7a). Pure: unit-tested in Node (tests/menu-tablet.test.mjs).
|
||||
import { latin } from '@xenia/i18n/latin' // plain JS (Node tests)
|
||||
|
||||
/** Lowercase, no accents: "Σουβλάκι" and "σουβλακι" match. */
|
||||
export function fold(text) {
|
||||
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
|
||||
}
|
||||
|
||||
/** Does a product match a search? By its name in Greek or in Latin letters ("souvlaki"), or a tag. */
|
||||
export function matches(product, query) {
|
||||
const q = fold(query)
|
||||
if (!q) return true
|
||||
const name = fold(product.name)
|
||||
return name.includes(q) || fold(latin(product.name)).includes(q) || (product.tags || []).some(t => fold(t).includes(q))
|
||||
}
|
||||
|
||||
/** Every product once, A to Z (the ungrouped list and the search's results). */
|
||||
export function allProducts(data, language = 'el') {
|
||||
return Object.values(data?.products || {}).sort((a, b) => a.name.localeCompare(b.name, language))
|
||||
}
|
||||
|
||||
/** What a search finds: the products whose name (or tag) matches, A to Z; a name that starts with it first. */
|
||||
export function search(data, query, language = 'el') {
|
||||
const q = fold(query)
|
||||
if (!q) return []
|
||||
const found = allProducts(data, language).filter(p => matches(p, q))
|
||||
const starts = p => fold(p.name).startsWith(q) || fold(latin(p.name)).startsWith(q)
|
||||
return [...found.filter(starts), ...found.filter(p => !starts(p))]
|
||||
}
|
||||
|
||||
/** The sections to show: grouped = each category with its products; not grouped = one A–Z list. */
|
||||
export function sections(data, grouped, language = 'el') {
|
||||
if (!data) return []
|
||||
if (!grouped) return [{ id: 'all', name: null, depth: 0, products: allProducts(data, language) }]
|
||||
return (data.categories || [])
|
||||
.map(c => ({ ...c, products: c.products.map(id => data.products[String(id)]).filter(Boolean) }))
|
||||
.filter(c => c.products.length)
|
||||
}
|
||||
|
||||
/** Back to the start? After `seconds` without a touch (0 = never). */
|
||||
export function idle(lastTouchMs, seconds, nowMs = Date.now()) {
|
||||
return Number(seconds) > 0 && nowMs - lastTouchMs >= Number(seconds) * 1000
|
||||
}
|
||||
|
||||
/** The languages a guest can pick, the first one being where the tablet starts. */
|
||||
export function languagesOf(config) {
|
||||
if (config?.languages === 'el') return ['el']
|
||||
if (config?.languages === 'en') return ['en']
|
||||
return ['el', 'en']
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
// The apps a paired screen can run (plan step 3.1b, APPS_PLATFORM D-2): the device's
|
||||
// app_key (GET /api/devices/me) picks one. Each app is its own lazily loaded chunk, so a
|
||||
// kitchen screen never downloads the POS. The menu tablet arrives in step 5.7.
|
||||
// kitchen screen never downloads the POS.
|
||||
|
||||
export const APPS = {
|
||||
kds: () => import('./kds/KdsApp.jsx'),
|
||||
pos_counter: () => import('./pos/PosApp.jsx'),
|
||||
customer_display: () => import('./customer-display/CustomerDisplayApp.jsx'),
|
||||
signage: () => import('./signage/SignageApp.jsx'),
|
||||
menu_tablet: () => import('./menu-tablet/MenuTabletApp.jsx'),
|
||||
}
|
||||
|
||||
/** The loader of an app, or null when this terminal version doesn't have it. */
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// The menu tablet's logic (plan step 5.7a).
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { allProducts, fold, idle, languagesOf, matches, search, sections } from '../src/apps/menu-tablet/logic.js'
|
||||
|
||||
const data = {
|
||||
categories: [{ id: 1, name: 'Grill', depth: 0, products: [2, 1] }, { id: 3, name: 'Pita', depth: 1, products: [1] }, { id: 4, name: 'Empty', depth: 0, products: [9] }],
|
||||
products: { 1: { id: 1, name: 'Σουβλάκι χοιρινό', tags: [] }, 2: { id: 2, name: 'Μπριζόλα', tags: ['gluten-free'] }, 5: { id: 5, name: 'Αναψυκτικό', tags: [] } },
|
||||
}
|
||||
|
||||
test('search finds Greek names with or without accents, in Latin letters, and by tag', () => {
|
||||
assert.equal(fold('Σουβλάκι'), 'σουβλακι')
|
||||
assert.ok(matches(data.products[1], 'σουβλακι'))
|
||||
assert.ok(matches(data.products[1], 'souvl'))
|
||||
assert.ok(matches(data.products[2], 'gluten'))
|
||||
assert.ok(!matches(data.products[2], 'souvl'))
|
||||
assert.deepEqual(search(data, 'ι').map(p => p.id).slice(0, 1).length, 1)
|
||||
assert.deepEqual(search(data, 'mpriz').map(p => p.id), [2])
|
||||
assert.deepEqual(search(data, ' '), [])
|
||||
})
|
||||
|
||||
test('sections: grouped by category (empty ones left out) or one A–Z list', () => {
|
||||
assert.deepEqual(sections(data, true).map(s => [s.name, s.products.map(p => p.id)]), [['Grill', [2, 1]], ['Pita', [1]]])
|
||||
assert.deepEqual(sections(data, false)[0].products.map(p => p.id), allProducts(data).map(p => p.id))
|
||||
assert.deepEqual(allProducts(data).map(p => p.name), ['Αναψυκτικό', 'Μπριζόλα', 'Σουβλάκι χοιρινό'])
|
||||
assert.deepEqual(sections(null, true), [])
|
||||
})
|
||||
|
||||
test('back to the start after a while; the languages a guest can pick', () => {
|
||||
assert.equal(idle(0, 60, 59_000), false)
|
||||
assert.equal(idle(0, 60, 60_000), true)
|
||||
assert.equal(idle(0, 0, 9e9), false)
|
||||
assert.deepEqual(languagesOf({ languages: 'both' }), ['el', 'en'])
|
||||
assert.deepEqual(languagesOf({ languages: 'en' }), ['en'])
|
||||
assert.deepEqual(languagesOf(undefined), ['el', 'en'])
|
||||
})
|
||||
@@ -5,10 +5,10 @@ import { APPS, appLoader } from '../src/apps/registry.js'
|
||||
import { DEVICE_KEY, SESSION_KEY, createDeviceStore } from '../src/device/storage.js'
|
||||
import { deviceGone, formatCode, idleExpired, liveAction, pollOutcome, refusedAction, screenFor } from '../src/device/flow.js'
|
||||
|
||||
test('the apps a screen can run: KDS, counter POS, customer display, signage (the menu tablet in 5.7)', () => {
|
||||
assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'pos_counter', 'signage'])
|
||||
test('the apps a screen can run: KDS, counter POS, customer display, signage, menu tablet', () => {
|
||||
assert.deepEqual(Object.keys(APPS).sort(), ['customer_display', 'kds', 'menu_tablet', 'pos_counter', 'signage'])
|
||||
assert.equal(typeof appLoader('kds'), 'function')
|
||||
assert.equal(appLoader('menu_tablet'), null)
|
||||
assert.equal(appLoader('waiter'), null)
|
||||
assert.equal(appLoader('toString'), null) // never a prototype member
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user